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