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