Allow an open generic method instance to match its instantiations when setting breakp...
[mono.git] / mono / mini / debugger-agent.c
1 /*
2  * debugger-agent.c: Soft Debugger back-end module
3  *
4  * Author:
5  *   Zoltan Varga (vargaz@gmail.com)
6  *
7  * Copyright 2009-2010 Novell, Inc.
8  * Copyright 2011 Xamarin Inc.
9  */
10
11 #include <config.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
17 #endif
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
20 #endif
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
23 #endif
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
26 #endif
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
29 #endif
30 #ifdef HAVE_NETDB_H
31 #include <netdb.h>
32 #endif
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <errno.h>
37 #include <glib.h>
38
39 #ifdef HAVE_PTHREAD_H
40 #include <pthread.h>
41 #endif
42
43 #ifdef HAVE_UCONTEXT_H
44 #include <ucontext.h>
45 #endif
46
47 #ifdef HOST_WIN32
48 #ifdef _MSC_VER
49 #include <winsock2.h>
50 #endif
51 #include <ws2tcpip.h>
52 #ifdef __GNUC__
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
56                         struct addrinfo**);
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
58                        char*,DWORD,int);
59 #endif
60 #endif
61
62 #ifdef PLATFORM_ANDROID
63 #include <linux/in.h>
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
66 #endif
67
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/utils/mono-semaphore.h>
76 #include <mono/utils/mono-error-internals.h>
77 #include <mono/utils/mono-stack-unwinding.h>
78 #include <mono/utils/mono-time.h>
79 #include "debugger-agent.h"
80 #include "mini.h"
81
82 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
83 #define DISABLE_DEBUGGER_AGENT 1
84 #endif
85
86 #ifdef DISABLE_SOFT_DEBUG
87 #define DISABLE_DEBUGGER_AGENT 1
88 #endif
89
90 #if defined(__MACH__)
91 #include <mono/utils/mono-threads.h>
92 #endif
93
94 #ifndef DISABLE_DEBUGGER_AGENT
95
96 #include <mono/io-layer/mono-mutex.h>
97
98 /* Definitions to make backporting to 2.6 easier */
99 //#define MonoInternalThread MonoThread
100 //#define mono_thread_internal_current mono_thread_current
101 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
102
103 typedef struct {
104         gboolean enabled;
105         char *transport;
106         char *address;
107         int log_level;
108         char *log_file;
109         gboolean suspend;
110         gboolean server;
111         gboolean onuncaught;
112         GSList *onthrow;
113         int timeout;
114         char *launch;
115         gboolean embedding;
116         gboolean defer;
117         int keepalive;
118 } AgentConfig;
119
120 typedef struct
121 {
122         int id;
123         guint32 il_offset, native_offset;
124         MonoDomain *domain;
125         MonoMethod *method;
126         /*
127          * If method is gshared, this is the actual instance, otherwise this is equal to
128          * method.
129          */
130         MonoMethod *actual_method;
131         MonoContext ctx;
132         MonoDebugMethodJitInfo *jit;
133         int flags;
134         mgreg_t *reg_locations [MONO_MAX_IREGS];
135         /*
136          * Whenever ctx is set. This is FALSE for the last frame of running threads, since
137          * the frame can become invalid.
138          */
139         gboolean has_ctx;
140 } StackFrame;
141
142 typedef struct _InvokeData InvokeData;
143
144 struct _InvokeData
145 {
146         int id;
147         int flags;
148         guint8 *p;
149         guint8 *endp;
150         /* This is the context which needs to be restored after the invoke */
151         MonoContext ctx;
152         gboolean has_ctx;
153         /*
154          * If this is set, invoke this method with the arguments given by ARGS.
155          */
156         MonoMethod *method;
157         gpointer *args;
158         guint32 suspend_count;
159
160         InvokeData *last_invoke;
161 };
162
163 typedef struct {
164         MonoThreadUnwindState context;
165
166         gpointer resume_event;
167         /* This is computed on demand when it is requested using the wire protocol */
168         /* It is freed up when the thread is resumed */
169         int frame_count;
170         StackFrame **frames;
171         /* 
172          * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
173          * re-compute it.
174          */
175         gboolean frames_up_to_date;
176         /* 
177          * Points to data about a pending invoke which needs to be executed after the thread
178          * resumes.
179          */
180         InvokeData *pending_invoke;
181         /*
182          * Set to TRUE if this thread is suspended in suspend_current () or it is executing
183          * native code.
184          */
185         gboolean suspended;
186         /*
187          * Signals whenever the thread is in the process of suspending, i.e. it will suspend
188          * within a finite amount of time.
189          */
190         gboolean suspending;
191         /*
192          * Set to TRUE if this thread is suspended in suspend_current ().
193          */
194         gboolean really_suspended;
195         /* Used to pass the context to the breakpoint/single step handler */
196         MonoContext handler_ctx;
197         /* Whenever thread_stop () was called for this thread */
198         gboolean terminated;
199
200         /* Number of thread interruptions not yet processed */
201         gint32 interrupt_count;
202
203         /* Whenever to disable breakpoints (used during invokes) */
204         gboolean disable_breakpoints;
205
206         /*
207          * Number of times this thread has been resumed using resume_thread ().
208          */
209         guint32 resume_count;
210
211         MonoInternalThread *thread;
212
213         /*
214          * Information about the frame which transitioned to native code for running
215          * threads.
216          */
217         StackFrameInfo async_last_frame;
218
219         /*
220          * The context where the stack walk can be started for running threads.
221          */
222         MonoThreadUnwindState async_state;
223
224         /*
225      * The context used for filter clauses
226      */
227         MonoThreadUnwindState filter_state;
228
229         /*
230          * The callee address of the last mono_runtime_invoke call
231          */
232         gpointer invoke_addr;
233
234         gboolean abort_requested;
235
236         /*
237          * The current mono_runtime_invoke invocation.
238          */
239         InvokeData *invoke;
240
241         /*
242          * The context where single stepping should resume while the thread is suspended because
243          * of an EXCEPTION event.
244          */
245         MonoContext catch_ctx;
246
247         gboolean has_catch_ctx;
248
249         /*
250          * The context which needs to be restored after handling a single step/breakpoint
251          * event. This is the same as the ctx at step/breakpoint site, but includes changes
252          * to caller saved registers done by set_var ().
253          */
254         MonoContext restore_ctx;
255 } DebuggerTlsData;
256
257 typedef struct {
258         const char *name;
259         void (*connect) (const char *address);
260         void (*close1) (void);
261         void (*close2) (void);
262         gboolean (*send) (void *buf, int len);
263         int (*recv) (void *buf, int len);
264 } DebuggerTransport;
265
266 /* 
267  * Wire Protocol definitions
268  */
269
270 #define HEADER_LENGTH 11
271
272 #define MAJOR_VERSION 2
273 #define MINOR_VERSION 14
274
275 typedef enum {
276         CMD_SET_VM = 1,
277         CMD_SET_OBJECT_REF = 9,
278         CMD_SET_STRING_REF = 10,
279         CMD_SET_THREAD = 11,
280         CMD_SET_ARRAY_REF = 13,
281         CMD_SET_EVENT_REQUEST = 15,
282         CMD_SET_STACK_FRAME = 16,
283         CMD_SET_APPDOMAIN = 20,
284         CMD_SET_ASSEMBLY = 21,
285         CMD_SET_METHOD = 22,
286         CMD_SET_TYPE = 23,
287         CMD_SET_MODULE = 24,
288         CMD_SET_EVENT = 64
289 } CommandSet;
290
291 typedef enum {
292         EVENT_KIND_VM_START = 0,
293         EVENT_KIND_VM_DEATH = 1,
294         EVENT_KIND_THREAD_START = 2,
295         EVENT_KIND_THREAD_DEATH = 3,
296         EVENT_KIND_APPDOMAIN_CREATE = 4,
297         EVENT_KIND_APPDOMAIN_UNLOAD = 5,
298         EVENT_KIND_METHOD_ENTRY = 6,
299         EVENT_KIND_METHOD_EXIT = 7,
300         EVENT_KIND_ASSEMBLY_LOAD = 8,
301         EVENT_KIND_ASSEMBLY_UNLOAD = 9,
302         EVENT_KIND_BREAKPOINT = 10,
303         EVENT_KIND_STEP = 11,
304         EVENT_KIND_TYPE_LOAD = 12,
305         EVENT_KIND_EXCEPTION = 13,
306         EVENT_KIND_KEEPALIVE = 14,
307         EVENT_KIND_USER_BREAK = 15,
308         EVENT_KIND_USER_LOG = 16
309 } EventKind;
310
311 typedef enum {
312         SUSPEND_POLICY_NONE = 0,
313         SUSPEND_POLICY_EVENT_THREAD = 1,
314         SUSPEND_POLICY_ALL = 2
315 } SuspendPolicy;
316
317 typedef enum {
318         ERR_NONE = 0,
319         ERR_INVALID_OBJECT = 20,
320         ERR_INVALID_FIELDID = 25,
321         ERR_INVALID_FRAMEID = 30,
322         ERR_NOT_IMPLEMENTED = 100,
323         ERR_NOT_SUSPENDED = 101,
324         ERR_INVALID_ARGUMENT = 102,
325         ERR_UNLOADED = 103,
326         ERR_NO_INVOCATION = 104,
327         ERR_ABSENT_INFORMATION = 105,
328         ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
329         ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
330 } ErrorCode;
331
332 typedef enum {
333         MOD_KIND_COUNT = 1,
334         MOD_KIND_THREAD_ONLY = 3,
335         MOD_KIND_LOCATION_ONLY = 7,
336         MOD_KIND_EXCEPTION_ONLY = 8,
337         MOD_KIND_STEP = 10,
338         MOD_KIND_ASSEMBLY_ONLY = 11,
339         MOD_KIND_SOURCE_FILE_ONLY = 12,
340         MOD_KIND_TYPE_NAME_ONLY = 13
341 } ModifierKind;
342
343 typedef enum {
344         STEP_DEPTH_INTO = 0,
345         STEP_DEPTH_OVER = 1,
346         STEP_DEPTH_OUT = 2
347 } StepDepth;
348
349 typedef enum {
350         STEP_SIZE_MIN = 0,
351         STEP_SIZE_LINE = 1
352 } StepSize;
353
354 typedef enum {
355         TOKEN_TYPE_STRING = 0,
356         TOKEN_TYPE_TYPE = 1,
357         TOKEN_TYPE_FIELD = 2,
358         TOKEN_TYPE_METHOD = 3,
359         TOKEN_TYPE_UNKNOWN = 4
360 } DebuggerTokenType;
361
362 typedef enum {
363         VALUE_TYPE_ID_NULL = 0xf0,
364         VALUE_TYPE_ID_TYPE = 0xf1
365 } ValueTypeId;
366
367 typedef enum {
368         FRAME_FLAG_DEBUGGER_INVOKE = 1
369 } StackFrameFlags;
370
371 typedef enum {
372         INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
373         INVOKE_FLAG_SINGLE_THREADED = 2
374 } InvokeFlags;
375
376 typedef enum {
377         BINDING_FLAGS_IGNORE_CASE = 0x70000000,
378 } BindingFlagsExtensions;
379
380 typedef enum {
381         CMD_VM_VERSION = 1,
382         CMD_VM_ALL_THREADS = 2,
383         CMD_VM_SUSPEND = 3,
384         CMD_VM_RESUME = 4,
385         CMD_VM_EXIT = 5,
386         CMD_VM_DISPOSE = 6,
387         CMD_VM_INVOKE_METHOD = 7,
388         CMD_VM_SET_PROTOCOL_VERSION = 8,
389         CMD_VM_ABORT_INVOKE = 9,
390         CMD_VM_SET_KEEPALIVE = 10,
391         CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
392         CMD_VM_GET_TYPES = 12
393 } CmdVM;
394
395 typedef enum {
396         CMD_THREAD_GET_FRAME_INFO = 1,
397         CMD_THREAD_GET_NAME = 2,
398         CMD_THREAD_GET_STATE = 3,
399         CMD_THREAD_GET_INFO = 4,
400         CMD_THREAD_GET_ID = 5,
401         CMD_THREAD_GET_TID = 6
402 } CmdThread;
403
404 typedef enum {
405         CMD_EVENT_REQUEST_SET = 1,
406         CMD_EVENT_REQUEST_CLEAR = 2,
407         CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
408 } CmdEvent;
409
410 typedef enum {
411         CMD_COMPOSITE = 100
412 } CmdComposite;
413
414 typedef enum {
415         CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
416         CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
417         CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
418         CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
419         CMD_APPDOMAIN_CREATE_STRING = 5,
420         CMD_APPDOMAIN_GET_CORLIB = 6,
421         CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
422 } CmdAppDomain;
423
424 typedef enum {
425         CMD_ASSEMBLY_GET_LOCATION = 1,
426         CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
427         CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
428         CMD_ASSEMBLY_GET_OBJECT = 4,
429         CMD_ASSEMBLY_GET_TYPE = 5,
430         CMD_ASSEMBLY_GET_NAME = 6
431 } CmdAssembly;
432
433 typedef enum {
434         CMD_MODULE_GET_INFO = 1,
435 } CmdModule;
436
437 typedef enum {
438         CMD_METHOD_GET_NAME = 1,
439         CMD_METHOD_GET_DECLARING_TYPE = 2,
440         CMD_METHOD_GET_DEBUG_INFO = 3,
441         CMD_METHOD_GET_PARAM_INFO = 4,
442         CMD_METHOD_GET_LOCALS_INFO = 5,
443         CMD_METHOD_GET_INFO = 6,
444         CMD_METHOD_GET_BODY = 7,
445         CMD_METHOD_RESOLVE_TOKEN = 8,
446 } CmdMethod;
447
448 typedef enum {
449         CMD_TYPE_GET_INFO = 1,
450         CMD_TYPE_GET_METHODS = 2,
451         CMD_TYPE_GET_FIELDS = 3,
452         CMD_TYPE_GET_VALUES = 4,
453         CMD_TYPE_GET_OBJECT = 5,
454         CMD_TYPE_GET_SOURCE_FILES = 6,
455         CMD_TYPE_SET_VALUES = 7,
456         CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
457         CMD_TYPE_GET_PROPERTIES = 9,
458         CMD_TYPE_GET_CATTRS = 10,
459         CMD_TYPE_GET_FIELD_CATTRS = 11,
460         CMD_TYPE_GET_PROPERTY_CATTRS = 12,
461         CMD_TYPE_GET_SOURCE_FILES_2 = 13,
462         CMD_TYPE_GET_VALUES_2 = 14,
463         CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
464         CMD_TYPE_GET_INTERFACES = 16,
465         CMD_TYPE_GET_INTERFACE_MAP = 17,
466 } CmdType;
467
468 typedef enum {
469         CMD_STACK_FRAME_GET_VALUES = 1,
470         CMD_STACK_FRAME_GET_THIS = 2,
471         CMD_STACK_FRAME_SET_VALUES = 3
472 } CmdStackFrame;
473
474 typedef enum {
475         CMD_ARRAY_REF_GET_LENGTH = 1,
476         CMD_ARRAY_REF_GET_VALUES = 2,
477         CMD_ARRAY_REF_SET_VALUES = 3,
478 } CmdArray;
479
480 typedef enum {
481         CMD_STRING_REF_GET_VALUE = 1,
482         CMD_STRING_REF_GET_LENGTH = 2,
483         CMD_STRING_REF_GET_CHARS = 3
484 } CmdString;
485
486 typedef enum {
487         CMD_OBJECT_REF_GET_TYPE = 1,
488         CMD_OBJECT_REF_GET_VALUES = 2,
489         CMD_OBJECT_REF_IS_COLLECTED = 3,
490         CMD_OBJECT_REF_GET_ADDRESS = 4,
491         CMD_OBJECT_REF_GET_DOMAIN = 5,
492         CMD_OBJECT_REF_SET_VALUES = 6,
493         CMD_OBJECT_REF_GET_INFO = 7,
494 } CmdObject;
495
496 typedef struct {
497         ModifierKind kind;
498         union {
499                 int count; /* For kind == MOD_KIND_COUNT */
500                 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
501                 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
502                 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
503                 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
504                 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
505         } data;
506         gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
507 } Modifier;
508
509 typedef struct{
510         int id;
511         int event_kind;
512         int suspend_policy;
513         int nmodifiers;
514         gpointer info;
515         Modifier modifiers [MONO_ZERO_LEN_ARRAY];
516 } EventRequest;
517
518 /*
519  * Describes a single step request.
520  */
521 typedef struct {
522         EventRequest *req;
523         MonoInternalThread *thread;
524         StepDepth depth;
525         StepSize size;
526         gpointer last_sp;
527         gpointer start_sp;
528         MonoMethod *last_method;
529         int last_line;
530         /* Whenever single stepping is performed using start/stop_single_stepping () */
531         gboolean global;
532         /* The list of breakpoints used to implement step-over */
533         GSList *bps;
534 } SingleStepReq;
535
536 /*
537  * Contains additional information for an event
538  */
539 typedef struct {
540         /* For EVENT_KIND_EXCEPTION */
541         MonoObject *exc;
542         MonoContext catch_ctx;
543         gboolean caught;
544         /* For EVENT_KIND_USER_LOG */
545         int level;
546         char *category, *message;
547         /* For EVENT_KIND_TYPE_LOAD */
548         MonoClass *klass;
549 } EventInfo;
550
551 /* Dummy structure used for the profiler callbacks */
552 typedef struct {
553         void* dummy;
554 } DebuggerProfiler;
555
556 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
557
558 #ifdef HOST_WIN32
559 #define get_last_sock_error() WSAGetLastError()
560 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
561 #define MONO_EINTR WSAEINTR
562 #else
563 #define get_last_sock_error() errno
564 #define MONO_EWOULDBLOCK EWOULDBLOCK
565 #define MONO_EINTR EINTR
566 #endif
567
568 #define CHECK_PROTOCOL_VERSION(major,minor) \
569         (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
570
571 /*
572  * Globals
573  */
574
575 static AgentConfig agent_config;
576
577 /* 
578  * Whenever the agent is fully initialized.
579  * When using the onuncaught or onthrow options, only some parts of the agent are
580  * initialized on startup, and the full initialization which includes connection
581  * establishment and the startup of the agent thread is only done in response to
582  * an event.
583  */
584 static gint32 inited;
585
586 #ifndef DISABLE_SOCKET_TRANSPORT
587 static int conn_fd;
588 static int listen_fd;
589 #endif
590
591 static int packet_id = 0;
592
593 static int objref_id = 0;
594
595 static int event_request_id = 0;
596
597 static int frame_id = 0;
598
599 static GPtrArray *event_requests;
600
601 static MonoNativeTlsKey debugger_tls_id;
602
603 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
604
605 /* Maps MonoInternalThread -> DebuggerTlsData */
606 static MonoGHashTable *thread_to_tls;
607
608 /* Maps tid -> MonoInternalThread */
609 static MonoGHashTable *tid_to_thread;
610
611 /* Maps tid -> MonoThread (not MonoInternalThread) */
612 static MonoGHashTable *tid_to_thread_obj;
613
614 static gsize debugger_thread_id;
615
616 static HANDLE debugger_thread_handle;
617
618 static int log_level;
619
620 static gboolean embedding;
621
622 static FILE *log_file;
623
624 /* Assemblies whose assembly load event has no been sent yet */
625 static GPtrArray *pending_assembly_loads;
626
627 /* Whenever the debugger thread has exited */
628 static gboolean debugger_thread_exited;
629
630 /* Cond variable used to wait for debugger_thread_exited becoming true */
631 static mono_cond_t debugger_thread_exited_cond;
632
633 /* Mutex for the cond var above */
634 static mono_mutex_t debugger_thread_exited_mutex;
635
636 static DebuggerProfiler debugger_profiler;
637
638 /* The single step request instance */
639 static SingleStepReq *ss_req = NULL;
640 static gpointer ss_invoke_addr = NULL;
641
642 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
643 /* Number of single stepping operations in progress */
644 static int ss_count;
645 #endif
646
647 /* The protocol version of the client */
648 static int major_version, minor_version;
649
650 /* Whenever the variables above are set by the client */
651 static gboolean protocol_version_set;
652
653 /* A hash table containing all active domains */
654 static GHashTable *domains;
655
656 static void transport_init (void);
657 static void transport_connect (const char *address);
658 static gboolean transport_handshake (void);
659 static void register_transport (DebuggerTransport *trans);
660
661 static guint32 WINAPI debugger_thread (void *arg);
662
663 static void runtime_initialized (MonoProfiler *prof);
664
665 static void runtime_shutdown (MonoProfiler *prof);
666
667 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
668
669 static void thread_end (MonoProfiler *prof, uintptr_t tid);
670
671 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
672
673 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
674
675 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
676
677 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
678
679 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
680
681 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
682
683 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
684
685 static void emit_assembly_load (gpointer assembly, gpointer user_data);
686
687 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
688
689 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
690
691 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
692
693 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
694
695 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
696
697 static void start_single_stepping (void);
698
699 static void stop_single_stepping (void);
700
701 static void suspend_current (void);
702
703 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
704
705 static void clear_types_for_assembly (MonoAssembly *assembly);
706
707 static void clear_breakpoints_for_domain (MonoDomain *domain);
708
709 static void process_profiler_event (EventKind event, gpointer arg);
710
711 /* Submodule init/cleanup */
712 static void breakpoints_init (void);
713 static void breakpoints_cleanup (void);
714
715 static void objrefs_init (void);
716 static void objrefs_cleanup (void);
717
718 static void ids_init (void);
719 static void ids_cleanup (void);
720
721 static void suspend_init (void);
722
723 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
724 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
725 static void ss_destroy (SingleStepReq *req);
726
727 static void start_debugger_thread (void);
728 static void stop_debugger_thread (void);
729
730 static void finish_agent_init (gboolean on_startup);
731
732 static void process_profiler_event (EventKind event, gpointer arg);
733
734 #ifndef DISABLE_SOCKET_TRANSPORT
735 static void
736 register_socket_transport (void);
737 #endif
738
739 static int
740 parse_address (char *address, char **host, int *port)
741 {
742         char *pos = strchr (address, ':');
743
744         if (pos == NULL || pos == address)
745                 return 1;
746
747         *host = g_malloc (pos - address + 1);
748         strncpy (*host, address, pos - address);
749         (*host) [pos - address] = '\0';
750
751         *port = atoi (pos + 1);
752
753         return 0;
754 }
755
756 static void
757 print_usage (void)
758 {
759         fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
760         fprintf (stderr, "Available options:\n");
761         fprintf (stderr, "  transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
762         fprintf (stderr, "  address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
763         fprintf (stderr, "  loglevel=<n>\t\t\tLog level (defaults to 0)\n");
764         fprintf (stderr, "  logfile=<file>\t\tFile to log to (defaults to stdout)\n");
765         fprintf (stderr, "  suspend=y/n\t\t\tWhether to suspend after startup.\n");
766         fprintf (stderr, "  timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
767         fprintf (stderr, "  server=y/n\t\t\tWhether to listen for a client connection.\n");
768         fprintf (stderr, "  keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
769         fprintf (stderr, "  help\t\t\t\tPrint this help.\n");
770 }
771
772 static gboolean
773 parse_flag (const char *option, char *flag)
774 {
775         if (!strcmp (flag, "y"))
776                 return TRUE;
777         else if (!strcmp (flag, "n"))
778                 return FALSE;
779         else {
780                 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
781                 exit (1);
782                 return FALSE;
783         }
784 }
785
786 void
787 mono_debugger_agent_parse_options (char *options)
788 {
789         char **args, **ptr;
790         char *host;
791         int port;
792         char *extra;
793
794 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
795         fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
796         exit (1);
797 #endif
798
799         extra = getenv ("MONO_SDB_ENV_OPTIONS");
800         if (extra)
801                 options = g_strdup_printf ("%s,%s", options, extra);
802
803         agent_config.enabled = TRUE;
804         agent_config.suspend = TRUE;
805         agent_config.server = FALSE;
806         agent_config.defer = FALSE;
807         agent_config.address = NULL;
808
809         args = g_strsplit (options, ",", -1);
810         for (ptr = args; ptr && *ptr; ptr ++) {
811                 char *arg = *ptr;
812
813                 if (strncmp (arg, "transport=", 10) == 0) {
814                         agent_config.transport = g_strdup (arg + 10);
815                 } else if (strncmp (arg, "address=", 8) == 0) {
816                         agent_config.address = g_strdup (arg + 8);
817                 } else if (strncmp (arg, "loglevel=", 9) == 0) {
818                         agent_config.log_level = atoi (arg + 9);
819                 } else if (strncmp (arg, "logfile=", 8) == 0) {
820                         agent_config.log_file = g_strdup (arg + 8);
821                 } else if (strncmp (arg, "suspend=", 8) == 0) {
822                         agent_config.suspend = parse_flag ("suspend", arg + 8);
823                 } else if (strncmp (arg, "server=", 7) == 0) {
824                         agent_config.server = parse_flag ("server", arg + 7);
825                 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
826                         agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
827                 } else if (strncmp (arg, "onthrow=", 8) == 0) {
828                         /* We support multiple onthrow= options */
829                         agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
830                 } else if (strncmp (arg, "onthrow", 7) == 0) {
831                         agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
832                 } else if (strncmp (arg, "help", 4) == 0) {
833                         print_usage ();
834                         exit (0);
835                 } else if (strncmp (arg, "timeout=", 8) == 0) {
836                         agent_config.timeout = atoi (arg + 8);
837                 } else if (strncmp (arg, "launch=", 7) == 0) {
838                         agent_config.launch = g_strdup (arg + 7);
839                 } else if (strncmp (arg, "embedding=", 10) == 0) {
840                         agent_config.embedding = atoi (arg + 10) == 1;
841                 } else if (strncmp (arg, "keepalive=", 10) == 0) {
842                         agent_config.keepalive = atoi (arg + 10);
843                 } else {
844                         print_usage ();
845                         exit (1);
846                 }
847         }
848
849         if (agent_config.server && !agent_config.suspend) {
850                 /* Waiting for deferred attachment */
851                 agent_config.defer = TRUE;
852                 if (agent_config.address == NULL) {
853                         agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
854                 }
855         }
856
857         if (agent_config.transport == NULL) {
858                 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
859                 exit (1);
860         }
861
862         if (agent_config.address == NULL && !agent_config.server) {
863                 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
864                 exit (1);
865         }
866
867         // FIXME:
868         if (!strcmp (agent_config.transport, "dt_socket")) {
869                 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
870                         fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
871                         exit (1);
872                 }
873         }
874 }
875
876 void
877 mono_debugger_agent_init (void)
878 {
879         if (!agent_config.enabled)
880                 return;
881
882         transport_init ();
883
884         /* Need to know whenever a thread has acquired the loader mutex */
885         mono_loader_lock_track_ownership (TRUE);
886
887         event_requests = g_ptr_array_new ();
888
889         mono_mutex_init (&debugger_thread_exited_mutex, NULL);
890         mono_cond_init (&debugger_thread_exited_cond, NULL);
891
892         mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
893         mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
894         mono_profiler_install_runtime_initialized (runtime_initialized);
895         mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
896         mono_profiler_install_thread (thread_startup, thread_end);
897         mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
898         mono_profiler_install_jit_end (jit_end);
899         mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
900
901         mono_native_tls_alloc (&debugger_tls_id, NULL);
902
903         thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
904         MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
905
906         tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
907         MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
908
909         tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
910         MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
911
912         pending_assembly_loads = g_ptr_array_new ();
913         domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
914
915         log_level = agent_config.log_level;
916
917         embedding = agent_config.embedding;
918         disconnected = TRUE;
919
920         if (agent_config.log_file) {
921                 log_file = fopen (agent_config.log_file, "w+");
922                 if (!log_file) {
923                         fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
924                         exit (1);
925                 }
926         } else {
927                 log_file = stdout;
928         }
929
930         ids_init ();
931         objrefs_init ();
932         breakpoints_init ();
933         suspend_init ();
934
935         mini_get_debug_options ()->gen_seq_points = TRUE;
936         /* 
937          * This is needed because currently we don't handle liveness info.
938          */
939         mini_get_debug_options ()->mdb_optimizations = TRUE;
940
941 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
942         /* This is needed because we can't set local variables in registers yet */
943         mono_disable_optimizations (MONO_OPT_LINEARS);
944 #endif
945
946         if (!agent_config.onuncaught && !agent_config.onthrow)
947                 finish_agent_init (TRUE);
948
949         /* FIXME: Is this still needed ? */
950 #if defined(__MACH__)
951         mono_thread_info_disable_new_interrupt (TRUE);
952 #endif
953 }
954
955 /*
956  * finish_agent_init:
957  *
958  *   Finish the initialization of the agent. This involves connecting the transport
959  * and starting the agent thread. This is either done at startup, or
960  * in response to some event like an unhandled exception.
961  */
962 static void
963 finish_agent_init (gboolean on_startup)
964 {
965         int res;
966
967         if (InterlockedCompareExchange (&inited, 1, 0) == 1)
968                 return;
969
970         if (agent_config.launch) {
971                 char *argv [16];
972
973                 // FIXME: Generated address
974                 // FIXME: Races with transport_connect ()
975
976                 argv [0] = agent_config.launch;
977                 argv [1] = agent_config.transport;
978                 argv [2] = agent_config.address;
979                 argv [3] = NULL;
980
981                 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
982                 if (!res) {
983                         fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
984                         exit (1);
985                 }
986         }
987
988         transport_connect (agent_config.address);
989
990         if (!on_startup) {
991                 /* Do some which is usually done after sending the VMStart () event */
992                 vm_start_event_sent = TRUE;
993                 start_debugger_thread ();
994         }
995 }
996
997 static void
998 mono_debugger_agent_cleanup (void)
999 {
1000         if (!inited)
1001                 return;
1002
1003         stop_debugger_thread ();
1004
1005         breakpoints_cleanup ();
1006         objrefs_cleanup ();
1007         ids_cleanup ();
1008         
1009         mono_mutex_destroy (&debugger_thread_exited_mutex);
1010         mono_cond_destroy (&debugger_thread_exited_cond);
1011 }
1012
1013 /*
1014  * SOCKET TRANSPORT
1015  */
1016
1017 #ifndef DISABLE_SOCKET_TRANSPORT
1018
1019 /*
1020  * recv_length:
1021  *
1022  * recv() + handle incomplete reads and EINTR
1023  */
1024 static int
1025 socket_transport_recv (void *buf, int len)
1026 {
1027         int res;
1028         int total = 0;
1029         int fd = conn_fd;
1030         int flags = 0;
1031
1032         do {
1033         again:
1034                 res = recv (fd, (char *) buf + total, len - total, flags);
1035                 if (res > 0)
1036                         total += res;
1037                 if (agent_config.keepalive && res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1038                         process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1039                         goto again;
1040                 }
1041         } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1042         return total;
1043 }
1044
1045 #ifndef TARGET_PS3
1046 #define HAVE_GETADDRINFO 1
1047 #endif
1048  
1049 static void
1050 set_keepalive (void)
1051 {
1052         struct timeval tv;
1053         int result;
1054
1055         if (!agent_config.keepalive)
1056                 return;
1057
1058         tv.tv_sec = agent_config.keepalive / 1000;
1059         tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1060
1061         result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1062         g_assert (result >= 0);
1063 }
1064
1065 static int
1066 socket_transport_accept (int socket_fd)
1067 {
1068         conn_fd = accept (socket_fd, NULL, NULL);
1069         if (conn_fd == -1) {
1070                 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1071         } else {
1072                 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1073         }
1074         
1075         return conn_fd;
1076 }
1077
1078 static gboolean
1079 socket_transport_send (void *data, int len)
1080 {
1081         int res;
1082
1083         do {
1084                 res = send (conn_fd, data, len, 0);
1085         } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1086         if (res != len)
1087                 return FALSE;
1088         else
1089                 return TRUE;
1090 }
1091
1092 /*
1093  * socket_transport_connect:
1094  *
1095  *   Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1096  */
1097 static void
1098 socket_transport_connect (const char *address)
1099 {
1100 #ifdef HAVE_GETADDRINFO
1101         struct addrinfo hints;
1102         struct addrinfo *result, *rp;
1103 #else
1104         struct hostent *result;
1105 #endif
1106         int sfd = -1, s, res;
1107         char port_string [128];
1108         char *host;
1109         int port;
1110
1111         if (agent_config.address) {
1112                 res = parse_address (agent_config.address, &host, &port);
1113                 g_assert (res == 0);
1114         } else {
1115                 host = NULL;
1116                 port = 0;
1117         }
1118
1119         conn_fd = -1;
1120         listen_fd = -1;
1121
1122         if (host) {
1123                 sprintf (port_string, "%d", port);
1124
1125                 mono_network_init ();
1126
1127                 /* Obtain address(es) matching host/port */
1128 #ifdef HAVE_GETADDRINFO
1129                 memset (&hints, 0, sizeof (struct addrinfo));
1130                 hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
1131                 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1132                 hints.ai_flags = 0;
1133                 hints.ai_protocol = 0;          /* Any protocol */
1134
1135                 s = getaddrinfo (host, port_string, &hints, &result);
1136                 if (s != 0) {
1137                         fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1138                         exit (1);
1139                 }
1140 #else
1141                 /* The PS3 doesn't even have _r or hstrerror () */
1142                 result = gethostbyname (host);
1143                 if (!result) {
1144                         fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1145                 }
1146 #endif
1147         }
1148
1149         if (agent_config.server) {
1150 #ifdef HAVE_GETADDRINFO
1151                 /* Wait for a connection */
1152                 if (!host) {
1153                         struct sockaddr_in addr;
1154                         socklen_t addrlen;
1155
1156                         /* No address, generate one */
1157                         sfd = socket (AF_INET, SOCK_STREAM, 0);
1158                         g_assert (sfd);
1159
1160                         /* This will bind the socket to a random port */
1161                         res = listen (sfd, 16);
1162                         if (res == -1) {
1163                                 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1164                                 exit (1);
1165                         }
1166                         listen_fd = sfd;
1167
1168                         addrlen = sizeof (addr);
1169                         memset (&addr, 0, sizeof (addr));
1170                         res = getsockname (sfd, &addr, &addrlen);
1171                         g_assert (res == 0);
1172
1173                         host = (char*)"127.0.0.1";
1174                         port = ntohs (addr.sin_port);
1175
1176                         /* Emit the address to stdout */
1177                         /* FIXME: Should print another interface, not localhost */
1178                         printf ("%s:%d\n", host, port);
1179                 } else {
1180                         /* Listen on the provided address */
1181                         for (rp = result; rp != NULL; rp = rp->ai_next) {
1182                                 int n = 1;
1183
1184                                 sfd = socket (rp->ai_family, rp->ai_socktype,
1185                                                           rp->ai_protocol);
1186                                 if (sfd == -1)
1187                                         continue;
1188
1189                                 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1190                                         continue;
1191
1192                                 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1193                                 if (res == -1)
1194                                         continue;
1195
1196                                 res = listen (sfd, 16);
1197                                 if (res == -1)
1198                                         continue;
1199                                 listen_fd = sfd;
1200                                 break;
1201                         }
1202
1203 #ifndef HOST_WIN32
1204                         /*
1205                          * this function is not present on win2000 which we still support, and the
1206                          * workaround described here:
1207                          * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1208                          * only works with MSVC.
1209                          */
1210 #ifdef HAVE_GETADDRINFO
1211                         freeaddrinfo (result);
1212 #endif
1213 #endif
1214                 }
1215
1216                 if (agent_config.defer)
1217                         return;
1218
1219                 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1220
1221                 if (agent_config.timeout) {
1222                         fd_set readfds;
1223                         struct timeval tv;
1224
1225                         tv.tv_sec = 0;
1226                         tv.tv_usec = agent_config.timeout * 1000;
1227                         FD_ZERO (&readfds);
1228                         FD_SET (sfd, &readfds);
1229                         res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1230                         if (res == 0) {
1231                                 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1232                                 exit (1);
1233                         }
1234                 }
1235
1236                 conn_fd = socket_transport_accept (sfd);
1237                 if (conn_fd == -1)
1238                         exit (1);
1239
1240                 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1241 #else
1242                 NOT_IMPLEMENTED;
1243 #endif /* HAVE_GETADDRINFO */
1244         } else {
1245                 /* Connect to the specified address */
1246 #ifdef HAVE_GETADDRINFO
1247                 /* FIXME: Respect the timeout */
1248                 for (rp = result; rp != NULL; rp = rp->ai_next) {
1249                         sfd = socket (rp->ai_family, rp->ai_socktype,
1250                                                   rp->ai_protocol);
1251                         if (sfd == -1)
1252                                 continue;
1253
1254                         if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1255                                 break;       /* Success */
1256                         
1257                         close (sfd);
1258                 }
1259
1260                 if (rp == 0) {
1261                         fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1262                         exit (1);
1263                 }
1264 #else
1265                         sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1266                         if (sfd == -1)
1267                                 g_assert_not_reached ();
1268                         res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1269                         if (res == -1)
1270                                 g_assert_not_reached ();
1271 #endif
1272
1273                 conn_fd = sfd;
1274
1275 #ifndef HOST_WIN32
1276                 /* See the comment above */
1277 #ifdef HAVE_GETADDRINFO
1278                 freeaddrinfo (result);
1279 #endif
1280 #endif
1281         }
1282         
1283         disconnected = !transport_handshake ();
1284         if (disconnected)
1285                 exit (1);
1286 }
1287
1288 static void
1289 socket_transport_close1 (void)
1290 {
1291         /* This will interrupt the agent thread */
1292         /* Close the read part only so it can still send back replies */
1293         /* Also shut down the connection listener so that we can exit normally */
1294 #ifdef HOST_WIN32
1295         /* SD_RECEIVE doesn't break the recv in the debugger thread */
1296         shutdown (conn_fd, SD_BOTH);
1297         shutdown (listen_fd, SD_BOTH);
1298         closesocket (listen_fd);
1299 #else
1300         shutdown (conn_fd, SHUT_RD);
1301         shutdown (listen_fd, SHUT_RDWR);
1302         close (listen_fd);
1303 #endif
1304 }
1305
1306 static void
1307 socket_transport_close2 (void)
1308 {
1309 #ifdef HOST_WIN32
1310         shutdown (conn_fd, SD_BOTH);
1311 #else
1312         shutdown (conn_fd, SHUT_RDWR);
1313 #endif
1314 }
1315
1316 static void
1317 register_socket_transport (void)
1318 {
1319         DebuggerTransport trans;
1320
1321         trans.name = "dt_socket";
1322         trans.connect = socket_transport_connect;
1323         trans.close1 = socket_transport_close1;
1324         trans.close2 = socket_transport_close2;
1325         trans.send = socket_transport_send;
1326         trans.recv = socket_transport_recv;
1327
1328         register_transport (&trans);
1329 }
1330
1331 #endif /* DISABLE_SOCKET_TRANSPORT */
1332
1333 /*
1334  * TRANSPORT CODE
1335  */
1336
1337 #define MAX_TRANSPORTS 16
1338
1339 static DebuggerTransport *transport;
1340
1341 static DebuggerTransport transports [MAX_TRANSPORTS];
1342 static int ntransports;
1343
1344 static void
1345 register_transport (DebuggerTransport *trans)
1346 {
1347         g_assert (ntransports < MAX_TRANSPORTS);
1348
1349         memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1350         ntransports ++;
1351 }
1352
1353 static void
1354 transport_init (void)
1355 {
1356         int i;
1357
1358 #ifndef DISABLE_SOCKET_TRANSPORT
1359         register_socket_transport ();
1360 #endif
1361
1362         for (i = 0; i < ntransports; ++i) {
1363                 if (!strcmp (agent_config.transport, transports [i].name))
1364                         break;
1365         }
1366         if (i == ntransports) {
1367                 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1368                 for (i = 0; i < ntransports; ++i)
1369                         fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1370                 fprintf (stderr, "\n");
1371                 exit (1);
1372         }
1373         transport = &transports [i];
1374 }
1375
1376 void
1377 transport_connect (const char *address)
1378 {
1379         transport->connect (address);
1380 }
1381
1382 static void
1383 transport_close1 (void)
1384 {
1385         transport->close1 ();
1386 }
1387
1388 static void
1389 transport_close2 (void)
1390 {
1391         transport->close2 ();
1392 }
1393
1394 static int
1395 transport_send (void *buf, int len)
1396 {
1397         return transport->send (buf, len);
1398 }
1399
1400 static int
1401 transport_recv (void *buf, int len)
1402 {
1403         return transport->recv (buf, len);
1404 }
1405
1406 static gboolean
1407 transport_handshake (void)
1408 {
1409         char handshake_msg [128];
1410         guint8 buf [128];
1411         int res;
1412         
1413         /* Write handshake message */
1414         sprintf (handshake_msg, "DWP-Handshake");
1415         do {
1416                 res = transport_send (handshake_msg, strlen (handshake_msg));
1417         } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1418         g_assert (res != -1);
1419
1420         /* Read answer */
1421         res = transport_recv (buf, strlen (handshake_msg));
1422         if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1423                 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1424                 return FALSE;
1425         }
1426
1427         /*
1428          * To support older clients, the client sends its protocol version after connecting
1429          * using a command. Until that is received, default to our protocol version.
1430          */
1431         major_version = MAJOR_VERSION;
1432         minor_version = MINOR_VERSION;
1433         protocol_version_set = FALSE;
1434
1435 #ifndef DISABLE_SOCKET_TRANSPORT
1436         // FIXME: Move this somewhere else
1437         /* 
1438          * Set TCP_NODELAY on the socket so the client receives events/command
1439          * results immediately.
1440          */
1441         {
1442                 int flag = 1;
1443                 int result = setsockopt (conn_fd,
1444                                  IPPROTO_TCP,
1445                                  TCP_NODELAY,
1446                                  (char *) &flag,
1447                                  sizeof(int));
1448                 g_assert (result >= 0);
1449         }
1450
1451         set_keepalive ();
1452 #endif
1453         
1454         return TRUE;
1455 }
1456
1457 static void
1458 stop_debugger_thread (void)
1459 {
1460         if (!inited)
1461                 return;
1462
1463         transport_close1 ();
1464
1465         /* 
1466          * Wait for the thread to exit.
1467          *
1468          * If we continue with the shutdown without waiting for it, then the client might
1469          * not receive an answer to its last command like a resume.
1470          * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1471          * use pthreads.
1472          */
1473         //WaitForSingleObject (debugger_thread_handle, INFINITE);
1474         if (GetCurrentThreadId () != debugger_thread_id) {
1475                 do {
1476                         mono_mutex_lock (&debugger_thread_exited_mutex);
1477                         if (!debugger_thread_exited) {
1478 #ifdef HOST_WIN32
1479                                 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1480                                         mono_mutex_unlock (&debugger_thread_exited_mutex);
1481                                         Sleep(1);
1482                                         mono_mutex_lock (&debugger_thread_exited_mutex);
1483                                 }
1484 #else
1485                                 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1486 #endif
1487                         }
1488                         mono_mutex_unlock (&debugger_thread_exited_mutex);
1489                 } while (!debugger_thread_exited);
1490         }
1491
1492         transport_close2 ();
1493 }
1494
1495 static void
1496 start_debugger_thread (void)
1497 {
1498         gsize tid;
1499
1500         debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1501         g_assert (debugger_thread_handle);
1502 }
1503
1504 /*
1505  * Functions to decode protocol data
1506  */
1507
1508 static inline int
1509 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1510 {
1511         *endbuf = buf + 1;
1512         g_assert (*endbuf <= limit);
1513         return buf [0];
1514 }
1515
1516 static inline int
1517 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1518 {
1519         *endbuf = buf + 4;
1520         g_assert (*endbuf <= limit);
1521
1522         return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1523 }
1524
1525 static inline gint64
1526 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1527 {
1528         guint32 high = decode_int (buf, &buf, limit);
1529         guint32 low = decode_int (buf, &buf, limit);
1530
1531         *endbuf = buf;
1532
1533         return ((((guint64)high) << 32) | ((guint64)low));
1534 }
1535
1536 static inline int
1537 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1538 {
1539         return decode_int (buf, endbuf, limit);
1540 }
1541
1542 static inline char*
1543 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1544 {
1545         int len = decode_int (buf, &buf, limit);
1546         char *s;
1547
1548         if (len < 0) {
1549                 *endbuf = buf;
1550                 return NULL;
1551         }
1552
1553         s = g_malloc (len + 1);
1554         g_assert (s);
1555
1556         memcpy (s, buf, len);
1557         s [len] = '\0';
1558         buf += len;
1559         *endbuf = buf;
1560
1561         return s;
1562 }
1563
1564 /*
1565  * Functions to encode protocol data
1566  */
1567
1568 typedef struct {
1569         guint8 *buf, *p, *end;
1570 } Buffer;
1571
1572 static inline void
1573 buffer_init (Buffer *buf, int size)
1574 {
1575         buf->buf = g_malloc (size);
1576         buf->p = buf->buf;
1577         buf->end = buf->buf + size;
1578 }
1579
1580 static inline void
1581 buffer_make_room (Buffer *buf, int size)
1582 {
1583         if (buf->end - buf->p < size) {
1584                 int new_size = buf->end - buf->buf + size + 32;
1585                 guint8 *p = g_realloc (buf->buf, new_size);
1586                 size = buf->p - buf->buf;
1587                 buf->buf = p;
1588                 buf->p = p + size;
1589                 buf->end = buf->buf + new_size;
1590         }
1591 }
1592
1593 static inline void
1594 buffer_add_byte (Buffer *buf, guint8 val)
1595 {
1596         buffer_make_room (buf, 1);
1597         buf->p [0] = val;
1598         buf->p++;
1599 }
1600
1601 static inline void
1602 buffer_add_short (Buffer *buf, guint32 val)
1603 {
1604         buffer_make_room (buf, 2);
1605         buf->p [0] = (val >> 8) & 0xff;
1606         buf->p [1] = (val >> 0) & 0xff;
1607         buf->p += 2;
1608 }
1609
1610 static inline void
1611 buffer_add_int (Buffer *buf, guint32 val)
1612 {
1613         buffer_make_room (buf, 4);
1614         buf->p [0] = (val >> 24) & 0xff;
1615         buf->p [1] = (val >> 16) & 0xff;
1616         buf->p [2] = (val >> 8) & 0xff;
1617         buf->p [3] = (val >> 0) & 0xff;
1618         buf->p += 4;
1619 }
1620
1621 static inline void
1622 buffer_add_long (Buffer *buf, guint64 l)
1623 {
1624         buffer_add_int (buf, (l >> 32) & 0xffffffff);
1625         buffer_add_int (buf, (l >> 0) & 0xffffffff);
1626 }
1627
1628 static inline void
1629 buffer_add_id (Buffer *buf, int id)
1630 {
1631         buffer_add_int (buf, (guint64)id);
1632 }
1633
1634 static inline void
1635 buffer_add_data (Buffer *buf, guint8 *data, int len)
1636 {
1637         buffer_make_room (buf, len);
1638         memcpy (buf->p, data, len);
1639         buf->p += len;
1640 }
1641
1642 static inline void
1643 buffer_add_string (Buffer *buf, const char *str)
1644 {
1645         int len;
1646
1647         if (str == NULL) {
1648                 buffer_add_int (buf, 0);
1649         } else {
1650                 len = strlen (str);
1651                 buffer_add_int (buf, len);
1652                 buffer_add_data (buf, (guint8*)str, len);
1653         }
1654 }
1655
1656 static inline void
1657 buffer_free (Buffer *buf)
1658 {
1659         g_free (buf->buf);
1660 }
1661
1662 static gboolean
1663 send_packet (int command_set, int command, Buffer *data)
1664 {
1665         Buffer buf;
1666         int len, id;
1667         gboolean res;
1668
1669         id = InterlockedIncrement (&packet_id);
1670
1671         len = data->p - data->buf + 11;
1672         buffer_init (&buf, len);
1673         buffer_add_int (&buf, len);
1674         buffer_add_int (&buf, id);
1675         buffer_add_byte (&buf, 0); /* flags */
1676         buffer_add_byte (&buf, command_set);
1677         buffer_add_byte (&buf, command);
1678         memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1679
1680         res = transport_send (buf.buf, len);
1681
1682         buffer_free (&buf);
1683
1684         return res;
1685 }
1686
1687 static gboolean
1688 send_reply_packet (int id, int error, Buffer *data)
1689 {
1690         Buffer buf;
1691         int len;
1692         gboolean res;
1693         
1694         len = data->p - data->buf + 11;
1695         buffer_init (&buf, len);
1696         buffer_add_int (&buf, len);
1697         buffer_add_int (&buf, id);
1698         buffer_add_byte (&buf, 0x80); /* flags */
1699         buffer_add_byte (&buf, (error >> 8) & 0xff);
1700         buffer_add_byte (&buf, error);
1701         memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1702
1703         res = transport_send (buf.buf, len);
1704
1705         buffer_free (&buf);
1706
1707         return res;
1708 }
1709
1710 /*
1711  * OBJECT IDS
1712  */
1713
1714 /*
1715  * Represents an object accessible by the debugger client.
1716  */
1717 typedef struct {
1718         /* Unique id used in the wire protocol to refer to objects */
1719         int id;
1720         /*
1721          * A weakref gc handle pointing to the object. The gc handle is used to 
1722          * detect if the object was garbage collected.
1723          */
1724         guint32 handle;
1725 } ObjRef;
1726
1727 /* Maps objid -> ObjRef */
1728 static GHashTable *objrefs;
1729
1730 static void
1731 free_objref (gpointer value)
1732 {
1733         ObjRef *o = value;
1734
1735         mono_gchandle_free (o->handle);
1736
1737         g_free (o);
1738 }
1739
1740 static void
1741 objrefs_init (void)
1742 {
1743         objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1744 }
1745
1746 static void
1747 objrefs_cleanup (void)
1748 {
1749         g_hash_table_destroy (objrefs);
1750         objrefs = NULL;
1751 }
1752
1753 static GHashTable *obj_to_objref;
1754
1755 /*
1756  * Return an ObjRef for OBJ.
1757  */
1758 static ObjRef*
1759 get_objref (MonoObject *obj)
1760 {
1761         ObjRef *ref;
1762         GSList *reflist = NULL, *l;
1763         int hash = 0;
1764
1765         if (obj == NULL)
1766                 return 0;
1767
1768         mono_loader_lock ();
1769
1770         if (!obj_to_objref)
1771                 obj_to_objref = g_hash_table_new (NULL, NULL);
1772         
1773         /* FIXME: The tables can grow indefinitely */
1774
1775         if (mono_gc_is_moving ()) {
1776                 /*
1777                  * Objects can move, so use a hash table mapping hash codes to lists of
1778                  * ObjRef structures.
1779                  */
1780                 hash = mono_object_hash (obj);
1781
1782                 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1783                 for (l = reflist; l; l = l->next) {
1784                         ref = l->data;
1785                         if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1786                                 mono_loader_unlock ();
1787                                 return ref;
1788                         }
1789                 }
1790         } else {
1791                 /* Use a hash table with masked pointers to internalize object references */
1792                 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1793                 /* ref might refer to a different object with the same addr which was GCd */
1794                 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1795                         mono_loader_unlock ();
1796                         return ref;
1797                 }
1798         }
1799
1800         ref = g_new0 (ObjRef, 1);
1801         ref->id = InterlockedIncrement (&objref_id);
1802         ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1803
1804         g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1805
1806         if (mono_gc_is_moving ()) {
1807                 reflist = g_slist_append (reflist, ref);
1808                 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1809         } else {
1810                 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1811         }
1812
1813         mono_loader_unlock ();
1814
1815         return ref;
1816 }
1817
1818 static inline int
1819 get_objid (MonoObject *obj)
1820 {
1821         return get_objref (obj)->id;
1822 }
1823
1824 /*
1825  * Set OBJ to the object identified by OBJID.
1826  * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1827  * collected.
1828  */
1829 static ErrorCode
1830 get_object_allow_null (int objid, MonoObject **obj)
1831 {
1832         ObjRef *ref;
1833
1834         if (objid == 0) {
1835                 *obj = NULL;
1836                 return 0;
1837         }
1838
1839         if (!objrefs)
1840                 return ERR_INVALID_OBJECT;
1841
1842         mono_loader_lock ();
1843
1844         ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1845
1846         if (ref) {
1847                 *obj = mono_gchandle_get_target (ref->handle);
1848                 mono_loader_unlock ();
1849                 if (!(*obj))
1850                         return ERR_INVALID_OBJECT;
1851                 return 0;
1852         } else {
1853                 mono_loader_unlock ();
1854                 return ERR_INVALID_OBJECT;
1855         }
1856 }
1857
1858 static ErrorCode
1859 get_object (int objid, MonoObject **obj)
1860 {
1861         int err = get_object_allow_null (objid, obj);
1862
1863         if (err)
1864                 return err;
1865         if (!(*obj))
1866                 return ERR_INVALID_OBJECT;
1867         return 0;
1868 }
1869
1870 static inline int
1871 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1872 {
1873         return decode_id (buf, endbuf, limit);
1874 }
1875
1876 static inline void
1877 buffer_add_objid (Buffer *buf, MonoObject *o)
1878 {
1879         buffer_add_id (buf, get_objid (o));
1880 }
1881
1882 /*
1883  * IDS
1884  */
1885
1886 typedef enum {
1887         ID_ASSEMBLY = 0,
1888         ID_MODULE = 1,
1889         ID_TYPE = 2,
1890         ID_METHOD = 3,
1891         ID_FIELD = 4,
1892         ID_DOMAIN = 5,
1893         ID_PROPERTY = 6,
1894         ID_NUM
1895 } IdType;
1896
1897 /*
1898  * Represents a runtime structure accessible to the debugger client
1899  */
1900 typedef struct {
1901         /* Unique id used in the wire protocol */
1902         int id;
1903         /* Domain of the runtime structure, NULL if the domain was unloaded */
1904         MonoDomain *domain;
1905         union {
1906                 gpointer val;
1907                 MonoClass *klass;
1908                 MonoMethod *method;
1909                 MonoImage *image;
1910                 MonoAssembly *assembly;
1911                 MonoClassField *field;
1912                 MonoDomain *domain;
1913                 MonoProperty *property;
1914         } data;
1915 } Id;
1916
1917 typedef struct {
1918         /* Maps runtime structure -> Id */
1919         GHashTable *val_to_id [ID_NUM];
1920         /* Classes whose class load event has been sent */
1921         GHashTable *loaded_classes;
1922         /* Maps MonoClass->GPtrArray of file names */
1923         GHashTable *source_files;
1924         /* Maps source file basename -> GSList of classes */
1925         GHashTable *source_file_to_class;
1926         /* Same with ignore-case */
1927         GHashTable *source_file_to_class_ignorecase;
1928 } AgentDomainInfo;
1929
1930 /* Maps id -> Id */
1931 static GPtrArray *ids [ID_NUM];
1932
1933 static void
1934 ids_init (void)
1935 {
1936         int i;
1937
1938         for (i = 0; i < ID_NUM; ++i)
1939                 ids [i] = g_ptr_array_new ();
1940 }
1941
1942 static void
1943 ids_cleanup (void)
1944 {
1945         int i, j;
1946
1947         for (i = 0; i < ID_NUM; ++i) {
1948                 if (ids [i]) {
1949                         for (j = 0; j < ids [i]->len; ++j)
1950                                 g_free (g_ptr_array_index (ids [i], j));
1951                         g_ptr_array_free (ids [i], TRUE);
1952                 }
1953                 ids [i] = NULL;
1954         }
1955 }
1956
1957 void
1958 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1959 {
1960         AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1961         int i, j;
1962         GHashTableIter iter;
1963         GPtrArray *file_names;
1964         char *basename;
1965         GSList *l;
1966
1967         if (info) {
1968                 for (i = 0; i < ID_NUM; ++i)
1969                         if (info->val_to_id [i])
1970                                 g_hash_table_destroy (info->val_to_id [i]);
1971                 g_hash_table_destroy (info->loaded_classes);
1972
1973                 g_hash_table_iter_init (&iter, info->source_files);
1974                 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
1975                         for (i = 0; i < file_names->len; ++i)
1976                                 g_free (g_ptr_array_index (file_names, i));
1977                         g_ptr_array_free (file_names, TRUE);
1978                 }
1979
1980                 g_hash_table_iter_init (&iter, info->source_file_to_class);
1981                 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
1982                         g_free (basename);
1983                         g_slist_free (l);
1984                 }
1985
1986                 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
1987                 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
1988                         g_free (basename);
1989                         g_slist_free (l);
1990                 }
1991
1992                 g_free (info);
1993         }
1994
1995         domain_jit_info (domain)->agent_info = NULL;
1996
1997         /* Clear ids referencing structures in the domain */
1998         for (i = 0; i < ID_NUM; ++i) {
1999                 if (ids [i]) {
2000                         for (j = 0; j < ids [i]->len; ++j) {
2001                                 Id *id = g_ptr_array_index (ids [i], j);
2002                                 if (id->domain == domain)
2003                                         id->domain = NULL;
2004                         }
2005                 }
2006         }
2007
2008         mono_loader_lock ();
2009         g_hash_table_remove (domains, domain);
2010         mono_loader_unlock ();
2011 }
2012
2013 static AgentDomainInfo*
2014 get_agent_domain_info (MonoDomain *domain)
2015 {
2016         AgentDomainInfo *info = NULL;
2017
2018         mono_domain_lock (domain);
2019
2020         info = domain_jit_info (domain)->agent_info;
2021         if (!info) {
2022                 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2023                 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2024                 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2025                 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2026                 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2027         }
2028
2029         mono_domain_unlock (domain);
2030
2031         return info;
2032 }
2033
2034 static int
2035 get_id (MonoDomain *domain, IdType type, gpointer val)
2036 {
2037         Id *id;
2038         AgentDomainInfo *info;
2039
2040         if (val == NULL)
2041                 return 0;
2042
2043         mono_loader_lock ();
2044
2045         mono_domain_lock (domain);
2046
2047         info = get_agent_domain_info (domain);
2048
2049         if (info->val_to_id [type] == NULL)
2050                 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2051
2052         id = g_hash_table_lookup (info->val_to_id [type], val);
2053         if (id) {
2054                 mono_domain_unlock (domain);
2055                 mono_loader_unlock ();
2056                 return id->id;
2057         }
2058
2059         id = g_new0 (Id, 1);
2060         /* Reserve id 0 */
2061         id->id = ids [type]->len + 1;
2062         id->domain = domain;
2063         id->data.val = val;
2064
2065         g_hash_table_insert (info->val_to_id [type], val, id);
2066
2067         mono_domain_unlock (domain);
2068
2069         g_ptr_array_add (ids [type], id);
2070
2071         mono_loader_unlock ();
2072
2073         return id->id;
2074 }
2075
2076 static inline gpointer
2077 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2078 {
2079         Id *res;
2080
2081         int id = decode_id (buf, endbuf, limit);
2082
2083         *err = 0;
2084         if (domain)
2085                 *domain = NULL;
2086
2087         if (id == 0)
2088                 return NULL;
2089
2090         // FIXME: error handling
2091         mono_loader_lock ();
2092         g_assert (id > 0 && id <= ids [type]->len);
2093
2094         res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2095         mono_loader_unlock ();
2096
2097         if (res->domain == NULL) {
2098                 *err = ERR_UNLOADED;
2099                 return NULL;
2100         }
2101
2102         if (domain)
2103                 *domain = res->domain;
2104
2105         return res->data.val;
2106 }
2107
2108 static inline void
2109 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2110 {
2111         buffer_add_id (buf, get_id (domain, type, val));
2112 }
2113
2114 static inline MonoClass*
2115 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2116 {
2117         return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2118 }
2119
2120 static inline MonoAssembly*
2121 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2122 {
2123         return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2124 }
2125
2126 static inline MonoImage*
2127 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2128 {
2129         return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2130 }
2131
2132 static inline MonoMethod*
2133 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2134 {
2135         return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2136 }
2137
2138 static inline MonoClassField*
2139 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2140 {
2141         return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2142 }
2143
2144 static inline MonoDomain*
2145 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2146 {
2147         return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2148 }
2149
2150 static inline MonoProperty*
2151 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2152 {
2153         return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2154 }
2155
2156 static inline void
2157 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2158 {
2159         buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2160 }
2161
2162 static inline void
2163 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2164 {
2165         buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2166 }
2167
2168 static inline void
2169 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2170 {
2171         buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2172 }
2173
2174 static inline void
2175 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2176 {
2177         buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2178 }
2179
2180 static inline void
2181 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2182 {
2183         buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2184 }
2185
2186 static inline void
2187 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2188 {
2189         buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2190 }
2191
2192 static inline void
2193 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2194 {
2195         buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2196 }
2197
2198 static void invoke_method (void);
2199
2200 /*
2201  * SUSPEND/RESUME
2202  */
2203
2204 /*
2205  * save_thread_context:
2206  *
2207  *   Set CTX as the current threads context which is used for computing stack traces.
2208  * This function is signal-safe.
2209  */
2210 static void
2211 save_thread_context (MonoContext *ctx)
2212 {
2213         DebuggerTlsData *tls;
2214
2215         tls = mono_native_tls_get_value (debugger_tls_id);
2216         g_assert (tls);
2217
2218         if (ctx)
2219                 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2220         else
2221                 mono_thread_state_init_from_current (&tls->context);
2222 }
2223
2224 /* The number of times the runtime is suspended */
2225 static gint32 suspend_count;
2226
2227 /* Number of threads suspended */
2228 /* 
2229  * If this is equal to the size of thread_to_tls, the runtime is considered
2230  * suspended.
2231  */
2232 static gint32 threads_suspend_count;
2233
2234 static mono_mutex_t suspend_mutex;
2235
2236 /* Cond variable used to wait for suspend_count becoming 0 */
2237 static mono_cond_t suspend_cond;
2238
2239 /* Semaphore used to wait for a thread becoming suspended */
2240 static MonoSemType suspend_sem;
2241
2242 static void
2243 suspend_init (void)
2244 {
2245         mono_mutex_init (&suspend_mutex, NULL);
2246         mono_cond_init (&suspend_cond, NULL);   
2247         MONO_SEM_INIT (&suspend_sem, 0);
2248 }
2249
2250 typedef struct
2251 {
2252         StackFrameInfo last_frame;
2253         gboolean last_frame_set;
2254         MonoContext ctx;
2255         gpointer lmf;
2256 } GetLastFrameUserData;
2257
2258 static gboolean
2259 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2260 {
2261         GetLastFrameUserData *data = user_data;
2262
2263         if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2264                 return FALSE;
2265
2266         if (!data->last_frame_set) {
2267                 /* Store the last frame */
2268                 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2269                 data->last_frame_set = TRUE;
2270                 return FALSE;
2271         } else {
2272                 /* Store the context/lmf for the frame above the last frame */
2273                 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2274                 data->lmf = info->lmf;
2275
2276                 return TRUE;
2277         }
2278 }
2279
2280 /*
2281  * thread_interrupt:
2282  *
2283  *   Process interruption of a thread. If SIGCTX is set, process the current thread. If
2284  * INFO is set, process the thread described by INFO.
2285  * This should be signal safe.
2286  */
2287 static gboolean
2288 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2289 {
2290         gboolean res;
2291         gpointer ip;
2292         MonoNativeThreadId tid;
2293
2294         /*
2295          * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2296          * guarantee the signal handler will be called that many times.  Instead of tracking
2297          * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2298          * has been requested that hasn't been handled yet, otherwise we can have threads
2299          * refuse to die when VM_EXIT is called
2300          */
2301 #if defined(__APPLE__)
2302         if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2303                 return FALSE;
2304 #else
2305         /*
2306          * We use interrupt_count to determine whenever this interrupt should be processed
2307          * by us or the normal interrupt processing code in the signal handler.
2308          * There is no race here with notify_thread (), since the signal is sent after
2309          * incrementing interrupt_count.
2310          */
2311         if (tls->interrupt_count == 0)
2312                 return FALSE;
2313
2314         InterlockedDecrement (&tls->interrupt_count);
2315 #endif
2316
2317         if (sigctx)
2318                 ip = mono_arch_ip_from_context (sigctx);
2319         else if (info)
2320                 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2321         else
2322                 ip = NULL;
2323
2324         if (info)
2325                 tid = mono_thread_info_get_tid (info);
2326         else
2327                 tid = GetCurrentThreadId ();
2328
2329         // FIXME: Races when the thread leaves managed code before hitting a single step
2330         // event.
2331
2332         if (ji) {
2333                 /* Running managed code, will be suspended by the single step code */
2334                 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2335                 return TRUE;
2336         } else {
2337                 /* 
2338                  * Running native code, will be suspended when it returns to/enters 
2339                  * managed code. Treat it as already suspended.
2340                  * This might interrupt the code in process_single_step_inner (), we use the
2341                  * tls->suspending flag to avoid races when that happens.
2342                  */
2343                 if (!tls->suspended && !tls->suspending) {
2344                         MonoContext ctx;
2345                         GetLastFrameUserData data;
2346
2347                         // FIXME: printf is not signal safe, but this is only used during
2348                         // debugger debugging
2349                         if (ip)
2350                                 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2351                         //save_thread_context (&ctx);
2352
2353                         if (!tls->thread)
2354                                 /* Already terminated */
2355                                 return TRUE;
2356
2357                         tls->context.valid = FALSE;
2358
2359                         /*
2360                          * We are in a difficult position: we want to be able to provide stack
2361                          * traces for this thread, but we can't use the current ctx+lmf, since
2362                          * the thread is still running, so it might return to managed code,
2363                          * making these invalid.
2364                          * So we start a stack walk and save the first frame, along with the
2365                          * parent frame's ctx+lmf. This (hopefully) works because the thread will be 
2366                          * suspended when it returns to managed code, so the parent's ctx should
2367                          * remain valid.
2368                          */
2369                         data.last_frame_set = FALSE;
2370                         if (sigctx) {
2371                                 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2372                                 /* 
2373                                  * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2374                                  * get_last_frame () doesn't need it, the last frame cannot be a ginst
2375                                  * since we are not in a JITted method.
2376                                  */
2377                                 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2378                         } else if (info) {
2379                                 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2380                         }
2381                         if (data.last_frame_set) {
2382                                 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2383                                 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2384                                 g_assert (res);
2385                                 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2386                                 g_assert (res);
2387
2388                                 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2389                                 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2390                                 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2391                         } else {
2392                                 /* No managed frames */
2393                                 tls->async_state.valid = FALSE;
2394                         }
2395                         mono_memory_barrier ();
2396
2397                         tls->suspended = TRUE;
2398                         MONO_SEM_POST (&suspend_sem);
2399                 }
2400                 return TRUE;
2401         }
2402 }
2403
2404 /*
2405  * mono_debugger_agent_thread_interrupt:
2406  *
2407  *   Called by the abort signal handler.
2408  * Should be signal safe.
2409  */
2410 gboolean
2411 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2412 {
2413         DebuggerTlsData *tls;
2414
2415         if (!inited)
2416                 return FALSE;
2417
2418         tls = mono_native_tls_get_value (debugger_tls_id);
2419         if (!tls)
2420                 return FALSE;
2421
2422         return thread_interrupt (tls, NULL, sigctx, ji);
2423 }
2424
2425 #ifdef HOST_WIN32
2426 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2427 {
2428         //DebugBreak ();
2429         mono_debugger_agent_thread_interrupt (NULL, NULL);
2430 }
2431 #endif /* HOST_WIN32 */
2432
2433 /*
2434  * reset_native_thread_suspend_state:
2435  * 
2436  *   Reset the suspended flag on native threads
2437  */
2438 static void
2439 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2440 {
2441         DebuggerTlsData *tls = value;
2442
2443         if (!tls->really_suspended && tls->suspended)
2444                 tls->suspended = FALSE;
2445 }
2446
2447 /*
2448  * notify_thread:
2449  *
2450  *   Notify a thread that it needs to suspend.
2451  */
2452 static void
2453 notify_thread (gpointer key, gpointer value, gpointer user_data)
2454 {
2455         MonoInternalThread *thread = key;
2456         DebuggerTlsData *tls = value;
2457         gsize tid = thread->tid;
2458         int res;
2459
2460         if (GetCurrentThreadId () == tid || tls->terminated)
2461                 return;
2462
2463         DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2464
2465         /*
2466          * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2467          * guarantee the signal handler will be called that many times.  Instead of tracking
2468          * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2469          * has been requested that hasn't been handled yet, otherwise we can have threads
2470          * refuse to die when VM_EXIT is called
2471          */
2472 #if defined(__APPLE__)
2473         if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2474                 return;
2475 #else
2476         /*
2477          * Maybe we could use the normal interrupt infrastructure, but that does a lot
2478          * of things like breaking waits etc. which we don't want.
2479          */
2480         InterlockedIncrement (&tls->interrupt_count);
2481 #endif
2482
2483         /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2484 #ifdef HOST_WIN32
2485         QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2486 #else
2487         if (mono_thread_info_new_interrupt_enabled ()) {
2488                 MonoThreadInfo *info;
2489                 MonoJitInfo *ji;
2490
2491                 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2492                 g_assert (info);
2493
2494                 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2495
2496                 thread_interrupt (tls, info, NULL, ji);
2497
2498                 mono_thread_info_resume (mono_thread_info_get_tid (info));
2499         } else {
2500                 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2501                 if (res)
2502                         /* 
2503                          * Attached thread which died without detaching.
2504                          */
2505                         tls->terminated = TRUE;
2506         }
2507 #endif
2508 }
2509
2510 static void
2511 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2512 {
2513         guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2514         MonoJitInfo *ji;
2515
2516         if (mono_loader_lock_is_owned_by_self ()) {
2517                 /*
2518                  * Shortcut for the check in suspend_current (). This speeds up processing
2519                  * when executing long running code inside the loader lock, i.e. assembly load
2520                  * hooks.
2521                  */
2522                 return;
2523         }
2524
2525         if (debugger_thread_id == GetCurrentThreadId ())
2526                 return;
2527
2528         /* Prevent races with mono_debugger_agent_thread_interrupt () */
2529         if (suspend_count - tls->resume_count > 0)
2530                 tls->suspending = TRUE;
2531
2532         DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2533
2534         if (suspend_count - tls->resume_count == 0) {
2535                 /* 
2536                  * We are executing a single threaded invoke but the single step for 
2537                  * suspending is still active.
2538                  * FIXME: This slows down single threaded invokes.
2539                  */
2540                 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2541                 return;
2542         }
2543
2544         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2545
2546         /* Can't suspend in these methods */
2547         if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2548                 return;
2549
2550         save_thread_context (ctx);
2551
2552         suspend_current ();
2553 }
2554
2555 /*
2556  * suspend_vm:
2557  *
2558  * Increase the suspend count of the VM. While the suspend count is greater 
2559  * than 0, runtime threads are suspended at certain points during execution.
2560  */
2561 static void
2562 suspend_vm (void)
2563 {
2564         mono_loader_lock ();
2565
2566         mono_mutex_lock (&suspend_mutex);
2567
2568         suspend_count ++;
2569
2570         DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2571
2572         if (suspend_count == 1) {
2573                 // FIXME: Is it safe to call this inside the lock ?
2574                 start_single_stepping ();
2575                 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2576         }
2577
2578         mono_mutex_unlock (&suspend_mutex);
2579
2580         mono_loader_unlock ();
2581 }
2582
2583 /*
2584  * resume_vm:
2585  *
2586  * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2587  * are resumed.
2588  */
2589 static void
2590 resume_vm (void)
2591 {
2592         int err;
2593
2594         g_assert (debugger_thread_id == GetCurrentThreadId ());
2595
2596         mono_loader_lock ();
2597
2598         mono_mutex_lock (&suspend_mutex);
2599
2600         g_assert (suspend_count > 0);
2601         suspend_count --;
2602
2603         DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2604
2605         if (suspend_count == 0) {
2606                 // FIXME: Is it safe to call this inside the lock ?
2607                 stop_single_stepping ();
2608                 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2609         }
2610
2611         /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2612         err = mono_cond_broadcast (&suspend_cond);
2613         g_assert (err == 0);
2614
2615         mono_mutex_unlock (&suspend_mutex);
2616         //g_assert (err == 0);
2617
2618         mono_loader_unlock ();
2619 }
2620
2621 /*
2622  * resume_thread:
2623  *
2624  *   Resume just one thread.
2625  */
2626 static void
2627 resume_thread (MonoInternalThread *thread)
2628 {
2629         int err;
2630         DebuggerTlsData *tls;
2631
2632         g_assert (debugger_thread_id == GetCurrentThreadId ());
2633
2634         mono_loader_lock ();
2635
2636         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2637         g_assert (tls);
2638         
2639         mono_mutex_lock (&suspend_mutex);
2640
2641         g_assert (suspend_count > 0);
2642
2643         DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2644
2645         tls->resume_count += suspend_count;
2646
2647         /* 
2648          * Signal suspend_count without decreasing suspend_count, the threads will wake up
2649          * but only the one whose resume_count field is > 0 will be resumed.
2650          */
2651         err = mono_cond_broadcast (&suspend_cond);
2652         g_assert (err == 0);
2653
2654         mono_mutex_unlock (&suspend_mutex);
2655         //g_assert (err == 0);
2656
2657         mono_loader_unlock ();
2658 }
2659
2660 static void
2661 invalidate_frames (DebuggerTlsData *tls)
2662 {
2663         int i;
2664
2665         if (!tls)
2666                 tls = mono_native_tls_get_value (debugger_tls_id);
2667         g_assert (tls);
2668
2669         for (i = 0; i < tls->frame_count; ++i) {
2670                 if (tls->frames [i]->jit)
2671                         mono_debug_free_method_jit_info (tls->frames [i]->jit);
2672                 g_free (tls->frames [i]);
2673         }
2674         g_free (tls->frames);
2675         tls->frame_count = 0;
2676         tls->frames = NULL;
2677 }
2678
2679 /*
2680  * suspend_current:
2681  *
2682  *   Suspend the current thread until the runtime is resumed. If the thread has a 
2683  * pending invoke, then the invoke is executed before this function returns. 
2684  */
2685 static void
2686 suspend_current (void)
2687 {
2688         int err;
2689         DebuggerTlsData *tls;
2690
2691         g_assert (debugger_thread_id != GetCurrentThreadId ());
2692
2693         if (mono_loader_lock_is_owned_by_self ()) {
2694                 /*
2695                  * If we own the loader mutex, can't suspend until we release it, since the
2696                  * whole runtime can deadlock otherwise.
2697                  */
2698                 return;
2699         }
2700
2701         tls = mono_native_tls_get_value (debugger_tls_id);
2702         g_assert (tls);
2703
2704         mono_mutex_lock (&suspend_mutex);
2705
2706         tls->suspending = FALSE;
2707         tls->really_suspended = TRUE;
2708
2709         if (!tls->suspended) {
2710                 tls->suspended = TRUE;
2711                 MONO_SEM_POST (&suspend_sem);
2712         }
2713
2714         DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2715
2716         while (suspend_count - tls->resume_count > 0) {
2717 #ifdef HOST_WIN32
2718                 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2719                 {
2720                         mono_mutex_unlock (&suspend_mutex);
2721                         Sleep(1);
2722                         mono_mutex_lock (&suspend_mutex);
2723                 }
2724                 else
2725                 {
2726                 }
2727 #else
2728                 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2729                 g_assert (err == 0);
2730 #endif
2731         }
2732
2733         tls->suspended = FALSE;
2734         tls->really_suspended = FALSE;
2735
2736         threads_suspend_count --;
2737
2738         mono_mutex_unlock (&suspend_mutex);
2739
2740         DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2741
2742         if (tls->pending_invoke) {
2743                 /* Save the original context */
2744                 tls->pending_invoke->has_ctx = TRUE;
2745                 tls->pending_invoke->ctx = tls->context.ctx;
2746
2747                 invoke_method ();
2748         }
2749
2750         /* The frame info becomes invalid after a resume */
2751         tls->context.valid = FALSE;
2752         tls->async_state.valid = FALSE;
2753         invalidate_frames (NULL);
2754 }
2755
2756 static void
2757 count_thread (gpointer key, gpointer value, gpointer user_data)
2758 {
2759         DebuggerTlsData *tls = value;
2760
2761         if (!tls->suspended && !tls->terminated)
2762                 *(int*)user_data = *(int*)user_data + 1;
2763 }
2764
2765 static int
2766 count_threads_to_wait_for (void)
2767 {
2768         int count = 0;
2769
2770         mono_loader_lock ();
2771         mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2772         mono_loader_unlock ();
2773
2774         return count;
2775 }       
2776
2777 /*
2778  * wait_for_suspend:
2779  *
2780  *   Wait until the runtime is completely suspended.
2781  */
2782 static void
2783 wait_for_suspend (void)
2784 {
2785         int nthreads, nwait, err;
2786         gboolean waited = FALSE;
2787
2788         // FIXME: Threads starting/stopping ?
2789         mono_loader_lock ();
2790         nthreads = mono_g_hash_table_size (thread_to_tls);
2791         mono_loader_unlock ();
2792
2793         while (TRUE) {
2794                 nwait = count_threads_to_wait_for ();
2795                 if (nwait) {
2796                         DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2797                         err = MONO_SEM_WAIT (&suspend_sem);
2798                         g_assert (err == 0);
2799                         waited = TRUE;
2800                 } else {
2801                         break;
2802                 }
2803         }
2804
2805         if (waited)
2806                 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2807 }
2808
2809 /*
2810  * is_suspended:
2811  *
2812  *   Return whenever the runtime is suspended.
2813  */
2814 static gboolean
2815 is_suspended (void)
2816 {
2817         return count_threads_to_wait_for () == 0;
2818 }
2819
2820 static MonoSeqPointInfo*
2821 get_seq_points (MonoDomain *domain, MonoMethod *method)
2822 {
2823         MonoSeqPointInfo *seq_points;
2824
2825         mono_domain_lock (domain);
2826         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2827         if (!seq_points && method->is_inflated) {
2828                 /* generic sharing + aot */
2829                 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2830                 if (!seq_points)
2831                         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2832         }
2833         mono_domain_unlock (domain);
2834
2835         return seq_points;
2836 }
2837
2838 static MonoSeqPointInfo*
2839 find_seq_points (MonoDomain *domain, MonoMethod *method)
2840 {
2841         MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2842
2843         if (!seq_points)
2844                 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2845         g_assert (seq_points);
2846
2847         return seq_points;
2848 }
2849
2850 /*
2851  * find_next_seq_point_for_native_offset:
2852  *
2853  *   Find the first sequence point after NATIVE_OFFSET.
2854  */
2855 static SeqPoint*
2856 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2857 {
2858         MonoSeqPointInfo *seq_points;
2859         int i;
2860
2861         seq_points = find_seq_points (domain, method);
2862         if (info)
2863                 *info = seq_points;
2864
2865         for (i = 0; i < seq_points->len; ++i) {
2866                 if (seq_points->seq_points [i].native_offset >= native_offset)
2867                         return &seq_points->seq_points [i];
2868         }
2869
2870         return NULL;
2871 }
2872
2873 /*
2874  * find_prev_seq_point_for_native_offset:
2875  *
2876  *   Find the first sequence point before NATIVE_OFFSET.
2877  */
2878 static SeqPoint*
2879 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2880 {
2881         MonoSeqPointInfo *seq_points;
2882         int i;
2883
2884         seq_points = find_seq_points (domain, method);
2885         if (info)
2886                 *info = seq_points;
2887
2888         for (i = seq_points->len - 1; i >= 0; --i) {
2889                 if (seq_points->seq_points [i].native_offset <= native_offset)
2890                         return &seq_points->seq_points [i];
2891         }
2892
2893         return NULL;
2894 }
2895
2896 /*
2897  * find_seq_point:
2898  *
2899  *   Find the sequence point corresponding to the IL offset IL_OFFSET, which
2900  * should be the location of a sequence point.
2901  */
2902 static G_GNUC_UNUSED SeqPoint*
2903 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2904 {
2905         MonoSeqPointInfo *seq_points;
2906         int i;
2907
2908         *info = NULL;
2909
2910         seq_points = get_seq_points (domain, method);
2911         if (!seq_points)
2912                 return NULL;
2913         *info = seq_points;
2914
2915         for (i = 0; i < seq_points->len; ++i) {
2916                 if (seq_points->seq_points [i].il_offset == il_offset)
2917                         return &seq_points->seq_points [i];
2918         }
2919
2920         return NULL;
2921 }
2922
2923 typedef struct {
2924         DebuggerTlsData *tls;
2925         GSList *frames;
2926 } ComputeFramesUserData;
2927
2928 static gboolean
2929 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2930 {
2931         ComputeFramesUserData *ud = user_data;
2932         StackFrame *frame;
2933         MonoMethod *method, *actual_method;
2934         SeqPoint *sp;
2935
2936         if (info->type != FRAME_TYPE_MANAGED) {
2937                 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2938                         /* Mark the last frame as an invoke frame */
2939                         if (ud->frames)
2940                                 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2941                 }
2942                 return FALSE;
2943         }
2944
2945         if (info->ji)
2946                 method = info->ji->method;
2947         else
2948                 method = info->method;
2949         actual_method = info->actual_method;
2950
2951         if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2952                 return FALSE;
2953
2954         if (info->il_offset == -1) {
2955                 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
2956                 if (ud->frames == NULL) {
2957                         sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
2958                         if (sp)
2959                                 info->il_offset = sp->il_offset;
2960                 }
2961                 if (info->il_offset == -1)
2962                         info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2963         }
2964
2965         DEBUG (1, fprintf (log_file, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed));
2966
2967         if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2968                 /*
2969                  * mono_arch_find_jit_info () returns the context stored in the LMF for 
2970                  * native frames, but it should unwind once. This is why we have duplicate
2971                  * frames on the stack sometimes.
2972                  * !managed also seems to be set for dynamic methods.
2973                  */
2974                 return FALSE;
2975         }
2976
2977         frame = g_new0 (StackFrame, 1);
2978         frame->method = method;
2979         frame->actual_method = actual_method;
2980         frame->il_offset = info->il_offset;
2981         frame->native_offset = info->native_offset;
2982         memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
2983         if (ctx) {
2984                 frame->ctx = *ctx;
2985                 frame->has_ctx = TRUE;
2986         }
2987         frame->domain = info->domain;
2988
2989         ud->frames = g_slist_append (ud->frames, frame);
2990
2991         return FALSE;
2992 }
2993
2994 static gboolean
2995 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2996 {
2997         ComputeFramesUserData *ud = user_data;
2998
2999         /*
3000          * 'tls->filter_ctx' is the location of the throw site.
3001          *
3002          * mono_walk_stack() will never actually hit the throw site, but unwind
3003          * directly from the filter to the call site; we abort stack unwinding here
3004          * once this happens and resume from the throw site.
3005          */
3006
3007         if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3008                 return TRUE;
3009
3010         return process_frame (info, ctx, user_data);
3011 }
3012
3013 static void
3014 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3015 {
3016         ComputeFramesUserData user_data;
3017         GSList *tmp;
3018         int i, findex, new_frame_count;
3019         StackFrame **new_frames, *f;
3020         MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3021
3022         // FIXME: Locking on tls
3023         if (tls->frames && tls->frames_up_to_date)
3024                 return;
3025
3026         DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3027
3028         user_data.tls = tls;
3029         user_data.frames = NULL;
3030         if (tls->terminated) {
3031                 tls->frame_count = 0;
3032                 return;
3033         } if (!tls->really_suspended && tls->async_state.valid) {
3034                 /* Have to use the state saved by the signal handler */
3035                 process_frame (&tls->async_last_frame, NULL, &user_data);
3036                 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3037         } else if (tls->filter_state.valid) {
3038                 /*
3039                  * We are inside an exception filter.
3040                  *
3041                  * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3042                  */
3043                 if (tls->context.valid)
3044                         mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3045                 /*
3046                  * After that, we resume unwinding from the location where the exception has been thrown.
3047                  */
3048                 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3049         } else if (tls->context.valid) {
3050                 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3051         } else {
3052                 // FIXME:
3053                 tls->frame_count = 0;
3054                 return;
3055         }
3056
3057         new_frame_count = g_slist_length (user_data.frames);
3058         new_frames = g_new0 (StackFrame*, new_frame_count);
3059         findex = 0;
3060         for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3061                 f = tmp->data;
3062
3063                 /* 
3064                  * Reuse the id for already existing stack frames, so invokes don't invalidate
3065                  * the still valid stack frames.
3066                  */
3067                 for (i = 0; i < tls->frame_count; ++i) {
3068                         if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3069                                 f->id = tls->frames [i]->id;
3070                                 break;
3071                         }
3072                 }
3073
3074                 if (i >= tls->frame_count)
3075                         f->id = InterlockedIncrement (&frame_id);
3076
3077                 new_frames [findex ++] = f;
3078         }
3079
3080         g_slist_free (user_data.frames);
3081
3082         invalidate_frames (tls);
3083
3084         tls->frames = new_frames;
3085         tls->frame_count = new_frame_count;
3086         tls->frames_up_to_date = TRUE;
3087 }
3088
3089 /*
3090  * GHFunc to emit an appdomain creation event
3091  * @param key Don't care
3092  * @param value A loaded appdomain
3093  * @param user_data Don't care
3094  */
3095 static void
3096 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3097 {
3098         process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3099         g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3100 }
3101
3102 /*
3103  * GHFunc to emit a thread start event
3104  * @param key A thread id
3105  * @param value A thread object
3106  * @param user_data Don't care
3107  */
3108 static void
3109 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3110 {
3111         if (GPOINTER_TO_INT (key) != debugger_thread_id)
3112                 process_profiler_event (EVENT_KIND_THREAD_START, value);
3113 }
3114
3115 /*
3116  * GFunc to emit an assembly load event
3117  * @param value A loaded assembly
3118  * @param user_data Don't care
3119  */
3120 static void
3121 emit_assembly_load (gpointer value, gpointer user_data)
3122 {
3123         process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3124 }
3125
3126 /*
3127  * GFunc to emit a type load event
3128  * @param value A loaded type
3129  * @param user_data Don't care
3130  */
3131 static void
3132 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3133 {
3134         process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3135 }
3136
3137 static char*
3138 strdup_tolower (char *s)
3139 {
3140         char *s2, *p;
3141
3142         s2 = g_strdup (s);
3143         for (p = s2; *p; ++p)
3144                 *p = tolower (*p);
3145         return s2;
3146 }
3147
3148 /*
3149  * EVENT HANDLING
3150  */
3151
3152 /*
3153  * create_event_list:
3154  *
3155  *   Return a list of event request ids matching EVENT, starting from REQS, which
3156  * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3157  * policy.
3158  * We return request ids, instead of requests, to simplify threading, since 
3159  * requests could be deleted anytime when the loader lock is not held.
3160  * LOCKING: Assumes the loader lock is held.
3161  */
3162 static GSList*
3163 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3164 {
3165         int i, j;
3166         GSList *events = NULL;
3167
3168         *suspend_policy = SUSPEND_POLICY_NONE;
3169
3170         if (!reqs)
3171                 reqs = event_requests;
3172
3173         if (!reqs)
3174                 return NULL;
3175
3176         for (i = 0; i < reqs->len; ++i) {
3177                 EventRequest *req = g_ptr_array_index (reqs, i);
3178                 if (req->event_kind == event) {
3179                         gboolean filtered = FALSE;
3180
3181                         /* Apply filters */
3182                         for (j = 0; j < req->nmodifiers; ++j) {
3183                                 Modifier *mod = &req->modifiers [j];
3184
3185                                 if (mod->kind == MOD_KIND_COUNT) {
3186                                         filtered = TRUE;
3187                                         if (mod->data.count > 0) {
3188                                                 if (mod->data.count > 0) {
3189                                                         mod->data.count --;
3190                                                         if (mod->data.count == 0)
3191                                                                 filtered = FALSE;
3192                                                 }
3193                                         }
3194                                 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3195                                         if (mod->data.thread != mono_thread_internal_current ())
3196                                                 filtered = TRUE;
3197                                 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3198                                         if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3199                                                 filtered = TRUE;
3200                                         if (ei->caught && !mod->caught)
3201                                                 filtered = TRUE;
3202                                         if (!ei->caught && !mod->uncaught)
3203                                                 filtered = TRUE;
3204                                 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3205                                         int k;
3206                                         gboolean found = FALSE;
3207                                         MonoAssembly **assemblies = mod->data.assemblies;
3208
3209                                         if (assemblies) {
3210                                                 for (k = 0; assemblies [k]; ++k)
3211                                                         if (assemblies [k] == ji->method->klass->image->assembly)
3212                                                                 found = TRUE;
3213                                         }
3214                                         if (!found)
3215                                                 filtered = TRUE;
3216                                 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3217                                         gpointer iter = NULL;
3218                                         MonoMethod *method;
3219                                         MonoDebugSourceInfo *sinfo;
3220                                         char *source_file, *s;
3221                                         gboolean found = FALSE;
3222                                         int i;
3223                                         GPtrArray *source_file_list;
3224
3225                                         while ((method = mono_class_get_methods (ei->klass, &iter))) {
3226                                                 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3227
3228                                                 if (minfo) {
3229                                                         mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL);
3230                                                         for (i = 0; i < source_file_list->len; ++i) {
3231                                                                 sinfo = g_ptr_array_index (source_file_list, i);
3232                                                                 /*
3233                                                                  * Do a case-insesitive match by converting the file name to
3234                                                                  * lowercase.
3235                                                                  */
3236                                                                 s = strdup_tolower (sinfo->source_file);
3237                                                                 if (g_hash_table_lookup (mod->data.source_files, s))
3238                                                                         found = TRUE;
3239                                                                 g_free (s);
3240                                                         }
3241                                                         g_ptr_array_free (source_file_list, TRUE);
3242                                                 }
3243                                         }
3244                                         if (!found)
3245                                                 filtered = TRUE;
3246                                 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3247                                         char *s;
3248
3249                                         s = mono_type_full_name (&ei->klass->byval_arg);
3250                                         if (!g_hash_table_lookup (mod->data.type_names, s))
3251                                                 filtered = TRUE;
3252                                         g_free (s);
3253                                 }
3254                         }
3255
3256                         if (!filtered) {
3257                                 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3258                                 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3259                         }
3260                 }
3261         }
3262
3263         /* Send a VM START/DEATH event by default */
3264         if (event == EVENT_KIND_VM_START)
3265                 events = g_slist_append (events, GINT_TO_POINTER (0));
3266         if (event == EVENT_KIND_VM_DEATH)
3267                 events = g_slist_append (events, GINT_TO_POINTER (0));
3268
3269         return events;
3270 }
3271
3272 static G_GNUC_UNUSED const char*
3273 event_to_string (EventKind event)
3274 {
3275         switch (event) {
3276         case EVENT_KIND_VM_START: return "VM_START";
3277         case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3278         case EVENT_KIND_THREAD_START: return "THREAD_START";
3279         case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3280         case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3281         case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3282         case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3283         case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3284         case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3285         case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3286         case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3287         case EVENT_KIND_STEP: return "STEP";
3288         case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3289         case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3290         case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3291         case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3292         case EVENT_KIND_USER_LOG: return "USER_LOG";
3293         default:
3294                 g_assert_not_reached ();
3295         }
3296 }
3297
3298 /*
3299  * process_event:
3300  *
3301  *   Send an event to the client, suspending the vm if needed.
3302  * LOCKING: Since this can suspend the calling thread, no locks should be held
3303  * by the caller.
3304  * The EVENTS list is freed by this function.
3305  */
3306 static void
3307 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3308 {
3309         Buffer buf;
3310         GSList *l;
3311         MonoDomain *domain = mono_domain_get ();
3312         MonoThread *thread = NULL;
3313         gboolean send_success = FALSE;
3314         static int ecount;
3315         int nevents;
3316
3317         if (!inited) {
3318                 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3319                 return;
3320         }
3321
3322         if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3323                 // FIXME: We miss those events
3324                 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3325                 return;
3326         }
3327
3328         if (vm_death_event_sent) {
3329                 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3330                 return;
3331         }
3332
3333         if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3334                 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3335                 return;
3336         }
3337
3338         if (disconnected) {
3339                 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3340                 return;
3341         }
3342
3343         if (event == EVENT_KIND_KEEPALIVE)
3344                 suspend_policy = SUSPEND_POLICY_NONE;
3345         else {
3346                 if (events == NULL)
3347                         return;
3348
3349                 if (agent_config.defer) {
3350                         /* Make sure the thread id is always set when doing deferred debugging */
3351                         if (debugger_thread_id == GetCurrentThreadId ()) {
3352                                 /* Don't suspend on events from the debugger thread */
3353                                 suspend_policy = SUSPEND_POLICY_NONE;
3354                                 thread = mono_thread_get_main ();
3355                         }
3356                         else thread = mono_thread_current ();
3357                 } else {
3358                         if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3359                                 // FIXME: Send these with a NULL thread, don't suspend the current thread
3360                                 return;
3361                 }
3362         }
3363
3364         nevents = g_slist_length (events);
3365         buffer_init (&buf, 128);
3366         buffer_add_byte (&buf, suspend_policy);
3367         buffer_add_int (&buf, nevents);
3368
3369         for (l = events; l; l = l->next) {
3370                 buffer_add_byte (&buf, event); // event kind
3371                 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3372
3373                 ecount ++;
3374
3375                 if (!thread)
3376                         thread = mono_thread_current ();
3377
3378                 if (event == EVENT_KIND_VM_START && arg != NULL)
3379                         thread = arg;
3380
3381                 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3382
3383                 switch (event) {
3384                 case EVENT_KIND_THREAD_START:
3385                 case EVENT_KIND_THREAD_DEATH:
3386                         break;
3387                 case EVENT_KIND_APPDOMAIN_CREATE:
3388                 case EVENT_KIND_APPDOMAIN_UNLOAD:
3389                         buffer_add_domainid (&buf, arg);
3390                         break;
3391                 case EVENT_KIND_METHOD_ENTRY:
3392                 case EVENT_KIND_METHOD_EXIT:
3393                         buffer_add_methodid (&buf, domain, arg);
3394                         break;
3395                 case EVENT_KIND_ASSEMBLY_LOAD:
3396                 case EVENT_KIND_ASSEMBLY_UNLOAD:
3397                         buffer_add_assemblyid (&buf, domain, arg);
3398                         break;
3399                 case EVENT_KIND_TYPE_LOAD:
3400                         buffer_add_typeid (&buf, domain, arg);
3401                         break;
3402                 case EVENT_KIND_BREAKPOINT:
3403                 case EVENT_KIND_STEP:
3404                         buffer_add_methodid (&buf, domain, arg);
3405                         buffer_add_long (&buf, il_offset);
3406                         break;
3407                 case EVENT_KIND_VM_START:
3408                         buffer_add_domainid (&buf, mono_get_root_domain ());
3409                         break;
3410                 case EVENT_KIND_VM_DEATH:
3411                         break;
3412                 case EVENT_KIND_EXCEPTION: {
3413                         EventInfo *ei = arg;
3414                         buffer_add_objid (&buf, ei->exc);
3415                         break;
3416                 }
3417                 case EVENT_KIND_USER_BREAK:
3418                         break;
3419                 case EVENT_KIND_USER_LOG: {
3420                         EventInfo *ei = arg;
3421                         buffer_add_int (&buf, ei->level);
3422                         buffer_add_string (&buf, ei->category ? ei->category : "");
3423                         buffer_add_string (&buf, ei->message ? ei->message : "");
3424                         break;
3425                 }
3426                 case EVENT_KIND_KEEPALIVE:
3427                         suspend_policy = SUSPEND_POLICY_NONE;
3428                         break;
3429                 default:
3430                         g_assert_not_reached ();
3431                 }
3432         }
3433
3434         if (event == EVENT_KIND_VM_START) {
3435                 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3436                 if (!agent_config.defer)
3437                         start_debugger_thread ();
3438         }
3439    
3440         if (event == EVENT_KIND_VM_DEATH) {
3441                 vm_death_event_sent = TRUE;
3442                 suspend_policy = SUSPEND_POLICY_NONE;
3443         }
3444
3445         if (mono_runtime_is_shutting_down ())
3446                 suspend_policy = SUSPEND_POLICY_NONE;
3447
3448         if (suspend_policy != SUSPEND_POLICY_NONE) {
3449                 /* 
3450                  * Save the thread context and start suspending before sending the packet,
3451                  * since we could be receiving the resume request before send_packet ()
3452                  * returns.
3453                  */
3454                 save_thread_context (ctx);
3455                 suspend_vm ();
3456         }
3457
3458         send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3459
3460         buffer_free (&buf);
3461
3462         g_slist_free (events);
3463         events = NULL;
3464
3465         if (!send_success) {
3466                 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3467                 return;
3468         }
3469         
3470         if (event == EVENT_KIND_VM_START) {
3471                 vm_start_event_sent = TRUE;
3472         }
3473
3474         DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3475
3476         switch (suspend_policy) {
3477         case SUSPEND_POLICY_NONE:
3478                 break;
3479         case SUSPEND_POLICY_ALL:
3480                 suspend_current ();
3481                 break;
3482         case SUSPEND_POLICY_EVENT_THREAD:
3483                 NOT_IMPLEMENTED;
3484                 break;
3485         default:
3486                 g_assert_not_reached ();
3487         }
3488 }
3489
3490 static void
3491 process_profiler_event (EventKind event, gpointer arg)
3492 {
3493         int suspend_policy;
3494         GSList *events;
3495         EventInfo ei, *ei_arg = NULL;
3496
3497         if (event == EVENT_KIND_TYPE_LOAD) {
3498                 ei.klass = arg;
3499                 ei_arg = &ei;
3500         }
3501
3502         mono_loader_lock ();
3503         events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3504         mono_loader_unlock ();
3505
3506         process_event (event, arg, 0, NULL, events, suspend_policy);
3507 }
3508
3509 static void
3510 runtime_initialized (MonoProfiler *prof)
3511 {
3512         process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3513         if (agent_config.defer)
3514                 start_debugger_thread ();
3515 }
3516
3517 static void
3518 runtime_shutdown (MonoProfiler *prof)
3519 {
3520         process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3521
3522         mono_debugger_agent_cleanup ();
3523 }
3524
3525 static void
3526 thread_startup (MonoProfiler *prof, uintptr_t tid)
3527 {
3528         MonoInternalThread *thread = mono_thread_internal_current ();
3529         MonoInternalThread *old_thread;
3530         DebuggerTlsData *tls;
3531
3532         if (tid == debugger_thread_id)
3533                 return;
3534
3535         g_assert (thread->tid == tid);
3536
3537         mono_loader_lock ();
3538         old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3539         mono_loader_unlock ();
3540         if (old_thread) {
3541                 if (thread == old_thread) {
3542                         /* 
3543                          * For some reason, thread_startup () might be called for the same thread
3544                          * multiple times (attach ?).
3545                          */
3546                         DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3547                         return;
3548                 } else {
3549                         /*
3550                          * thread_end () might not be called for some threads, and the tid could
3551                          * get reused.
3552                          */
3553                         DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3554                         mono_loader_lock ();
3555                         mono_g_hash_table_remove (thread_to_tls, old_thread);
3556                         mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3557                         mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3558                         mono_loader_unlock ();
3559                 }
3560         }
3561
3562         tls = mono_native_tls_get_value (debugger_tls_id);
3563         g_assert (!tls);
3564         // FIXME: Free this somewhere
3565         tls = g_new0 (DebuggerTlsData, 1);
3566         tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3567         MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3568         tls->thread = thread;
3569         mono_native_tls_set_value (debugger_tls_id, tls);
3570
3571         DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3572
3573         mono_loader_lock ();
3574         mono_g_hash_table_insert (thread_to_tls, thread, tls);
3575         mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3576         mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3577         mono_loader_unlock ();
3578
3579         process_profiler_event (EVENT_KIND_THREAD_START, thread);
3580
3581         /* 
3582          * suspend_vm () could have missed this thread, so wait for a resume.
3583          */
3584         suspend_current ();
3585 }
3586
3587 static void
3588 thread_end (MonoProfiler *prof, uintptr_t tid)
3589 {
3590         MonoInternalThread *thread;
3591         DebuggerTlsData *tls = NULL;
3592
3593         mono_loader_lock ();
3594         thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3595         if (thread) {
3596                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3597                 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3598                 tls->terminated = TRUE;
3599                 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3600                 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3601                 MONO_GC_UNREGISTER_ROOT (tls->thread);
3602                 tls->thread = NULL;
3603         }
3604         mono_loader_unlock ();
3605
3606         /* We might be called for threads started before we registered the start callback */
3607         if (thread) {
3608                 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3609                 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3610         }
3611 }
3612
3613 static void
3614 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3615 {
3616         mono_loader_lock ();
3617         g_hash_table_insert (domains, domain, domain);
3618         mono_loader_unlock ();
3619
3620         process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3621 }
3622
3623 static void
3624 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3625 {
3626         clear_breakpoints_for_domain (domain);
3627         
3628         mono_loader_lock ();
3629         /* Invalidate each thread's frame stack */
3630         mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3631         mono_loader_unlock ();
3632         
3633         process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3634 }
3635
3636 /*
3637  * invalidate_each_thread:
3638  *
3639  *   A GHFunc to invalidate frames.
3640  *   value must be a DebuggerTlsData*
3641  */
3642 static void
3643 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3644 {
3645         invalidate_frames (value);
3646 }
3647
3648 static void
3649 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3650 {
3651         /* Sent later in jit_end () */
3652         mono_loader_lock ();
3653         g_ptr_array_add (pending_assembly_loads, assembly);
3654         mono_loader_unlock ();
3655 }
3656
3657 static void
3658 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3659 {
3660         process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3661
3662         clear_event_requests_for_assembly (assembly);
3663         clear_types_for_assembly (assembly);
3664 }
3665
3666 static void
3667 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3668 {
3669 #if defined(HOST_WIN32) && !defined(__GNUC__)
3670         gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3671 #else
3672         gpointer stackptr = __builtin_frame_address (1);
3673 #endif
3674         MonoInternalThread *thread = mono_thread_internal_current ();
3675         DebuggerTlsData *tls;
3676
3677         mono_loader_lock ();
3678         
3679         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3680         /* Could be the debugger thread with assembly/type load hooks */
3681         if (tls)
3682                 tls->invoke_addr = stackptr;
3683
3684         mono_loader_unlock ();
3685 }
3686
3687 static void
3688 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3689 {
3690         int i;
3691 #if defined(HOST_WIN32) && !defined(__GNUC__)
3692         gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3693 #else
3694         gpointer stackptr = __builtin_frame_address (1);
3695 #endif
3696
3697         if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3698                 return;
3699
3700         /*
3701          * We need to stop single stepping when exiting a runtime invoke, since if it is
3702          * a step out, it may return to native code, and thus never end.
3703          */
3704         mono_loader_lock ();
3705         ss_invoke_addr = NULL;
3706
3707         for (i = 0; i < event_requests->len; ++i) {
3708                 EventRequest *req = g_ptr_array_index (event_requests, i);
3709
3710                 if (req->event_kind == EVENT_KIND_STEP) {
3711                         ss_destroy (req->info);
3712                         g_ptr_array_remove_index_fast (event_requests, i);
3713                         g_free (req);
3714                         break;
3715                 }
3716         }
3717         mono_loader_unlock ();
3718 }
3719
3720 static void
3721 send_type_load (MonoClass *klass)
3722 {
3723         gboolean type_load = FALSE;
3724         MonoDomain *domain = mono_domain_get ();
3725         AgentDomainInfo *info = NULL;
3726
3727         mono_loader_lock ();
3728         mono_domain_lock (domain);
3729
3730         info = get_agent_domain_info (domain);
3731
3732         if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3733                 type_load = TRUE;
3734                 g_hash_table_insert (info->loaded_classes, klass, klass);
3735         }
3736
3737         mono_domain_unlock (domain);
3738         mono_loader_unlock ();
3739         if (type_load)
3740                 emit_type_load (klass, klass, NULL);
3741 }
3742
3743 /*
3744  * Emit load events for all types currently loaded in the domain.
3745  * Takes the loader and domain locks.
3746  * user_data is unused.
3747  */
3748 static void
3749 send_types_for_domain (MonoDomain *domain, void *user_data)
3750 {
3751         AgentDomainInfo *info = NULL;
3752         
3753         mono_loader_lock ();
3754         mono_domain_lock (domain);
3755         info =  get_agent_domain_info (domain);
3756         g_assert (info);
3757         g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3758         mono_domain_unlock (domain);
3759         mono_loader_unlock ();
3760 }
3761
3762 static void
3763 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3764 {
3765         /*
3766          * We emit type load events when the first method of the type is JITted,
3767          * since the class load profiler callbacks might be called with the
3768          * loader lock held. They could also occur in the debugger thread.
3769          * Same for assembly load events.
3770          */
3771         while (TRUE) {
3772                 MonoAssembly *assembly = NULL;
3773
3774                 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3775                 mono_loader_lock ();
3776                 if (pending_assembly_loads->len > 0) {
3777                         assembly = g_ptr_array_index (pending_assembly_loads, 0);
3778                         g_ptr_array_remove_index (pending_assembly_loads, 0);
3779                 }
3780                 mono_loader_unlock ();
3781
3782                 if (assembly) {
3783                         process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3784                 } else {
3785                         break;
3786                 }
3787         }
3788
3789         send_type_load (method->klass);
3790
3791         if (!result)
3792                 add_pending_breakpoints (method, jinfo);
3793 }
3794
3795 /*
3796  * BREAKPOINTS/SINGLE STEPPING
3797  */
3798
3799 /* 
3800  * Contains information about an inserted breakpoint.
3801  */
3802 typedef struct {
3803         long il_offset, native_offset;
3804         guint8 *ip;
3805         MonoJitInfo *ji;
3806         MonoDomain *domain;
3807         SeqPoint *sp;
3808 } BreakpointInstance;
3809
3810 /*
3811  * Contains generic information about a breakpoint.
3812  */
3813 typedef struct {
3814         /* 
3815          * The method where the breakpoint is placed. Can be NULL in which case it 
3816          * is inserted into every method. This is used to implement method entry/
3817          * exit events. Can be a generic method definition, in which case the
3818          * breakpoint is inserted into every instance.
3819          */
3820         MonoMethod *method;
3821         long il_offset;
3822         EventRequest *req;
3823         /* 
3824          * A list of BreakpointInstance structures describing where the breakpoint
3825          * was inserted. There could be more than one because of 
3826          * generics/appdomains/method entry/exit.
3827          */
3828         GPtrArray *children;
3829 } MonoBreakpoint;
3830
3831 /* List of breakpoints */
3832 static GPtrArray *breakpoints;
3833 /* Maps breakpoint locations to the number of breakpoints at that location */
3834 static GHashTable *bp_locs;
3835
3836 static void
3837 breakpoints_init (void)
3838 {
3839         breakpoints = g_ptr_array_new ();
3840         bp_locs = g_hash_table_new (NULL, NULL);
3841 }       
3842
3843 /*
3844  * insert_breakpoint:
3845  *
3846  *   Insert the breakpoint described by BP into the method described by
3847  * JI.
3848  */
3849 static void
3850 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3851 {
3852         int i, count;
3853         BreakpointInstance *inst;
3854         SeqPoint *sp = NULL;
3855
3856         if (error)
3857                 mono_error_init (error);
3858
3859         for (i = 0; i < seq_points->len; ++i) {
3860                 sp = &seq_points->seq_points [i];
3861
3862                 if (sp->il_offset == bp->il_offset)
3863                         break;
3864         }
3865
3866         if (i == seq_points->len) {
3867                 /*
3868                  * The set of IL offsets with seq points doesn't completely match the
3869                  * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3870                  */
3871                 for (i = 0; i < seq_points->len; ++i) {
3872                         sp = &seq_points->seq_points [i];
3873
3874                         if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3875                                 break;
3876                 }
3877         }
3878
3879         if (i == seq_points->len) {
3880                 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (ji->method, TRUE), bp->il_offset, seq_points->len);
3881
3882                 for (i = 0; i < seq_points->len; ++i)
3883                         printf ("%d\n", seq_points->seq_points [i].il_offset);
3884
3885                 if (error) {
3886                         mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3887                         g_free (s);
3888                         return;
3889                 } else {
3890                         g_error ("%s", s);
3891                         g_free (s);
3892                 }
3893         }
3894
3895         inst = g_new0 (BreakpointInstance, 1);
3896         inst->sp = sp;
3897         inst->native_offset = sp->native_offset;
3898         inst->ip = (guint8*)ji->code_start + sp->native_offset;
3899         inst->ji = ji;
3900         inst->domain = domain;
3901
3902         mono_loader_lock ();
3903
3904         g_ptr_array_add (bp->children, inst);
3905
3906         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3907         g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3908         mono_loader_unlock ();
3909
3910         if (count == 0) {
3911 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3912                 mono_arch_set_breakpoint (ji, inst->ip);
3913 #else
3914                 NOT_IMPLEMENTED;
3915 #endif
3916         }
3917
3918         DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));  
3919 }
3920
3921 static void
3922 remove_breakpoint (BreakpointInstance *inst)
3923 {
3924 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3925         int count;
3926         MonoJitInfo *ji = inst->ji;
3927         guint8 *ip = inst->ip;
3928
3929         mono_loader_lock ();
3930         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3931         g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3932         mono_loader_unlock ();
3933
3934         g_assert (count > 0);
3935
3936         if (count == 1) {
3937                 mono_arch_clear_breakpoint (ji, ip);
3938         }
3939 #else
3940         NOT_IMPLEMENTED;
3941 #endif
3942 }       
3943
3944 static inline gboolean
3945 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3946 {
3947         int i;
3948
3949         if (!bp->method)
3950                 return TRUE;
3951         if (method == bp->method)
3952                 return TRUE;
3953         if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
3954                 return TRUE;
3955
3956         if (bp->method->is_inflated && method->is_inflated) {
3957                 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
3958                 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3959
3960                 /* Open generic methods should match closed generic methods of the same class */
3961                 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
3962                         for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
3963                                 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
3964
3965                                 /* FIXME: Handle !mvar */
3966                                 if (t1->type != MONO_TYPE_MVAR)
3967                                         return FALSE;
3968                         }
3969                         return TRUE;
3970                 }
3971         }
3972
3973         return FALSE;
3974 }
3975
3976 /*
3977  * add_pending_breakpoints:
3978  *
3979  *   Insert pending breakpoints into the newly JITted method METHOD.
3980  */
3981 static void
3982 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3983 {
3984         int i, j;
3985         MonoSeqPointInfo *seq_points;
3986         MonoDomain *domain;
3987
3988         if (!breakpoints)
3989                 return;
3990
3991         domain = mono_domain_get ();
3992
3993         mono_loader_lock ();
3994
3995         for (i = 0; i < breakpoints->len; ++i) {
3996                 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3997                 gboolean found = FALSE;
3998
3999                 if (!bp_matches_method (bp, method))
4000                         continue;
4001
4002                 for (j = 0; j < bp->children->len; ++j) {
4003                         BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4004
4005                         if (inst->ji == ji)
4006                                 found = TRUE;
4007                 }
4008
4009                 if (!found) {
4010                         mono_domain_lock (domain);
4011                         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4012                         if (!seq_points && ji->method->is_inflated)
4013                                 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4014                         mono_domain_unlock (domain);
4015                         if (!seq_points)
4016                                 /* Could be AOT code */
4017                                 continue;
4018                         g_assert (seq_points);
4019
4020                         insert_breakpoint (seq_points, domain, ji, bp, NULL);
4021                 }
4022         }
4023
4024         mono_loader_unlock ();
4025 }
4026
4027 static void
4028 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4029 {
4030         gpointer code;
4031         MonoJitInfo *ji;
4032
4033         if (error)
4034                 mono_error_init (error);
4035
4036         code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4037         if (!code) {
4038                 /* Might be AOTed code */
4039                 code = mono_aot_get_method (domain, method);
4040                 g_assert (code);
4041                 ji = mono_jit_info_table_find (domain, code);
4042                 g_assert (ji);
4043         }
4044         g_assert (code);
4045
4046         insert_breakpoint (seq_points, domain, ji, bp, error);
4047 }
4048
4049 static void
4050 clear_breakpoint (MonoBreakpoint *bp);
4051
4052 /*
4053  * set_breakpoint:
4054  *
4055  *   Set a breakpoint at IL_OFFSET in METHOD.
4056  * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4057  * METHOD can also be a generic method definition, in which case a breakpoint
4058  * is placed in all instances of the method.
4059  * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4060  * inserted.
4061  */
4062 static MonoBreakpoint*
4063 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4064 {
4065         MonoBreakpoint *bp;
4066         GHashTableIter iter, iter2;
4067         MonoDomain *domain;
4068         MonoMethod *m;
4069         MonoSeqPointInfo *seq_points;
4070
4071         if (error)
4072                 mono_error_init (error);
4073
4074         // FIXME:
4075         // - suspend/resume the vm to prevent code patching problems
4076         // - multiple breakpoints on the same location
4077         // - dynamic methods
4078         // - races
4079
4080         bp = g_new0 (MonoBreakpoint, 1);
4081         bp->method = method;
4082         bp->il_offset = il_offset;
4083         bp->req = req;
4084         bp->children = g_ptr_array_new ();
4085
4086         DEBUG(1, fprintf (log_file, "[dbg] Setting %sbreakpoint at %s:0x%x.\n", (req->event_kind == EVENT_KIND_STEP) ? "single step " : "", method ? mono_method_full_name (method, TRUE) : "<all>", (int)il_offset));
4087
4088         mono_loader_lock ();
4089
4090         g_hash_table_iter_init (&iter, domains);
4091         while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4092                 mono_domain_lock (domain);
4093
4094                 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4095                 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4096                         if (bp_matches_method (bp, m))
4097                                 set_bp_in_method (domain, m, seq_points, bp, error);
4098                 }
4099
4100                 mono_domain_unlock (domain);
4101         }
4102
4103         mono_loader_unlock ();
4104
4105         mono_loader_lock ();
4106         g_ptr_array_add (breakpoints, bp);
4107         mono_loader_unlock ();
4108
4109         if (error && !mono_error_ok (error)) {
4110                 clear_breakpoint (bp);
4111                 return NULL;
4112         }
4113
4114         return bp;
4115 }
4116
4117 static void
4118 clear_breakpoint (MonoBreakpoint *bp)
4119 {
4120         int i;
4121
4122         // FIXME: locking, races
4123         for (i = 0; i < bp->children->len; ++i) {
4124                 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4125
4126                 remove_breakpoint (inst);
4127
4128                 g_free (inst);
4129         }
4130
4131         mono_loader_lock ();
4132         g_ptr_array_remove (breakpoints, bp);
4133         mono_loader_unlock ();
4134
4135         g_ptr_array_free (bp->children, TRUE);
4136         g_free (bp);
4137 }
4138
4139 static void
4140 breakpoints_cleanup (void)
4141 {
4142         int i;
4143
4144         mono_loader_lock ();
4145         i = 0;
4146         while (i < event_requests->len) {
4147                 EventRequest *req = g_ptr_array_index (event_requests, i);
4148
4149                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4150                         clear_breakpoint (req->info);
4151                         g_ptr_array_remove_index_fast (event_requests, i);
4152                         g_free (req);
4153                 } else {
4154                         i ++;
4155                 }
4156         }
4157
4158         for (i = 0; i < breakpoints->len; ++i)
4159                 g_free (g_ptr_array_index (breakpoints, i));
4160
4161         g_ptr_array_free (breakpoints, TRUE);
4162         g_hash_table_destroy (bp_locs);
4163
4164         breakpoints = NULL;
4165         bp_locs = NULL;
4166
4167         mono_loader_unlock ();
4168 }
4169
4170 /*
4171  * clear_breakpoints_for_domain:
4172  *
4173  *   Clear breakpoint instances which reference DOMAIN.
4174  */
4175 static void
4176 clear_breakpoints_for_domain (MonoDomain *domain)
4177 {
4178         int i, j;
4179
4180         /* This could be called after shutdown */
4181         if (!breakpoints)
4182                 return;
4183
4184         mono_loader_lock ();
4185         for (i = 0; i < breakpoints->len; ++i) {
4186                 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4187
4188                 j = 0;
4189                 while (j < bp->children->len) {
4190                         BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4191
4192                         if (inst->domain == domain) {
4193                                 remove_breakpoint (inst);
4194
4195                                 g_free (inst);
4196
4197                                 g_ptr_array_remove_index_fast (bp->children, j);
4198                         } else {
4199                                 j ++;
4200                         }
4201                 }
4202         }
4203         mono_loader_unlock ();
4204 }
4205
4206 static gboolean
4207 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4208 {
4209         return bp->method && bp->method->klass->image->assembly == assembly;
4210 }
4211
4212 static void
4213 process_breakpoint_inner (DebuggerTlsData *tls)
4214 {
4215         MonoJitInfo *ji;
4216         guint8 *ip;
4217         int i, j, suspend_policy;
4218         guint32 native_offset;
4219         MonoBreakpoint *bp;
4220         BreakpointInstance *inst;
4221         GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4222         GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4223         EventKind kind = EVENT_KIND_BREAKPOINT;
4224         MonoContext *ctx = &tls->restore_ctx;
4225         MonoSeqPointInfo *info;
4226         SeqPoint *sp;
4227
4228         // FIXME: Speed this up
4229
4230         ip = MONO_CONTEXT_GET_IP (ctx);
4231         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4232         g_assert (ji);
4233         g_assert (ji->method);
4234
4235         /* Compute the native offset of the breakpoint from the ip */
4236         native_offset = ip - (guint8*)ji->code_start;   
4237
4238         /* 
4239          * Skip the instruction causing the breakpoint signal.
4240          */
4241         mono_arch_skip_breakpoint (ctx, ji);
4242
4243         if (ji->method->wrapper_type || tls->disable_breakpoints)
4244                 return;
4245
4246         bp_reqs = g_ptr_array_new ();
4247         ss_reqs = g_ptr_array_new ();
4248         ss_reqs_orig = g_ptr_array_new ();
4249
4250         DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
4251
4252         mono_loader_lock ();
4253
4254         /*
4255          * The ip points to the instruction causing the breakpoint event, which is after
4256          * the offset recorded in the seq point map, so find the prev seq point before ip.
4257          */
4258         sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4259
4260         bp = NULL;
4261         for (i = 0; i < breakpoints->len; ++i) {
4262                 bp = g_ptr_array_index (breakpoints, i);
4263
4264                 if (!bp->method)
4265                         continue;
4266
4267                 for (j = 0; j < bp->children->len; ++j) {
4268                         inst = g_ptr_array_index (bp->children, j);
4269                         if (inst->ji == ji && inst->sp == sp) {
4270                                 if (bp->req->event_kind == EVENT_KIND_STEP) {
4271                                         g_ptr_array_add (ss_reqs_orig, bp->req);
4272                                 } else {
4273                                         g_ptr_array_add (bp_reqs, bp->req);
4274                                 }
4275                         }
4276                 }
4277         }
4278         if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4279                 /* Maybe a method entry/exit event */
4280                 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4281                         kind = EVENT_KIND_METHOD_ENTRY;
4282                 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4283                         kind = EVENT_KIND_METHOD_EXIT;
4284         }
4285
4286         /* Process single step requests */
4287         for (i = 0; i < ss_reqs_orig->len; ++i) {
4288                 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4289                 SingleStepReq *ss_req = req->info;
4290                 gboolean hit = TRUE;
4291
4292                 if (ss_req->size == STEP_SIZE_LINE) {
4293                         /* Have to check whenever a different source line was reached */
4294                         MonoDebugMethodInfo *minfo;
4295                         MonoDebugSourceLocation *loc = NULL;
4296
4297                         minfo = mono_debug_lookup_method (ji->method);
4298
4299                         if (minfo)
4300                                 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4301
4302                         if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
4303                                 /* Have to continue single stepping */
4304                                 hit = FALSE;
4305                                 
4306                         if (loc) {
4307                                 ss_req->last_method = ji->method;
4308                                 ss_req->last_line = loc->row;
4309                                 mono_debug_free_source_location (loc);
4310                         }
4311                 }
4312
4313                 if (hit)
4314                         g_ptr_array_add (ss_reqs, req);
4315
4316                 /* Start single stepping again from the current sequence point */
4317                 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4318         }
4319         
4320         if (ss_reqs->len > 0)
4321                 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4322         if (bp_reqs->len > 0)
4323                 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4324         if (kind != EVENT_KIND_BREAKPOINT)
4325                 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4326
4327         mono_loader_unlock ();
4328
4329         g_ptr_array_free (bp_reqs, TRUE);
4330         g_ptr_array_free (ss_reqs, TRUE);
4331
4332         /* 
4333          * FIXME: The first event will suspend, so the second will only be sent after the
4334          * resume.
4335          */
4336         if (ss_events)
4337                 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4338         if (bp_events)
4339                 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4340         if (enter_leave_events)
4341                 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4342 }
4343
4344 /* Process a breakpoint/single step event after resuming from a signal handler */
4345 static void
4346 process_signal_event (void (*func) (DebuggerTlsData*))
4347 {
4348         DebuggerTlsData *tls;
4349         MonoContext orig_restore_ctx, ctx;
4350         static void (*restore_context) (void *);
4351
4352         if (!restore_context)
4353                 restore_context = mono_get_restore_context ();
4354
4355         tls = mono_native_tls_get_value (debugger_tls_id);
4356         /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4357         memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4358         memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4359
4360         func (tls);
4361
4362         /* This is called when resuming from a signal handler, so it shouldn't return */
4363         memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4364         memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4365         restore_context (&ctx);
4366         g_assert_not_reached ();
4367 }
4368
4369 static void
4370 process_breakpoint (void)
4371 {
4372         process_signal_event (process_breakpoint_inner);
4373 }
4374
4375 static void
4376 resume_from_signal_handler (void *sigctx, void *func)
4377 {
4378         DebuggerTlsData *tls;
4379         MonoContext ctx;
4380
4381         /* Save the original context in TLS */
4382         // FIXME: This might not work on an altstack ?
4383         tls = mono_native_tls_get_value (debugger_tls_id);
4384         g_assert (tls);
4385
4386         // FIXME: MonoContext usually doesn't include the fp registers, so these are 
4387         // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4388         // clob:c could be added to op_seq_point.
4389
4390         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4391         memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4392 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4393         mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4394 #else
4395         MONO_CONTEXT_SET_IP (&ctx, func);
4396 #endif
4397         mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4398
4399 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4400         mono_ppc_set_func_into_sigctx (sigctx, func);
4401 #endif
4402 }
4403
4404 void
4405 mono_debugger_agent_breakpoint_hit (void *sigctx)
4406 {
4407         /*
4408          * We are called from a signal handler, and running code there causes all kinds of
4409          * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4410          * So set up the signal context to return to the real breakpoint handler function.
4411          */
4412
4413         resume_from_signal_handler (sigctx, process_breakpoint);
4414 }
4415
4416 static gboolean
4417 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4418 {
4419         if (frame->managed) {
4420                 *(MonoContext*)data = *ctx;
4421
4422                 return TRUE;
4423         } else {
4424                 return FALSE;
4425         }
4426 }
4427
4428 /*
4429  * Called by System.Diagnostics.Debugger:Break ().
4430  */
4431 void
4432 mono_debugger_agent_user_break (void)
4433 {
4434         if (agent_config.enabled) {
4435                 MonoContext ctx;
4436                 int suspend_policy;
4437                 GSList *events;
4438
4439                 /* Obtain a context */
4440                 MONO_CONTEXT_SET_IP (&ctx, NULL);
4441                 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4442                 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4443
4444                 mono_loader_lock ();
4445                 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4446                 mono_loader_unlock ();
4447
4448                 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4449         } else {
4450                 G_BREAKPOINT ();
4451         }
4452 }
4453
4454 static const char*
4455 ss_depth_to_string (StepDepth depth)
4456 {
4457         switch (depth) {
4458         case STEP_DEPTH_OVER:
4459                 return "over";
4460         case STEP_DEPTH_OUT:
4461                 return "out";
4462         case STEP_DEPTH_INTO:
4463                 return "into";
4464         default:
4465                 g_assert_not_reached ();
4466                 return NULL;
4467         }
4468 }
4469
4470 static void
4471 process_single_step_inner (DebuggerTlsData *tls)
4472 {
4473         MonoJitInfo *ji;
4474         guint8 *ip;
4475         GPtrArray *reqs;
4476         int il_offset, suspend_policy;
4477         MonoDomain *domain;
4478         GSList *events;
4479         MonoContext *ctx = &tls->restore_ctx;
4480         SeqPoint *sp;
4481         MonoSeqPointInfo *info;
4482
4483         ip = MONO_CONTEXT_GET_IP (ctx);
4484
4485         /* Skip the instruction causing the single step */
4486         mono_arch_skip_single_step (ctx);
4487
4488         if (suspend_count > 0) {
4489                 process_suspend (tls, ctx);
4490                 return;
4491         }
4492
4493         if (!ss_req)
4494                 // FIXME: A suspend race
4495                 return;
4496
4497         if (mono_thread_internal_current () != ss_req->thread)
4498                 return;
4499
4500         if (log_level > 0) {
4501                 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4502
4503                 DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_depth_to_string (ss_req->depth), mono_method_full_name (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4504         }
4505
4506         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4507         g_assert (ji);
4508         g_assert (ji->method);
4509
4510         if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4511                 return;
4512
4513         /* 
4514          * FIXME: 
4515          * Stopping in memset makes half-initialized vtypes visible.
4516          * Stopping in memcpy makes half-copied vtypes visible.
4517          */
4518         if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4519                 return;
4520
4521         /*
4522          * The ip points to the instruction causing the single step event, which is before
4523          * the offset recorded in the seq point map, so find the next seq point after ip.
4524          */
4525         sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4526         if (!sp)
4527                 return;
4528         il_offset = sp->il_offset;
4529
4530         // FIXME: No tests fail if this is disabled
4531 #if 0
4532         if (ss_req->size == STEP_SIZE_LINE) {
4533                 // FIXME:
4534                 NOT_IMPLEMENTED;
4535
4536                 /* Step until a different source line is reached */
4537                 MonoDebugMethodInfo *minfo;
4538
4539                 minfo = mono_debug_lookup_method (ji->method);
4540
4541                 if (minfo) {
4542                         MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4543
4544                         if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4545                                 mono_debug_free_source_location (loc);
4546                                 return;
4547                         }
4548                         if (!loc)
4549                                 /*
4550                                  * Step until we reach a location with line number info, 
4551                                  * otherwise the client can't show a location.
4552                                  * This can happen for example with statics initialized inline
4553                                  * outside of a cctor.
4554                                  */
4555                                 return;
4556
4557                         if (loc) {
4558                                 ss_req->last_method = ji->method;
4559                                 ss_req->last_line = loc->row;
4560                                 mono_debug_free_source_location (loc);
4561                         }
4562                 }
4563         }
4564 #endif
4565
4566         /* Start single stepping again from the current sequence point */
4567         ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4568
4569         // FIXME: Has to lock earlier
4570
4571         reqs = g_ptr_array_new ();
4572
4573         mono_loader_lock ();
4574
4575         g_ptr_array_add (reqs, ss_req->req);
4576
4577         events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4578
4579         g_ptr_array_free (reqs, TRUE);
4580
4581         mono_loader_unlock ();
4582
4583         process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4584 }
4585
4586 static void
4587 process_single_step (void)
4588 {
4589         process_signal_event (process_single_step_inner);
4590 }
4591
4592 /*
4593  * mono_debugger_agent_single_step_event:
4594  *
4595  *   Called from a signal handler to handle a single step event.
4596  */
4597 void
4598 mono_debugger_agent_single_step_event (void *sigctx)
4599 {
4600         /* Resume to process_single_step through the signal context */
4601
4602         // FIXME: Since step out/over is implemented using step in, the step in case should
4603         // be as fast as possible. Move the relevant code from process_single_step_inner ()
4604         // here
4605
4606         if (GetCurrentThreadId () == debugger_thread_id) {
4607                 /* 
4608                  * This could happen despite our best effors when the runtime calls 
4609                  * assembly/type resolve hooks.
4610                  * FIXME: Breakpoints too.
4611                  */
4612                 MonoContext ctx;
4613
4614                 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4615                 mono_arch_skip_single_step (&ctx);
4616                 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4617                 return;
4618         }
4619
4620         resume_from_signal_handler (sigctx, process_single_step);
4621 }
4622
4623 void
4624 debugger_agent_single_step_from_context (MonoContext *ctx)
4625 {
4626         DebuggerTlsData *tls;
4627         MonoContext orig_restore_ctx;
4628
4629         tls = mono_native_tls_get_value (debugger_tls_id);
4630         g_assert (tls);
4631
4632         /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4633         memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4634         memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4635
4636         process_single_step_inner (tls);
4637
4638         memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4639         memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4640 }
4641
4642 void
4643 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4644 {
4645         DebuggerTlsData *tls;
4646         MonoContext orig_restore_ctx;
4647
4648         tls = mono_native_tls_get_value (debugger_tls_id);
4649         g_assert (tls);
4650         memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4651         memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4652
4653         process_breakpoint_inner (tls);
4654
4655         memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4656         memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4657 }
4658
4659 /*
4660  * start_single_stepping:
4661  *
4662  *   Turn on single stepping. Can be called multiple times, for example,
4663  * by a single step event request + a suspend.
4664  */
4665 static void
4666 start_single_stepping (void)
4667 {
4668 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4669         int val = InterlockedIncrement (&ss_count);
4670
4671         if (val == 1)
4672                 mono_arch_start_single_stepping ();
4673
4674         if (ss_req != NULL && ss_invoke_addr == NULL) {
4675                 DebuggerTlsData *tls;
4676         
4677                 mono_loader_lock ();
4678         
4679                 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4680                 ss_invoke_addr = tls->invoke_addr;
4681                 
4682                 mono_loader_unlock ();
4683         }
4684 #else
4685         g_assert_not_reached ();
4686 #endif
4687 }
4688
4689 static void
4690 stop_single_stepping (void)
4691 {
4692 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4693         int val = InterlockedDecrement (&ss_count);
4694
4695         if (val == 0)
4696                 mono_arch_stop_single_stepping ();
4697 #else
4698         g_assert_not_reached ();
4699 #endif
4700 }
4701
4702 /*
4703  * ss_stop:
4704  *
4705  *   Stop the single stepping operation given by SS_REQ.
4706  */
4707 static void
4708 ss_stop (SingleStepReq *ss_req)
4709 {
4710         if (ss_req->bps) {
4711                 GSList *l;
4712
4713                 for (l = ss_req->bps; l; l = l->next) {
4714                         clear_breakpoint (l->data);
4715                 }
4716                 g_slist_free (ss_req->bps);
4717                 ss_req->bps = NULL;
4718         }
4719
4720         if (ss_req->global) {
4721                 stop_single_stepping ();
4722                 ss_req->global = FALSE;
4723         }
4724 }
4725
4726 /*
4727  * ss_start:
4728  *
4729  *   Start the single stepping operation given by SS_REQ from the sequence point SP.
4730  * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4731  * belong to the same thread as CTX.
4732  */
4733 static void
4734 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4735 {
4736         int i, frame_index;
4737         SeqPoint *next_sp;
4738         MonoBreakpoint *bp;
4739         gboolean enable_global = FALSE;
4740
4741         /* Stop the previous operation */
4742         ss_stop (ss_req);
4743
4744         /*
4745          * Implement single stepping using breakpoints if possible.
4746          */
4747         if (step_to_catch) {
4748                 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4749                 ss_req->bps = g_slist_append (ss_req->bps, bp);
4750         } else {
4751                 frame_index = 1;
4752
4753                 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT) && ctx) {
4754                         /* Need parent frames */
4755                         if (!tls->context.valid)
4756                                 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4757                         compute_frame_info (tls->thread, tls);
4758                 }
4759
4760                 /*
4761                  * Find the first sequence point in the current or in a previous frame which
4762                  * is not the last in its method.
4763                  */
4764                 if (ss_req->depth == STEP_DEPTH_OUT) {
4765                         /* Ignore seq points in current method */
4766                         while (frame_index < tls->frame_count) {
4767                                 StackFrame *frame = tls->frames [frame_index];
4768
4769                                 method = frame->method;
4770                                 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4771                                 frame_index ++;
4772                                 if (sp && sp->next_len != 0)
4773                                         break;
4774                         }
4775                 } else {
4776                         while (sp && sp->next_len == 0) {
4777                                 sp = NULL;
4778                                 if (frame_index < tls->frame_count) {
4779                                         StackFrame *frame = tls->frames [frame_index];
4780
4781                                         method = frame->method;
4782                                         sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4783                                         frame_index ++;
4784                                 }
4785                         }
4786                 }
4787
4788                 if (sp && sp->next_len > 0) {
4789                         for (i = 0; i < sp->next_len; ++i) {
4790                                 next_sp = &info->seq_points [sp->next [i]];
4791
4792                                 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4793                                 ss_req->bps = g_slist_append (ss_req->bps, bp);
4794                         }
4795                 }
4796
4797                 if (ss_req->depth == STEP_DEPTH_INTO) {
4798                         /* Enable global stepping so we stop at method entry too */
4799                         enable_global = TRUE;
4800                 }
4801
4802                 /*
4803                  * The ctx/frame info computed above will become invalid when we continue.
4804                  */
4805                 tls->context.valid = FALSE;
4806                 tls->async_state.valid = FALSE;
4807                 invalidate_frames (tls);
4808         }
4809
4810         if (enable_global) {
4811                 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4812                 ss_req->global = TRUE;
4813                 start_single_stepping ();
4814         } else if (!ss_req->bps) {
4815                 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4816                 ss_req->global = TRUE;
4817                 start_single_stepping ();
4818         } else {
4819                 ss_req->global = FALSE;
4820         }
4821 }
4822
4823 /*
4824  * Start single stepping of thread THREAD
4825  */
4826 static ErrorCode
4827 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4828 {
4829         DebuggerTlsData *tls;
4830         MonoSeqPointInfo *info = NULL;
4831         SeqPoint *sp = NULL;
4832         MonoMethod *method = NULL;
4833         MonoDebugMethodInfo *minfo;
4834         gboolean step_to_catch = FALSE;
4835
4836         if (suspend_count == 0)
4837                 return ERR_NOT_SUSPENDED;
4838
4839         wait_for_suspend ();
4840
4841         // FIXME: Multiple requests
4842         if (ss_req) {
4843                 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4844                 return ERR_NOT_IMPLEMENTED;
4845         }
4846
4847         DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4848
4849         ss_req = g_new0 (SingleStepReq, 1);
4850         ss_req->req = req;
4851         ss_req->thread = thread;
4852         ss_req->size = size;
4853         ss_req->depth = depth;
4854         req->info = ss_req;
4855
4856         mono_loader_lock ();
4857         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4858         mono_loader_unlock ();
4859         g_assert (tls);
4860         g_assert (tls->context.valid);
4861         ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4862
4863         if (tls->has_catch_ctx) {
4864                 gboolean res;
4865                 StackFrameInfo frame;
4866                 MonoContext new_ctx;
4867                 MonoLMF *lmf = NULL;
4868
4869                 /*
4870                  * We are stopped at a throw site. Stepping should go to the catch site.
4871                  */
4872
4873                 /* Find the the jit info for the catch context */
4874                 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4875                 g_assert (res);
4876                 g_assert (frame.type == FRAME_TYPE_MANAGED);
4877
4878                 /*
4879                  * Find the seq point corresponding to the landing site ip, which is the first seq
4880                  * point after ip.
4881                  */
4882                 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4883                 g_assert (sp);
4884
4885                 method = frame.method;
4886
4887                 step_to_catch = TRUE;
4888                 /* This make sure the seq point is not skipped by process_single_step () */
4889                 ss_req->last_sp = NULL;
4890         }
4891
4892         if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4893                 StackFrame *frame;
4894
4895                 /* Compute the initial line info */
4896                 compute_frame_info (thread, tls);
4897
4898                 if (tls->frame_count) {
4899                         frame = tls->frames [0];
4900
4901                         ss_req->last_method = frame->method;
4902                         ss_req->last_line = -1;
4903
4904                         minfo = mono_debug_lookup_method (frame->method);
4905                         if (minfo && frame->il_offset != -1) {
4906                                 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4907
4908                                 if (loc) {
4909                                         ss_req->last_line = loc->row;
4910                                         g_free (loc);
4911                                 }
4912                         }
4913                 }
4914         }
4915
4916         if (!step_to_catch) {
4917                 StackFrame *frame;
4918
4919                 compute_frame_info (thread, tls);
4920
4921                 if (tls->frame_count) {
4922                         frame = tls->frames [0];
4923
4924                         if (!method && frame->il_offset != -1) {
4925                                 /* FIXME: Sort the table and use a binary search */
4926                                 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4927                                 g_assert (sp);
4928                                 method = frame->method;
4929                         }
4930                 }
4931         }
4932
4933         ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
4934
4935         return 0;
4936 }
4937
4938 static void
4939 ss_destroy (SingleStepReq *req)
4940 {
4941         // FIXME: Locking
4942         g_assert (ss_req == req);
4943
4944         ss_stop (ss_req);
4945
4946         g_free (ss_req);
4947         ss_req = NULL;
4948 }
4949
4950 /*
4951  * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
4952  */
4953 void
4954 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
4955 {
4956         int suspend_policy;
4957         GSList *events;
4958         EventInfo ei;
4959
4960         if (!agent_config.enabled)
4961                 return;
4962
4963         mono_loader_lock ();
4964         events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
4965         mono_loader_unlock ();
4966
4967         ei.level = level;
4968         ei.category = category ? mono_string_to_utf8 (category) : NULL;
4969         ei.message = message ? mono_string_to_utf8 (message) : NULL;
4970
4971         process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
4972
4973         g_free (ei.category);
4974         g_free (ei.message);
4975 }
4976
4977 gboolean
4978 mono_debugger_agent_debug_log_is_enabled (void)
4979 {
4980         /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
4981         return agent_config.enabled;
4982 }
4983
4984 void
4985 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx, 
4986                                       MonoContext *catch_ctx)
4987 {
4988         int suspend_policy;
4989         GSList *events;
4990         MonoJitInfo *ji;
4991         EventInfo ei;
4992         DebuggerTlsData *tls = NULL;
4993
4994         if (thread_to_tls != NULL) {
4995                 MonoInternalThread *thread = mono_thread_internal_current ();
4996
4997                 mono_loader_lock ();
4998                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4999                 mono_loader_unlock ();
5000
5001                 if (tls && tls->abort_requested)
5002                         return;
5003                 if (tls && tls->disable_breakpoints)
5004                         return;
5005         }
5006
5007         memset (&ei, 0, sizeof (EventInfo));
5008
5009         /* Just-In-Time debugging */
5010         if (!catch_ctx) {
5011                 if (agent_config.onuncaught && !inited) {
5012                         finish_agent_init (FALSE);
5013
5014                         /*
5015                          * Send an unsolicited EXCEPTION event with a dummy request id.
5016                          */
5017                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5018                         ei.exc = (MonoObject*)exc;
5019                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5020                         return;
5021                 }
5022         } else if (agent_config.onthrow && !inited) {
5023                 GSList *l;
5024                 gboolean found = FALSE;
5025
5026                 for (l = agent_config.onthrow; l; l = l->next) {
5027                         char *ex_type = l->data;
5028                         char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5029
5030                         if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5031                                 found = TRUE;
5032
5033                         g_free (f);
5034                 }
5035
5036                 if (found) {
5037                         finish_agent_init (FALSE);
5038
5039                         /*
5040                          * Send an unsolicited EXCEPTION event with a dummy request id.
5041                          */
5042                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5043                         ei.exc = (MonoObject*)exc;
5044                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5045                         return;
5046                 }
5047         }
5048
5049         if (!inited)
5050                 return;
5051
5052         ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5053
5054         ei.exc = (MonoObject*)exc;
5055         ei.caught = catch_ctx != NULL;
5056
5057         mono_loader_lock ();
5058         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5059         mono_loader_unlock ();
5060
5061         if (tls && catch_ctx) {
5062                 tls->catch_ctx = *catch_ctx;
5063                 tls->has_catch_ctx = TRUE;
5064         }
5065
5066         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5067
5068         if (tls)
5069                 tls->has_catch_ctx = FALSE;
5070 }
5071
5072 void
5073 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5074 {
5075         DebuggerTlsData *tls;
5076
5077         if (!inited)
5078                 return;
5079
5080         tls = mono_native_tls_get_value (debugger_tls_id);
5081         if (!tls)
5082                 return;
5083
5084         /*
5085          * We're about to invoke an exception filter during the first pass of exception handling.
5086          *
5087          * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5088          * 'orig_ctx' is the context where the exception has been thrown.
5089          *
5090          *
5091          * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5092          *
5093          * If we're stopped in Filter(), normal stack unwinding would first unwind to
5094          * the call site (line 37) and then continue to Main(), but it would never
5095          * include the throw site (line 32).
5096          *
5097          * Since exception filters are invoked during the first pass of exception handling,
5098          * the stack frames of the throw site are still intact, so we should include them
5099          * in a stack trace.
5100          *
5101          * We do this here by saving the context of the throw site in 'tls->filter_state'.
5102          *
5103          * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5104          * but report the location of the 'throw' to the user.
5105          *
5106          */
5107
5108         g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5109 }
5110
5111 void
5112 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5113 {
5114         DebuggerTlsData *tls;
5115
5116         if (!inited)
5117                 return;
5118
5119         tls = mono_native_tls_get_value (debugger_tls_id);
5120         if (!tls)
5121                 return;
5122
5123         tls->filter_state.valid = FALSE;
5124 }
5125
5126 /*
5127  * buffer_add_value_full:
5128  *
5129  *   Add the encoding of the value at ADDR described by T to the buffer.
5130  * AS_VTYPE determines whenever to treat primitive types as primitive types or
5131  * vtypes.
5132  */
5133 static void
5134 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5135                                            gboolean as_vtype)
5136 {
5137         MonoObject *obj;
5138
5139         if (t->byref) {
5140                 g_assert (*(void**)addr);
5141                 addr = *(void**)addr;
5142         }
5143
5144         if (as_vtype) {
5145                 switch (t->type) {
5146                 case MONO_TYPE_BOOLEAN:
5147                 case MONO_TYPE_I1:
5148                 case MONO_TYPE_U1:
5149                 case MONO_TYPE_CHAR:
5150                 case MONO_TYPE_I2:
5151                 case MONO_TYPE_U2:
5152                 case MONO_TYPE_I4:
5153                 case MONO_TYPE_U4:
5154                 case MONO_TYPE_R4:
5155                 case MONO_TYPE_I8:
5156                 case MONO_TYPE_U8:
5157                 case MONO_TYPE_R8:
5158                 case MONO_TYPE_I:
5159                 case MONO_TYPE_U:
5160                 case MONO_TYPE_PTR:
5161                         goto handle_vtype;
5162                         break;
5163                 default:
5164                         break;
5165                 }
5166         }
5167
5168         switch (t->type) {
5169         case MONO_TYPE_VOID:
5170                 buffer_add_byte (buf, t->type);
5171                 break;
5172         case MONO_TYPE_BOOLEAN:
5173         case MONO_TYPE_I1:
5174         case MONO_TYPE_U1:
5175                 buffer_add_byte (buf, t->type);
5176                 buffer_add_int (buf, *(gint8*)addr);
5177                 break;
5178         case MONO_TYPE_CHAR:
5179         case MONO_TYPE_I2:
5180         case MONO_TYPE_U2:
5181                 buffer_add_byte (buf, t->type);
5182                 buffer_add_int (buf, *(gint16*)addr);
5183                 break;
5184         case MONO_TYPE_I4:
5185         case MONO_TYPE_U4:
5186         case MONO_TYPE_R4:
5187                 buffer_add_byte (buf, t->type);
5188                 buffer_add_int (buf, *(gint32*)addr);
5189                 break;
5190         case MONO_TYPE_I8:
5191         case MONO_TYPE_U8:
5192         case MONO_TYPE_R8:
5193                 buffer_add_byte (buf, t->type);
5194                 buffer_add_long (buf, *(gint64*)addr);
5195                 break;
5196         case MONO_TYPE_I:
5197         case MONO_TYPE_U:
5198                 /* Treat it as a vtype */
5199                 goto handle_vtype;
5200         case MONO_TYPE_PTR: {
5201                 gssize val = *(gssize*)addr;
5202                 
5203                 buffer_add_byte (buf, t->type);
5204                 buffer_add_long (buf, val);
5205                 break;
5206         }
5207         handle_ref:
5208         case MONO_TYPE_STRING:
5209         case MONO_TYPE_SZARRAY:
5210         case MONO_TYPE_OBJECT:
5211         case MONO_TYPE_CLASS:
5212         case MONO_TYPE_ARRAY:
5213                 obj = *(MonoObject**)addr;
5214
5215                 if (!obj) {
5216                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5217                 } else {
5218                         if (obj->vtable->klass->valuetype) {
5219                                 t = &obj->vtable->klass->byval_arg;
5220                                 addr = mono_object_unbox (obj);
5221                                 goto handle_vtype;
5222                         } else if (obj->vtable->klass->rank) {
5223                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5224                         } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5225                                 buffer_add_byte (buf, MONO_TYPE_CLASS);
5226                         } else {
5227                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5228                         }
5229                         buffer_add_objid (buf, obj);
5230                 }
5231                 break;
5232         handle_vtype:
5233         case MONO_TYPE_VALUETYPE: {
5234                 int nfields;
5235                 gpointer iter;
5236                 MonoClassField *f;
5237                 MonoClass *klass = mono_class_from_mono_type (t);
5238
5239                 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5240                 buffer_add_byte (buf, klass->enumtype);
5241                 buffer_add_typeid (buf, domain, klass);
5242
5243                 nfields = 0;
5244                 iter = NULL;
5245                 while ((f = mono_class_get_fields (klass, &iter))) {
5246                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5247                                 continue;
5248                         if (mono_field_is_deleted (f))
5249                                 continue;
5250                         nfields ++;
5251                 }
5252                 buffer_add_int (buf, nfields);
5253
5254                 iter = NULL;
5255                 while ((f = mono_class_get_fields (klass, &iter))) {
5256                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5257                                 continue;
5258                         if (mono_field_is_deleted (f))
5259                                 continue;
5260                         buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5261                 }
5262                 break;
5263         }
5264         case MONO_TYPE_GENERICINST:
5265                 if (mono_type_generic_inst_is_valuetype (t)) {
5266                         goto handle_vtype;
5267                 } else {
5268                         goto handle_ref;
5269                 }
5270                 break;
5271         default:
5272                 NOT_IMPLEMENTED;
5273         }
5274 }
5275
5276 static void
5277 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5278 {
5279         buffer_add_value_full (buf, t, addr, domain, FALSE);
5280 }
5281
5282 static ErrorCode
5283 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5284 {
5285         int err;
5286         int type = decode_byte (buf, &buf, limit);
5287
5288         if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5289                 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5290                 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5291                 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5292                 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5293                 char *name = mono_type_full_name (t);
5294                 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5295                 g_free (name);
5296                 return ERR_INVALID_ARGUMENT;
5297         }
5298
5299         switch (t->type) {
5300         case MONO_TYPE_BOOLEAN:
5301                 *(guint8*)addr = decode_int (buf, &buf, limit);
5302                 break;
5303         case MONO_TYPE_CHAR:
5304                 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5305                 break;
5306         case MONO_TYPE_I1:
5307                 *(gint8*)addr = decode_int (buf, &buf, limit);
5308                 break;
5309         case MONO_TYPE_U1:
5310                 *(guint8*)addr = decode_int (buf, &buf, limit);
5311                 break;
5312         case MONO_TYPE_I2:
5313                 *(gint16*)addr = decode_int (buf, &buf, limit);
5314                 break;
5315         case MONO_TYPE_U2:
5316                 *(guint16*)addr = decode_int (buf, &buf, limit);
5317                 break;
5318         case MONO_TYPE_I4:
5319                 *(gint32*)addr = decode_int (buf, &buf, limit);
5320                 break;
5321         case MONO_TYPE_U4:
5322                 *(guint32*)addr = decode_int (buf, &buf, limit);
5323                 break;
5324         case MONO_TYPE_I8:
5325                 *(gint64*)addr = decode_long (buf, &buf, limit);
5326                 break;
5327         case MONO_TYPE_U8:
5328                 *(guint64*)addr = decode_long (buf, &buf, limit);
5329                 break;
5330         case MONO_TYPE_R4:
5331                 *(guint32*)addr = decode_int (buf, &buf, limit);
5332                 break;
5333         case MONO_TYPE_R8:
5334                 *(guint64*)addr = decode_long (buf, &buf, limit);
5335                 break;
5336         case MONO_TYPE_PTR:
5337                 /* We send these as I8, so we get them back as such */
5338                 g_assert (type == MONO_TYPE_I8);
5339                 *(gssize*)addr = decode_long (buf, &buf, limit);
5340                 break;
5341         case MONO_TYPE_GENERICINST:
5342                 if (MONO_TYPE_ISSTRUCT (t)) {
5343                         /* The client sends these as a valuetype */
5344                         goto handle_vtype;
5345                 } else {
5346                         goto handle_ref;
5347                 }
5348                 break;
5349         case MONO_TYPE_I:
5350         case MONO_TYPE_U:
5351                 /* We send these as vtypes, so we get them back as such */
5352                 g_assert (type == MONO_TYPE_VALUETYPE);
5353                 /* Fall through */
5354                 handle_vtype:
5355         case MONO_TYPE_VALUETYPE: {
5356                 gboolean is_enum = decode_byte (buf, &buf, limit);
5357                 MonoClass *klass;
5358                 MonoClassField *f;
5359                 int nfields;
5360                 gpointer iter = NULL;
5361                 MonoDomain *d;
5362
5363                 /* Enums are sent as a normal vtype */
5364                 if (is_enum)
5365                         return ERR_NOT_IMPLEMENTED;
5366                 klass = decode_typeid (buf, &buf, limit, &d, &err);
5367                 if (err)
5368                         return err;
5369
5370                 if (klass != mono_class_from_mono_type (t))
5371                         return ERR_INVALID_ARGUMENT;
5372
5373                 nfields = decode_int (buf, &buf, limit);
5374                 while ((f = mono_class_get_fields (klass, &iter))) {
5375                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5376                                 continue;
5377                         if (mono_field_is_deleted (f))
5378                                 continue;
5379                         err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5380                         if (err)
5381                                 return err;
5382                         nfields --;
5383                 }
5384                 g_assert (nfields == 0);
5385                 break;
5386         }
5387         handle_ref:
5388         default:
5389                 if (MONO_TYPE_IS_REFERENCE (t)) {
5390                         if (type == MONO_TYPE_OBJECT) {
5391                                 int objid = decode_objid (buf, &buf, limit);
5392                                 int err;
5393                                 MonoObject *obj;
5394
5395                                 err = get_object (objid, (MonoObject**)&obj);
5396                                 if (err)
5397                                         return err;
5398
5399                                 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
5400                                         return ERR_INVALID_ARGUMENT;
5401                                 if (obj && obj->vtable->domain != domain)
5402                                         return ERR_INVALID_ARGUMENT;
5403
5404                                 mono_gc_wbarrier_generic_store (addr, obj);
5405                         } else if (type == VALUE_TYPE_ID_NULL) {
5406                                 *(MonoObject**)addr = NULL;
5407                         } else {
5408                                 return ERR_INVALID_ARGUMENT;
5409                         }
5410                 } else {
5411                         NOT_IMPLEMENTED;
5412                 }
5413                 break;
5414         }
5415
5416         *endbuf = buf;
5417
5418         return 0;
5419 }
5420
5421 static void
5422 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5423 {
5424         guint32 flags;
5425         int reg;
5426         guint8 *addr;
5427         mgreg_t reg_val;
5428
5429         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5430         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5431
5432         switch (flags) {
5433         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5434                 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5435
5436                 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype);
5437                 break;
5438         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5439                 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5440                 addr += (gint32)var->offset;
5441
5442                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5443
5444                 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5445                 break;
5446         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5447                 NOT_IMPLEMENTED;
5448                 break;
5449         default:
5450                 g_assert_not_reached ();
5451         }
5452 }
5453
5454 static void
5455 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5456 {
5457         guint32 flags;
5458         int reg, size;
5459         guint8 *addr;
5460
5461         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5462         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5463
5464         if (MONO_TYPE_IS_REFERENCE (t))
5465                 size = sizeof (gpointer);
5466         else
5467                 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5468
5469         switch (flags) {
5470         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5471 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5472                 mgreg_t v;
5473                 gboolean is_signed = FALSE;
5474
5475                 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5476                         is_signed = TRUE;
5477
5478                 switch (size) {
5479                 case 1:
5480                         v = is_signed ? *(gint8*)val : *(guint8*)val;
5481                         break;
5482                 case 2:
5483                         v = is_signed ? *(gint16*)val : *(guint16*)val;
5484                         break;
5485                 case 4:
5486                         v = is_signed ? *(gint32*)val : *(guint32*)val;
5487                         break;
5488                 case 8:
5489                         v = is_signed ? *(gint64*)val : *(guint64*)val;
5490                         break;
5491                 default:
5492                         g_assert_not_reached ();
5493                 }
5494
5495                 /* Set value on the stack or in the return ctx */
5496                 if (reg_locations [reg]) {
5497                         /* Saved on the stack */
5498                         DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5499                         *(reg_locations [reg]) = v;
5500                 } else {
5501                         /* Not saved yet */
5502                         DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5503                         mono_arch_context_set_int_reg (restore_ctx, reg, v);
5504                 }                       
5505
5506                 // FIXME: Move these to mono-context.h/c.
5507                 mono_arch_context_set_int_reg (ctx, reg, v);
5508 #else
5509                 // FIXME: Can't set registers, so we disable linears
5510                 NOT_IMPLEMENTED;
5511 #endif
5512                 break;
5513         }
5514         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5515                 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5516                 addr += (gint32)var->offset;
5517
5518                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5519
5520                 // FIXME: Write barriers
5521                 memcpy (addr, val, size);
5522                 break;
5523         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5524                 NOT_IMPLEMENTED;
5525                 break;
5526         default:
5527                 g_assert_not_reached ();
5528         }
5529 }
5530
5531 static void
5532 clear_event_request (int req_id, int etype)
5533 {
5534         int i;
5535
5536         mono_loader_lock ();
5537         for (i = 0; i < event_requests->len; ++i) {
5538                 EventRequest *req = g_ptr_array_index (event_requests, i);
5539
5540                 if (req->id == req_id && req->event_kind == etype) {
5541                         if (req->event_kind == EVENT_KIND_BREAKPOINT)
5542                                 clear_breakpoint (req->info);
5543                         if (req->event_kind == EVENT_KIND_STEP)
5544                                 ss_destroy (req->info);
5545                         if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5546                                 clear_breakpoint (req->info);
5547                         if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5548                                 clear_breakpoint (req->info);
5549                         g_ptr_array_remove_index_fast (event_requests, i);
5550                         g_free (req);
5551                         break;
5552                 }
5553         }
5554         mono_loader_unlock ();
5555 }
5556
5557 static gboolean
5558 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5559 {
5560         if (req->event_kind == EVENT_KIND_BREAKPOINT)
5561                 return breakpoint_matches_assembly (req->info, assembly);
5562         else {
5563                 int i, j;
5564
5565                 for (i = 0; i < req->nmodifiers; ++i) {
5566                         Modifier *m = &req->modifiers [i];
5567
5568                         if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5569                                 return TRUE;
5570                         if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5571                                 for (j = 0; m->data.assemblies [j]; ++j)
5572                                         if (m->data.assemblies [j] == assembly)
5573                                                 return TRUE;
5574                         }
5575                 }
5576         }
5577
5578         return FALSE;
5579 }
5580
5581 /*
5582  * clear_event_requests_for_assembly:
5583  *
5584  *   Clear all events requests which reference ASSEMBLY.
5585  */
5586 static void
5587 clear_event_requests_for_assembly (MonoAssembly *assembly)
5588 {
5589         int i;
5590         gboolean found;
5591
5592         mono_loader_lock ();
5593         found = TRUE;
5594         while (found) {
5595                 found = FALSE;
5596                 for (i = 0; i < event_requests->len; ++i) {
5597                         EventRequest *req = g_ptr_array_index (event_requests, i);
5598
5599                         if (event_req_matches_assembly (req, assembly)) {
5600                                 clear_event_request (req->id, req->event_kind);
5601                                 found = TRUE;
5602                                 break;
5603                         }
5604                 }
5605         }
5606         mono_loader_unlock ();
5607 }
5608
5609 /*
5610  * type_comes_from_assembly:
5611  *
5612  *   GHRFunc that returns TRUE if klass comes from assembly
5613  */
5614 static gboolean
5615 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5616 {
5617         return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5618 }
5619
5620 /*
5621  * clear_types_for_assembly:
5622  *
5623  *   Clears types from loaded_classes for a given assembly
5624  */
5625 static void
5626 clear_types_for_assembly (MonoAssembly *assembly)
5627 {
5628         MonoDomain *domain = mono_domain_get ();
5629         AgentDomainInfo *info = NULL;
5630
5631         mono_loader_lock ();
5632         info = get_agent_domain_info (domain);
5633         g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5634         mono_loader_unlock ();
5635 }
5636
5637 static void
5638 add_thread (gpointer key, gpointer value, gpointer user_data)
5639 {
5640         MonoInternalThread *thread = value;
5641         Buffer *buf = user_data;
5642
5643         buffer_add_objid (buf, (MonoObject*)thread);
5644 }
5645
5646 static ErrorCode
5647 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5648 {
5649         guint8 *p = invoke->p;
5650         guint8 *end = invoke->endp;
5651         MonoMethod *m;
5652         int i, err, nargs;
5653         MonoMethodSignature *sig;
5654         guint8 **arg_buf;
5655         void **args;
5656         MonoObject *this, *res, *exc;
5657         MonoDomain *domain;
5658         guint8 *this_buf;
5659 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5660         MonoLMFExt ext;
5661 #endif
5662         MonoStopwatch watch;
5663
5664         if (invoke->method) {
5665                 /* 
5666                  * Invoke this method directly, currently only Environment.Exit () is supported.
5667                  */
5668                 this = NULL;
5669                 DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this ? this->vtable->klass->name : "<null>"));
5670                 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5671                 g_assert_not_reached ();
5672         }
5673
5674         m = decode_methodid (p, &p, end, &domain, &err);
5675         if (err)
5676                 return err;
5677         sig = mono_method_signature (m);
5678
5679         if (m->klass->valuetype)
5680                 this_buf = g_alloca (mono_class_instance_size (m->klass));
5681         else
5682                 this_buf = g_alloca (sizeof (MonoObject*));
5683         if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5684                 /* Should be null */
5685                 int type = decode_byte (p, &p, end);
5686                 if (type != VALUE_TYPE_ID_NULL)
5687                         return ERR_INVALID_ARGUMENT;
5688                 memset (this_buf, 0, mono_class_instance_size (m->klass));
5689         } else {
5690                 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5691                 if (err)
5692                         return err;
5693         }
5694
5695         if (!m->klass->valuetype)
5696                 this = *(MonoObject**)this_buf;
5697         else
5698                 this = NULL;
5699
5700         DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this ? this->vtable->klass->name : "<null>"));
5701
5702         if (this && this->vtable->domain != domain)
5703                 NOT_IMPLEMENTED;
5704
5705         if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5706                 if (!strcmp (m->name, ".ctor")) {
5707                         if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5708                                 return ERR_INVALID_ARGUMENT;
5709                         else
5710                                 this = mono_object_new (domain, m->klass);
5711                 } else {
5712                         return ERR_INVALID_ARGUMENT;
5713                 }
5714         }
5715
5716         if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5717                 return ERR_INVALID_ARGUMENT;
5718
5719         nargs = decode_int (p, &p, end);
5720         if (nargs != sig->param_count)
5721                 return ERR_INVALID_ARGUMENT;
5722         /* Use alloca to get gc tracking */
5723         arg_buf = g_alloca (nargs * sizeof (gpointer));
5724         memset (arg_buf, 0, nargs * sizeof (gpointer));
5725         args = g_alloca (nargs * sizeof (gpointer));
5726         for (i = 0; i < nargs; ++i) {
5727                 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5728                         err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5729                         if (err)
5730                                 break;
5731
5732                         if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5733                                 NOT_IMPLEMENTED;
5734                 } else {
5735                         arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5736                         err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5737                         if (err)
5738                                 break;
5739                         args [i] = arg_buf [i];
5740                 }
5741         }
5742
5743         if (i < nargs)
5744                 return err;
5745
5746         if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5747                 tls->disable_breakpoints = TRUE;
5748         else
5749                 tls->disable_breakpoints = FALSE;
5750
5751         /* 
5752          * Add an LMF frame to link the stack frames on the invoke method with our caller.
5753          */
5754         /* FIXME: Move this to arch specific code */
5755 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5756         if (invoke->has_ctx) {
5757                 MonoLMF **lmf_addr;
5758
5759                 lmf_addr = mono_get_lmf_addr ();
5760
5761                 /* Setup our lmf */
5762                 memset (&ext, 0, sizeof (ext));
5763 #ifdef TARGET_AMD64
5764                 ext.lmf.previous_lmf = *(lmf_addr);
5765                 /* Mark that this is a MonoLMFExt */
5766                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5767                 ext.lmf.rsp = (gssize)&ext;
5768 #elif defined(TARGET_X86)
5769                 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5770                 /* Mark that this is a MonoLMFExt */
5771                 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5772                 ext.lmf.ebp = (gssize)&ext;
5773 #elif defined(TARGET_ARM)
5774                 ext.lmf.previous_lmf = *(lmf_addr);
5775                 /* Mark that this is a MonoLMFExt */
5776                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5777                 ext.lmf.sp = (gssize)&ext;
5778 #elif defined(TARGET_POWERPC)
5779                 ext.lmf.previous_lmf = *(lmf_addr);
5780                 /* Mark that this is a MonoLMFExt */
5781                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5782                 ext.lmf.ebp = (gssize)&ext;
5783 #elif defined(TARGET_S390X)
5784                 ext.lmf.previous_lmf = *(lmf_addr);
5785                 /* Mark that this is a MonoLMFExt */
5786                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5787                 ext.lmf.ebp = (gssize)&ext;
5788 #elif defined(TARGET_MIPS)
5789                 ext.lmf.previous_lmf = *(lmf_addr);
5790                 /* Mark that this is a MonoLMFExt */
5791                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5792                 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5793 #else
5794                 g_assert_not_reached ();
5795 #endif
5796
5797                 ext.debugger_invoke = TRUE;
5798                 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5799
5800                 mono_set_lmf ((MonoLMF*)&ext);
5801         }
5802 #endif
5803
5804         mono_stopwatch_start (&watch);
5805         if (m->klass->valuetype)
5806                 res = mono_runtime_invoke (m, this_buf, args, &exc);
5807         else
5808                 res = mono_runtime_invoke (m, this, args, &exc);
5809         mono_stopwatch_stop (&watch);
5810         DEBUG (1, fprintf (log_file, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer)GetCurrentThreadId (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch)));
5811         if (exc) {
5812                 buffer_add_byte (buf, 0);
5813                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5814         } else {
5815                 buffer_add_byte (buf, 1);
5816                 if (sig->ret->type == MONO_TYPE_VOID) {
5817                         if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5818                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5819                         }
5820                         else
5821                                 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5822                 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5823                         buffer_add_value (buf, sig->ret, &res, domain);
5824                 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5825                         if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5826                                 if (!res)
5827                                         buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &res, domain);
5828                                 else
5829                                         buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5830                         } else {
5831                                 g_assert (res);
5832                                 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5833                         }
5834                 } else {
5835                         NOT_IMPLEMENTED;
5836                 }
5837         }
5838
5839         tls->disable_breakpoints = FALSE;
5840
5841 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5842         if (invoke->has_ctx)
5843                 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5844 #endif
5845
5846         // FIXME: byref arguments
5847         // FIXME: varargs
5848         return ERR_NONE;
5849 }
5850
5851 /*
5852  * invoke_method:
5853  *
5854  *   Invoke the method given by tls->pending_invoke in the current thread.
5855  */
5856 static void
5857 invoke_method (void)
5858 {
5859         DebuggerTlsData *tls;
5860         InvokeData *invoke;
5861         int id;
5862         int err;
5863         Buffer buf;
5864         static void (*restore_context) (void *);
5865         MonoContext restore_ctx;
5866
5867         if (!restore_context)
5868                 restore_context = mono_get_restore_context ();
5869
5870         tls = mono_native_tls_get_value (debugger_tls_id);
5871         g_assert (tls);
5872
5873         /*
5874          * Store the `InvokeData *' in `tls->invoke' until we're done with
5875          * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5876          */
5877
5878         mono_loader_lock ();
5879
5880         invoke = tls->pending_invoke;
5881         g_assert (invoke);
5882         tls->pending_invoke = NULL;
5883
5884         invoke->last_invoke = tls->invoke;
5885         tls->invoke = invoke;
5886
5887         mono_loader_unlock ();
5888
5889         tls->frames_up_to_date = FALSE;
5890
5891         id = invoke->id;
5892
5893         buffer_init (&buf, 128);
5894
5895         err = do_invoke_method (tls, &buf, invoke);
5896
5897         /* Start suspending before sending the reply */
5898         if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5899                 suspend_vm ();
5900
5901         send_reply_packet (id, err, &buf);
5902         
5903         buffer_free (&buf);
5904
5905         memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5906
5907         if (invoke->has_ctx)
5908                 save_thread_context (&restore_ctx);
5909
5910         if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5911                 g_assert (tls->resume_count);
5912                 tls->resume_count -= invoke->suspend_count;
5913         }
5914
5915         DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5916
5917         /*
5918          * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5919          *
5920          * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5921          * after the mono_runtime_invoke() already returned, but it doesn't matter
5922          * because we reset the abort here.
5923          */
5924
5925         mono_loader_lock ();
5926
5927         if (tls->abort_requested)
5928                 mono_thread_internal_reset_abort (tls->thread);
5929
5930         tls->invoke = tls->invoke->last_invoke;
5931         tls->abort_requested = FALSE;
5932
5933         mono_loader_unlock ();
5934
5935         g_free (invoke->p);
5936         g_free (invoke);
5937
5938         suspend_current ();
5939 }
5940
5941 static gboolean
5942 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5943 {
5944         MonoThread *thread = value;
5945         DebuggerTlsData *tls;
5946         gboolean res;
5947
5948         mono_loader_lock ();
5949         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5950         g_assert (tls);
5951         res = tls->really_suspended;
5952         mono_loader_unlock ();
5953
5954         return res;
5955 }
5956
5957 static GPtrArray*
5958 get_source_files_for_type (MonoClass *klass)
5959 {
5960         gpointer iter = NULL;
5961         MonoMethod *method;
5962         MonoDebugSourceInfo *sinfo;
5963         GPtrArray *files;
5964         int i, j;
5965
5966         files = g_ptr_array_new ();
5967
5968         while ((method = mono_class_get_methods (klass, &iter))) {
5969                 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
5970                 GPtrArray *source_file_list;
5971
5972                 if (minfo) {
5973                         mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL);
5974                         for (j = 0; j < source_file_list->len; ++j) {
5975                                 sinfo = g_ptr_array_index (source_file_list, j);
5976                                 for (i = 0; i < files->len; ++i)
5977                                         if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
5978                                                 break;
5979                                 if (i == files->len)
5980                                         g_ptr_array_add (files, g_strdup (sinfo->source_file));
5981                         }
5982                         g_ptr_array_free (source_file_list, TRUE);
5983                 }
5984         }
5985
5986         return files;
5987 }
5988
5989 static ErrorCode
5990 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
5991 {
5992         switch (command) {
5993         case CMD_VM_VERSION: {
5994                 char *build_info, *version;
5995
5996                 build_info = mono_get_runtime_build_info ();
5997                 version = g_strdup_printf ("mono %s", build_info);
5998
5999                 buffer_add_string (buf, version); /* vm version */
6000                 buffer_add_int (buf, MAJOR_VERSION);
6001                 buffer_add_int (buf, MINOR_VERSION);
6002                 g_free (build_info);
6003                 g_free (version);
6004                 break;
6005         }
6006         case CMD_VM_SET_PROTOCOL_VERSION: {
6007                 major_version = decode_int (p, &p, end);
6008                 minor_version = decode_int (p, &p, end);
6009                 protocol_version_set = TRUE;
6010                 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6011                 break;
6012         }
6013         case CMD_VM_ALL_THREADS: {
6014                 // FIXME: Domains
6015                 mono_loader_lock ();
6016                 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6017                 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6018                 mono_loader_unlock ();
6019                 break;
6020         }
6021         case CMD_VM_SUSPEND:
6022                 suspend_vm ();
6023                 wait_for_suspend ();
6024                 break;
6025         case CMD_VM_RESUME:
6026                 if (suspend_count == 0)
6027                         return ERR_NOT_SUSPENDED;
6028                 resume_vm ();
6029                 break;
6030         case CMD_VM_DISPOSE:
6031                 /* Clear all event requests */
6032                 mono_loader_lock ();
6033                 while (event_requests->len > 0) {
6034                         EventRequest *req = g_ptr_array_index (event_requests, 0);
6035
6036                         clear_event_request (req->id, req->event_kind);
6037                 }
6038                 mono_loader_unlock ();
6039
6040                 while (suspend_count > 0)
6041                         resume_vm ();
6042                 disconnected = TRUE;
6043                 vm_start_event_sent = FALSE;
6044                 break;
6045         case CMD_VM_EXIT: {
6046                 MonoInternalThread *thread;
6047                 DebuggerTlsData *tls;
6048                 MonoClass *env_class;
6049                 MonoMethod *exit_method = NULL;
6050                 gpointer *args;
6051                 int exit_code;
6052
6053                 exit_code = decode_int (p, &p, end);
6054
6055                 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6056
6057                 /* Have to send a reply before exiting */
6058                 send_reply_packet (id, 0, buf);
6059
6060                 /* Clear all event requests */
6061                 mono_loader_lock ();
6062                 while (event_requests->len > 0) {
6063                         EventRequest *req = g_ptr_array_index (event_requests, 0);
6064
6065                         clear_event_request (req->id, req->event_kind);
6066                 }
6067                 mono_loader_unlock ();
6068
6069                 /*
6070                  * The JDWP documentation says that the shutdown is not orderly. It doesn't
6071                  * specify whenever a VM_DEATH event is sent. We currently do an orderly
6072                  * shutdown by hijacking a thread to execute Environment.Exit (). This is
6073                  * better than doing the shutdown ourselves, since it avoids various races.
6074                  */
6075
6076                 suspend_vm ();
6077                 wait_for_suspend ();
6078
6079                 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6080                 if (env_class)
6081                         exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6082
6083                 mono_loader_lock ();
6084                 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6085                 mono_loader_unlock ();
6086
6087                 if (thread && exit_method) {
6088                         mono_loader_lock ();
6089                         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6090                         mono_loader_unlock ();
6091
6092                         args = g_new0 (gpointer, 1);
6093                         args [0] = g_malloc (sizeof (int));
6094                         *(int*)(args [0]) = exit_code;
6095
6096                         tls->pending_invoke = g_new0 (InvokeData, 1);
6097                         tls->pending_invoke->method = exit_method;
6098                         tls->pending_invoke->args = args;
6099
6100                         while (suspend_count > 0)
6101                                 resume_vm ();
6102                 } else {
6103                         /* 
6104                          * No thread found, do it ourselves.
6105                          * FIXME: This can race with normal shutdown etc.
6106                          */
6107                         while (suspend_count > 0)
6108                                 resume_vm ();
6109
6110                         mono_runtime_set_shutting_down ();
6111
6112                         mono_threads_set_shutting_down ();
6113
6114                         /* Suspend all managed threads since the runtime is going away */
6115                         DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6116                         mono_thread_suspend_all_other_threads ();
6117                         DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6118                         mono_runtime_quit ();
6119                         transport_close2 ();
6120                         DEBUG(1, fprintf (log_file, "Exiting...\n"));
6121
6122                         exit (exit_code);
6123                 }
6124                 break;
6125         }               
6126         case CMD_VM_INVOKE_METHOD: {
6127                 int objid = decode_objid (p, &p, end);
6128                 MonoThread *thread;
6129                 DebuggerTlsData *tls;
6130                 int err, flags;
6131
6132                 err = get_object (objid, (MonoObject**)&thread);
6133                 if (err)
6134                         return err;
6135
6136                 flags = decode_int (p, &p, end);
6137
6138                 // Wait for suspending if it already started
6139                 if (suspend_count)
6140                         wait_for_suspend ();
6141                 if (!is_suspended ())
6142                         return ERR_NOT_SUSPENDED;
6143
6144                 mono_loader_lock ();
6145                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6146                 mono_loader_unlock ();
6147                 g_assert (tls);
6148
6149                 if (!tls->really_suspended)
6150                         /* The thread is still running native code, can't do invokes */
6151                         return ERR_NOT_SUSPENDED;
6152
6153                 /* 
6154                  * Store the invoke data into tls, the thread will execute it after it is
6155                  * resumed.
6156                  */
6157                 if (tls->pending_invoke)
6158                         NOT_IMPLEMENTED;
6159                 tls->pending_invoke = g_new0 (InvokeData, 1);
6160                 tls->pending_invoke->id = id;
6161                 tls->pending_invoke->flags = flags;
6162                 tls->pending_invoke->p = g_malloc (end - p);
6163                 memcpy (tls->pending_invoke->p, p, end - p);
6164                 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6165                 tls->pending_invoke->suspend_count = suspend_count;
6166
6167                 if (flags & INVOKE_FLAG_SINGLE_THREADED)
6168                         resume_thread (THREAD_TO_INTERNAL (thread));
6169                 else
6170                         resume_vm ();
6171                 break;
6172         }
6173         case CMD_VM_ABORT_INVOKE: {
6174                 int objid = decode_objid (p, &p, end);
6175                 MonoThread *thread;
6176                 DebuggerTlsData *tls;
6177                 int invoke_id, err;
6178
6179                 err = get_object (objid, (MonoObject**)&thread);
6180                 if (err)
6181                         return err;
6182
6183                 invoke_id = decode_int (p, &p, end);
6184
6185                 mono_loader_lock ();
6186                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6187                 g_assert (tls);
6188
6189                 if (tls->abort_requested) {
6190                         mono_loader_unlock ();
6191                         break;
6192                 }
6193
6194                 /*
6195                  * Check whether we're still inside the mono_runtime_invoke() and that it's
6196                  * actually the correct invocation.
6197                  *
6198                  * Careful, we do not stop the thread that's doing the invocation, so we can't
6199                  * inspect its stack.  However, invoke_method() also acquires the loader lock
6200                  * when it's done, so we're safe here.
6201                  *
6202                  */
6203
6204                 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6205                         mono_loader_unlock ();
6206                         return ERR_NO_INVOCATION;
6207                 }
6208
6209                 tls->abort_requested = TRUE;
6210
6211                 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6212                 mono_loader_unlock ();
6213                 break;
6214         }
6215
6216         case CMD_VM_SET_KEEPALIVE: {
6217                 int timeout = decode_int (p, &p, end);
6218                 agent_config.keepalive = timeout;
6219                 // FIXME:
6220 #ifndef DISABLE_SOCKET_TRANSPORT
6221                 set_keepalive ();
6222 #else
6223                 NOT_IMPLEMENTED;
6224 #endif
6225                 break;
6226         }
6227         case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6228                 GHashTableIter iter, kiter;
6229                 MonoDomain *domain;
6230                 MonoClass *klass;
6231                 GPtrArray *files;
6232                 int i;
6233                 char *fname, *basename;
6234                 gboolean ignore_case;
6235                 GSList *class_list, *l;
6236                 GPtrArray *res_classes, *res_domains;
6237
6238                 fname = decode_string (p, &p, end);
6239                 ignore_case = decode_byte (p, &p, end);
6240
6241                 basename = g_path_get_basename (fname);
6242
6243                 res_classes = g_ptr_array_new ();
6244                 res_domains = g_ptr_array_new ();
6245
6246                 mono_loader_lock ();
6247                 g_hash_table_iter_init (&iter, domains);
6248                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6249                         AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6250
6251                         /* Update 'source_file_to_class' cache */
6252                         g_hash_table_iter_init (&kiter, info->loaded_classes);
6253                         while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6254                                 if (!g_hash_table_lookup (info->source_files, klass)) {
6255                                         files = get_source_files_for_type (klass);
6256                                         g_hash_table_insert (info->source_files, klass, files);
6257
6258                                         for (i = 0; i < files->len; ++i) {
6259                                                 char *s = g_ptr_array_index (files, i);
6260                                                 char *s2 = g_path_get_basename (s);
6261                                                 char *s3;
6262
6263                                                 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6264                                                 if (!class_list) {
6265                                                         class_list = g_slist_prepend (class_list, klass);
6266                                                         g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6267                                                 } else {
6268                                                         class_list = g_slist_prepend (class_list, klass);
6269                                                         g_hash_table_insert (info->source_file_to_class, s2, class_list);
6270                                                 }
6271
6272                                                 /* The _ignorecase hash contains the lowercase path */
6273                                                 s3 = strdup_tolower (s2);
6274                                                 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6275                                                 if (!class_list) {
6276                                                         class_list = g_slist_prepend (class_list, klass);
6277                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6278                                                 } else {
6279                                                         class_list = g_slist_prepend (class_list, klass);
6280                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6281                                                 }
6282
6283                                                 g_free (s2);
6284                                                 g_free (s3);
6285                                         }
6286                                 }
6287                         }
6288
6289                         if (ignore_case) {
6290                                 char *s;
6291
6292                                 s = strdup_tolower (basename);
6293                                 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6294                                 g_free (s);
6295                         } else {
6296                                 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6297                         }
6298
6299                         for (l = class_list; l; l = l->next) {
6300                                 klass = l->data;
6301
6302                                 g_ptr_array_add (res_classes, klass);
6303                                 g_ptr_array_add (res_domains, domain);
6304                         }
6305                 }
6306                 mono_loader_unlock ();
6307
6308                 g_free (fname);
6309                 g_free (basename);
6310
6311                 buffer_add_int (buf, res_classes->len);
6312                 for (i = 0; i < res_classes->len; ++i)
6313                         buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6314                 g_ptr_array_free (res_classes, TRUE);
6315                 g_ptr_array_free (res_domains, TRUE);
6316                 break;
6317         }
6318         case CMD_VM_GET_TYPES: {
6319                 GHashTableIter iter;
6320                 MonoDomain *domain;
6321                 int i;
6322                 char *name;
6323                 gboolean ignore_case;
6324                 GPtrArray *res_classes, *res_domains;
6325                 MonoTypeNameParse info;
6326
6327                 name = decode_string (p, &p, end);
6328                 ignore_case = decode_byte (p, &p, end);
6329
6330                 if (!mono_reflection_parse_type (name, &info)) {
6331                         g_free (name);
6332                         mono_reflection_free_type_info (&info);
6333                         return ERR_INVALID_ARGUMENT;
6334                 }
6335
6336                 res_classes = g_ptr_array_new ();
6337                 res_domains = g_ptr_array_new ();
6338
6339                 mono_loader_lock ();
6340                 g_hash_table_iter_init (&iter, domains);
6341                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6342                         MonoAssembly *ass;
6343                         gboolean type_resolve;
6344                         MonoType *t;
6345                         GSList *tmp;
6346
6347                         mono_domain_assemblies_lock (domain);
6348                         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6349                                 ass = tmp->data;
6350
6351                                 if (ass->image) {
6352                                         type_resolve = TRUE;
6353                                         t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6354                                         if (t) {
6355                                                 g_ptr_array_add (res_classes, mono_type_get_class (t));
6356                                                 g_ptr_array_add (res_domains, domain);
6357                                         }
6358                                 }
6359                         }
6360                         mono_domain_assemblies_unlock (domain);
6361                 }
6362                 mono_loader_unlock ();
6363
6364                 g_free (name);
6365                 mono_reflection_free_type_info (&info);
6366
6367                 buffer_add_int (buf, res_classes->len);
6368                 for (i = 0; i < res_classes->len; ++i)
6369                         buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6370                 g_ptr_array_free (res_classes, TRUE);
6371                 g_ptr_array_free (res_domains, TRUE);
6372                 break;
6373         }
6374
6375         default:
6376                 return ERR_NOT_IMPLEMENTED;
6377         }
6378
6379         return ERR_NONE;
6380 }
6381
6382 static ErrorCode
6383 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6384 {
6385         int err;
6386         MonoError error;
6387
6388         switch (command) {
6389         case CMD_EVENT_REQUEST_SET: {
6390                 EventRequest *req;
6391                 int i, event_kind, suspend_policy, nmodifiers, mod;
6392                 MonoMethod *method;
6393                 long location = 0;
6394                 MonoThread *step_thread;
6395                 int size = 0, depth = 0, step_thread_id = 0;
6396                 MonoDomain *domain;
6397                 Modifier *modifier;
6398
6399                 event_kind = decode_byte (p, &p, end);
6400                 suspend_policy = decode_byte (p, &p, end);
6401                 nmodifiers = decode_byte (p, &p, end);
6402
6403                 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6404                 req->id = InterlockedIncrement (&event_request_id);
6405                 req->event_kind = event_kind;
6406                 req->suspend_policy = suspend_policy;
6407                 req->nmodifiers = nmodifiers;
6408
6409                 method = NULL;
6410                 for (i = 0; i < nmodifiers; ++i) {
6411                         mod = decode_byte (p, &p, end);
6412
6413                         req->modifiers [i].kind = mod;
6414                         if (mod == MOD_KIND_COUNT) {
6415                                 req->modifiers [i].data.count = decode_int (p, &p, end);
6416                         } else if (mod == MOD_KIND_LOCATION_ONLY) {
6417                                 method = decode_methodid (p, &p, end, &domain, &err);
6418                                 if (err)
6419                                         return err;
6420                                 location = decode_long (p, &p, end);
6421                         } else if (mod == MOD_KIND_STEP) {
6422                                 step_thread_id = decode_id (p, &p, end);
6423                                 size = decode_int (p, &p, end);
6424                                 depth = decode_int (p, &p, end);
6425                         } else if (mod == MOD_KIND_THREAD_ONLY) {
6426                                 int id = decode_id (p, &p, end);
6427
6428                                 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6429                                 if (err) {
6430                                         g_free (req);
6431                                         return err;
6432                                 }
6433                         } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6434                                 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6435
6436                                 if (err)
6437                                         return err;
6438                                 req->modifiers [i].caught = decode_byte (p, &p, end);
6439                                 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6440                                 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : ""));
6441                                 if (exc_class) {
6442                                         req->modifiers [i].data.exc_class = exc_class;
6443
6444                                         if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6445                                                 g_free (req);
6446                                                 return ERR_INVALID_ARGUMENT;
6447                                         }
6448                                 }
6449                         } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6450                                 int n = decode_int (p, &p, end);
6451                                 int j;
6452
6453                                 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6454                                 for (j = 0; j < n; ++j) {
6455                                         req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6456                                         if (err) {
6457                                                 g_free (req->modifiers [i].data.assemblies);
6458                                                 return err;
6459                                         }
6460                                 }
6461                         } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6462                                 int n = decode_int (p, &p, end);
6463                                 int j;
6464
6465                                 modifier = &req->modifiers [i];
6466                                 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6467                                 for (j = 0; j < n; ++j) {
6468                                         char *s = decode_string (p, &p, end);
6469                                         char *s2;
6470
6471                                         if (s) {
6472                                                 s2 = strdup_tolower (s);
6473                                                 g_hash_table_insert (modifier->data.source_files, s2, s2);
6474                                                 g_free (s);
6475                                         }
6476                                 }
6477                         } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6478                                 int n = decode_int (p, &p, end);
6479                                 int j;
6480
6481                                 modifier = &req->modifiers [i];
6482                                 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6483                                 for (j = 0; j < n; ++j) {
6484                                         char *s = decode_string (p, &p, end);
6485
6486                                         if (s)
6487                                                 g_hash_table_insert (modifier->data.type_names, s, s);
6488                                 }
6489                         } else {
6490                                 g_free (req);
6491                                 return ERR_NOT_IMPLEMENTED;
6492                         }
6493                 }
6494
6495                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6496                         g_assert (method);
6497
6498                         req->info = set_breakpoint (method, location, req, &error);
6499                         if (!mono_error_ok (&error)) {
6500                                 g_free (req);
6501                                 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6502                                 mono_error_cleanup (&error);
6503                                 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6504                         }
6505                 } else if (req->event_kind == EVENT_KIND_STEP) {
6506                         g_assert (step_thread_id);
6507
6508                         err = get_object (step_thread_id, (MonoObject**)&step_thread);
6509                         if (err) {
6510                                 g_free (req);
6511                                 return err;
6512                         }
6513
6514                         err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6515                         if (err) {
6516                                 g_free (req);
6517                                 return err;
6518                         }
6519                 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6520                         req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6521                 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6522                         req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6523                 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6524                 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6525                 } else {
6526                         if (req->nmodifiers) {
6527                                 g_free (req);
6528                                 return ERR_NOT_IMPLEMENTED;
6529                         }
6530                 }
6531
6532                 mono_loader_lock ();
6533                 g_ptr_array_add (event_requests, req);
6534                 
6535                 if (agent_config.defer) {
6536                         /* Transmit cached data to the client on receipt of the event request */
6537                         switch (req->event_kind) {
6538                         case EVENT_KIND_APPDOMAIN_CREATE:
6539                                 /* Emit load events for currently loaded domains */
6540                                 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6541                                 break;
6542                         case EVENT_KIND_ASSEMBLY_LOAD:
6543                                 /* Emit load events for currently loaded assemblies */
6544                                 mono_assembly_foreach (emit_assembly_load, NULL);
6545                                 break;
6546                         case EVENT_KIND_THREAD_START:
6547                                 /* Emit start events for currently started threads */
6548                                 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6549                                 break;
6550                         case EVENT_KIND_TYPE_LOAD:
6551                                 /* Emit type load events for currently loaded types */
6552                                 mono_domain_foreach (send_types_for_domain, NULL);
6553                                 break;
6554                         default:
6555                                 break;
6556                         }
6557                 }
6558                 mono_loader_unlock ();
6559
6560                 buffer_add_int (buf, req->id);
6561                 break;
6562         }
6563         case CMD_EVENT_REQUEST_CLEAR: {
6564                 int etype = decode_byte (p, &p, end);
6565                 int req_id = decode_int (p, &p, end);
6566
6567                 // FIXME: Make a faster mapping from req_id to request
6568                 mono_loader_lock ();
6569                 clear_event_request (req_id, etype);
6570                 mono_loader_unlock ();
6571                 break;
6572         }
6573         case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6574                 int i;
6575
6576                 mono_loader_lock ();
6577                 i = 0;
6578                 while (i < event_requests->len) {
6579                         EventRequest *req = g_ptr_array_index (event_requests, i);
6580
6581                         if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6582                                 clear_breakpoint (req->info);
6583
6584                                 g_ptr_array_remove_index_fast (event_requests, i);
6585                                 g_free (req);
6586                         } else {
6587                                 i ++;
6588                         }
6589                 }
6590                 mono_loader_unlock ();
6591                 break;
6592         }
6593         default:
6594                 return ERR_NOT_IMPLEMENTED;
6595         }
6596
6597         return ERR_NONE;
6598 }
6599
6600 static ErrorCode
6601 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6602 {
6603         int err;
6604         MonoDomain *domain;
6605
6606         switch (command) {
6607         case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6608                 buffer_add_domainid (buf, mono_get_root_domain ());
6609                 break;
6610         }
6611         case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6612                 domain = decode_domainid (p, &p, end, NULL, &err);
6613                 if (err)
6614                         return err;
6615                 buffer_add_string (buf, domain->friendly_name);
6616                 break;
6617         }
6618         case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6619                 GSList *tmp;
6620                 MonoAssembly *ass;
6621                 int count;
6622
6623                 domain = decode_domainid (p, &p, end, NULL, &err);
6624                 if (err)
6625                         return err;
6626                 mono_loader_lock ();
6627                 count = 0;
6628                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6629                         count ++;
6630                 }
6631                 buffer_add_int (buf, count);
6632                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6633                         ass = tmp->data;
6634                         buffer_add_assemblyid (buf, domain, ass);
6635                 }
6636                 mono_loader_unlock ();
6637                 break;
6638         }
6639         case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6640                 domain = decode_domainid (p, &p, end, NULL, &err);
6641                 if (err)
6642                         return err;
6643
6644                 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6645                 break;
6646         }
6647         case CMD_APPDOMAIN_GET_CORLIB: {
6648                 domain = decode_domainid (p, &p, end, NULL, &err);
6649                 if (err)
6650                         return err;
6651
6652                 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6653                 break;
6654         }
6655         case CMD_APPDOMAIN_CREATE_STRING: {
6656                 char *s;
6657                 MonoString *o;
6658
6659                 domain = decode_domainid (p, &p, end, NULL, &err);
6660                 if (err)
6661                         return err;
6662                 s = decode_string (p, &p, end);
6663
6664                 o = mono_string_new (domain, s);
6665                 buffer_add_objid (buf, (MonoObject*)o);
6666                 break;
6667         }
6668         case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6669                 MonoClass *klass;
6670                 MonoDomain *domain2;
6671                 MonoObject *o;
6672
6673                 domain = decode_domainid (p, &p, end, NULL, &err);
6674                 if (err)
6675                         return err;
6676                 klass = decode_typeid (p, &p, end, &domain2, &err);
6677                 if (err)
6678                         return err;
6679
6680                 // FIXME:
6681                 g_assert (domain == domain2);
6682
6683                 o = mono_object_new (domain, klass);
6684
6685                 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6686                 if (err)
6687                         return err;
6688
6689                 buffer_add_objid (buf, o);
6690                 break;
6691         }
6692         default:
6693                 return ERR_NOT_IMPLEMENTED;
6694         }
6695
6696         return ERR_NONE;
6697 }
6698
6699 static ErrorCode
6700 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6701 {
6702         int err;
6703         MonoAssembly *ass;
6704         MonoDomain *domain;
6705
6706         ass = decode_assemblyid (p, &p, end, &domain, &err);
6707         if (err)
6708                 return err;
6709
6710         switch (command) {
6711         case CMD_ASSEMBLY_GET_LOCATION: {
6712                 buffer_add_string (buf, mono_image_get_filename (ass->image));
6713                 break;                  
6714         }
6715         case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6716                 guint32 token;
6717                 MonoMethod *m;
6718
6719                 if (ass->image->dynamic) {
6720                         buffer_add_id (buf, 0);
6721                 } else {
6722                         token = mono_image_get_entry_point (ass->image);
6723                         if (token == 0) {
6724                                 buffer_add_id (buf, 0);
6725                         } else {
6726                                 m = mono_get_method (ass->image, token, NULL);
6727                                 buffer_add_methodid (buf, domain, m);
6728                         }
6729                 }
6730                 break;                  
6731         }
6732         case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6733                 buffer_add_moduleid (buf, domain, ass->image);
6734                 break;
6735         }
6736         case CMD_ASSEMBLY_GET_OBJECT: {
6737                 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
6738                 buffer_add_objid (buf, o);
6739                 break;
6740         }
6741         case CMD_ASSEMBLY_GET_TYPE: {
6742                 char *s = decode_string (p, &p, end);
6743                 gboolean ignorecase = decode_byte (p, &p, end);
6744                 MonoTypeNameParse info;
6745                 MonoType *t;
6746                 gboolean type_resolve, res;
6747                 MonoDomain *d = mono_domain_get ();
6748
6749                 /* This is needed to be able to find referenced assemblies */
6750                 res = mono_domain_set (domain, FALSE);
6751                 g_assert (res);
6752
6753                 if (!mono_reflection_parse_type (s, &info)) {
6754                         t = NULL;
6755                 } else {
6756                         if (info.assembly.name)
6757                                 NOT_IMPLEMENTED;
6758                         t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6759                 }
6760                 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6761                 mono_reflection_free_type_info (&info);
6762                 g_free (s);
6763
6764                 mono_domain_set (d, TRUE);
6765
6766                 break;
6767         }
6768         case CMD_ASSEMBLY_GET_NAME: {
6769                 gchar *name;
6770                 MonoAssembly *mass = ass;
6771
6772                 name = g_strdup_printf (
6773                   "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6774                   mass->aname.name,
6775                   mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6776                   mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6777                   mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6778                   (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6779
6780                 buffer_add_string (buf, name);
6781                 g_free (name);
6782                 break;
6783         }
6784         default:
6785                 return ERR_NOT_IMPLEMENTED;
6786         }
6787
6788         return ERR_NONE;
6789 }
6790
6791 static ErrorCode
6792 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6793 {
6794         int err;
6795         MonoDomain *domain;
6796
6797         switch (command) {
6798         case CMD_MODULE_GET_INFO: {
6799                 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
6800                 char *basename;
6801
6802                 basename = g_path_get_basename (image->name);
6803                 buffer_add_string (buf, basename); // name
6804                 buffer_add_string (buf, image->module_name); // scopename
6805                 buffer_add_string (buf, image->name); // fqname
6806                 buffer_add_string (buf, mono_image_get_guid (image)); // guid
6807                 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
6808                 g_free (basename);
6809                 break;                  
6810         }
6811         default:
6812                 return ERR_NOT_IMPLEMENTED;
6813         }
6814
6815         return ERR_NONE;
6816 }
6817
6818 static void
6819 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6820 {
6821         if (val && val->vtable->klass == mono_defaults.monotype_class) {
6822                 /* Special case these so the client doesn't have to handle Type objects */
6823                 
6824                 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6825                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
6826         } else if (MONO_TYPE_IS_REFERENCE (t))
6827                 buffer_add_value (buf, t, &val, domain);
6828         else
6829                 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6830 }
6831
6832 static void
6833 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6834 {
6835         int i, j;
6836         int nattrs = 0;
6837
6838         if (!cinfo) {
6839                 buffer_add_int (buf, 0);
6840                 return;
6841         }
6842
6843         for (i = 0; i < cinfo->num_attrs; ++i) {
6844                 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6845                         nattrs ++;
6846         }
6847         buffer_add_int (buf, nattrs);
6848
6849         for (i = 0; i < cinfo->num_attrs; ++i) {
6850                 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6851                 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6852                         MonoArray *typed_args, *named_args;
6853                         MonoType *t;
6854                         CattrNamedArg *arginfo;
6855
6856                         mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6857
6858                         buffer_add_methodid (buf, domain, attr->ctor);
6859
6860                         /* Ctor args */
6861                         if (typed_args) {
6862                                 buffer_add_int (buf, mono_array_length (typed_args));
6863                                 for (j = 0; j < mono_array_length (typed_args); ++j) {
6864                                         MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6865
6866                                         t = mono_method_signature (attr->ctor)->params [j];
6867
6868                                         buffer_add_cattr_arg (buf, t, domain, val);
6869                                 }
6870                         } else {
6871                                 buffer_add_int (buf, 0);
6872                         }
6873
6874                         /* Named args */
6875                         if (named_args) {
6876                                 buffer_add_int (buf, mono_array_length (named_args));
6877
6878                                 for (j = 0; j < mono_array_length (named_args); ++j) {
6879                                         MonoObject *val = mono_array_get (named_args, MonoObject*, j);
6880
6881                                         if (arginfo [j].prop) {
6882                                                 buffer_add_byte (buf, 0x54);
6883                                                 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6884                                         } else if (arginfo [j].field) {
6885                                                 buffer_add_byte (buf, 0x53);
6886                                                 buffer_add_fieldid (buf, domain, arginfo [j].field);
6887                                         } else {
6888                                                 g_assert_not_reached ();
6889                                         }
6890
6891                                         buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6892                                 }
6893                         } else {
6894                                 buffer_add_int (buf, 0);
6895                         }
6896                 }
6897         }
6898 }
6899
6900 /* FIXME: Code duplication with icall.c */
6901 static void
6902 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
6903 {
6904         int i;
6905         MonoClass *ic;
6906
6907         mono_class_setup_interfaces (klass, error);
6908         if (!mono_error_ok (error))
6909                 return;
6910
6911         for (i = 0; i < klass->interface_count; i++) {
6912                 ic = klass->interfaces [i];
6913                 g_hash_table_insert (ifaces, ic, ic);
6914
6915                 collect_interfaces (ic, ifaces, error);
6916                 if (!mono_error_ok (error))
6917                         return;
6918         }
6919 }
6920
6921 static ErrorCode
6922 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6923 {
6924         MonoClass *nested;
6925         MonoType *type;
6926         gpointer iter;
6927         guint8 b;
6928         int err, nnested;
6929         char *name;
6930
6931         switch (command) {
6932         case CMD_TYPE_GET_INFO: {
6933                 buffer_add_string (buf, klass->name_space);
6934                 buffer_add_string (buf, klass->name);
6935                 // FIXME: byref
6936                 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
6937                 buffer_add_string (buf, name);
6938                 g_free (name);
6939                 buffer_add_assemblyid (buf, domain, klass->image->assembly);
6940                 buffer_add_moduleid (buf, domain, klass->image);
6941                 buffer_add_typeid (buf, domain, klass->parent);
6942                 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
6943                         buffer_add_typeid (buf, domain, klass->element_class);
6944                 else
6945                         buffer_add_id (buf, 0);
6946                 buffer_add_int (buf, klass->type_token);
6947                 buffer_add_byte (buf, klass->rank);
6948                 buffer_add_int (buf, klass->flags);
6949                 b = 0;
6950                 type = &klass->byval_arg;
6951                 // FIXME: Can't decide whenever a class represents a byref type
6952                 if (FALSE)
6953                         b |= (1 << 0);
6954                 if (type->type == MONO_TYPE_PTR)
6955                         b |= (1 << 1);
6956                 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
6957                         b |= (1 << 2);
6958                 if (type->type == MONO_TYPE_VALUETYPE)
6959                         b |= (1 << 3);
6960                 if (klass->enumtype)
6961                         b |= (1 << 4);
6962                 if (klass->generic_container)
6963                         b |= (1 << 5);
6964                 if (klass->generic_container || klass->generic_class)
6965                         b |= (1 << 6);
6966                 buffer_add_byte (buf, b);
6967                 nnested = 0;
6968                 iter = NULL;
6969                 while ((nested = mono_class_get_nested_types (klass, &iter)))
6970                         nnested ++;
6971                 buffer_add_int (buf, nnested);
6972                 iter = NULL;
6973                 while ((nested = mono_class_get_nested_types (klass, &iter)))
6974                         buffer_add_typeid (buf, domain, nested);
6975                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
6976                         if (klass->generic_container)
6977                                 buffer_add_typeid (buf, domain, klass);
6978                         else if (klass->generic_class)
6979                                 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
6980                         else
6981                                 buffer_add_id (buf, 0);
6982                 }                       
6983                 break;
6984         }
6985         case CMD_TYPE_GET_METHODS: {
6986                 int nmethods;
6987                 int i = 0;
6988                 gpointer iter = NULL;
6989                 MonoMethod *m;
6990
6991                 mono_class_setup_methods (klass);
6992
6993                 nmethods = mono_class_num_methods (klass);
6994
6995                 buffer_add_int (buf, nmethods);
6996
6997                 while ((m = mono_class_get_methods (klass, &iter))) {
6998                         buffer_add_methodid (buf, domain, m);
6999                         i ++;
7000                 }
7001                 g_assert (i == nmethods);
7002                 break;
7003         }
7004         case CMD_TYPE_GET_FIELDS: {
7005                 int nfields;
7006                 int i = 0;
7007                 gpointer iter = NULL;
7008                 MonoClassField *f;
7009
7010                 nfields = mono_class_num_fields (klass);
7011
7012                 buffer_add_int (buf, nfields);
7013
7014                 while ((f = mono_class_get_fields (klass, &iter))) {
7015                         buffer_add_fieldid (buf, domain, f);
7016                         buffer_add_string (buf, f->name);
7017                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7018                         buffer_add_int (buf, f->type->attrs);
7019                         i ++;
7020                 }
7021                 g_assert (i == nfields);
7022                 break;
7023         }
7024         case CMD_TYPE_GET_PROPERTIES: {
7025                 int nprops;
7026                 int i = 0;
7027                 gpointer iter = NULL;
7028                 MonoProperty *p;
7029
7030                 nprops = mono_class_num_properties (klass);
7031
7032                 buffer_add_int (buf, nprops);
7033
7034                 while ((p = mono_class_get_properties (klass, &iter))) {
7035                         buffer_add_propertyid (buf, domain, p);
7036                         buffer_add_string (buf, p->name);
7037                         buffer_add_methodid (buf, domain, p->get);
7038                         buffer_add_methodid (buf, domain, p->set);
7039                         buffer_add_int (buf, p->attrs);
7040                         i ++;
7041                 }
7042                 g_assert (i == nprops);
7043                 break;
7044         }
7045         case CMD_TYPE_GET_CATTRS: {
7046                 MonoClass *attr_klass;
7047                 MonoCustomAttrInfo *cinfo;
7048
7049                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7050                 /* attr_klass can be NULL */
7051                 if (err)
7052                         return err;
7053
7054                 cinfo = mono_custom_attrs_from_class (klass);
7055
7056                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7057                 break;
7058         }
7059         case CMD_TYPE_GET_FIELD_CATTRS: {
7060                 MonoClass *attr_klass;
7061                 MonoCustomAttrInfo *cinfo;
7062                 MonoClassField *field;
7063
7064                 field = decode_fieldid (p, &p, end, NULL, &err);
7065                 if (err)
7066                         return err;
7067                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7068                 if (err)
7069                         return err;
7070
7071                 cinfo = mono_custom_attrs_from_field (klass, field);
7072
7073                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7074                 break;
7075         }
7076         case CMD_TYPE_GET_PROPERTY_CATTRS: {
7077                 MonoClass *attr_klass;
7078                 MonoCustomAttrInfo *cinfo;
7079                 MonoProperty *prop;
7080
7081                 prop = decode_propertyid (p, &p, end, NULL, &err);
7082                 if (err)
7083                         return err;
7084                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7085                 if (err)
7086                         return err;
7087
7088                 cinfo = mono_custom_attrs_from_property (klass, prop);
7089
7090                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7091                 break;
7092         }
7093         case CMD_TYPE_GET_VALUES:
7094         case CMD_TYPE_GET_VALUES_2: {
7095                 guint8 *val;
7096                 MonoClassField *f;
7097                 MonoVTable *vtable;
7098                 MonoClass *k;
7099                 int len, i;
7100                 gboolean found;
7101                 MonoThread *thread_obj;
7102                 MonoInternalThread *thread = NULL;
7103                 guint32 special_static_type;
7104
7105                 if (command == CMD_TYPE_GET_VALUES_2) {
7106                         int objid = decode_objid (p, &p, end);
7107                         int err;
7108
7109                         err = get_object (objid, (MonoObject**)&thread_obj);
7110                         if (err)
7111                                 return err;
7112
7113                         thread = THREAD_TO_INTERNAL (thread_obj);
7114                 }
7115
7116                 len = decode_int (p, &p, end);
7117                 for (i = 0; i < len; ++i) {
7118                         f = decode_fieldid (p, &p, end, NULL, &err);
7119                         if (err)
7120                                 return err;
7121
7122                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7123                                 return ERR_INVALID_FIELDID;
7124                         special_static_type = mono_class_field_get_special_static_type (f);
7125                         if (special_static_type != SPECIAL_STATIC_NONE) {
7126                                 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7127                                         return ERR_INVALID_FIELDID;
7128                         }
7129
7130                         /* Check that the field belongs to the object */
7131                         found = FALSE;
7132                         for (k = klass; k; k = k->parent) {
7133                                 if (k == f->parent) {
7134                                         found = TRUE;
7135                                         break;
7136                                 }
7137                         }
7138                         if (!found)
7139                                 return ERR_INVALID_FIELDID;
7140
7141                         vtable = mono_class_vtable (domain, f->parent);
7142                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7143                         mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7144                         buffer_add_value (buf, f->type, val, domain);
7145                         g_free (val);
7146                 }
7147                 break;
7148         }
7149         case CMD_TYPE_SET_VALUES: {
7150                 guint8 *val;
7151                 MonoClassField *f;
7152                 MonoVTable *vtable;
7153                 MonoClass *k;
7154                 int len, i;
7155                 gboolean found;
7156
7157                 len = decode_int (p, &p, end);
7158                 for (i = 0; i < len; ++i) {
7159                         f = decode_fieldid (p, &p, end, NULL, &err);
7160                         if (err)
7161                                 return err;
7162
7163                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7164                                 return ERR_INVALID_FIELDID;
7165                         if (mono_class_field_is_special_static (f))
7166                                 return ERR_INVALID_FIELDID;
7167
7168                         /* Check that the field belongs to the object */
7169                         found = FALSE;
7170                         for (k = klass; k; k = k->parent) {
7171                                 if (k == f->parent) {
7172                                         found = TRUE;
7173                                         break;
7174                                 }
7175                         }
7176                         if (!found)
7177                                 return ERR_INVALID_FIELDID;
7178
7179                         // FIXME: Check for literal/const
7180
7181                         vtable = mono_class_vtable (domain, f->parent);
7182                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7183                         err = decode_value (f->type, domain, val, p, &p, end);
7184                         if (err) {
7185                                 g_free (val);
7186                                 return err;
7187                         }
7188                         if (MONO_TYPE_IS_REFERENCE (f->type))
7189                                 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7190                         else
7191                                 mono_field_static_set_value (vtable, f, val);
7192                         g_free (val);
7193                 }
7194                 break;
7195         }
7196         case CMD_TYPE_GET_OBJECT: {
7197                 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
7198                 buffer_add_objid (buf, o);
7199                 break;
7200         }
7201         case CMD_TYPE_GET_SOURCE_FILES:
7202         case CMD_TYPE_GET_SOURCE_FILES_2: {
7203                 char *source_file, *base;
7204                 GPtrArray *files;
7205                 int i;
7206
7207                 files = get_source_files_for_type (klass);
7208
7209                 buffer_add_int (buf, files->len);
7210                 for (i = 0; i < files->len; ++i) {
7211                         source_file = g_ptr_array_index (files, i);
7212                         if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7213                                 buffer_add_string (buf, source_file);
7214                         } else {
7215                                 base = g_path_get_basename (source_file);
7216                                 buffer_add_string (buf, base);
7217                                 g_free (base);
7218                         }
7219                         g_free (source_file);
7220                 }
7221                 g_ptr_array_free (files, TRUE);
7222                 break;
7223         }
7224         case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7225                 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7226
7227                 if (err)
7228                         return err;
7229                 if (mono_class_is_assignable_from (klass, oklass))
7230                         buffer_add_byte (buf, 1);
7231                 else
7232                         buffer_add_byte (buf, 0);
7233                 break;
7234         }
7235         case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7236                 char *name = decode_string (p, &p, end);
7237                 int i, flags = decode_int (p, &p, end);
7238                 MonoException *ex = NULL;
7239                 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7240
7241                 if (!array)
7242                         return ERR_LOADER_ERROR;
7243                 buffer_add_int (buf, array->len);
7244                 for (i = 0; i < array->len; ++i) {
7245                         MonoMethod *method = g_ptr_array_index (array, i);
7246                         buffer_add_methodid (buf, domain, method);
7247                 }
7248
7249                 g_ptr_array_free (array, TRUE);
7250                 g_free (name);
7251                 break;
7252         }
7253         case CMD_TYPE_GET_INTERFACES: {
7254                 MonoClass *parent;
7255                 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7256                 MonoError error;
7257                 MonoClass *tclass, *iface;
7258                 GHashTableIter iter;
7259
7260                 tclass = klass;
7261
7262                 for (parent = tclass; parent; parent = parent->parent) {
7263                         mono_class_setup_interfaces (parent, &error);
7264                         if (!mono_error_ok (&error))
7265                                 return ERR_LOADER_ERROR;
7266                         collect_interfaces (parent, iface_hash, &error);
7267                         if (!mono_error_ok (&error))
7268                                 return ERR_LOADER_ERROR;
7269                 }
7270
7271                 buffer_add_int (buf, g_hash_table_size (iface_hash));
7272
7273                 g_hash_table_iter_init (&iter, iface_hash);
7274                 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7275                         buffer_add_typeid (buf, domain, iface);
7276                 g_hash_table_destroy (iface_hash);
7277                 break;
7278         }
7279         case CMD_TYPE_GET_INTERFACE_MAP: {
7280                 int tindex, ioffset;
7281                 gboolean variance_used;
7282                 MonoClass *iclass;
7283                 int len, nmethods, i;
7284                 gpointer iter;
7285                 MonoMethod *method;
7286
7287                 len = decode_int (p, &p, end);
7288                 mono_class_setup_vtable (klass);
7289
7290                 for (tindex = 0; tindex < len; ++tindex) {
7291                         iclass = decode_typeid (p, &p, end, NULL, &err);
7292                         if (err)
7293                                 return err;
7294
7295                         ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7296                         if (ioffset == -1)
7297                                 return ERR_INVALID_ARGUMENT;
7298
7299                         nmethods = mono_class_num_methods (iclass);
7300                         buffer_add_int (buf, nmethods);
7301
7302                         iter = NULL;
7303                         while ((method = mono_class_get_methods (iclass, &iter))) {
7304                                 buffer_add_methodid (buf, domain, method);
7305                         }
7306                         for (i = 0; i < nmethods; ++i)
7307                                 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7308                 }
7309                 break;
7310         }
7311         default:
7312                 return ERR_NOT_IMPLEMENTED;
7313         }
7314
7315         return ERR_NONE;
7316 }
7317
7318 static ErrorCode
7319 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7320 {
7321         MonoClass *klass;
7322         MonoDomain *old_domain;
7323         MonoDomain *domain;
7324         int err;
7325
7326         klass = decode_typeid (p, &p, end, &domain, &err);
7327         if (err)
7328                 return err;
7329
7330         old_domain = mono_domain_get ();
7331
7332         mono_domain_set (domain, TRUE);
7333
7334         err = type_commands_internal (command, klass, domain, p, end, buf);
7335
7336         mono_domain_set (old_domain, TRUE);
7337
7338         return err;
7339 }
7340
7341 static ErrorCode
7342 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7343 {
7344         MonoMethodHeader *header;
7345
7346         switch (command) {
7347         case CMD_METHOD_GET_NAME: {
7348                 buffer_add_string (buf, method->name);
7349                 break;                  
7350         }
7351         case CMD_METHOD_GET_DECLARING_TYPE: {
7352                 buffer_add_typeid (buf, domain, method->klass);
7353                 break;
7354         }
7355         case CMD_METHOD_GET_DEBUG_INFO: {
7356                 MonoDebugMethodInfo *minfo;
7357                 char *source_file;
7358                 int i, j, n_il_offsets;
7359                 int *il_offsets;
7360                 int *line_numbers;
7361                 int *source_files;
7362                 GPtrArray *source_file_list;
7363
7364                 header = mono_method_get_header (method);
7365                 if (!header) {
7366                         buffer_add_int (buf, 0);
7367                         buffer_add_string (buf, "");
7368                         buffer_add_int (buf, 0);
7369                         break;
7370                 }
7371
7372                 minfo = mono_debug_lookup_method (method);
7373                 if (!minfo) {
7374                         buffer_add_int (buf, header->code_size);
7375                         buffer_add_string (buf, "");
7376                         buffer_add_int (buf, 0);
7377                         mono_metadata_free_mh (header);
7378                         break;
7379                 }
7380
7381                 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &source_files);
7382                 buffer_add_int (buf, header->code_size);
7383                 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7384                         buffer_add_int (buf, source_file_list->len);
7385                         for (i = 0; i < source_file_list->len; ++i) {
7386                                 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7387                                 buffer_add_string (buf, sinfo->source_file);
7388                                 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7389                                         for (j = 0; j < 16; ++j)
7390                                                 buffer_add_byte (buf, sinfo->hash [j]);
7391                                 }
7392                         }
7393                 } else {
7394                         buffer_add_string (buf, source_file);
7395                 }
7396                 buffer_add_int (buf, n_il_offsets);
7397                 DEBUG (10, printf ("Line number table for method %s:\n", mono_method_full_name (method,  TRUE)));
7398                 for (i = 0; i < n_il_offsets; ++i) {
7399                         const char *srcfile = "";
7400
7401                         if (source_files [i] != -1) {
7402                                 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7403                                 srcfile = sinfo->source_file;
7404                         }
7405                         DEBUG (10, printf ("IL%x -> %s:%d\n", il_offsets [i], srcfile, line_numbers [i]));
7406                         buffer_add_int (buf, il_offsets [i]);
7407                         buffer_add_int (buf, line_numbers [i]);
7408                         if (CHECK_PROTOCOL_VERSION (2, 13))
7409                                 buffer_add_int (buf, source_files [i]);
7410                 }
7411                 g_free (source_file);
7412                 g_free (il_offsets);
7413                 g_free (line_numbers);
7414                 g_free (source_files);
7415                 g_ptr_array_free (source_file_list, TRUE);
7416                 mono_metadata_free_mh (header);
7417                 break;
7418         }
7419         case CMD_METHOD_GET_PARAM_INFO: {
7420                 MonoMethodSignature *sig = mono_method_signature (method);
7421                 guint32 i;
7422                 char **names;
7423
7424                 /* FIXME: mono_class_from_mono_type () and byrefs */
7425
7426                 /* FIXME: Use a smaller encoding */
7427                 buffer_add_int (buf, sig->call_convention);
7428                 buffer_add_int (buf, sig->param_count);
7429                 buffer_add_int (buf, sig->generic_param_count);
7430                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7431                 for (i = 0; i < sig->param_count; ++i) {
7432                         /* FIXME: vararg */
7433                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7434                 }
7435
7436                 /* Emit parameter names */
7437                 names = g_new (char *, sig->param_count);
7438                 mono_method_get_param_names (method, (const char **) names);
7439                 for (i = 0; i < sig->param_count; ++i)
7440                         buffer_add_string (buf, names [i]);
7441                 g_free (names);
7442
7443                 break;
7444         }
7445         case CMD_METHOD_GET_LOCALS_INFO: {
7446                 int i, j, num_locals;
7447                 MonoDebugLocalsInfo *locals;
7448
7449                 header = mono_method_get_header (method);
7450                 g_assert (header);
7451
7452                 buffer_add_int (buf, header->num_locals);
7453
7454                 /* Types */
7455                 for (i = 0; i < header->num_locals; ++i)
7456                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7457
7458                 /* Names */
7459                 locals = mono_debug_lookup_locals (method);
7460                 if (locals)
7461                         num_locals = locals->num_locals;
7462                 else
7463                         num_locals = 0;
7464                 for (i = 0; i < header->num_locals; ++i) {
7465                         for (j = 0; j < num_locals; ++j)
7466                                 if (locals->locals [j].index == i)
7467                                         break;
7468                         if (j < num_locals)
7469                                 buffer_add_string (buf, locals->locals [j].name);
7470                         else
7471                                 buffer_add_string (buf, "");
7472                 }
7473
7474                 /* Scopes */
7475                 for (i = 0; i < header->num_locals; ++i) {
7476                         for (j = 0; j < num_locals; ++j)
7477                                 if (locals->locals [j].index == i)
7478                                         break;
7479                         if (j < num_locals && locals->locals [j].block) {
7480                                 buffer_add_int (buf, locals->locals [j].block->start_offset);
7481                                 buffer_add_int (buf, locals->locals [j].block->end_offset);
7482                         } else {
7483                                 buffer_add_int (buf, 0);
7484                                 buffer_add_int (buf, header->code_size);
7485                         }
7486                 }
7487                 mono_metadata_free_mh (header);
7488
7489                 if (locals)
7490                         mono_debug_symfile_free_locals (locals);
7491
7492                 break;
7493         }
7494         case CMD_METHOD_GET_INFO:
7495                 buffer_add_int (buf, method->flags);
7496                 buffer_add_int (buf, method->iflags);
7497                 buffer_add_int (buf, method->token);
7498                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7499                         guint8 attrs = 0;
7500                         if (method->is_generic)
7501                                 attrs |= (1 << 0);
7502                         if (mono_method_signature (method)->generic_param_count)
7503                                 attrs |= (1 << 1);
7504                         buffer_add_byte (buf, attrs);
7505                         if (method->is_generic || method->is_inflated) {
7506                                 MonoMethod *result;
7507
7508                                 if (method->is_generic) {
7509                                         result = method;
7510                                 } else {
7511                                         MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7512                                         
7513                                         result = imethod->declaring;
7514                                         if (imethod->context.class_inst) {
7515                                                 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7516                                                 /*Generic methods gets the context of the GTD.*/
7517                                                 if (mono_class_get_context (klass))
7518                                                         result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7519                                         }
7520                                 }
7521
7522                                 buffer_add_methodid (buf, domain, result);
7523                         } else {
7524                                 buffer_add_id (buf, 0);
7525                         }
7526                 }
7527                 break;
7528         case CMD_METHOD_GET_BODY: {
7529                 int i;
7530
7531                 header = mono_method_get_header (method);
7532                 if (!header) {
7533                         buffer_add_int (buf, 0);
7534                 } else {
7535                         buffer_add_int (buf, header->code_size);
7536                         for (i = 0; i < header->code_size; ++i)
7537                                 buffer_add_byte (buf, header->code [i]);
7538                 }
7539                 mono_metadata_free_mh (header);
7540                 break;
7541         }
7542         case CMD_METHOD_RESOLVE_TOKEN: {
7543                 guint32 token = decode_int (p, &p, end);
7544
7545                 // FIXME: Generics
7546                 switch (mono_metadata_token_code (token)) {
7547                 case MONO_TOKEN_STRING: {
7548                         MonoString *s;
7549                         char *s2;
7550
7551                         s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7552                         g_assert (s);
7553
7554                         s2 = mono_string_to_utf8 (s);
7555
7556                         buffer_add_byte (buf, TOKEN_TYPE_STRING);
7557                         buffer_add_string (buf, s2);
7558                         g_free (s2);
7559                         break;
7560                 }
7561                 default: {
7562                         gpointer val;
7563                         MonoClass *handle_class;
7564
7565                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7566                                 val = mono_method_get_wrapper_data (method, token);
7567                                 handle_class = mono_method_get_wrapper_data (method, token + 1);
7568
7569                                 if (handle_class == NULL) {
7570                                         // Can't figure out the token type
7571                                         buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7572                                         break;
7573                                 }
7574                         } else {
7575                                 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7576                                 g_assert (val);
7577                         }
7578
7579                         if (handle_class == mono_defaults.typehandle_class) {
7580                                 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7581                                 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7582                                         buffer_add_typeid (buf, domain, (MonoClass *) val);
7583                                 else
7584                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7585                         } else if (handle_class == mono_defaults.fieldhandle_class) {
7586                                 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7587                                 buffer_add_fieldid (buf, domain, val);
7588                         } else if (handle_class == mono_defaults.methodhandle_class) {
7589                                 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7590                                 buffer_add_methodid (buf, domain, val);
7591                         } else if (handle_class == mono_defaults.string_class) {
7592                                 char *s;
7593
7594                                 s = mono_string_to_utf8 (val);
7595                                 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7596                                 buffer_add_string (buf, s);
7597                                 g_free (s);
7598                         } else {
7599                                 g_assert_not_reached ();
7600                         }
7601                         break;
7602                 }
7603                 }
7604                 break;
7605         }
7606         default:
7607                 return ERR_NOT_IMPLEMENTED;
7608         }
7609
7610         return ERR_NONE;
7611 }
7612
7613 static ErrorCode
7614 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7615 {
7616         int err;
7617         MonoDomain *old_domain;
7618         MonoDomain *domain;
7619         MonoMethod *method;
7620
7621         method = decode_methodid (p, &p, end, &domain, &err);
7622         if (err)
7623                 return err;
7624
7625         old_domain = mono_domain_get ();
7626
7627         mono_domain_set (domain, TRUE);
7628
7629         err = method_commands_internal (command, method, domain, p, end, buf);
7630
7631         mono_domain_set (old_domain, TRUE);
7632
7633         return err;
7634 }
7635
7636 static ErrorCode
7637 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7638 {
7639         int objid = decode_objid (p, &p, end);
7640         int err;
7641         MonoThread *thread_obj;
7642         MonoInternalThread *thread;
7643
7644         err = get_object (objid, (MonoObject**)&thread_obj);
7645         if (err)
7646                 return err;
7647
7648         thread = THREAD_TO_INTERNAL (thread_obj);
7649            
7650         switch (command) {
7651         case CMD_THREAD_GET_NAME: {
7652                 guint32 name_len;
7653                 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7654
7655                 if (!s) {
7656                         buffer_add_int (buf, 0);
7657                 } else {
7658                         char *name;
7659                         glong len;
7660
7661                         name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7662                         g_assert (name);
7663                         buffer_add_int (buf, len);
7664                         buffer_add_data (buf, (guint8*)name, len);
7665                         g_free (s);
7666                 }
7667                 break;
7668         }
7669         case CMD_THREAD_GET_FRAME_INFO: {
7670                 DebuggerTlsData *tls;
7671                 int i, start_frame, length;
7672
7673                 // Wait for suspending if it already started
7674                 // FIXME: Races with suspend_count
7675                 while (!is_suspended ()) {
7676                         if (suspend_count)
7677                                 wait_for_suspend ();
7678                 }
7679                 /*
7680                 if (suspend_count)
7681                         wait_for_suspend ();
7682                 if (!is_suspended ())
7683                         return ERR_NOT_SUSPENDED;
7684                 */
7685
7686                 start_frame = decode_int (p, &p, end);
7687                 length = decode_int (p, &p, end);
7688
7689                 if (start_frame != 0 || length != -1)
7690                         return ERR_NOT_IMPLEMENTED;
7691
7692                 mono_loader_lock ();
7693                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7694                 mono_loader_unlock ();
7695                 g_assert (tls);
7696
7697                 compute_frame_info (thread, tls);
7698
7699                 buffer_add_int (buf, tls->frame_count);
7700                 for (i = 0; i < tls->frame_count; ++i) {
7701                         buffer_add_int (buf, tls->frames [i]->id);
7702                         buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
7703                         buffer_add_int (buf, tls->frames [i]->il_offset);
7704                         /*
7705                          * Instead of passing the frame type directly to the client, we associate
7706                          * it with the previous frame using a set of flags. This avoids lots of
7707                          * conditional code in the client, since a frame whose type isn't 
7708                          * FRAME_TYPE_MANAGED has no method, location, etc.
7709                          */
7710                         buffer_add_byte (buf, tls->frames [i]->flags);
7711                 }
7712
7713                 break;
7714         }
7715         case CMD_THREAD_GET_STATE:
7716                 buffer_add_int (buf, thread->state);
7717                 break;
7718         case CMD_THREAD_GET_INFO:
7719                 buffer_add_byte (buf, thread->threadpool_thread);
7720                 break;
7721         case CMD_THREAD_GET_ID:
7722                 buffer_add_long (buf, (guint64)(gsize)thread);
7723                 break;
7724         case CMD_THREAD_GET_TID:
7725                 buffer_add_long (buf, (guint64)thread->tid);
7726                 break;
7727         default:
7728                 return ERR_NOT_IMPLEMENTED;
7729         }
7730
7731         return ERR_NONE;
7732 }
7733
7734 static ErrorCode
7735 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7736 {
7737         int objid;
7738         int err;
7739         MonoThread *thread_obj;
7740         MonoInternalThread *thread;
7741         int pos, i, len, frame_idx;
7742         DebuggerTlsData *tls;
7743         StackFrame *frame;
7744         MonoDebugMethodJitInfo *jit;
7745         MonoDebugVarInfo *var;
7746         MonoMethodSignature *sig;
7747         gssize id;
7748         MonoMethodHeader *header;
7749
7750         objid = decode_objid (p, &p, end);
7751         err = get_object (objid, (MonoObject**)&thread_obj);
7752         if (err)
7753                 return err;
7754
7755         thread = THREAD_TO_INTERNAL (thread_obj);
7756
7757         id = decode_id (p, &p, end);
7758
7759         mono_loader_lock ();
7760         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7761         mono_loader_unlock ();
7762         g_assert (tls);
7763
7764         for (i = 0; i < tls->frame_count; ++i) {
7765                 if (tls->frames [i]->id == id)
7766                         break;
7767         }
7768         if (i == tls->frame_count)
7769                 return ERR_INVALID_FRAMEID;
7770
7771         frame_idx = i;
7772         frame = tls->frames [frame_idx];
7773
7774         if (!frame->has_ctx)
7775                 // FIXME:
7776                 return ERR_INVALID_FRAMEID;
7777
7778         if (!frame->jit) {
7779                 frame->jit = mono_debug_find_method (frame->method, frame->domain);
7780                 if (!frame->jit && frame->method->is_inflated)
7781                         frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->method), frame->domain);
7782                 if (!frame->jit) {
7783                         char *s;
7784
7785                         /* This could happen for aot images with no jit debug info */
7786                         s = mono_method_full_name (frame->method, TRUE);
7787                         DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
7788                         g_free (s);
7789                         return ERR_ABSENT_INFORMATION;
7790                 }
7791         }
7792         jit = frame->jit;
7793
7794         sig = mono_method_signature (frame->actual_method);
7795
7796         if (!get_seq_points (frame->domain, frame->actual_method))
7797                 /*
7798                  * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
7799                  */
7800                 return ERR_ABSENT_INFORMATION;
7801
7802         switch (command) {
7803         case CMD_STACK_FRAME_GET_VALUES: {
7804                 len = decode_int (p, &p, end);
7805                 header = mono_method_get_header (frame->actual_method);
7806
7807                 for (i = 0; i < len; ++i) {
7808                         pos = decode_int (p, &p, end);
7809
7810                         if (pos < 0) {
7811                                 pos = - pos - 1;
7812
7813                                 g_assert (pos >= 0 && pos < jit->num_params);
7814
7815                                 var = &jit->params [pos];
7816
7817                                 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
7818                         } else {
7819                                 g_assert (pos >= 0 && pos < jit->num_locals);
7820
7821                                 var = &jit->locals [pos];
7822                                 
7823                                 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
7824                         }
7825                 }
7826                 mono_metadata_free_mh (header);
7827                 break;
7828         }
7829         case CMD_STACK_FRAME_GET_THIS: {
7830                 if (frame->method->klass->valuetype) {
7831                         if (!sig->hasthis) {
7832                                 MonoObject *p = NULL;
7833                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
7834                         } else {
7835                                 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7836                         }
7837                 } else {
7838                         if (!sig->hasthis) {
7839                                 MonoObject *p = NULL;
7840                                 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
7841                         } else {
7842                                 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7843                         }
7844                 }
7845                 break;
7846         }
7847         case CMD_STACK_FRAME_SET_VALUES: {
7848                 guint8 *val_buf;
7849                 MonoType *t;
7850                 MonoDebugVarInfo *var;
7851
7852                 len = decode_int (p, &p, end);
7853                 header = mono_method_get_header (frame->actual_method);
7854
7855                 for (i = 0; i < len; ++i) {
7856                         pos = decode_int (p, &p, end);
7857
7858                         if (pos < 0) {
7859                                 pos = - pos - 1;
7860
7861                                 g_assert (pos >= 0 && pos < jit->num_params);
7862
7863                                 t = sig->params [pos];
7864                                 var = &jit->params [pos];
7865                         } else {
7866                                 g_assert (pos >= 0 && pos < jit->num_locals);
7867
7868                                 t = header->locals [pos];
7869                                 var = &jit->locals [pos];
7870                         }
7871
7872                         if (MONO_TYPE_IS_REFERENCE (t))
7873                                 val_buf = g_alloca (sizeof (MonoObject*));
7874                         else
7875                                 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
7876                         err = decode_value (t, frame->domain, val_buf, p, &p, end);
7877                         if (err)
7878                                 return err;
7879
7880                         set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
7881                 }
7882                 mono_metadata_free_mh (header);
7883                 break;
7884         }
7885         default:
7886                 return ERR_NOT_IMPLEMENTED;
7887         }
7888
7889         return ERR_NONE;
7890 }
7891
7892 static ErrorCode
7893 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7894 {
7895         MonoArray *arr;
7896         int objid, err, index, len, i, esize;
7897         gpointer elem;
7898
7899         objid = decode_objid (p, &p, end);
7900         err = get_object (objid, (MonoObject**)&arr);
7901         if (err)
7902                 return err;
7903
7904         switch (command) {
7905         case CMD_ARRAY_REF_GET_LENGTH:
7906                 buffer_add_int (buf, arr->obj.vtable->klass->rank);
7907                 if (!arr->bounds) {
7908                         buffer_add_int (buf, arr->max_length);
7909                         buffer_add_int (buf, 0);
7910                 } else {
7911                         for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
7912                                 buffer_add_int (buf, arr->bounds [i].length);
7913                                 buffer_add_int (buf, arr->bounds [i].lower_bound);
7914                         }
7915                 }
7916                 break;
7917         case CMD_ARRAY_REF_GET_VALUES:
7918                 index = decode_int (p, &p, end);
7919                 len = decode_int (p, &p, end);
7920
7921                 g_assert (index >= 0 && len >= 0);
7922                 // Reordered to avoid integer overflow
7923                 g_assert (!(index > arr->max_length - len));
7924
7925                 esize = mono_array_element_size (arr->obj.vtable->klass);
7926                 for (i = index; i < index + len; ++i) {
7927                         elem = (gpointer*)((char*)arr->vector + (i * esize));
7928                         buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
7929                 }
7930                 break;
7931         case CMD_ARRAY_REF_SET_VALUES:
7932                 index = decode_int (p, &p, end);
7933                 len = decode_int (p, &p, end);
7934
7935                 g_assert (index >= 0 && len >= 0);
7936                 // Reordered to avoid integer overflow
7937                 g_assert (!(index > arr->max_length - len));
7938
7939                 esize = mono_array_element_size (arr->obj.vtable->klass);
7940                 for (i = index; i < index + len; ++i) {
7941                         elem = (gpointer*)((char*)arr->vector + (i * esize));
7942
7943                         decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
7944                 }
7945                 break;
7946         default:
7947                 return ERR_NOT_IMPLEMENTED;
7948         }
7949
7950         return ERR_NONE;
7951 }
7952
7953 static ErrorCode
7954 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7955 {
7956         int objid, err;
7957         MonoString *str;
7958         char *s;
7959         int i, index, length;
7960         gunichar2 *c;
7961
7962         objid = decode_objid (p, &p, end);
7963         err = get_object (objid, (MonoObject**)&str);
7964         if (err)
7965                 return err;
7966
7967         switch (command) {
7968         case CMD_STRING_REF_GET_VALUE:
7969                 s = mono_string_to_utf8 (str);
7970                 buffer_add_string (buf, s);
7971                 g_free (s);
7972                 break;
7973         case CMD_STRING_REF_GET_LENGTH:
7974                 buffer_add_long (buf, mono_string_length (str));
7975                 break;
7976         case CMD_STRING_REF_GET_CHARS:
7977                 index = decode_long (p, &p, end);
7978                 length = decode_long (p, &p, end);
7979                 if (index > mono_string_length (str) - length)
7980                         return ERR_INVALID_ARGUMENT;
7981                 c = mono_string_chars (str) + index;
7982                 for (i = 0; i < length; ++i)
7983                         buffer_add_short (buf, c [i]);
7984                 break;
7985         default:
7986                 return ERR_NOT_IMPLEMENTED;
7987         }
7988
7989         return ERR_NONE;
7990 }
7991
7992 static ErrorCode
7993 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7994 {
7995         int objid, err;
7996         MonoObject *obj;
7997         int len, i;
7998         MonoClassField *f;
7999         MonoClass *k;
8000         gboolean found;
8001
8002         if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8003                 objid = decode_objid (p, &p, end);
8004                 err = get_object (objid, &obj);
8005                 if (err)
8006                         buffer_add_int (buf, 1);
8007                 else
8008                         buffer_add_int (buf, 0);
8009                 return 0;
8010         }
8011
8012         objid = decode_objid (p, &p, end);
8013         err = get_object (objid, &obj);
8014         if (err)
8015                 return err;
8016
8017         switch (command) {
8018         case CMD_OBJECT_REF_GET_TYPE:
8019                 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8020                 break;
8021         case CMD_OBJECT_REF_GET_VALUES:
8022                 len = decode_int (p, &p, end);
8023
8024                 for (i = 0; i < len; ++i) {
8025                         MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8026                         if (err)
8027                                 return err;
8028
8029                         /* Check that the field belongs to the object */
8030                         found = FALSE;
8031                         for (k = obj->vtable->klass; k; k = k->parent) {
8032                                 if (k == f->parent) {
8033                                         found = TRUE;
8034                                         break;
8035                                 }
8036                         }
8037                         if (!found)
8038                                 return ERR_INVALID_FIELDID;
8039
8040                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8041                                 guint8 *val;
8042                                 MonoVTable *vtable;
8043
8044                                 if (mono_class_field_is_special_static (f))
8045                                         return ERR_INVALID_FIELDID;
8046
8047                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8048                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8049                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8050                                 mono_field_static_get_value (vtable, f, val);
8051                                 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8052                                 g_free (val);
8053                         } else {
8054                                 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8055                         }
8056                 }
8057                 break;
8058         case CMD_OBJECT_REF_SET_VALUES:
8059                 len = decode_int (p, &p, end);
8060
8061                 for (i = 0; i < len; ++i) {
8062                         f = decode_fieldid (p, &p, end, NULL, &err);
8063                         if (err)
8064                                 return err;
8065
8066                         /* Check that the field belongs to the object */
8067                         found = FALSE;
8068                         for (k = obj->vtable->klass; k; k = k->parent) {
8069                                 if (k == f->parent) {
8070                                         found = TRUE;
8071                                         break;
8072                                 }
8073                         }
8074                         if (!found)
8075                                 return ERR_INVALID_FIELDID;
8076
8077                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8078                                 guint8 *val;
8079                                 MonoVTable *vtable;
8080
8081                                 if (mono_class_field_is_special_static (f))
8082                                         return ERR_INVALID_FIELDID;
8083
8084                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8085                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8086
8087                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8088                                 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8089                                 if (err) {
8090                                         g_free (val);
8091                                         return err;
8092                                 }
8093                                 mono_field_static_set_value (vtable, f, val);
8094                                 g_free (val);
8095                         } else {
8096                                 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8097                                 if (err)
8098                                         return err;
8099                         }
8100                 }
8101                 break;
8102         case CMD_OBJECT_REF_GET_ADDRESS:
8103                 buffer_add_long (buf, (gssize)obj);
8104                 break;
8105         case CMD_OBJECT_REF_GET_DOMAIN:
8106                 buffer_add_domainid (buf, obj->vtable->domain);
8107                 break;
8108         case CMD_OBJECT_REF_GET_INFO:
8109                 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8110                 buffer_add_domainid (buf, obj->vtable->domain);
8111                 break;
8112         default:
8113                 return ERR_NOT_IMPLEMENTED;
8114         }
8115
8116         return ERR_NONE;
8117 }
8118
8119 static const char*
8120 command_set_to_string (CommandSet command_set)
8121 {
8122         switch (command_set) {
8123         case CMD_SET_VM:
8124                 return "VM";
8125         case CMD_SET_OBJECT_REF:
8126                 return "OBJECT_REF";
8127         case CMD_SET_STRING_REF:
8128                 return "STRING_REF"; 
8129         case CMD_SET_THREAD:
8130                 return "THREAD"; 
8131         case CMD_SET_ARRAY_REF:
8132                 return "ARRAY_REF"; 
8133         case CMD_SET_EVENT_REQUEST:
8134                 return "EVENT_REQUEST"; 
8135         case CMD_SET_STACK_FRAME:
8136                 return "STACK_FRAME"; 
8137         case CMD_SET_APPDOMAIN:
8138                 return "APPDOMAIN"; 
8139         case CMD_SET_ASSEMBLY:
8140                 return "ASSEMBLY"; 
8141         case CMD_SET_METHOD:
8142                 return "METHOD"; 
8143         case CMD_SET_TYPE:
8144                 return "TYPE"; 
8145         case CMD_SET_MODULE:
8146                 return "MODULE"; 
8147         case CMD_SET_EVENT:
8148                 return "EVENT"; 
8149         default:
8150                 return "";
8151         }
8152 }
8153
8154 static const char*
8155 cmd_to_string (CommandSet set, int command)
8156 {
8157         switch (set) {
8158         case CMD_SET_VM: {
8159                 switch (command) {
8160                 case CMD_VM_VERSION:
8161                         return "VERSION";
8162                 case CMD_VM_ALL_THREADS:
8163                         return "ALL_THREADS";
8164                 case CMD_VM_SUSPEND:
8165                         return "SUSPEND";
8166                 case CMD_VM_RESUME:
8167                         return "RESUME";
8168                 case CMD_VM_EXIT:
8169                         return "EXIT";
8170                 case CMD_VM_DISPOSE:
8171                         return "DISPOSE";
8172                 case CMD_VM_INVOKE_METHOD:
8173                         return "INVOKE_METHOD";
8174                 case CMD_VM_SET_PROTOCOL_VERSION:
8175                         return "SET_PROTOCOL_VERSION";
8176                 case CMD_VM_ABORT_INVOKE:
8177                         return "ABORT_INVOKE";
8178                 default:
8179                         break;
8180                 }
8181                 break;
8182         }
8183         default:
8184                 break;
8185         }
8186         return NULL;
8187 }
8188
8189 static gboolean
8190 wait_for_attach (void)
8191 {
8192 #ifndef DISABLE_SOCKET_TRANSPORT
8193         if (listen_fd == -1) {
8194                 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8195                 return FALSE;
8196         }
8197
8198         /* Block and wait for client connection */
8199         conn_fd = socket_transport_accept (listen_fd);
8200         DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8201         if (conn_fd == -1) {
8202                 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8203                 return FALSE;
8204         }
8205 #else
8206         g_assert_not_reached ();
8207 #endif
8208
8209         /* Handshake */
8210         disconnected = !transport_handshake ();
8211         if (disconnected) {
8212                 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8213                 return FALSE;
8214         }
8215         
8216         return TRUE;
8217 }
8218
8219 /*
8220  * debugger_thread:
8221  *
8222  *   This thread handles communication with the debugger client using a JDWP
8223  * like protocol.
8224  */
8225 static guint32 WINAPI
8226 debugger_thread (void *arg)
8227 {
8228         int res, len, id, flags, command_set = 0, command = 0;
8229         guint8 header [HEADER_LENGTH];
8230         guint8 *data, *p, *end;
8231         Buffer buf;
8232         ErrorCode err;
8233         gboolean no_reply;
8234         gboolean attach_failed = FALSE;
8235
8236         DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8237
8238         debugger_thread_id = GetCurrentThreadId ();
8239
8240         mono_jit_thread_attach (mono_get_root_domain ());
8241
8242         mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8243
8244         mono_set_is_debugger_attached (TRUE);
8245         
8246         if (agent_config.defer) {
8247                 if (!wait_for_attach ()) {
8248                         DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8249                         attach_failed = TRUE; // Don't abort process when we can't listen
8250                 } else {
8251                         /* Send start event to client */
8252                         process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8253                 }
8254         }
8255         
8256         while (!attach_failed) {
8257                 res = transport_recv (header, HEADER_LENGTH);
8258
8259                 /* This will break if the socket is closed during shutdown too */
8260                 if (res != HEADER_LENGTH)
8261                         break;
8262
8263                 p = header;
8264                 end = header + HEADER_LENGTH;
8265
8266                 len = decode_int (p, &p, end);
8267                 id = decode_int (p, &p, end);
8268                 flags = decode_byte (p, &p, end);
8269                 command_set = decode_byte (p, &p, end);
8270                 command = decode_byte (p, &p, end);
8271
8272                 g_assert (flags == 0);
8273
8274                 if (log_level) {
8275                         const char *cmd_str;
8276                         char cmd_num [256];
8277
8278                         cmd_str = cmd_to_string (command_set, command);
8279                         if (!cmd_str) {
8280                                 sprintf (cmd_num, "%d", command);
8281                                 cmd_str = cmd_num;
8282                         }
8283                         
8284                         DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8285                 }
8286
8287                 data = g_malloc (len - HEADER_LENGTH);
8288                 if (len - HEADER_LENGTH > 0)
8289                 {
8290                         res = transport_recv (data, len - HEADER_LENGTH);
8291                         if (res != len - HEADER_LENGTH)
8292                                 break;
8293                 }
8294
8295                 p = data;
8296                 end = data + (len - HEADER_LENGTH);
8297
8298                 buffer_init (&buf, 128);
8299
8300                 err = ERR_NONE;
8301                 no_reply = FALSE;
8302
8303                 /* Process the request */
8304                 switch (command_set) {
8305                 case CMD_SET_VM:
8306                         err = vm_commands (command, id, p, end, &buf);
8307                         if (!err && command == CMD_VM_INVOKE_METHOD)
8308                                 /* Sent after the invoke is complete */
8309                                 no_reply = TRUE;
8310                         break;
8311                 case CMD_SET_EVENT_REQUEST:
8312                         err = event_commands (command, p, end, &buf);
8313                         break;
8314                 case CMD_SET_APPDOMAIN:
8315                         err = domain_commands (command, p, end, &buf);
8316                         break;
8317                 case CMD_SET_ASSEMBLY:
8318                         err = assembly_commands (command, p, end, &buf);
8319                         break;
8320                 case CMD_SET_MODULE:
8321                         err = module_commands (command, p, end, &buf);
8322                         break;
8323                 case CMD_SET_TYPE:
8324                         err = type_commands (command, p, end, &buf);
8325                         break;
8326                 case CMD_SET_METHOD:
8327                         err = method_commands (command, p, end, &buf);
8328                         break;
8329                 case CMD_SET_THREAD:
8330                         err = thread_commands (command, p, end, &buf);
8331                         break;
8332                 case CMD_SET_STACK_FRAME:
8333                         err = frame_commands (command, p, end, &buf);
8334                         break;
8335                 case CMD_SET_ARRAY_REF:
8336                         err = array_commands (command, p, end, &buf);
8337                         break;
8338                 case CMD_SET_STRING_REF:
8339                         err = string_commands (command, p, end, &buf);
8340                         break;
8341                 case CMD_SET_OBJECT_REF:
8342                         err = object_commands (command, p, end, &buf);
8343                         break;
8344                 default:
8345                         err = ERR_NOT_IMPLEMENTED;
8346                 }               
8347
8348                 if (!no_reply)
8349                         send_reply_packet (id, err, &buf);
8350
8351                 g_free (data);
8352                 buffer_free (&buf);
8353
8354                 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8355                         break;
8356         }
8357
8358         mono_set_is_debugger_attached (FALSE);
8359         
8360         mono_mutex_lock (&debugger_thread_exited_mutex);
8361         debugger_thread_exited = TRUE;
8362         mono_cond_signal (&debugger_thread_exited_cond);
8363         mono_mutex_unlock (&debugger_thread_exited_mutex);
8364
8365         DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8366         
8367         if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8368                 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8369                 start_debugger_thread ();
8370         }
8371         
8372         return 0;
8373 }
8374
8375 #else /* DISABLE_DEBUGGER_AGENT */
8376
8377 void
8378 mono_debugger_agent_parse_options (char *options)
8379 {
8380         g_error ("This runtime is configured with the debugger agent disabled.");
8381 }
8382
8383 void
8384 mono_debugger_agent_init (void)
8385 {
8386 }
8387
8388 void
8389 mono_debugger_agent_breakpoint_hit (void *sigctx)
8390 {
8391 }
8392
8393 void
8394 mono_debugger_agent_single_step_event (void *sigctx)
8395 {
8396 }
8397
8398 void
8399 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8400 {
8401 }
8402
8403 gboolean
8404 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8405 {
8406         return FALSE;
8407 }
8408
8409 void
8410 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8411                                                                           MonoContext *catch_ctx)
8412 {
8413 }
8414
8415 void
8416 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8417 {
8418 }
8419
8420 void
8421 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8422 {
8423 }
8424
8425 void
8426 mono_debugger_agent_user_break (void)
8427 {
8428         G_BREAKPOINT ();
8429 }
8430
8431 void
8432 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8433 {
8434 }
8435
8436 gboolean
8437 mono_debugger_agent_debug_log_is_enabled (void)
8438 {
8439         return FALSE;
8440 }
8441
8442 #endif
8443