[sdb] Improve logging a bit.
[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 24
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; /* 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         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 = 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, ji->method->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                         tls->context.valid = FALSE;
2484
2485                         /*
2486                          * We are in a difficult position: we want to be able to provide stack
2487                          * traces for this thread, but we can't use the current ctx+lmf, since
2488                          * the thread is still running, so it might return to managed code,
2489                          * making these invalid.
2490                          * So we start a stack walk and save the first frame, along with the
2491                          * parent frame's ctx+lmf. This (hopefully) works because the thread will be 
2492                          * suspended when it returns to managed code, so the parent's ctx should
2493                          * remain valid.
2494                          */
2495                         data.last_frame_set = FALSE;
2496                         if (sigctx) {
2497                                 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2498                                 /* 
2499                                  * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2500                                  * get_last_frame () doesn't need it, the last frame cannot be a ginst
2501                                  * since we are not in a JITted method.
2502                                  */
2503                                 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2504                         } else if (info) {
2505                                 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2506                         }
2507                         if (data.last_frame_set) {
2508                                 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2509                                 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2510                                 g_assert (res);
2511                                 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2512                                 g_assert (res);
2513
2514                                 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2515                                 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2516                                 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2517                         } else {
2518                                 /* No managed frames */
2519                                 tls->async_state.valid = FALSE;
2520                         }
2521                         mono_memory_barrier ();
2522
2523                         tls->suspended = TRUE;
2524                         MONO_SEM_POST (&suspend_sem);
2525                 }
2526                 return TRUE;
2527         }
2528 }
2529
2530 /*
2531  * mono_debugger_agent_thread_interrupt:
2532  *
2533  *   Called by the abort signal handler.
2534  * Should be signal safe.
2535  */
2536 gboolean
2537 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2538 {
2539         DebuggerTlsData *tls;
2540
2541         if (!inited)
2542                 return FALSE;
2543
2544         tls = mono_native_tls_get_value (debugger_tls_id);
2545         if (!tls) {
2546                 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2547                 return FALSE;
2548         }
2549
2550         return thread_interrupt (tls, NULL, sigctx, ji);
2551 }
2552
2553 #ifdef HOST_WIN32
2554 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2555 {
2556         //DebugBreak ();
2557         mono_debugger_agent_thread_interrupt (NULL, NULL);
2558 }
2559 #endif /* HOST_WIN32 */
2560
2561 /*
2562  * reset_native_thread_suspend_state:
2563  * 
2564  *   Reset the suspended flag and state on native threads
2565  */
2566 static void
2567 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2568 {
2569         DebuggerTlsData *tls = value;
2570
2571         if (!tls->really_suspended && tls->suspended) {
2572                 tls->suspended = FALSE;
2573                 /*
2574                  * The thread might still be running if it was executing native code, so the state won't be invalided by
2575                  * suspend_current ().
2576                  */
2577                 tls->context.valid = FALSE;
2578                 tls->async_state.valid = FALSE;
2579                 invalidate_frames (tls);
2580         }
2581 }
2582
2583 /*
2584  * notify_thread:
2585  *
2586  *   Notify a thread that it needs to suspend.
2587  */
2588 static void
2589 notify_thread (gpointer key, gpointer value, gpointer user_data)
2590 {
2591         MonoInternalThread *thread = key;
2592         DebuggerTlsData *tls = value;
2593         gsize tid = thread->tid;
2594         int res;
2595
2596         if (GetCurrentThreadId () == tid || tls->terminated)
2597                 return;
2598
2599         DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2600
2601         /*
2602          * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2603          * guarantee the signal handler will be called that many times.  Instead of tracking
2604          * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2605          * has been requested that hasn't been handled yet, otherwise we can have threads
2606          * refuse to die when VM_EXIT is called
2607          */
2608 #if defined(__APPLE__)
2609         if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2610                 return;
2611 #else
2612         /*
2613          * Maybe we could use the normal interrupt infrastructure, but that does a lot
2614          * of things like breaking waits etc. which we don't want.
2615          */
2616         InterlockedIncrement (&tls->interrupt_count);
2617 #endif
2618
2619         /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2620 #ifdef HOST_WIN32
2621         QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2622 #else
2623         if (mono_thread_info_new_interrupt_enabled ()) {
2624                 MonoThreadInfo *info;
2625                 MonoJitInfo *ji;
2626
2627                 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2628                 if (!info) {
2629                         DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2630                         /* 
2631                          * Attached thread which died without detaching.
2632                          */
2633                         tls->terminated = TRUE;
2634                 } else {
2635                         ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2636
2637                         thread_interrupt (tls, info, NULL, ji);
2638
2639                         mono_thread_info_resume (mono_thread_info_get_tid (info));
2640                 }
2641         } else {
2642                 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2643                 if (res) {
2644                         DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2645                         /* 
2646                          * Attached thread which died without detaching.
2647                          */
2648                         tls->terminated = TRUE;
2649                 }
2650         }
2651 #endif
2652 }
2653
2654 static void
2655 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2656 {
2657         guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2658         MonoJitInfo *ji;
2659
2660         if (mono_loader_lock_is_owned_by_self ()) {
2661                 /*
2662                  * Shortcut for the check in suspend_current (). This speeds up processing
2663                  * when executing long running code inside the loader lock, i.e. assembly load
2664                  * hooks.
2665                  */
2666                 return;
2667         }
2668
2669         if (debugger_thread_id == GetCurrentThreadId ())
2670                 return;
2671
2672         /* Prevent races with mono_debugger_agent_thread_interrupt () */
2673         if (suspend_count - tls->resume_count > 0)
2674                 tls->suspending = TRUE;
2675
2676         DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2677
2678         if (suspend_count - tls->resume_count == 0) {
2679                 /* 
2680                  * We are executing a single threaded invoke but the single step for 
2681                  * suspending is still active.
2682                  * FIXME: This slows down single threaded invokes.
2683                  */
2684                 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2685                 return;
2686         }
2687
2688         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2689
2690         /* Can't suspend in these methods */
2691         if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->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 = info->ji->method;
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 && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3367                                                 filtered = TRUE;
3368                                         if (ei->caught && !mod->caught)
3369                                                 filtered = TRUE;
3370                                         if (!ei->caught && !mod->uncaught)
3371                                                 filtered = TRUE;
3372                                 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3373                                         int k;
3374                                         gboolean found = FALSE;
3375                                         MonoAssembly **assemblies = mod->data.assemblies;
3376
3377                                         if (assemblies) {
3378                                                 for (k = 0; assemblies [k]; ++k)
3379                                                         if (assemblies [k] == ji->method->klass->image->assembly)
3380                                                                 found = TRUE;
3381                                         }
3382                                         if (!found)
3383                                                 filtered = TRUE;
3384                                 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3385                                         gpointer iter = NULL;
3386                                         MonoMethod *method;
3387                                         MonoDebugSourceInfo *sinfo;
3388                                         char *source_file, *s;
3389                                         gboolean found = FALSE;
3390                                         int i;
3391                                         GPtrArray *source_file_list;
3392
3393                                         while ((method = mono_class_get_methods (ei->klass, &iter))) {
3394                                                 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3395
3396                                                 if (minfo) {
3397                                                         mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3398                                                         for (i = 0; i < source_file_list->len; ++i) {
3399                                                                 sinfo = g_ptr_array_index (source_file_list, i);
3400                                                                 /*
3401                                                                  * Do a case-insesitive match by converting the file name to
3402                                                                  * lowercase.
3403                                                                  */
3404                                                                 s = strdup_tolower (sinfo->source_file);
3405                                                                 if (g_hash_table_lookup (mod->data.source_files, s))
3406                                                                         found = TRUE;
3407                                                                 else {
3408                                                                         char *s2 = g_path_get_basename (sinfo->source_file);
3409                                                                         char *s3 = strdup_tolower (s2);
3410
3411                                                                         if (g_hash_table_lookup (mod->data.source_files, s3))
3412                                                                                 found = TRUE;
3413                                                                         g_free (s2);
3414                                                                         g_free (s3);
3415                                                                 }
3416                                                                 g_free (s);
3417                                                         }
3418                                                         g_ptr_array_free (source_file_list, TRUE);
3419                                                 }
3420                                         }
3421                                         if (!found)
3422                                                 filtered = TRUE;
3423                                 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3424                                         char *s;
3425
3426                                         s = mono_type_full_name (&ei->klass->byval_arg);
3427                                         if (!g_hash_table_lookup (mod->data.type_names, s))
3428                                                 filtered = TRUE;
3429                                         g_free (s);
3430                                 } else if (mod->kind == MOD_KIND_STEP) {
3431                                         if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3432                                                 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3433                                                 !strcmp (ji->method->name, ".cctor"))
3434                                                 filtered = TRUE;
3435                                         if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3436                                                 MonoCustomAttrInfo *ainfo;
3437                                                 static MonoClass *klass;
3438
3439                                                 if (!klass) {
3440                                                         klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3441                                                         g_assert (klass);
3442                                                 }
3443                                                 if (!ji->dbg_hidden_inited) {
3444                                                         ainfo = mono_custom_attrs_from_method (ji->method);
3445                                                         if (ainfo) {
3446                                                                 if (mono_custom_attrs_has_attr (ainfo, klass))
3447                                                                         ji->dbg_hidden = TRUE;
3448                                                                 mono_custom_attrs_free (ainfo);
3449                                                         }
3450                                                         ji->dbg_hidden_inited = TRUE;
3451                                                 }
3452                                                 if (ji->dbg_hidden)
3453                                                         filtered = TRUE;
3454                                         }
3455                                 }
3456                         }
3457
3458                         if (!filtered) {
3459                                 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3460                                 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3461                         }
3462                 }
3463         }
3464
3465         /* Send a VM START/DEATH event by default */
3466         if (event == EVENT_KIND_VM_START)
3467                 events = g_slist_append (events, GINT_TO_POINTER (0));
3468         if (event == EVENT_KIND_VM_DEATH)
3469                 events = g_slist_append (events, GINT_TO_POINTER (0));
3470
3471         return events;
3472 }
3473
3474 static G_GNUC_UNUSED const char*
3475 event_to_string (EventKind event)
3476 {
3477         switch (event) {
3478         case EVENT_KIND_VM_START: return "VM_START";
3479         case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3480         case EVENT_KIND_THREAD_START: return "THREAD_START";
3481         case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3482         case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3483         case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3484         case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3485         case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3486         case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3487         case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3488         case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3489         case EVENT_KIND_STEP: return "STEP";
3490         case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3491         case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3492         case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3493         case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3494         case EVENT_KIND_USER_LOG: return "USER_LOG";
3495         default:
3496                 g_assert_not_reached ();
3497         }
3498 }
3499
3500 /*
3501  * process_event:
3502  *
3503  *   Send an event to the client, suspending the vm if needed.
3504  * LOCKING: Since this can suspend the calling thread, no locks should be held
3505  * by the caller.
3506  * The EVENTS list is freed by this function.
3507  */
3508 static void
3509 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3510 {
3511         Buffer buf;
3512         GSList *l;
3513         MonoDomain *domain = mono_domain_get ();
3514         MonoThread *thread = NULL;
3515         MonoObject *keepalive_obj = NULL;
3516         gboolean send_success = FALSE;
3517         static int ecount;
3518         int nevents;
3519
3520         if (!inited) {
3521                 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3522                 return;
3523         }
3524
3525         if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3526                 // FIXME: We miss those events
3527                 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3528                 return;
3529         }
3530
3531         if (vm_death_event_sent) {
3532                 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3533                 return;
3534         }
3535
3536         if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3537                 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3538                 return;
3539         }
3540
3541         if (disconnected) {
3542                 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3543                 return;
3544         }
3545
3546         if (event == EVENT_KIND_KEEPALIVE)
3547                 suspend_policy = SUSPEND_POLICY_NONE;
3548         else {
3549                 if (events == NULL)
3550                         return;
3551
3552                 if (agent_config.defer) {
3553                         /* Make sure the thread id is always set when doing deferred debugging */
3554                         if (debugger_thread_id == GetCurrentThreadId ()) {
3555                                 /* Don't suspend on events from the debugger thread */
3556                                 suspend_policy = SUSPEND_POLICY_NONE;
3557                                 thread = mono_thread_get_main ();
3558                         }
3559                         else thread = mono_thread_current ();
3560                 } else {
3561                         if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3562                                 // FIXME: Send these with a NULL thread, don't suspend the current thread
3563                                 return;
3564                 }
3565         }
3566
3567         nevents = g_slist_length (events);
3568         buffer_init (&buf, 128);
3569         buffer_add_byte (&buf, suspend_policy);
3570         buffer_add_int (&buf, nevents);
3571
3572         for (l = events; l; l = l->next) {
3573                 buffer_add_byte (&buf, event); // event kind
3574                 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3575
3576                 ecount ++;
3577
3578                 if (!thread)
3579                         thread = mono_thread_current ();
3580
3581                 if (event == EVENT_KIND_VM_START && arg != NULL)
3582                         thread = arg;
3583
3584                 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3585
3586                 switch (event) {
3587                 case EVENT_KIND_THREAD_START:
3588                 case EVENT_KIND_THREAD_DEATH:
3589                         break;
3590                 case EVENT_KIND_APPDOMAIN_CREATE:
3591                 case EVENT_KIND_APPDOMAIN_UNLOAD:
3592                         buffer_add_domainid (&buf, arg);
3593                         break;
3594                 case EVENT_KIND_METHOD_ENTRY:
3595                 case EVENT_KIND_METHOD_EXIT:
3596                         buffer_add_methodid (&buf, domain, arg);
3597                         break;
3598                 case EVENT_KIND_ASSEMBLY_LOAD:
3599                 case EVENT_KIND_ASSEMBLY_UNLOAD:
3600                         buffer_add_assemblyid (&buf, domain, arg);
3601                         break;
3602                 case EVENT_KIND_TYPE_LOAD:
3603                         buffer_add_typeid (&buf, domain, arg);
3604                         break;
3605                 case EVENT_KIND_BREAKPOINT:
3606                 case EVENT_KIND_STEP:
3607                         buffer_add_methodid (&buf, domain, arg);
3608                         buffer_add_long (&buf, il_offset);
3609                         break;
3610                 case EVENT_KIND_VM_START:
3611                         buffer_add_domainid (&buf, mono_get_root_domain ());
3612                         break;
3613                 case EVENT_KIND_VM_DEATH:
3614                         break;
3615                 case EVENT_KIND_EXCEPTION: {
3616                         EventInfo *ei = arg;
3617                         buffer_add_objid (&buf, ei->exc);
3618                         /*
3619                          * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3620                          * later after the suspension. (#12494).
3621                          */
3622                         keepalive_obj = ei->exc;
3623                         break;
3624                 }
3625                 case EVENT_KIND_USER_BREAK:
3626                         break;
3627                 case EVENT_KIND_USER_LOG: {
3628                         EventInfo *ei = arg;
3629                         buffer_add_int (&buf, ei->level);
3630                         buffer_add_string (&buf, ei->category ? ei->category : "");
3631                         buffer_add_string (&buf, ei->message ? ei->message : "");
3632                         break;
3633                 }
3634                 case EVENT_KIND_KEEPALIVE:
3635                         suspend_policy = SUSPEND_POLICY_NONE;
3636                         break;
3637                 default:
3638                         g_assert_not_reached ();
3639                 }
3640         }
3641
3642         if (event == EVENT_KIND_VM_START) {
3643                 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3644                 if (!agent_config.defer)
3645                         start_debugger_thread ();
3646         }
3647    
3648         if (event == EVENT_KIND_VM_DEATH) {
3649                 vm_death_event_sent = TRUE;
3650                 suspend_policy = SUSPEND_POLICY_NONE;
3651         }
3652
3653         if (mono_runtime_is_shutting_down ())
3654                 suspend_policy = SUSPEND_POLICY_NONE;
3655
3656         if (suspend_policy != SUSPEND_POLICY_NONE) {
3657                 /* 
3658                  * Save the thread context and start suspending before sending the packet,
3659                  * since we could be receiving the resume request before send_packet ()
3660                  * returns.
3661                  */
3662                 save_thread_context (ctx);
3663                 suspend_vm ();
3664
3665                 if (keepalive_obj)
3666                         /* This will keep this object alive */
3667                         get_objref (keepalive_obj);
3668         }
3669
3670         send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3671
3672         buffer_free (&buf);
3673
3674         g_slist_free (events);
3675         events = NULL;
3676
3677         if (!send_success) {
3678                 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3679                 return;
3680         }
3681         
3682         if (event == EVENT_KIND_VM_START) {
3683                 vm_start_event_sent = TRUE;
3684         }
3685
3686         DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3687
3688         switch (suspend_policy) {
3689         case SUSPEND_POLICY_NONE:
3690                 break;
3691         case SUSPEND_POLICY_ALL:
3692                 suspend_current ();
3693                 break;
3694         case SUSPEND_POLICY_EVENT_THREAD:
3695                 NOT_IMPLEMENTED;
3696                 break;
3697         default:
3698                 g_assert_not_reached ();
3699         }
3700 }
3701
3702 static void
3703 process_profiler_event (EventKind event, gpointer arg)
3704 {
3705         int suspend_policy;
3706         GSList *events;
3707         EventInfo ei, *ei_arg = NULL;
3708
3709         if (event == EVENT_KIND_TYPE_LOAD) {
3710                 ei.klass = arg;
3711                 ei_arg = &ei;
3712         }
3713
3714         mono_loader_lock ();
3715         events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3716         mono_loader_unlock ();
3717
3718         process_event (event, arg, 0, NULL, events, suspend_policy);
3719 }
3720
3721 static void
3722 runtime_initialized (MonoProfiler *prof)
3723 {
3724         process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3725         if (agent_config.defer)
3726                 start_debugger_thread ();
3727 }
3728
3729 static void
3730 runtime_shutdown (MonoProfiler *prof)
3731 {
3732         process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3733
3734         mono_debugger_agent_cleanup ();
3735 }
3736
3737 static void
3738 thread_startup (MonoProfiler *prof, uintptr_t tid)
3739 {
3740         MonoInternalThread *thread = mono_thread_internal_current ();
3741         MonoInternalThread *old_thread;
3742         DebuggerTlsData *tls;
3743
3744         if (tid == debugger_thread_id)
3745                 return;
3746
3747         g_assert (thread->tid == tid);
3748
3749         mono_loader_lock ();
3750         old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3751         mono_loader_unlock ();
3752         if (old_thread) {
3753                 if (thread == old_thread) {
3754                         /* 
3755                          * For some reason, thread_startup () might be called for the same thread
3756                          * multiple times (attach ?).
3757                          */
3758                         DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3759                         return;
3760                 } else {
3761                         /*
3762                          * thread_end () might not be called for some threads, and the tid could
3763                          * get reused.
3764                          */
3765                         DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3766                         mono_loader_lock ();
3767                         mono_g_hash_table_remove (thread_to_tls, old_thread);
3768                         mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3769                         mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3770                         mono_loader_unlock ();
3771                 }
3772         }
3773
3774         tls = mono_native_tls_get_value (debugger_tls_id);
3775         g_assert (!tls);
3776         // FIXME: Free this somewhere
3777         tls = g_new0 (DebuggerTlsData, 1);
3778         MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3779         tls->thread = thread;
3780         mono_native_tls_set_value (debugger_tls_id, tls);
3781
3782         DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3783
3784         mono_loader_lock ();
3785         mono_g_hash_table_insert (thread_to_tls, thread, tls);
3786         mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3787         mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3788         mono_loader_unlock ();
3789
3790         process_profiler_event (EVENT_KIND_THREAD_START, thread);
3791
3792         /* 
3793          * suspend_vm () could have missed this thread, so wait for a resume.
3794          */
3795         suspend_current ();
3796 }
3797
3798 static void
3799 thread_end (MonoProfiler *prof, uintptr_t tid)
3800 {
3801         MonoInternalThread *thread;
3802         DebuggerTlsData *tls = NULL;
3803
3804         mono_loader_lock ();
3805         thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3806         if (thread) {
3807                 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3808                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3809                 if (tls) {
3810                         /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3811                         tls->terminated = TRUE;
3812                         /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3813                         MONO_GC_UNREGISTER_ROOT (tls->thread);
3814                         tls->thread = NULL;
3815                 }
3816         }
3817         mono_loader_unlock ();
3818
3819         /* We might be called for threads started before we registered the start callback */
3820         if (thread) {
3821                 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3822                 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3823         }
3824 }
3825
3826 static void
3827 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3828 {
3829         mono_loader_lock ();
3830         g_hash_table_insert (domains, domain, domain);
3831         mono_loader_unlock ();
3832
3833         process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3834 }
3835
3836 static void
3837 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3838 {
3839         clear_breakpoints_for_domain (domain);
3840         
3841         mono_loader_lock ();
3842         /* Invalidate each thread's frame stack */
3843         mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3844         mono_loader_unlock ();
3845         
3846         process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3847 }
3848
3849 /*
3850  * invalidate_each_thread:
3851  *
3852  *   A GHFunc to invalidate frames.
3853  *   value must be a DebuggerTlsData*
3854  */
3855 static void
3856 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3857 {
3858         invalidate_frames (value);
3859 }
3860
3861 static void
3862 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3863 {
3864         /* Sent later in jit_end () */
3865         mono_loader_lock ();
3866         g_ptr_array_add (pending_assembly_loads, assembly);
3867         mono_loader_unlock ();
3868 }
3869
3870 static void
3871 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3872 {
3873         process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3874
3875         clear_event_requests_for_assembly (assembly);
3876         clear_types_for_assembly (assembly);
3877 }
3878
3879 static void
3880 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3881 {
3882 #if defined(HOST_WIN32) && !defined(__GNUC__)
3883         gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3884 #else
3885         gpointer stackptr = __builtin_frame_address (1);
3886 #endif
3887         MonoInternalThread *thread = mono_thread_internal_current ();
3888         DebuggerTlsData *tls;
3889
3890         mono_loader_lock ();
3891         
3892         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3893         /* Could be the debugger thread with assembly/type load hooks */
3894         if (tls)
3895                 tls->invoke_addr = stackptr;
3896
3897         mono_loader_unlock ();
3898 }
3899
3900 static void
3901 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3902 {
3903         int i;
3904 #if defined(HOST_WIN32) && !defined(__GNUC__)
3905         gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3906 #else
3907         gpointer stackptr = __builtin_frame_address (1);
3908 #endif
3909
3910         if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3911                 return;
3912
3913         /*
3914          * We need to stop single stepping when exiting a runtime invoke, since if it is
3915          * a step out, it may return to native code, and thus never end.
3916          */
3917         mono_loader_lock ();
3918         ss_invoke_addr = NULL;
3919
3920         for (i = 0; i < event_requests->len; ++i) {
3921                 EventRequest *req = g_ptr_array_index (event_requests, i);
3922
3923                 if (req->event_kind == EVENT_KIND_STEP) {
3924                         ss_destroy (req->info);
3925                         g_ptr_array_remove_index_fast (event_requests, i);
3926                         g_free (req);
3927                         break;
3928                 }
3929         }
3930         mono_loader_unlock ();
3931 }
3932
3933 static void
3934 send_type_load (MonoClass *klass)
3935 {
3936         gboolean type_load = FALSE;
3937         MonoDomain *domain = mono_domain_get ();
3938         AgentDomainInfo *info = NULL;
3939
3940         mono_loader_lock ();
3941         mono_domain_lock (domain);
3942
3943         info = get_agent_domain_info (domain);
3944
3945         if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3946                 type_load = TRUE;
3947                 g_hash_table_insert (info->loaded_classes, klass, klass);
3948         }
3949
3950         mono_domain_unlock (domain);
3951         mono_loader_unlock ();
3952         if (type_load)
3953                 emit_type_load (klass, klass, NULL);
3954 }
3955
3956 /*
3957  * Emit load events for all types currently loaded in the domain.
3958  * Takes the loader and domain locks.
3959  * user_data is unused.
3960  */
3961 static void
3962 send_types_for_domain (MonoDomain *domain, void *user_data)
3963 {
3964         AgentDomainInfo *info = NULL;
3965         
3966         mono_loader_lock ();
3967         mono_domain_lock (domain);
3968         info =  get_agent_domain_info (domain);
3969         g_assert (info);
3970         g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3971         mono_domain_unlock (domain);
3972         mono_loader_unlock ();
3973 }
3974
3975 static void
3976 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3977 {
3978         /*
3979          * We emit type load events when the first method of the type is JITted,
3980          * since the class load profiler callbacks might be called with the
3981          * loader lock held. They could also occur in the debugger thread.
3982          * Same for assembly load events.
3983          */
3984         while (TRUE) {
3985                 MonoAssembly *assembly = NULL;
3986
3987                 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3988                 mono_loader_lock ();
3989                 if (pending_assembly_loads->len > 0) {
3990                         assembly = g_ptr_array_index (pending_assembly_loads, 0);
3991                         g_ptr_array_remove_index (pending_assembly_loads, 0);
3992                 }
3993                 mono_loader_unlock ();
3994
3995                 if (assembly) {
3996                         process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3997                 } else {
3998                         break;
3999                 }
4000         }
4001
4002         send_type_load (method->klass);
4003
4004         if (!result)
4005                 add_pending_breakpoints (method, jinfo);
4006 }
4007
4008 /*
4009  * BREAKPOINTS/SINGLE STEPPING
4010  */
4011
4012 /* 
4013  * Contains information about an inserted breakpoint.
4014  */
4015 typedef struct {
4016         long il_offset, native_offset;
4017         guint8 *ip;
4018         MonoJitInfo *ji;
4019         MonoDomain *domain;
4020         SeqPoint *sp;
4021 } BreakpointInstance;
4022
4023 /*
4024  * Contains generic information about a breakpoint.
4025  */
4026 typedef struct {
4027         /* 
4028          * The method where the breakpoint is placed. Can be NULL in which case it 
4029          * is inserted into every method. This is used to implement method entry/
4030          * exit events. Can be a generic method definition, in which case the
4031          * breakpoint is inserted into every instance.
4032          */
4033         MonoMethod *method;
4034         long il_offset;
4035         EventRequest *req;
4036         /* 
4037          * A list of BreakpointInstance structures describing where the breakpoint
4038          * was inserted. There could be more than one because of 
4039          * generics/appdomains/method entry/exit.
4040          */
4041         GPtrArray *children;
4042 } MonoBreakpoint;
4043
4044 /* List of breakpoints */
4045 static GPtrArray *breakpoints;
4046 /* Maps breakpoint locations to the number of breakpoints at that location */
4047 static GHashTable *bp_locs;
4048
4049 static void
4050 breakpoints_init (void)
4051 {
4052         breakpoints = g_ptr_array_new ();
4053         bp_locs = g_hash_table_new (NULL, NULL);
4054 }       
4055
4056 /*
4057  * insert_breakpoint:
4058  *
4059  *   Insert the breakpoint described by BP into the method described by
4060  * JI.
4061  */
4062 static void
4063 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4064 {
4065         int i, count;
4066         BreakpointInstance *inst;
4067         SeqPoint *sp = NULL;
4068
4069         if (error)
4070                 mono_error_init (error);
4071
4072         for (i = 0; i < seq_points->len; ++i) {
4073                 sp = &seq_points->seq_points [i];
4074
4075                 if (sp->il_offset == bp->il_offset)
4076                         break;
4077         }
4078
4079         if (i == seq_points->len) {
4080                 /*
4081                  * The set of IL offsets with seq points doesn't completely match the
4082                  * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4083                  */
4084                 for (i = 0; i < seq_points->len; ++i) {
4085                         sp = &seq_points->seq_points [i];
4086
4087                         if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4088                                 break;
4089                 }
4090         }
4091
4092         if (i == seq_points->len) {
4093                 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (ji->method, TRUE), bp->il_offset, seq_points->len);
4094
4095                 for (i = 0; i < seq_points->len; ++i)
4096                         DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4097
4098                 if (error) {
4099                         mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4100                         g_warning ("%s", s);
4101                         g_free (s);
4102                         return;
4103                 } else {
4104                         g_warning ("%s", s);
4105                         g_free (s);
4106                         return;
4107                 }
4108         }
4109
4110         inst = g_new0 (BreakpointInstance, 1);
4111         inst->sp = sp;
4112         inst->native_offset = sp->native_offset;
4113         inst->ip = (guint8*)ji->code_start + sp->native_offset;
4114         inst->ji = ji;
4115         inst->domain = domain;
4116
4117         mono_loader_lock ();
4118
4119         g_ptr_array_add (bp->children, inst);
4120
4121         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4122         g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4123         mono_loader_unlock ();
4124
4125         if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4126                 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4127         } else if (count == 0) {
4128 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4129                 mono_arch_set_breakpoint (ji, inst->ip);
4130 #else
4131                 NOT_IMPLEMENTED;
4132 #endif
4133         }
4134
4135         DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));  
4136 }
4137
4138 static void
4139 remove_breakpoint (BreakpointInstance *inst)
4140 {
4141 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4142         int count;
4143         MonoJitInfo *ji = inst->ji;
4144         guint8 *ip = inst->ip;
4145
4146         mono_loader_lock ();
4147         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4148         g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4149         mono_loader_unlock ();
4150
4151         g_assert (count > 0);
4152
4153         if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4154                 mono_arch_clear_breakpoint (ji, ip);
4155         }
4156 #else
4157         NOT_IMPLEMENTED;
4158 #endif
4159 }       
4160
4161 static inline gboolean
4162 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4163 {
4164         int i;
4165
4166         if (!bp->method)
4167                 return TRUE;
4168         if (method == bp->method)
4169                 return TRUE;
4170         if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4171                 return TRUE;
4172
4173         if (bp->method->is_inflated && method->is_inflated) {
4174                 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4175                 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4176
4177                 /* Open generic methods should match closed generic methods of the same class */
4178                 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4179                         for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4180                                 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4181
4182                                 /* FIXME: Handle !mvar */
4183                                 if (t1->type != MONO_TYPE_MVAR)
4184                                         return FALSE;
4185                         }
4186                         return TRUE;
4187                 }
4188         }
4189
4190         return FALSE;
4191 }
4192
4193 /*
4194  * add_pending_breakpoints:
4195  *
4196  *   Insert pending breakpoints into the newly JITted method METHOD.
4197  */
4198 static void
4199 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4200 {
4201         int i, j;
4202         MonoSeqPointInfo *seq_points;
4203         MonoDomain *domain;
4204
4205         if (!breakpoints)
4206                 return;
4207
4208         domain = mono_domain_get ();
4209
4210         mono_loader_lock ();
4211
4212         for (i = 0; i < breakpoints->len; ++i) {
4213                 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4214                 gboolean found = FALSE;
4215
4216                 if (!bp_matches_method (bp, method))
4217                         continue;
4218
4219                 for (j = 0; j < bp->children->len; ++j) {
4220                         BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4221
4222                         if (inst->ji == ji)
4223                                 found = TRUE;
4224                 }
4225
4226                 if (!found) {
4227                         mono_domain_lock (domain);
4228                         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4229                         if (!seq_points && ji->method->is_inflated)
4230                                 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4231                         mono_domain_unlock (domain);
4232                         if (!seq_points)
4233                                 /* Could be AOT code */
4234                                 continue;
4235                         g_assert (seq_points);
4236
4237                         insert_breakpoint (seq_points, domain, ji, bp, NULL);
4238                 }
4239         }
4240
4241         mono_loader_unlock ();
4242 }
4243
4244 static void
4245 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4246 {
4247         gpointer code;
4248         MonoJitInfo *ji;
4249
4250         if (error)
4251                 mono_error_init (error);
4252
4253         code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4254         if (!code) {
4255                 /* Might be AOTed code */
4256                 code = mono_aot_get_method (domain, method);
4257                 g_assert (code);
4258                 ji = mono_jit_info_table_find (domain, code);
4259                 g_assert (ji);
4260         }
4261         g_assert (code);
4262
4263         insert_breakpoint (seq_points, domain, ji, bp, error);
4264 }
4265
4266 static void
4267 clear_breakpoint (MonoBreakpoint *bp);
4268
4269 /*
4270  * set_breakpoint:
4271  *
4272  *   Set a breakpoint at IL_OFFSET in METHOD.
4273  * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4274  * METHOD can also be a generic method definition, in which case a breakpoint
4275  * is placed in all instances of the method.
4276  * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4277  * inserted.
4278  */
4279 static MonoBreakpoint*
4280 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4281 {
4282         MonoBreakpoint *bp;
4283         GHashTableIter iter, iter2;
4284         MonoDomain *domain;
4285         MonoMethod *m;
4286         MonoSeqPointInfo *seq_points;
4287
4288         if (error)
4289                 mono_error_init (error);
4290
4291         // FIXME:
4292         // - suspend/resume the vm to prevent code patching problems
4293         // - multiple breakpoints on the same location
4294         // - dynamic methods
4295         // - races
4296
4297         bp = g_new0 (MonoBreakpoint, 1);
4298         bp->method = method;
4299         bp->il_offset = il_offset;
4300         bp->req = req;
4301         bp->children = g_ptr_array_new ();
4302
4303         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));
4304
4305         mono_loader_lock ();
4306
4307         g_hash_table_iter_init (&iter, domains);
4308         while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4309                 mono_domain_lock (domain);
4310
4311                 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4312                 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4313                         if (bp_matches_method (bp, m))
4314                                 set_bp_in_method (domain, m, seq_points, bp, error);
4315                 }
4316
4317                 mono_domain_unlock (domain);
4318         }
4319
4320         mono_loader_unlock ();
4321
4322         mono_loader_lock ();
4323         g_ptr_array_add (breakpoints, bp);
4324         mono_loader_unlock ();
4325
4326         if (error && !mono_error_ok (error)) {
4327                 clear_breakpoint (bp);
4328                 return NULL;
4329         }
4330
4331         return bp;
4332 }
4333
4334 static void
4335 clear_breakpoint (MonoBreakpoint *bp)
4336 {
4337         int i;
4338
4339         // FIXME: locking, races
4340         for (i = 0; i < bp->children->len; ++i) {
4341                 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4342
4343                 remove_breakpoint (inst);
4344
4345                 g_free (inst);
4346         }
4347
4348         mono_loader_lock ();
4349         g_ptr_array_remove (breakpoints, bp);
4350         mono_loader_unlock ();
4351
4352         g_ptr_array_free (bp->children, TRUE);
4353         g_free (bp);
4354 }
4355
4356 static void
4357 breakpoints_cleanup (void)
4358 {
4359         int i;
4360
4361         mono_loader_lock ();
4362         i = 0;
4363         while (i < event_requests->len) {
4364                 EventRequest *req = g_ptr_array_index (event_requests, i);
4365
4366                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4367                         clear_breakpoint (req->info);
4368                         g_ptr_array_remove_index_fast (event_requests, i);
4369                         g_free (req);
4370                 } else {
4371                         i ++;
4372                 }
4373         }
4374
4375         for (i = 0; i < breakpoints->len; ++i)
4376                 g_free (g_ptr_array_index (breakpoints, i));
4377
4378         g_ptr_array_free (breakpoints, TRUE);
4379         g_hash_table_destroy (bp_locs);
4380
4381         breakpoints = NULL;
4382         bp_locs = NULL;
4383
4384         mono_loader_unlock ();
4385 }
4386
4387 /*
4388  * clear_breakpoints_for_domain:
4389  *
4390  *   Clear breakpoint instances which reference DOMAIN.
4391  */
4392 static void
4393 clear_breakpoints_for_domain (MonoDomain *domain)
4394 {
4395         int i, j;
4396
4397         /* This could be called after shutdown */
4398         if (!breakpoints)
4399                 return;
4400
4401         mono_loader_lock ();
4402         for (i = 0; i < breakpoints->len; ++i) {
4403                 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4404
4405                 j = 0;
4406                 while (j < bp->children->len) {
4407                         BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4408
4409                         if (inst->domain == domain) {
4410                                 remove_breakpoint (inst);
4411
4412                                 g_free (inst);
4413
4414                                 g_ptr_array_remove_index_fast (bp->children, j);
4415                         } else {
4416                                 j ++;
4417                         }
4418                 }
4419         }
4420         mono_loader_unlock ();
4421 }
4422
4423 /*
4424  * ss_update:
4425  *
4426  * Return FALSE if single stepping needs to continue because we are at the same line.
4427  */
4428 static gboolean
4429 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp)
4430 {
4431         MonoDebugMethodInfo *minfo;
4432         MonoDebugSourceLocation *loc = NULL;
4433         gboolean hit = TRUE;
4434
4435         if (req->size != STEP_SIZE_LINE)
4436                 return TRUE;
4437
4438         /* Have to check whenever a different source line was reached */
4439         minfo = mono_debug_lookup_method (ji->method);
4440
4441         if (minfo)
4442                 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4443
4444         if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4445                 /* Have to continue single stepping */
4446                 if (!loc)
4447                         DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4448                 else
4449                         DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4450                 hit = FALSE;
4451         }
4452                                 
4453         if (loc) {
4454                 ss_req->last_method = ji->method;
4455                 ss_req->last_line = loc->row;
4456                 mono_debug_free_source_location (loc);
4457         }
4458
4459         return hit;
4460 }
4461
4462 static gboolean
4463 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4464 {
4465         return bp->method && bp->method->klass->image->assembly == assembly;
4466 }
4467
4468 static void
4469 process_breakpoint_inner (DebuggerTlsData *tls)
4470 {
4471         MonoJitInfo *ji;
4472         guint8 *ip;
4473         int i, j, suspend_policy;
4474         guint32 native_offset;
4475         MonoBreakpoint *bp;
4476         BreakpointInstance *inst;
4477         GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4478         GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4479         EventKind kind = EVENT_KIND_BREAKPOINT;
4480         MonoContext *ctx = &tls->restore_ctx;
4481         MonoSeqPointInfo *info;
4482         SeqPoint *sp;
4483
4484         // FIXME: Speed this up
4485
4486         ip = MONO_CONTEXT_GET_IP (ctx);
4487         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4488         g_assert (ji);
4489         g_assert (ji->method);
4490
4491         /* Compute the native offset of the breakpoint from the ip */
4492         native_offset = ip - (guint8*)ji->code_start;   
4493
4494         /* 
4495          * Skip the instruction causing the breakpoint signal.
4496          */
4497         mono_arch_skip_breakpoint (ctx, ji);
4498
4499         if (ji->method->wrapper_type || tls->disable_breakpoints)
4500                 return;
4501
4502         bp_reqs = g_ptr_array_new ();
4503         ss_reqs = g_ptr_array_new ();
4504         ss_reqs_orig = g_ptr_array_new ();
4505
4506         mono_loader_lock ();
4507
4508         /*
4509          * The ip points to the instruction causing the breakpoint event, which is after
4510          * the offset recorded in the seq point map, so find the prev seq point before ip.
4511          */
4512         sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4513         if (!sp)
4514                 no_seq_points_found (ji->method);
4515         g_assert (sp);
4516
4517         DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, ip, native_offset, sp ? sp->il_offset : -1));
4518
4519         bp = NULL;
4520         for (i = 0; i < breakpoints->len; ++i) {
4521                 bp = g_ptr_array_index (breakpoints, i);
4522
4523                 if (!bp->method)
4524                         continue;
4525
4526                 for (j = 0; j < bp->children->len; ++j) {
4527                         inst = g_ptr_array_index (bp->children, j);
4528                         if (inst->ji == ji && inst->sp == sp) {
4529                                 if (bp->req->event_kind == EVENT_KIND_STEP) {
4530                                         g_ptr_array_add (ss_reqs_orig, bp->req);
4531                                 } else {
4532                                         g_ptr_array_add (bp_reqs, bp->req);
4533                                 }
4534                         }
4535                 }
4536         }
4537         if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4538                 /* Maybe a method entry/exit event */
4539                 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4540                         kind = EVENT_KIND_METHOD_ENTRY;
4541                 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4542                         kind = EVENT_KIND_METHOD_EXIT;
4543         }
4544
4545         /* Process single step requests */
4546         for (i = 0; i < ss_reqs_orig->len; ++i) {
4547                 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4548                 SingleStepReq *ss_req = req->info;
4549                 gboolean hit;
4550
4551                 hit = ss_update (ss_req, ji, sp);
4552                 if (hit)
4553                         g_ptr_array_add (ss_reqs, req);
4554
4555                 /* Start single stepping again from the current sequence point */
4556                 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4557         }
4558         
4559         if (ss_reqs->len > 0)
4560                 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4561         if (bp_reqs->len > 0)
4562                 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4563         if (kind != EVENT_KIND_BREAKPOINT)
4564                 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4565
4566         mono_loader_unlock ();
4567
4568         g_ptr_array_free (bp_reqs, TRUE);
4569         g_ptr_array_free (ss_reqs, TRUE);
4570
4571         /* 
4572          * FIXME: The first event will suspend, so the second will only be sent after the
4573          * resume.
4574          */
4575         if (ss_events)
4576                 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4577         if (bp_events)
4578                 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4579         if (enter_leave_events)
4580                 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4581 }
4582
4583 /* Process a breakpoint/single step event after resuming from a signal handler */
4584 static void
4585 process_signal_event (void (*func) (DebuggerTlsData*))
4586 {
4587         DebuggerTlsData *tls;
4588         MonoContext orig_restore_ctx, ctx;
4589         static void (*restore_context) (void *);
4590
4591         if (!restore_context)
4592                 restore_context = mono_get_restore_context ();
4593
4594         tls = mono_native_tls_get_value (debugger_tls_id);
4595         /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4596         memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4597         memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4598
4599         func (tls);
4600
4601         /* This is called when resuming from a signal handler, so it shouldn't return */
4602         memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4603         memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4604         restore_context (&ctx);
4605         g_assert_not_reached ();
4606 }
4607
4608 static void
4609 process_breakpoint (void)
4610 {
4611         process_signal_event (process_breakpoint_inner);
4612 }
4613
4614 static void
4615 resume_from_signal_handler (void *sigctx, void *func)
4616 {
4617         DebuggerTlsData *tls;
4618         MonoContext ctx;
4619
4620         /* Save the original context in TLS */
4621         // FIXME: This might not work on an altstack ?
4622         tls = mono_native_tls_get_value (debugger_tls_id);
4623         if (!tls)
4624                 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4625         g_assert (tls);
4626
4627         // FIXME: MonoContext usually doesn't include the fp registers, so these are 
4628         // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4629         // clob:c could be added to op_seq_point.
4630
4631         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4632         memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4633 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4634         mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4635 #else
4636         MONO_CONTEXT_SET_IP (&ctx, func);
4637 #endif
4638         mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4639
4640 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4641         mono_ppc_set_func_into_sigctx (sigctx, func);
4642 #endif
4643 }
4644
4645 void
4646 mono_debugger_agent_breakpoint_hit (void *sigctx)
4647 {
4648         /*
4649          * We are called from a signal handler, and running code there causes all kinds of
4650          * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4651          * So set up the signal context to return to the real breakpoint handler function.
4652          */
4653         resume_from_signal_handler (sigctx, process_breakpoint);
4654 }
4655
4656 static gboolean
4657 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4658 {
4659         if (frame->managed) {
4660                 *(MonoContext*)data = *ctx;
4661
4662                 return TRUE;
4663         } else {
4664                 return FALSE;
4665         }
4666 }
4667
4668 /*
4669  * Called by System.Diagnostics.Debugger:Break ().
4670  */
4671 void
4672 mono_debugger_agent_user_break (void)
4673 {
4674         if (agent_config.enabled) {
4675                 MonoContext ctx;
4676                 int suspend_policy;
4677                 GSList *events;
4678
4679                 /* Obtain a context */
4680                 MONO_CONTEXT_SET_IP (&ctx, NULL);
4681                 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4682                 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4683
4684                 mono_loader_lock ();
4685                 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4686                 mono_loader_unlock ();
4687
4688                 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4689         } else {
4690                 G_BREAKPOINT ();
4691         }
4692 }
4693
4694 static const char*
4695 ss_depth_to_string (StepDepth depth)
4696 {
4697         switch (depth) {
4698         case STEP_DEPTH_OVER:
4699                 return "over";
4700         case STEP_DEPTH_OUT:
4701                 return "out";
4702         case STEP_DEPTH_INTO:
4703                 return "into";
4704         default:
4705                 g_assert_not_reached ();
4706                 return NULL;
4707         }
4708 }
4709
4710 static void
4711 process_single_step_inner (DebuggerTlsData *tls)
4712 {
4713         MonoJitInfo *ji;
4714         guint8 *ip;
4715         GPtrArray *reqs;
4716         int il_offset, suspend_policy;
4717         MonoDomain *domain;
4718         GSList *events;
4719         MonoContext *ctx = &tls->restore_ctx;
4720         SeqPoint *sp;
4721         MonoSeqPointInfo *info;
4722
4723         ip = MONO_CONTEXT_GET_IP (ctx);
4724
4725         /* Skip the instruction causing the single step */
4726         mono_arch_skip_single_step (ctx);
4727
4728         if (suspend_count > 0) {
4729                 process_suspend (tls, ctx);
4730                 return;
4731         }
4732
4733         if (!ss_req)
4734                 // FIXME: A suspend race
4735                 return;
4736
4737         if (mono_thread_internal_current () != ss_req->thread)
4738                 return;
4739
4740         if (log_level > 0) {
4741                 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4742
4743                 DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_depth_to_string (ss_req->depth), mono_method_full_name (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4744         }
4745
4746         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4747         g_assert (ji);
4748         g_assert (ji->method);
4749
4750         if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4751                 return;
4752
4753         /* 
4754          * FIXME: 
4755          * Stopping in memset makes half-initialized vtypes visible.
4756          * Stopping in memcpy makes half-copied vtypes visible.
4757          */
4758         if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4759                 return;
4760
4761         /*
4762          * The ip points to the instruction causing the single step event, which is before
4763          * the offset recorded in the seq point map, so find the next seq point after ip.
4764          */
4765         sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4766         if (!sp)
4767                 return;
4768         il_offset = sp->il_offset;
4769
4770         if (!ss_update (ss_req, ji, sp))
4771                 return;
4772
4773         /* Start single stepping again from the current sequence point */
4774         ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4775
4776         if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4777                 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4778                 !strcmp (ji->method->name, ".cctor"))
4779                 return;
4780
4781         // FIXME: Has to lock earlier
4782
4783         reqs = g_ptr_array_new ();
4784
4785         mono_loader_lock ();
4786
4787         g_ptr_array_add (reqs, ss_req->req);
4788
4789         events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4790
4791         g_ptr_array_free (reqs, TRUE);
4792
4793         mono_loader_unlock ();
4794
4795         process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4796 }
4797
4798 static void
4799 process_single_step (void)
4800 {
4801         process_signal_event (process_single_step_inner);
4802 }
4803
4804 /*
4805  * mono_debugger_agent_single_step_event:
4806  *
4807  *   Called from a signal handler to handle a single step event.
4808  */
4809 void
4810 mono_debugger_agent_single_step_event (void *sigctx)
4811 {
4812         /* Resume to process_single_step through the signal context */
4813
4814         // FIXME: Since step out/over is implemented using step in, the step in case should
4815         // be as fast as possible. Move the relevant code from process_single_step_inner ()
4816         // here
4817
4818         if (GetCurrentThreadId () == debugger_thread_id) {
4819                 /* 
4820                  * This could happen despite our best effors when the runtime calls 
4821                  * assembly/type resolve hooks.
4822                  * FIXME: Breakpoints too.
4823                  */
4824                 MonoContext ctx;
4825
4826                 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4827                 mono_arch_skip_single_step (&ctx);
4828                 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4829                 return;
4830         }
4831
4832         resume_from_signal_handler (sigctx, process_single_step);
4833 }
4834
4835 void
4836 debugger_agent_single_step_from_context (MonoContext *ctx)
4837 {
4838         DebuggerTlsData *tls;
4839         MonoContext orig_restore_ctx;
4840
4841         tls = mono_native_tls_get_value (debugger_tls_id);
4842         g_assert (tls);
4843
4844         /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4845         memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4846         memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4847
4848         process_single_step_inner (tls);
4849
4850         memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4851         memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4852 }
4853
4854 void
4855 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4856 {
4857         DebuggerTlsData *tls;
4858         MonoContext orig_restore_ctx;
4859
4860         tls = mono_native_tls_get_value (debugger_tls_id);
4861         g_assert (tls);
4862         memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4863         memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4864
4865         process_breakpoint_inner (tls);
4866
4867         memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4868         memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4869 }
4870
4871 /*
4872  * start_single_stepping:
4873  *
4874  *   Turn on single stepping. Can be called multiple times, for example,
4875  * by a single step event request + a suspend.
4876  */
4877 static void
4878 start_single_stepping (void)
4879 {
4880 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4881         int val = InterlockedIncrement (&ss_count);
4882
4883         if (val == 1)
4884                 mono_arch_start_single_stepping ();
4885
4886         if (ss_req != NULL && ss_invoke_addr == NULL) {
4887                 DebuggerTlsData *tls;
4888         
4889                 mono_loader_lock ();
4890         
4891                 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4892                 ss_invoke_addr = tls->invoke_addr;
4893                 
4894                 mono_loader_unlock ();
4895         }
4896 #else
4897         g_assert_not_reached ();
4898 #endif
4899 }
4900
4901 static void
4902 stop_single_stepping (void)
4903 {
4904 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4905         int val = InterlockedDecrement (&ss_count);
4906
4907         if (val == 0)
4908                 mono_arch_stop_single_stepping ();
4909         if (ss_req != NULL)
4910                 ss_invoke_addr = NULL;
4911 #else
4912         g_assert_not_reached ();
4913 #endif
4914 }
4915
4916 /*
4917  * ss_stop:
4918  *
4919  *   Stop the single stepping operation given by SS_REQ.
4920  */
4921 static void
4922 ss_stop (SingleStepReq *ss_req)
4923 {
4924         if (ss_req->bps) {
4925                 GSList *l;
4926
4927                 for (l = ss_req->bps; l; l = l->next) {
4928                         clear_breakpoint (l->data);
4929                 }
4930                 g_slist_free (ss_req->bps);
4931                 ss_req->bps = NULL;
4932         }
4933
4934         if (ss_req->global) {
4935                 stop_single_stepping ();
4936                 ss_req->global = FALSE;
4937         }
4938 }
4939
4940 /*
4941  * ss_start:
4942  *
4943  *   Start the single stepping operation given by SS_REQ from the sequence point SP.
4944  * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4945  * belong to the same thread as CTX.
4946  */
4947 static void
4948 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4949 {
4950         int i, j, frame_index;
4951         SeqPoint *next_sp;
4952         MonoBreakpoint *bp;
4953         gboolean enable_global = FALSE;
4954
4955         /* Stop the previous operation */
4956         ss_stop (ss_req);
4957
4958         /*
4959          * Implement single stepping using breakpoints if possible.
4960          */
4961         if (step_to_catch) {
4962                 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4963                 ss_req->bps = g_slist_append (ss_req->bps, bp);
4964         } else {
4965                 frame_index = 1;
4966
4967                 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4968                         /* Need parent frames */
4969                         if (!tls->context.valid)
4970                                 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4971                         compute_frame_info (tls->thread, tls);
4972                 }
4973
4974                 /*
4975                  * Find the first sequence point in the current or in a previous frame which
4976                  * is not the last in its method.
4977                  */
4978                 if (ss_req->depth == STEP_DEPTH_OUT) {
4979                         /* Ignore seq points in current method */
4980                         while (frame_index < tls->frame_count) {
4981                                 StackFrame *frame = tls->frames [frame_index];
4982
4983                                 method = frame->method;
4984                                 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4985                                 frame_index ++;
4986                                 if (sp && sp->next_len != 0)
4987                                         break;
4988                         }
4989                         // There could be method calls before the next seq point in the caller when using nested calls
4990                         //enable_global = TRUE;
4991                 } else {
4992                         if (sp && sp->next_len == 0) {
4993                                 sp = NULL;
4994                                 while (frame_index < tls->frame_count) {
4995                                         StackFrame *frame = tls->frames [frame_index];
4996
4997                                         method = frame->method;
4998                                         sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4999                                         if (sp && sp->next_len != 0)
5000                                                 break;
5001                                         sp = NULL;
5002                                         frame_index ++;
5003                                 }
5004                         }
5005                 }
5006
5007                 if (sp && sp->next_len > 0) {
5008                         for (i = 0; i < sp->next_len; ++i) {
5009                                 next_sp = &info->seq_points [sp->next [i]];
5010
5011                                 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5012                                 ss_req->bps = g_slist_append (ss_req->bps, bp);
5013                         }
5014                 }
5015
5016                 if (ss_req->depth == STEP_DEPTH_OVER) {
5017                         /* Need to stop in catch clauses as well */
5018                         for (i = 0; i < tls->frame_count; ++i) {
5019                                 StackFrame *frame = tls->frames [i];
5020
5021                                 if (frame->ji) {
5022                                         MonoJitInfo *jinfo = frame->ji;
5023                                         for (j = 0; j < jinfo->num_clauses; ++j) {
5024                                                 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5025
5026                                                 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5027                                                 if (sp) {
5028                                                         bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5029                                                         ss_req->bps = g_slist_append (ss_req->bps, bp);
5030                                                 }
5031                                         }
5032                                 }
5033                         }
5034                 }
5035
5036
5037                 if (ss_req->depth == STEP_DEPTH_INTO) {
5038                         /* Enable global stepping so we stop at method entry too */
5039                         enable_global = TRUE;
5040                 }
5041
5042                 /*
5043                  * The ctx/frame info computed above will become invalid when we continue.
5044                  */
5045                 tls->context.valid = FALSE;
5046                 tls->async_state.valid = FALSE;
5047                 invalidate_frames (tls);
5048         }
5049
5050         if (enable_global) {
5051                 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5052                 ss_req->global = TRUE;
5053                 start_single_stepping ();
5054         } else if (!ss_req->bps) {
5055                 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5056                 ss_req->global = TRUE;
5057                 start_single_stepping ();
5058         } else {
5059                 ss_req->global = FALSE;
5060         }
5061 }
5062
5063 /*
5064  * Start single stepping of thread THREAD
5065  */
5066 static ErrorCode
5067 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5068 {
5069         DebuggerTlsData *tls;
5070         MonoSeqPointInfo *info = NULL;
5071         SeqPoint *sp = NULL;
5072         MonoMethod *method = NULL;
5073         MonoDebugMethodInfo *minfo;
5074         gboolean step_to_catch = FALSE;
5075
5076         if (suspend_count == 0)
5077                 return ERR_NOT_SUSPENDED;
5078
5079         wait_for_suspend ();
5080
5081         // FIXME: Multiple requests
5082         if (ss_req) {
5083                 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5084                 return ERR_NOT_IMPLEMENTED;
5085         }
5086
5087         DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5088
5089         ss_req = g_new0 (SingleStepReq, 1);
5090         ss_req->req = req;
5091         ss_req->thread = thread;
5092         ss_req->size = size;
5093         ss_req->depth = depth;
5094         req->info = ss_req;
5095
5096         mono_loader_lock ();
5097         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5098         mono_loader_unlock ();
5099         g_assert (tls);
5100         g_assert (tls->context.valid);
5101         ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5102
5103         if (tls->catch_state.valid) {
5104                 gboolean res;
5105                 StackFrameInfo frame;
5106                 MonoContext new_ctx;
5107                 MonoLMF *lmf = NULL;
5108
5109                 /*
5110                  * We are stopped at a throw site. Stepping should go to the catch site.
5111                  */
5112
5113                 /* Find the the jit info for the catch context */
5114                 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);
5115                 g_assert (res);
5116                 g_assert (frame.type == FRAME_TYPE_MANAGED);
5117
5118                 /*
5119                  * Find the seq point corresponding to the landing site ip, which is the first seq
5120                  * point after ip.
5121                  */
5122                 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5123                 if (!sp)
5124                         no_seq_points_found (frame.method);
5125                 g_assert (sp);
5126
5127                 method = frame.method;
5128
5129                 step_to_catch = TRUE;
5130                 /* This make sure the seq point is not skipped by process_single_step () */
5131                 ss_req->last_sp = NULL;
5132         }
5133
5134         if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5135                 StackFrame *frame;
5136
5137                 /* Compute the initial line info */
5138                 compute_frame_info (thread, tls);
5139
5140                 if (tls->frame_count) {
5141                         frame = tls->frames [0];
5142
5143                         ss_req->last_method = frame->method;
5144                         ss_req->last_line = -1;
5145
5146                         minfo = mono_debug_lookup_method (frame->method);
5147                         if (minfo && frame->il_offset != -1) {
5148                                 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5149
5150                                 if (loc) {
5151                                         ss_req->last_line = loc->row;
5152                                         g_free (loc);
5153                                 }
5154                         }
5155                 }
5156         }
5157
5158         if (!step_to_catch) {
5159                 StackFrame *frame;
5160
5161                 compute_frame_info (thread, tls);
5162
5163                 if (tls->frame_count) {
5164                         frame = tls->frames [0];
5165
5166                         if (!method && frame->il_offset != -1) {
5167                                 /* FIXME: Sort the table and use a binary search */
5168                                 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5169                                 if (!sp)
5170                                         no_seq_points_found (frame->method);
5171                                 g_assert (sp);
5172                                 method = frame->method;
5173                         }
5174                 }
5175         }
5176
5177         ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5178
5179         return 0;
5180 }
5181
5182 static void
5183 ss_destroy (SingleStepReq *req)
5184 {
5185         // FIXME: Locking
5186         g_assert (ss_req == req);
5187
5188         ss_stop (ss_req);
5189
5190         g_free (ss_req);
5191         ss_req = NULL;
5192 }
5193
5194 /*
5195  * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5196  */
5197 void
5198 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5199 {
5200         int suspend_policy;
5201         GSList *events;
5202         EventInfo ei;
5203
5204         if (!agent_config.enabled)
5205                 return;
5206
5207         mono_loader_lock ();
5208         events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5209         mono_loader_unlock ();
5210
5211         ei.level = level;
5212         ei.category = category ? mono_string_to_utf8 (category) : NULL;
5213         ei.message = message ? mono_string_to_utf8 (message) : NULL;
5214
5215         process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5216
5217         g_free (ei.category);
5218         g_free (ei.message);
5219 }
5220
5221 gboolean
5222 mono_debugger_agent_debug_log_is_enabled (void)
5223 {
5224         /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5225         return agent_config.enabled;
5226 }
5227
5228 #ifdef PLATFORM_ANDROID
5229 void
5230 mono_debugger_agent_unhandled_exception (MonoException *exc)
5231 {
5232         int suspend_policy;
5233         GSList *events;
5234         EventInfo ei;
5235
5236         if (!inited)
5237                 return;
5238
5239         memset (&ei, 0, sizeof (EventInfo));
5240         ei.exc = (MonoObject*)exc;
5241
5242         mono_loader_lock ();
5243         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5244         mono_loader_unlock ();
5245
5246         process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5247 }
5248 #endif
5249
5250 void
5251 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx, 
5252                                       MonoContext *catch_ctx)
5253 {
5254         int i, j, suspend_policy;
5255         GSList *events;
5256         MonoJitInfo *ji, *catch_ji;
5257         EventInfo ei;
5258         DebuggerTlsData *tls = NULL;
5259
5260         if (thread_to_tls != NULL) {
5261                 MonoInternalThread *thread = mono_thread_internal_current ();
5262
5263                 mono_loader_lock ();
5264                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5265                 mono_loader_unlock ();
5266
5267                 if (tls && tls->abort_requested)
5268                         return;
5269                 if (tls && tls->disable_breakpoints)
5270                         return;
5271         }
5272
5273         memset (&ei, 0, sizeof (EventInfo));
5274
5275         /* Just-In-Time debugging */
5276         if (!catch_ctx) {
5277                 if (agent_config.onuncaught && !inited) {
5278                         finish_agent_init (FALSE);
5279
5280                         /*
5281                          * Send an unsolicited EXCEPTION event with a dummy request id.
5282                          */
5283                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5284                         ei.exc = (MonoObject*)exc;
5285                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5286                         return;
5287                 }
5288         } else if (agent_config.onthrow && !inited) {
5289                 GSList *l;
5290                 gboolean found = FALSE;
5291
5292                 for (l = agent_config.onthrow; l; l = l->next) {
5293                         char *ex_type = l->data;
5294                         char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5295
5296                         if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5297                                 found = TRUE;
5298
5299                         g_free (f);
5300                 }
5301
5302                 if (found) {
5303                         finish_agent_init (FALSE);
5304
5305                         /*
5306                          * Send an unsolicited EXCEPTION event with a dummy request id.
5307                          */
5308                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5309                         ei.exc = (MonoObject*)exc;
5310                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5311                         return;
5312                 }
5313         }
5314
5315         if (!inited)
5316                 return;
5317
5318         ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5319         if (catch_ctx)
5320                 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5321         else
5322                 catch_ji = NULL;
5323
5324         ei.exc = (MonoObject*)exc;
5325         ei.caught = catch_ctx != NULL;
5326
5327         mono_loader_lock ();
5328
5329         /* Treat exceptions which are caught in non-user code as unhandled */
5330         for (i = 0; i < event_requests->len; ++i) {
5331                 EventRequest *req = g_ptr_array_index (event_requests, i);
5332                 if (req->event_kind != EVENT_KIND_EXCEPTION)
5333                         continue;
5334
5335                 for (j = 0; j < req->nmodifiers; ++j) {
5336                         Modifier *mod = &req->modifiers [j];
5337
5338                         if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5339                                 int k;
5340                                 gboolean found = FALSE;
5341                                 MonoAssembly **assemblies = mod->data.assemblies;
5342
5343                                 if (assemblies) {
5344                                         for (k = 0; assemblies [k]; ++k)
5345                                                 if (assemblies [k] == catch_ji->method->klass->image->assembly)
5346                                                         found = TRUE;
5347                                 }
5348                                 if (!found)
5349                                         ei.caught = FALSE;
5350                         }
5351                 }
5352         }
5353
5354         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5355         mono_loader_unlock ();
5356
5357         if (tls && ei.caught && catch_ctx) {
5358                 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5359                 tls->catch_state.ctx = *catch_ctx;
5360                 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5361                 tls->catch_state.valid = TRUE;
5362         }
5363
5364         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5365
5366         if (tls)
5367                 tls->catch_state.valid = FALSE;
5368 }
5369
5370 void
5371 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5372 {
5373         DebuggerTlsData *tls;
5374
5375         if (!inited)
5376                 return;
5377
5378         tls = mono_native_tls_get_value (debugger_tls_id);
5379         if (!tls)
5380                 return;
5381
5382         /*
5383          * We're about to invoke an exception filter during the first pass of exception handling.
5384          *
5385          * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5386          * 'orig_ctx' is the context where the exception has been thrown.
5387          *
5388          *
5389          * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5390          *
5391          * If we're stopped in Filter(), normal stack unwinding would first unwind to
5392          * the call site (line 37) and then continue to Main(), but it would never
5393          * include the throw site (line 32).
5394          *
5395          * Since exception filters are invoked during the first pass of exception handling,
5396          * the stack frames of the throw site are still intact, so we should include them
5397          * in a stack trace.
5398          *
5399          * We do this here by saving the context of the throw site in 'tls->filter_state'.
5400          *
5401          * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5402          * but report the location of the 'throw' to the user.
5403          *
5404          */
5405
5406         g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5407 }
5408
5409 void
5410 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5411 {
5412         DebuggerTlsData *tls;
5413
5414         if (!inited)
5415                 return;
5416
5417         tls = mono_native_tls_get_value (debugger_tls_id);
5418         if (!tls)
5419                 return;
5420
5421         tls->filter_state.valid = FALSE;
5422 }
5423
5424 /*
5425  * buffer_add_value_full:
5426  *
5427  *   Add the encoding of the value at ADDR described by T to the buffer.
5428  * AS_VTYPE determines whenever to treat primitive types as primitive types or
5429  * vtypes.
5430  */
5431 static void
5432 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5433                                            gboolean as_vtype)
5434 {
5435         MonoObject *obj;
5436
5437         if (t->byref) {
5438                 if (!(*(void**)addr)) {
5439                         /* This can happen with compiler generated locals */
5440                         //printf ("%s\n", mono_type_full_name (t));
5441                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5442                         return;
5443                 }
5444                 g_assert (*(void**)addr);
5445                 addr = *(void**)addr;
5446         }
5447
5448         if (as_vtype) {
5449                 switch (t->type) {
5450                 case MONO_TYPE_BOOLEAN:
5451                 case MONO_TYPE_I1:
5452                 case MONO_TYPE_U1:
5453                 case MONO_TYPE_CHAR:
5454                 case MONO_TYPE_I2:
5455                 case MONO_TYPE_U2:
5456                 case MONO_TYPE_I4:
5457                 case MONO_TYPE_U4:
5458                 case MONO_TYPE_R4:
5459                 case MONO_TYPE_I8:
5460                 case MONO_TYPE_U8:
5461                 case MONO_TYPE_R8:
5462                 case MONO_TYPE_I:
5463                 case MONO_TYPE_U:
5464                 case MONO_TYPE_PTR:
5465                         goto handle_vtype;
5466                         break;
5467                 default:
5468                         break;
5469                 }
5470         }
5471
5472         switch (t->type) {
5473         case MONO_TYPE_VOID:
5474                 buffer_add_byte (buf, t->type);
5475                 break;
5476         case MONO_TYPE_BOOLEAN:
5477         case MONO_TYPE_I1:
5478         case MONO_TYPE_U1:
5479                 buffer_add_byte (buf, t->type);
5480                 buffer_add_int (buf, *(gint8*)addr);
5481                 break;
5482         case MONO_TYPE_CHAR:
5483         case MONO_TYPE_I2:
5484         case MONO_TYPE_U2:
5485                 buffer_add_byte (buf, t->type);
5486                 buffer_add_int (buf, *(gint16*)addr);
5487                 break;
5488         case MONO_TYPE_I4:
5489         case MONO_TYPE_U4:
5490         case MONO_TYPE_R4:
5491                 buffer_add_byte (buf, t->type);
5492                 buffer_add_int (buf, *(gint32*)addr);
5493                 break;
5494         case MONO_TYPE_I8:
5495         case MONO_TYPE_U8:
5496         case MONO_TYPE_R8:
5497                 buffer_add_byte (buf, t->type);
5498                 buffer_add_long (buf, *(gint64*)addr);
5499                 break;
5500         case MONO_TYPE_I:
5501         case MONO_TYPE_U:
5502                 /* Treat it as a vtype */
5503                 goto handle_vtype;
5504         case MONO_TYPE_PTR: {
5505                 gssize val = *(gssize*)addr;
5506                 
5507                 buffer_add_byte (buf, t->type);
5508                 buffer_add_long (buf, val);
5509                 break;
5510         }
5511         handle_ref:
5512         case MONO_TYPE_STRING:
5513         case MONO_TYPE_SZARRAY:
5514         case MONO_TYPE_OBJECT:
5515         case MONO_TYPE_CLASS:
5516         case MONO_TYPE_ARRAY:
5517                 obj = *(MonoObject**)addr;
5518
5519                 if (!obj) {
5520                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5521                 } else {
5522                         if (obj->vtable->klass->valuetype) {
5523                                 t = &obj->vtable->klass->byval_arg;
5524                                 addr = mono_object_unbox (obj);
5525                                 goto handle_vtype;
5526                         } else if (obj->vtable->klass->rank) {
5527                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5528                         } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5529                                 buffer_add_byte (buf, MONO_TYPE_CLASS);
5530                         } else {
5531                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5532                         }
5533                         buffer_add_objid (buf, obj);
5534                 }
5535                 break;
5536         handle_vtype:
5537         case MONO_TYPE_VALUETYPE: {
5538                 int nfields;
5539                 gpointer iter;
5540                 MonoClassField *f;
5541                 MonoClass *klass = mono_class_from_mono_type (t);
5542
5543                 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5544                 buffer_add_byte (buf, klass->enumtype);
5545                 buffer_add_typeid (buf, domain, klass);
5546
5547                 nfields = 0;
5548                 iter = NULL;
5549                 while ((f = mono_class_get_fields (klass, &iter))) {
5550                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5551                                 continue;
5552                         if (mono_field_is_deleted (f))
5553                                 continue;
5554                         nfields ++;
5555                 }
5556                 buffer_add_int (buf, nfields);
5557
5558                 iter = NULL;
5559                 while ((f = mono_class_get_fields (klass, &iter))) {
5560                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5561                                 continue;
5562                         if (mono_field_is_deleted (f))
5563                                 continue;
5564                         buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5565                 }
5566                 break;
5567         }
5568         case MONO_TYPE_GENERICINST:
5569                 if (mono_type_generic_inst_is_valuetype (t)) {
5570                         goto handle_vtype;
5571                 } else {
5572                         goto handle_ref;
5573                 }
5574                 break;
5575         default:
5576                 NOT_IMPLEMENTED;
5577         }
5578 }
5579
5580 static void
5581 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5582 {
5583         buffer_add_value_full (buf, t, addr, domain, FALSE);
5584 }
5585
5586 static gboolean
5587 obj_is_of_type (MonoObject *obj, MonoType *t)
5588 {
5589         MonoClass *klass = obj->vtable->klass;
5590         if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5591                 if (mono_class_is_transparent_proxy (klass)) {
5592                         klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5593                         if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5594                                 return TRUE;
5595                         }
5596                 }
5597                 return FALSE;
5598         }
5599         return TRUE;
5600 }
5601
5602 static ErrorCode
5603 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5604
5605 static ErrorCode
5606 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5607 {
5608         gboolean is_enum;
5609         MonoClass *klass;
5610         MonoClassField *f;
5611         int nfields;
5612         gpointer iter = NULL;
5613         MonoDomain *d;
5614         int err;
5615
5616         is_enum = decode_byte (buf, &buf, limit);
5617         /* Enums are sent as a normal vtype */
5618         if (is_enum)
5619                 return ERR_NOT_IMPLEMENTED;
5620         klass = decode_typeid (buf, &buf, limit, &d, &err);
5621         if (err)
5622                 return err;
5623
5624         if (t && klass != mono_class_from_mono_type (t)) {
5625                 char *name = mono_type_full_name (t);
5626                 char *name2 = mono_type_full_name (&klass->byval_arg);
5627                 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5628                 g_free (name);
5629                 g_free (name2);
5630                 return ERR_INVALID_ARGUMENT;
5631         }
5632
5633         nfields = decode_int (buf, &buf, limit);
5634         while ((f = mono_class_get_fields (klass, &iter))) {
5635                 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5636                         continue;
5637                 if (mono_field_is_deleted (f))
5638                         continue;
5639                 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5640                 if (err)
5641                         return err;
5642                 nfields --;
5643         }
5644         g_assert (nfields == 0);
5645         return 0;
5646 }
5647
5648 static ErrorCode
5649 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5650 {
5651         int err;
5652
5653         if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5654                 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5655                 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5656                 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5657                 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5658                 char *name = mono_type_full_name (t);
5659                 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5660                 g_free (name);
5661                 return ERR_INVALID_ARGUMENT;
5662         }
5663
5664         switch (t->type) {
5665         case MONO_TYPE_BOOLEAN:
5666                 *(guint8*)addr = decode_int (buf, &buf, limit);
5667                 break;
5668         case MONO_TYPE_CHAR:
5669                 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5670                 break;
5671         case MONO_TYPE_I1:
5672                 *(gint8*)addr = decode_int (buf, &buf, limit);
5673                 break;
5674         case MONO_TYPE_U1:
5675                 *(guint8*)addr = decode_int (buf, &buf, limit);
5676                 break;
5677         case MONO_TYPE_I2:
5678                 *(gint16*)addr = decode_int (buf, &buf, limit);
5679                 break;
5680         case MONO_TYPE_U2:
5681                 *(guint16*)addr = decode_int (buf, &buf, limit);
5682                 break;
5683         case MONO_TYPE_I4:
5684                 *(gint32*)addr = decode_int (buf, &buf, limit);
5685                 break;
5686         case MONO_TYPE_U4:
5687                 *(guint32*)addr = decode_int (buf, &buf, limit);
5688                 break;
5689         case MONO_TYPE_I8:
5690                 *(gint64*)addr = decode_long (buf, &buf, limit);
5691                 break;
5692         case MONO_TYPE_U8:
5693                 *(guint64*)addr = decode_long (buf, &buf, limit);
5694                 break;
5695         case MONO_TYPE_R4:
5696                 *(guint32*)addr = decode_int (buf, &buf, limit);
5697                 break;
5698         case MONO_TYPE_R8:
5699                 *(guint64*)addr = decode_long (buf, &buf, limit);
5700                 break;
5701         case MONO_TYPE_PTR:
5702                 /* We send these as I8, so we get them back as such */
5703                 g_assert (type == MONO_TYPE_I8);
5704                 *(gssize*)addr = decode_long (buf, &buf, limit);
5705                 break;
5706         case MONO_TYPE_GENERICINST:
5707                 if (MONO_TYPE_ISSTRUCT (t)) {
5708                         /* The client sends these as a valuetype */
5709                         goto handle_vtype;
5710                 } else {
5711                         goto handle_ref;
5712                 }
5713                 break;
5714         case MONO_TYPE_I:
5715         case MONO_TYPE_U:
5716                 /* We send these as vtypes, so we get them back as such */
5717                 g_assert (type == MONO_TYPE_VALUETYPE);
5718                 /* Fall through */
5719                 handle_vtype:
5720         case MONO_TYPE_VALUETYPE:
5721                 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5722                 if (err)
5723                         return err;
5724                 break;
5725         handle_ref:
5726         default:
5727                 if (MONO_TYPE_IS_REFERENCE (t)) {
5728                         if (type == MONO_TYPE_OBJECT) {
5729                                 int objid = decode_objid (buf, &buf, limit);
5730                                 int err;
5731                                 MonoObject *obj;
5732
5733                                 err = get_object (objid, (MonoObject**)&obj);
5734                                 if (err)
5735                                         return err;
5736
5737                                 if (obj) {
5738                                         if (!obj_is_of_type (obj, t)) {
5739                                                 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5740                                                 return ERR_INVALID_ARGUMENT;
5741                                         }
5742                                 }
5743                                 if (obj && obj->vtable->domain != domain)
5744                                         return ERR_INVALID_ARGUMENT;
5745
5746                                 mono_gc_wbarrier_generic_store (addr, obj);
5747                         } else if (type == VALUE_TYPE_ID_NULL) {
5748                                 *(MonoObject**)addr = NULL;
5749                         } else if (type == MONO_TYPE_VALUETYPE) {
5750                                 guint8 *buf2;
5751                                 gboolean is_enum;
5752                                 MonoClass *klass;
5753                                 MonoDomain *d;
5754                                 guint8 *vtype_buf;
5755                                 int vtype_buf_size;
5756
5757                                 /* This can happen when round-tripping boxed vtypes */
5758                                 /*
5759                                  * Obtain vtype class.
5760                                  * Same as the beginning of the handle_vtype case above.
5761                                  */
5762                                 buf2 = buf;
5763                                 is_enum = decode_byte (buf, &buf, limit);
5764                                 if (is_enum)
5765                                         return ERR_NOT_IMPLEMENTED;
5766                                 klass = decode_typeid (buf, &buf, limit, &d, &err);
5767                                 if (err)
5768                                         return err;
5769
5770                                 /* Decode the vtype into a temporary buffer, then box it. */
5771                                 vtype_buf_size = mono_class_value_size (klass, NULL);
5772                                 vtype_buf = g_malloc0 (vtype_buf_size);
5773                                 g_assert (vtype_buf);
5774
5775                                 buf = buf2;
5776                                 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
5777                                 if (err) {
5778                                         g_free (vtype_buf);
5779                                         return err;
5780                                 }
5781                                 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
5782                                 g_free (vtype_buf);
5783                         } else {
5784                                 char *name = mono_type_full_name (t);
5785                                 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5786                                 g_free (name);
5787                                 return ERR_INVALID_ARGUMENT;
5788                         }
5789                 } else {
5790                         NOT_IMPLEMENTED;
5791                 }
5792                 break;
5793         }
5794
5795         *endbuf = buf;
5796
5797         return 0;
5798 }
5799
5800 static ErrorCode
5801 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5802 {
5803         int err;
5804         int type = decode_byte (buf, &buf, limit);
5805
5806         if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5807                 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5808                 guint8 *nullable_buf;
5809
5810                 /*
5811                  * First try decoding it as a Nullable`1
5812                  */
5813                 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5814                 if (!err)
5815                         return err;
5816
5817                 /*
5818                  * Then try decoding as a primitive value or null.
5819                  */
5820                 if (targ->type == type) {
5821                         nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5822                         err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5823                         if (err) {
5824                                 g_free (nullable_buf);
5825                                 return err;
5826                         }
5827                         mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5828                         g_free (nullable_buf);
5829                         *endbuf = buf;
5830                         return ERR_NONE;
5831                 } else if (type == VALUE_TYPE_ID_NULL) {
5832                         mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5833                         *endbuf = buf;
5834                         return ERR_NONE;
5835                 }
5836         }
5837
5838         return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5839 }
5840
5841 static void
5842 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5843 {
5844         guint32 flags;
5845         int reg;
5846         guint8 *addr, *gaddr;
5847         mgreg_t reg_val;
5848
5849         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5850         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5851
5852         switch (flags) {
5853         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5854                 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5855
5856                 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype);
5857                 break;
5858         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5859                 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5860                 addr += (gint32)var->offset;
5861
5862                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5863
5864                 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5865                 break;
5866         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5867                 NOT_IMPLEMENTED;
5868                 break;
5869         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5870                 /* Same as regoffset, but with an indirection */
5871                 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5872                 addr += (gint32)var->offset;
5873
5874                 gaddr = *(gpointer*)addr;
5875                 g_assert (gaddr);
5876                 buffer_add_value_full (buf, t, gaddr, domain, as_vtype);
5877                 break;
5878         case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5879                 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5880                 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5881                 MonoGSharedVtMethodRuntimeInfo *info;
5882                 guint8 *locals;
5883                 int idx;
5884
5885                 idx = reg;
5886
5887                 g_assert (info_var);
5888                 g_assert (locals_var);
5889
5890                 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5891                 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5892                 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5893                         addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5894                         addr += (gint32)info_var->offset;
5895                         info = *(gpointer*)addr;
5896                 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5897                         info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5898                 } else {
5899                         g_assert_not_reached ();
5900                 }
5901                 g_assert (info);
5902
5903                 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5904                 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5905                 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5906                         addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5907                         addr += (gint32)locals_var->offset;
5908                         locals = *(gpointer*)addr;
5909                 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5910                         locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5911                 } else {
5912                         g_assert_not_reached ();
5913                 }
5914                 g_assert (locals);
5915
5916                 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5917
5918                 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5919                 break;
5920         }
5921
5922         default:
5923                 g_assert_not_reached ();
5924         }
5925 }
5926
5927 static void
5928 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5929 {
5930         guint32 flags;
5931         int reg, size;
5932         guint8 *addr, *gaddr;
5933
5934         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5935         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5936
5937         if (MONO_TYPE_IS_REFERENCE (t))
5938                 size = sizeof (gpointer);
5939         else
5940                 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5941
5942         switch (flags) {
5943         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5944 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5945                 mgreg_t v;
5946                 gboolean is_signed = FALSE;
5947
5948                 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5949                         is_signed = TRUE;
5950
5951                 switch (size) {
5952                 case 1:
5953                         v = is_signed ? *(gint8*)val : *(guint8*)val;
5954                         break;
5955                 case 2:
5956                         v = is_signed ? *(gint16*)val : *(guint16*)val;
5957                         break;
5958                 case 4:
5959                         v = is_signed ? *(gint32*)val : *(guint32*)val;
5960                         break;
5961                 case 8:
5962                         v = is_signed ? *(gint64*)val : *(guint64*)val;
5963                         break;
5964                 default:
5965                         g_assert_not_reached ();
5966                 }
5967
5968                 if (t->byref)
5969                         NOT_IMPLEMENTED;
5970
5971                 /* Set value on the stack or in the return ctx */
5972                 if (reg_locations [reg]) {
5973                         /* Saved on the stack */
5974                         DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5975                         *(reg_locations [reg]) = v;
5976                 } else {
5977                         /* Not saved yet */
5978                         DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5979                         mono_arch_context_set_int_reg (restore_ctx, reg, v);
5980                 }                       
5981
5982                 // FIXME: Move these to mono-context.h/c.
5983                 mono_arch_context_set_int_reg (ctx, reg, v);
5984 #else
5985                 // FIXME: Can't set registers, so we disable linears
5986                 NOT_IMPLEMENTED;
5987 #endif
5988                 break;
5989         }
5990         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5991                 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5992                 addr += (gint32)var->offset;
5993
5994                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5995
5996                 if (t->byref) {
5997                         addr = *(guint8**)addr;
5998
5999                         if (!addr)
6000                                 break;
6001                 }
6002                         
6003                 // FIXME: Write barriers
6004                 mono_gc_memmove (addr, val, size);
6005                 break;
6006         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6007                 /* Same as regoffset, but with an indirection */
6008                 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6009                 addr += (gint32)var->offset;
6010
6011                 gaddr = *(gpointer*)addr;
6012                 g_assert (gaddr);
6013                 // FIXME: Write barriers
6014                 mono_gc_memmove (gaddr, val, size);
6015                 break;
6016         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6017                 NOT_IMPLEMENTED;
6018                 break;
6019         default:
6020                 g_assert_not_reached ();
6021         }
6022 }
6023
6024 static void
6025 clear_event_request (int req_id, int etype)
6026 {
6027         int i;
6028
6029         mono_loader_lock ();
6030         for (i = 0; i < event_requests->len; ++i) {
6031                 EventRequest *req = g_ptr_array_index (event_requests, i);
6032
6033                 if (req->id == req_id && req->event_kind == etype) {
6034                         if (req->event_kind == EVENT_KIND_BREAKPOINT)
6035                                 clear_breakpoint (req->info);
6036                         if (req->event_kind == EVENT_KIND_STEP)
6037                                 ss_destroy (req->info);
6038                         if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6039                                 clear_breakpoint (req->info);
6040                         if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6041                                 clear_breakpoint (req->info);
6042                         g_ptr_array_remove_index_fast (event_requests, i);
6043                         g_free (req);
6044                         break;
6045                 }
6046         }
6047         mono_loader_unlock ();
6048 }
6049
6050 static gboolean
6051 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
6052 {
6053         if (req->event_kind == EVENT_KIND_BREAKPOINT)
6054                 return breakpoint_matches_assembly (req->info, assembly);
6055         else {
6056                 int i, j;
6057
6058                 for (i = 0; i < req->nmodifiers; ++i) {
6059                         Modifier *m = &req->modifiers [i];
6060
6061                         if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6062                                 return TRUE;
6063                         if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6064                                 for (j = 0; m->data.assemblies [j]; ++j)
6065                                         if (m->data.assemblies [j] == assembly)
6066                                                 return TRUE;
6067                         }
6068                 }
6069         }
6070
6071         return FALSE;
6072 }
6073
6074 /*
6075  * clear_event_requests_for_assembly:
6076  *
6077  *   Clear all events requests which reference ASSEMBLY.
6078  */
6079 static void
6080 clear_event_requests_for_assembly (MonoAssembly *assembly)
6081 {
6082         int i;
6083         gboolean found;
6084
6085         mono_loader_lock ();
6086         found = TRUE;
6087         while (found) {
6088                 found = FALSE;
6089                 for (i = 0; i < event_requests->len; ++i) {
6090                         EventRequest *req = g_ptr_array_index (event_requests, i);
6091
6092                         if (event_req_matches_assembly (req, assembly)) {
6093                                 clear_event_request (req->id, req->event_kind);
6094                                 found = TRUE;
6095                                 break;
6096                         }
6097                 }
6098         }
6099         mono_loader_unlock ();
6100 }
6101
6102 /*
6103  * type_comes_from_assembly:
6104  *
6105  *   GHRFunc that returns TRUE if klass comes from assembly
6106  */
6107 static gboolean
6108 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6109 {
6110         return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6111 }
6112
6113 /*
6114  * clear_types_for_assembly:
6115  *
6116  *   Clears types from loaded_classes for a given assembly
6117  */
6118 static void
6119 clear_types_for_assembly (MonoAssembly *assembly)
6120 {
6121         MonoDomain *domain = mono_domain_get ();
6122         AgentDomainInfo *info = NULL;
6123
6124         mono_loader_lock ();
6125         info = get_agent_domain_info (domain);
6126         g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6127         mono_loader_unlock ();
6128 }
6129
6130 static void
6131 add_thread (gpointer key, gpointer value, gpointer user_data)
6132 {
6133         MonoInternalThread *thread = value;
6134         Buffer *buf = user_data;
6135
6136         buffer_add_objid (buf, (MonoObject*)thread);
6137 }
6138
6139 static ErrorCode
6140 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6141 {
6142         guint8 *end = invoke->endp;
6143         MonoMethod *m;
6144         int i, err, nargs;
6145         MonoMethodSignature *sig;
6146         guint8 **arg_buf;
6147         void **args;
6148         MonoObject *this, *res, *exc;
6149         MonoDomain *domain;
6150         guint8 *this_buf;
6151 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6152         MonoLMFExt ext;
6153 #endif
6154         MonoStopwatch watch;
6155
6156         if (invoke->method) {
6157                 /* 
6158                  * Invoke this method directly, currently only Environment.Exit () is supported.
6159                  */
6160                 this = NULL;
6161                 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>"));
6162                 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6163                 g_assert_not_reached ();
6164         }
6165
6166         m = decode_methodid (p, &p, end, &domain, &err);
6167         if (err)
6168                 return err;
6169         sig = mono_method_signature (m);
6170
6171         if (m->klass->valuetype)
6172                 this_buf = g_alloca (mono_class_instance_size (m->klass));
6173         else
6174                 this_buf = g_alloca (sizeof (MonoObject*));
6175         if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6176                 /* Should be null */
6177                 int type = decode_byte (p, &p, end);
6178                 if (type != VALUE_TYPE_ID_NULL) {
6179                         DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6180                         return ERR_INVALID_ARGUMENT;
6181                 }
6182                 memset (this_buf, 0, mono_class_instance_size (m->klass));
6183         } else {
6184                 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6185                 if (err)
6186                         return err;
6187         }
6188
6189         if (!m->klass->valuetype)
6190                 this = *(MonoObject**)this_buf;
6191         else
6192                 this = NULL;
6193
6194         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>"));
6195
6196         if (this && this->vtable->domain != domain)
6197                 NOT_IMPLEMENTED;
6198
6199         if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6200                 if (!strcmp (m->name, ".ctor")) {
6201                         if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6202                                 return ERR_INVALID_ARGUMENT;
6203                         else
6204                                 this = mono_object_new (domain, m->klass);
6205                 } else {
6206                         return ERR_INVALID_ARGUMENT;
6207                 }
6208         }
6209
6210         if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6211                 return ERR_INVALID_ARGUMENT;
6212
6213         nargs = decode_int (p, &p, end);
6214         if (nargs != sig->param_count)
6215                 return ERR_INVALID_ARGUMENT;
6216         /* Use alloca to get gc tracking */
6217         arg_buf = g_alloca (nargs * sizeof (gpointer));
6218         memset (arg_buf, 0, nargs * sizeof (gpointer));
6219         args = g_alloca (nargs * sizeof (gpointer));
6220         for (i = 0; i < nargs; ++i) {
6221                 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6222                         err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6223                         if (err)
6224                                 break;
6225
6226                         if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6227                                 NOT_IMPLEMENTED;
6228                 } else {
6229                         arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6230                         err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6231                         if (err)
6232                                 break;
6233                         args [i] = arg_buf [i];
6234                 }
6235         }
6236
6237         if (i < nargs)
6238                 return err;
6239
6240         if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6241                 tls->disable_breakpoints = TRUE;
6242         else
6243                 tls->disable_breakpoints = FALSE;
6244
6245         /* 
6246          * Add an LMF frame to link the stack frames on the invoke method with our caller.
6247          */
6248         /* FIXME: Move this to arch specific code */
6249 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6250         if (invoke->has_ctx) {
6251                 MonoLMF **lmf_addr;
6252
6253                 lmf_addr = mono_get_lmf_addr ();
6254
6255                 /* Setup our lmf */
6256                 memset (&ext, 0, sizeof (ext));
6257 #ifdef TARGET_AMD64
6258                 ext.lmf.previous_lmf = *(lmf_addr);
6259                 /* Mark that this is a MonoLMFExt */
6260                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6261                 ext.lmf.rsp = (gssize)&ext;
6262 #elif defined(TARGET_X86)
6263                 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6264                 /* Mark that this is a MonoLMFExt */
6265                 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6266                 ext.lmf.ebp = (gssize)&ext;
6267 #elif defined(TARGET_ARM)
6268                 ext.lmf.previous_lmf = *(lmf_addr);
6269                 /* Mark that this is a MonoLMFExt */
6270                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6271                 ext.lmf.sp = (gssize)&ext;
6272 #elif defined(TARGET_POWERPC)
6273                 ext.lmf.previous_lmf = *(lmf_addr);
6274                 /* Mark that this is a MonoLMFExt */
6275                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6276                 ext.lmf.ebp = (gssize)&ext;
6277 #elif defined(TARGET_S390X)
6278                 ext.lmf.previous_lmf = *(lmf_addr);
6279                 /* Mark that this is a MonoLMFExt */
6280                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6281                 ext.lmf.ebp = (gssize)&ext;
6282 #elif defined(TARGET_MIPS)
6283                 ext.lmf.previous_lmf = *(lmf_addr);
6284                 /* Mark that this is a MonoLMFExt */
6285                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6286                 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6287 #else
6288                 g_assert_not_reached ();
6289 #endif
6290
6291                 ext.debugger_invoke = TRUE;
6292                 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6293
6294                 mono_set_lmf ((MonoLMF*)&ext);
6295         }
6296 #endif
6297
6298         mono_stopwatch_start (&watch);
6299         if (m->klass->valuetype)
6300                 res = mono_runtime_invoke (m, this_buf, args, &exc);
6301         else
6302                 res = mono_runtime_invoke (m, this, args, &exc);
6303         mono_stopwatch_stop (&watch);
6304         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)));
6305         if (exc) {
6306                 buffer_add_byte (buf, 0);
6307                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6308         } else {
6309                 buffer_add_byte (buf, 1);
6310                 if (sig->ret->type == MONO_TYPE_VOID) {
6311                         if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6312                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6313                         }
6314                         else
6315                                 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6316                 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6317                         buffer_add_value (buf, sig->ret, &res, domain);
6318                 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6319                         if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6320                                 MonoClass *k = mono_class_from_mono_type (sig->ret);
6321                                 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6322
6323                                 g_assert (nullable_buf);
6324                                 mono_nullable_init (nullable_buf, res, k);
6325                                 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6326                         } else {
6327                                 g_assert (res);
6328                                 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6329                         }
6330                 } else {
6331                         NOT_IMPLEMENTED;
6332                 }
6333         }
6334
6335         tls->disable_breakpoints = FALSE;
6336
6337 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6338         if (invoke->has_ctx)
6339                 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6340 #endif
6341
6342         *endp = p;
6343         // FIXME: byref arguments
6344         // FIXME: varargs
6345         return ERR_NONE;
6346 }
6347
6348 /*
6349  * invoke_method:
6350  *
6351  *   Invoke the method given by tls->pending_invoke in the current thread.
6352  */
6353 static void
6354 invoke_method (void)
6355 {
6356         DebuggerTlsData *tls;
6357         InvokeData *invoke;
6358         int id;
6359         int i, err, mindex;
6360         Buffer buf;
6361         static void (*restore_context) (void *);
6362         MonoContext restore_ctx;
6363         guint8 *p;
6364
6365         if (!restore_context)
6366                 restore_context = mono_get_restore_context ();
6367
6368         tls = mono_native_tls_get_value (debugger_tls_id);
6369         g_assert (tls);
6370
6371         /*
6372          * Store the `InvokeData *' in `tls->invoke' until we're done with
6373          * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6374          */
6375
6376         mono_loader_lock ();
6377
6378         invoke = tls->pending_invoke;
6379         g_assert (invoke);
6380         tls->pending_invoke = NULL;
6381
6382         invoke->last_invoke = tls->invoke;
6383         tls->invoke = invoke;
6384
6385         mono_loader_unlock ();
6386
6387         tls->frames_up_to_date = FALSE;
6388
6389         id = invoke->id;
6390
6391         p = invoke->p;
6392         err = 0;
6393         for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6394                 buffer_init (&buf, 128);
6395
6396                 if (err) {
6397                         /* Fail the other invokes as well */
6398                 } else {
6399                         err = do_invoke_method (tls, &buf, invoke, p, &p);
6400                 }
6401
6402                 /* Start suspending before sending the reply */
6403                 if (mindex == invoke->nmethods - 1) {
6404                         if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6405                                 for (i = 0; i < invoke->suspend_count; ++i)
6406                                         suspend_vm ();
6407                         }
6408                 }
6409
6410                 send_reply_packet (id, err, &buf);
6411         
6412                 buffer_free (&buf);
6413         }
6414
6415         memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6416
6417         if (invoke->has_ctx)
6418                 save_thread_context (&restore_ctx);
6419
6420         if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6421                 g_assert (tls->resume_count);
6422                 tls->resume_count -= invoke->suspend_count;
6423         }
6424
6425         DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6426
6427         /*
6428          * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6429          *
6430          * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6431          * after the mono_runtime_invoke() already returned, but it doesn't matter
6432          * because we reset the abort here.
6433          */
6434
6435         mono_loader_lock ();
6436
6437         if (tls->abort_requested)
6438                 mono_thread_internal_reset_abort (tls->thread);
6439
6440         tls->invoke = tls->invoke->last_invoke;
6441         tls->abort_requested = FALSE;
6442
6443         mono_loader_unlock ();
6444
6445         g_free (invoke->p);
6446         g_free (invoke);
6447
6448         suspend_current ();
6449 }
6450
6451 static gboolean
6452 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6453 {
6454         MonoThread *thread = value;
6455         DebuggerTlsData *tls;
6456         gboolean res;
6457
6458         mono_loader_lock ();
6459         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6460         g_assert (tls);
6461         res = tls->really_suspended;
6462         mono_loader_unlock ();
6463
6464         return res;
6465 }
6466
6467 static GPtrArray*
6468 get_source_files_for_type (MonoClass *klass)
6469 {
6470         gpointer iter = NULL;
6471         MonoMethod *method;
6472         MonoDebugSourceInfo *sinfo;
6473         GPtrArray *files;
6474         int i, j;
6475
6476         files = g_ptr_array_new ();
6477
6478         while ((method = mono_class_get_methods (klass, &iter))) {
6479                 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6480                 GPtrArray *source_file_list;
6481
6482                 if (minfo) {
6483                         mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6484                         for (j = 0; j < source_file_list->len; ++j) {
6485                                 sinfo = g_ptr_array_index (source_file_list, j);
6486                                 for (i = 0; i < files->len; ++i)
6487                                         if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6488                                                 break;
6489                                 if (i == files->len)
6490                                         g_ptr_array_add (files, g_strdup (sinfo->source_file));
6491                         }
6492                         g_ptr_array_free (source_file_list, TRUE);
6493                 }
6494         }
6495
6496         return files;
6497 }
6498
6499 static ErrorCode
6500 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6501 {
6502         switch (command) {
6503         case CMD_VM_VERSION: {
6504                 char *build_info, *version;
6505
6506                 build_info = mono_get_runtime_build_info ();
6507                 version = g_strdup_printf ("mono %s", build_info);
6508
6509                 buffer_add_string (buf, version); /* vm version */
6510                 buffer_add_int (buf, MAJOR_VERSION);
6511                 buffer_add_int (buf, MINOR_VERSION);
6512                 g_free (build_info);
6513                 g_free (version);
6514                 break;
6515         }
6516         case CMD_VM_SET_PROTOCOL_VERSION: {
6517                 major_version = decode_int (p, &p, end);
6518                 minor_version = decode_int (p, &p, end);
6519                 protocol_version_set = TRUE;
6520                 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6521                 break;
6522         }
6523         case CMD_VM_ALL_THREADS: {
6524                 // FIXME: Domains
6525                 mono_loader_lock ();
6526                 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6527                 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6528                 mono_loader_unlock ();
6529                 break;
6530         }
6531         case CMD_VM_SUSPEND:
6532                 suspend_vm ();
6533                 wait_for_suspend ();
6534                 break;
6535         case CMD_VM_RESUME:
6536                 if (suspend_count == 0)
6537                         return ERR_NOT_SUSPENDED;
6538                 resume_vm ();
6539                 clear_suspended_objs ();
6540                 break;
6541         case CMD_VM_DISPOSE:
6542                 /* Clear all event requests */
6543                 mono_loader_lock ();
6544                 while (event_requests->len > 0) {
6545                         EventRequest *req = g_ptr_array_index (event_requests, 0);
6546
6547                         clear_event_request (req->id, req->event_kind);
6548                 }
6549                 mono_loader_unlock ();
6550
6551                 while (suspend_count > 0)
6552                         resume_vm ();
6553                 disconnected = TRUE;
6554                 vm_start_event_sent = FALSE;
6555                 break;
6556         case CMD_VM_EXIT: {
6557                 MonoInternalThread *thread;
6558                 DebuggerTlsData *tls;
6559 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6560                 MonoClass *env_class;
6561 #endif
6562                 MonoMethod *exit_method = NULL;
6563                 gpointer *args;
6564                 int exit_code;
6565
6566                 exit_code = decode_int (p, &p, end);
6567
6568                 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6569
6570                 /* Have to send a reply before exiting */
6571                 send_reply_packet (id, 0, buf);
6572
6573                 /* Clear all event requests */
6574                 mono_loader_lock ();
6575                 while (event_requests->len > 0) {
6576                         EventRequest *req = g_ptr_array_index (event_requests, 0);
6577
6578                         clear_event_request (req->id, req->event_kind);
6579                 }
6580                 mono_loader_unlock ();
6581
6582                 /*
6583                  * The JDWP documentation says that the shutdown is not orderly. It doesn't
6584                  * specify whenever a VM_DEATH event is sent. We currently do an orderly
6585                  * shutdown by hijacking a thread to execute Environment.Exit (). This is
6586                  * better than doing the shutdown ourselves, since it avoids various races.
6587                  */
6588
6589                 suspend_vm ();
6590                 wait_for_suspend ();
6591
6592 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6593                 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6594                 if (env_class)
6595                         exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6596 #endif
6597
6598                 mono_loader_lock ();
6599                 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6600                 mono_loader_unlock ();
6601
6602                 if (thread && exit_method) {
6603                         mono_loader_lock ();
6604                         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6605                         mono_loader_unlock ();
6606
6607                         args = g_new0 (gpointer, 1);
6608                         args [0] = g_malloc (sizeof (int));
6609                         *(int*)(args [0]) = exit_code;
6610
6611                         tls->pending_invoke = g_new0 (InvokeData, 1);
6612                         tls->pending_invoke->method = exit_method;
6613                         tls->pending_invoke->args = args;
6614                         tls->pending_invoke->nmethods = 1;
6615
6616                         while (suspend_count > 0)
6617                                 resume_vm ();
6618                 } else {
6619                         /* 
6620                          * No thread found, do it ourselves.
6621                          * FIXME: This can race with normal shutdown etc.
6622                          */
6623                         while (suspend_count > 0)
6624                                 resume_vm ();
6625
6626                         if (!mono_runtime_try_shutdown ())
6627                                 break;
6628
6629                         /* Suspend all managed threads since the runtime is going away */
6630                         DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6631                         mono_thread_suspend_all_other_threads ();
6632                         DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6633                         mono_runtime_quit ();
6634                         transport_close2 ();
6635                         DEBUG(1, fprintf (log_file, "Exiting...\n"));
6636
6637                         exit (exit_code);
6638                 }
6639                 break;
6640         }               
6641         case CMD_VM_INVOKE_METHOD:
6642         case CMD_VM_INVOKE_METHODS: {
6643                 int objid = decode_objid (p, &p, end);
6644                 MonoThread *thread;
6645                 DebuggerTlsData *tls;
6646                 int i, count, err, flags, nmethods;
6647
6648                 err = get_object (objid, (MonoObject**)&thread);
6649                 if (err)
6650                         return err;
6651
6652                 flags = decode_int (p, &p, end);
6653
6654                 if (command == CMD_VM_INVOKE_METHODS)
6655                         nmethods = decode_int (p, &p, end);
6656                 else
6657                         nmethods = 1;
6658
6659                 // Wait for suspending if it already started
6660                 if (suspend_count)
6661                         wait_for_suspend ();
6662                 if (!is_suspended ())
6663                         return ERR_NOT_SUSPENDED;
6664
6665                 mono_loader_lock ();
6666                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6667                 mono_loader_unlock ();
6668                 g_assert (tls);
6669
6670                 if (!tls->really_suspended)
6671                         /* The thread is still running native code, can't do invokes */
6672                         return ERR_NOT_SUSPENDED;
6673
6674                 /* 
6675                  * Store the invoke data into tls, the thread will execute it after it is
6676                  * resumed.
6677                  */
6678                 if (tls->pending_invoke)
6679                         return ERR_NOT_SUSPENDED;
6680                 tls->pending_invoke = g_new0 (InvokeData, 1);
6681                 tls->pending_invoke->id = id;
6682                 tls->pending_invoke->flags = flags;
6683                 tls->pending_invoke->p = g_malloc (end - p);
6684                 memcpy (tls->pending_invoke->p, p, end - p);
6685                 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6686                 tls->pending_invoke->suspend_count = suspend_count;
6687                 tls->pending_invoke->nmethods = nmethods;
6688
6689                 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6690                         resume_thread (THREAD_TO_INTERNAL (thread));
6691                 }
6692                 else {
6693                         count = suspend_count;
6694                         for (i = 0; i < count; ++i)
6695                                 resume_vm ();
6696                 }
6697                 break;
6698         }
6699         case CMD_VM_ABORT_INVOKE: {
6700                 int objid = decode_objid (p, &p, end);
6701                 MonoThread *thread;
6702                 DebuggerTlsData *tls;
6703                 int invoke_id, err;
6704
6705                 err = get_object (objid, (MonoObject**)&thread);
6706                 if (err)
6707                         return err;
6708
6709                 invoke_id = decode_int (p, &p, end);
6710
6711                 mono_loader_lock ();
6712                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6713                 g_assert (tls);
6714
6715                 if (tls->abort_requested) {
6716                         mono_loader_unlock ();
6717                         break;
6718                 }
6719
6720                 /*
6721                  * Check whether we're still inside the mono_runtime_invoke() and that it's
6722                  * actually the correct invocation.
6723                  *
6724                  * Careful, we do not stop the thread that's doing the invocation, so we can't
6725                  * inspect its stack.  However, invoke_method() also acquires the loader lock
6726                  * when it's done, so we're safe here.
6727                  *
6728                  */
6729
6730                 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6731                         mono_loader_unlock ();
6732                         return ERR_NO_INVOCATION;
6733                 }
6734
6735                 tls->abort_requested = TRUE;
6736
6737                 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6738                 mono_loader_unlock ();
6739                 break;
6740         }
6741
6742         case CMD_VM_SET_KEEPALIVE: {
6743                 int timeout = decode_int (p, &p, end);
6744                 agent_config.keepalive = timeout;
6745                 // FIXME:
6746 #ifndef DISABLE_SOCKET_TRANSPORT
6747                 set_keepalive ();
6748 #else
6749                 NOT_IMPLEMENTED;
6750 #endif
6751                 break;
6752         }
6753         case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6754                 GHashTableIter iter, kiter;
6755                 MonoDomain *domain;
6756                 MonoClass *klass;
6757                 GPtrArray *files;
6758                 int i;
6759                 char *fname, *basename;
6760                 gboolean ignore_case;
6761                 GSList *class_list, *l;
6762                 GPtrArray *res_classes, *res_domains;
6763
6764                 fname = decode_string (p, &p, end);
6765                 ignore_case = decode_byte (p, &p, end);
6766
6767                 basename = g_path_get_basename (fname);
6768
6769                 res_classes = g_ptr_array_new ();
6770                 res_domains = g_ptr_array_new ();
6771
6772                 mono_loader_lock ();
6773                 g_hash_table_iter_init (&iter, domains);
6774                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6775                         AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6776
6777                         /* Update 'source_file_to_class' cache */
6778                         g_hash_table_iter_init (&kiter, info->loaded_classes);
6779                         while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6780                                 if (!g_hash_table_lookup (info->source_files, klass)) {
6781                                         files = get_source_files_for_type (klass);
6782                                         g_hash_table_insert (info->source_files, klass, files);
6783
6784                                         for (i = 0; i < files->len; ++i) {
6785                                                 char *s = g_ptr_array_index (files, i);
6786                                                 char *s2 = g_path_get_basename (s);
6787                                                 char *s3;
6788
6789                                                 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6790                                                 if (!class_list) {
6791                                                         class_list = g_slist_prepend (class_list, klass);
6792                                                         g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6793                                                 } else {
6794                                                         class_list = g_slist_prepend (class_list, klass);
6795                                                         g_hash_table_insert (info->source_file_to_class, s2, class_list);
6796                                                 }
6797
6798                                                 /* The _ignorecase hash contains the lowercase path */
6799                                                 s3 = strdup_tolower (s2);
6800                                                 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6801                                                 if (!class_list) {
6802                                                         class_list = g_slist_prepend (class_list, klass);
6803                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6804                                                 } else {
6805                                                         class_list = g_slist_prepend (class_list, klass);
6806                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6807                                                 }
6808
6809                                                 g_free (s2);
6810                                                 g_free (s3);
6811                                         }
6812                                 }
6813                         }
6814
6815                         if (ignore_case) {
6816                                 char *s;
6817
6818                                 s = strdup_tolower (basename);
6819                                 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6820                                 g_free (s);
6821                         } else {
6822                                 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6823                         }
6824
6825                         for (l = class_list; l; l = l->next) {
6826                                 klass = l->data;
6827
6828                                 g_ptr_array_add (res_classes, klass);
6829                                 g_ptr_array_add (res_domains, domain);
6830                         }
6831                 }
6832                 mono_loader_unlock ();
6833
6834                 g_free (fname);
6835                 g_free (basename);
6836
6837                 buffer_add_int (buf, res_classes->len);
6838                 for (i = 0; i < res_classes->len; ++i)
6839                         buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6840                 g_ptr_array_free (res_classes, TRUE);
6841                 g_ptr_array_free (res_domains, TRUE);
6842                 break;
6843         }
6844         case CMD_VM_GET_TYPES: {
6845                 GHashTableIter iter;
6846                 MonoDomain *domain;
6847                 int i;
6848                 char *name;
6849                 gboolean ignore_case;
6850                 GPtrArray *res_classes, *res_domains;
6851                 MonoTypeNameParse info;
6852
6853                 name = decode_string (p, &p, end);
6854                 ignore_case = decode_byte (p, &p, end);
6855
6856                 if (!mono_reflection_parse_type (name, &info)) {
6857                         g_free (name);
6858                         mono_reflection_free_type_info (&info);
6859                         return ERR_INVALID_ARGUMENT;
6860                 }
6861
6862                 res_classes = g_ptr_array_new ();
6863                 res_domains = g_ptr_array_new ();
6864
6865                 mono_loader_lock ();
6866                 g_hash_table_iter_init (&iter, domains);
6867                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6868                         MonoAssembly *ass;
6869                         gboolean type_resolve;
6870                         MonoType *t;
6871                         GSList *tmp;
6872
6873                         mono_domain_assemblies_lock (domain);
6874                         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6875                                 ass = tmp->data;
6876
6877                                 if (ass->image) {
6878                                         type_resolve = TRUE;
6879                                         t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6880                                         if (t) {
6881                                                 g_ptr_array_add (res_classes, mono_type_get_class (t));
6882                                                 g_ptr_array_add (res_domains, domain);
6883                                         }
6884                                 }
6885                         }
6886                         mono_domain_assemblies_unlock (domain);
6887                 }
6888                 mono_loader_unlock ();
6889
6890                 g_free (name);
6891                 mono_reflection_free_type_info (&info);
6892
6893                 buffer_add_int (buf, res_classes->len);
6894                 for (i = 0; i < res_classes->len; ++i)
6895                         buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6896                 g_ptr_array_free (res_classes, TRUE);
6897                 g_ptr_array_free (res_domains, TRUE);
6898                 break;
6899         }
6900
6901         default:
6902                 return ERR_NOT_IMPLEMENTED;
6903         }
6904
6905         return ERR_NONE;
6906 }
6907
6908 static ErrorCode
6909 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6910 {
6911         int err;
6912         MonoError error;
6913
6914         switch (command) {
6915         case CMD_EVENT_REQUEST_SET: {
6916                 EventRequest *req;
6917                 int i, event_kind, suspend_policy, nmodifiers, mod;
6918                 MonoMethod *method;
6919                 long location = 0;
6920                 MonoThread *step_thread;
6921                 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6922                 MonoDomain *domain;
6923                 Modifier *modifier;
6924
6925                 event_kind = decode_byte (p, &p, end);
6926                 suspend_policy = decode_byte (p, &p, end);
6927                 nmodifiers = decode_byte (p, &p, end);
6928
6929                 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6930                 req->id = InterlockedIncrement (&event_request_id);
6931                 req->event_kind = event_kind;
6932                 req->suspend_policy = suspend_policy;
6933                 req->nmodifiers = nmodifiers;
6934
6935                 method = NULL;
6936                 for (i = 0; i < nmodifiers; ++i) {
6937                         mod = decode_byte (p, &p, end);
6938
6939                         req->modifiers [i].kind = mod;
6940                         if (mod == MOD_KIND_COUNT) {
6941                                 req->modifiers [i].data.count = decode_int (p, &p, end);
6942                         } else if (mod == MOD_KIND_LOCATION_ONLY) {
6943                                 method = decode_methodid (p, &p, end, &domain, &err);
6944                                 if (err)
6945                                         return err;
6946                                 location = decode_long (p, &p, end);
6947                         } else if (mod == MOD_KIND_STEP) {
6948                                 step_thread_id = decode_id (p, &p, end);
6949                                 size = decode_int (p, &p, end);
6950                                 depth = decode_int (p, &p, end);
6951                                 if (CHECK_PROTOCOL_VERSION (2, 16))
6952                                         filter = decode_int (p, &p, end);
6953                                 req->modifiers [i].data.filter = filter;
6954                         } else if (mod == MOD_KIND_THREAD_ONLY) {
6955                                 int id = decode_id (p, &p, end);
6956
6957                                 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6958                                 if (err) {
6959                                         g_free (req);
6960                                         return err;
6961                                 }
6962                         } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6963                                 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6964
6965                                 if (err)
6966                                         return err;
6967                                 req->modifiers [i].caught = decode_byte (p, &p, end);
6968                                 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6969                                 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : ""));
6970                                 if (exc_class) {
6971                                         req->modifiers [i].data.exc_class = exc_class;
6972
6973                                         if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6974                                                 g_free (req);
6975                                                 return ERR_INVALID_ARGUMENT;
6976                                         }
6977                                 }
6978                         } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6979                                 int n = decode_int (p, &p, end);
6980                                 int j;
6981
6982                                 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6983                                 for (j = 0; j < n; ++j) {
6984                                         req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6985                                         if (err) {
6986                                                 g_free (req->modifiers [i].data.assemblies);
6987                                                 return err;
6988                                         }
6989                                 }
6990                         } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6991                                 int n = decode_int (p, &p, end);
6992                                 int j;
6993
6994                                 modifier = &req->modifiers [i];
6995                                 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6996                                 for (j = 0; j < n; ++j) {
6997                                         char *s = decode_string (p, &p, end);
6998                                         char *s2;
6999
7000                                         if (s) {
7001                                                 s2 = strdup_tolower (s);
7002                                                 g_hash_table_insert (modifier->data.source_files, s2, s2);
7003                                                 g_free (s);
7004                                         }
7005                                 }
7006                         } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7007                                 int n = decode_int (p, &p, end);
7008                                 int j;
7009
7010                                 modifier = &req->modifiers [i];
7011                                 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7012                                 for (j = 0; j < n; ++j) {
7013                                         char *s = decode_string (p, &p, end);
7014
7015                                         if (s)
7016                                                 g_hash_table_insert (modifier->data.type_names, s, s);
7017                                 }
7018                         } else {
7019                                 g_free (req);
7020                                 return ERR_NOT_IMPLEMENTED;
7021                         }
7022                 }
7023
7024                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7025                         g_assert (method);
7026
7027                         req->info = set_breakpoint (method, location, req, &error);
7028                         if (!mono_error_ok (&error)) {
7029                                 g_free (req);
7030                                 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7031                                 mono_error_cleanup (&error);
7032                                 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7033                         }
7034                 } else if (req->event_kind == EVENT_KIND_STEP) {
7035                         g_assert (step_thread_id);
7036
7037                         err = get_object (step_thread_id, (MonoObject**)&step_thread);
7038                         if (err) {
7039                                 g_free (req);
7040                                 return err;
7041                         }
7042
7043                         err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7044                         if (err) {
7045                                 g_free (req);
7046                                 return err;
7047                         }
7048                 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7049                         req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7050                 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7051                         req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7052                 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7053                 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7054                 } else {
7055                         if (req->nmodifiers) {
7056                                 g_free (req);
7057                                 return ERR_NOT_IMPLEMENTED;
7058                         }
7059                 }
7060
7061                 mono_loader_lock ();
7062                 g_ptr_array_add (event_requests, req);
7063                 
7064                 if (agent_config.defer) {
7065                         /* Transmit cached data to the client on receipt of the event request */
7066                         switch (req->event_kind) {
7067                         case EVENT_KIND_APPDOMAIN_CREATE:
7068                                 /* Emit load events for currently loaded domains */
7069                                 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7070                                 break;
7071                         case EVENT_KIND_ASSEMBLY_LOAD:
7072                                 /* Emit load events for currently loaded assemblies */
7073                                 mono_assembly_foreach (emit_assembly_load, NULL);
7074                                 break;
7075                         case EVENT_KIND_THREAD_START:
7076                                 /* Emit start events for currently started threads */
7077                                 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7078                                 break;
7079                         case EVENT_KIND_TYPE_LOAD:
7080                                 /* Emit type load events for currently loaded types */
7081                                 mono_domain_foreach (send_types_for_domain, NULL);
7082                                 break;
7083                         default:
7084                                 break;
7085                         }
7086                 }
7087                 mono_loader_unlock ();
7088
7089                 buffer_add_int (buf, req->id);
7090                 break;
7091         }
7092         case CMD_EVENT_REQUEST_CLEAR: {
7093                 int etype = decode_byte (p, &p, end);
7094                 int req_id = decode_int (p, &p, end);
7095
7096                 // FIXME: Make a faster mapping from req_id to request
7097                 mono_loader_lock ();
7098                 clear_event_request (req_id, etype);
7099                 mono_loader_unlock ();
7100                 break;
7101         }
7102         case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7103                 int i;
7104
7105                 mono_loader_lock ();
7106                 i = 0;
7107                 while (i < event_requests->len) {
7108                         EventRequest *req = g_ptr_array_index (event_requests, i);
7109
7110                         if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7111                                 clear_breakpoint (req->info);
7112
7113                                 g_ptr_array_remove_index_fast (event_requests, i);
7114                                 g_free (req);
7115                         } else {
7116                                 i ++;
7117                         }
7118                 }
7119                 mono_loader_unlock ();
7120                 break;
7121         }
7122         default:
7123                 return ERR_NOT_IMPLEMENTED;
7124         }
7125
7126         return ERR_NONE;
7127 }
7128
7129 static ErrorCode
7130 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7131 {
7132         int err;
7133         MonoDomain *domain;
7134
7135         switch (command) {
7136         case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7137                 buffer_add_domainid (buf, mono_get_root_domain ());
7138                 break;
7139         }
7140         case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7141                 domain = decode_domainid (p, &p, end, NULL, &err);
7142                 if (err)
7143                         return err;
7144                 buffer_add_string (buf, domain->friendly_name);
7145                 break;
7146         }
7147         case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7148                 GSList *tmp;
7149                 MonoAssembly *ass;
7150                 int count;
7151
7152                 domain = decode_domainid (p, &p, end, NULL, &err);
7153                 if (err)
7154                         return err;
7155                 mono_loader_lock ();
7156                 count = 0;
7157                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7158                         count ++;
7159                 }
7160                 buffer_add_int (buf, count);
7161                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7162                         ass = tmp->data;
7163                         buffer_add_assemblyid (buf, domain, ass);
7164                 }
7165                 mono_loader_unlock ();
7166                 break;
7167         }
7168         case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7169                 domain = decode_domainid (p, &p, end, NULL, &err);
7170                 if (err)
7171                         return err;
7172
7173                 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7174                 break;
7175         }
7176         case CMD_APPDOMAIN_GET_CORLIB: {
7177                 domain = decode_domainid (p, &p, end, NULL, &err);
7178                 if (err)
7179                         return err;
7180
7181                 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7182                 break;
7183         }
7184         case CMD_APPDOMAIN_CREATE_STRING: {
7185                 char *s;
7186                 MonoString *o;
7187
7188                 domain = decode_domainid (p, &p, end, NULL, &err);
7189                 if (err)
7190                         return err;
7191                 s = decode_string (p, &p, end);
7192
7193                 o = mono_string_new (domain, s);
7194                 buffer_add_objid (buf, (MonoObject*)o);
7195                 break;
7196         }
7197         case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7198                 MonoClass *klass;
7199                 MonoDomain *domain2;
7200                 MonoObject *o;
7201
7202                 domain = decode_domainid (p, &p, end, NULL, &err);
7203                 if (err)
7204                         return err;
7205                 klass = decode_typeid (p, &p, end, &domain2, &err);
7206                 if (err)
7207                         return err;
7208
7209                 // FIXME:
7210                 g_assert (domain == domain2);
7211
7212                 o = mono_object_new (domain, klass);
7213
7214                 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7215                 if (err)
7216                         return err;
7217
7218                 buffer_add_objid (buf, o);
7219                 break;
7220         }
7221         default:
7222                 return ERR_NOT_IMPLEMENTED;
7223         }
7224
7225         return ERR_NONE;
7226 }
7227
7228 static ErrorCode
7229 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7230 {
7231         int err;
7232         MonoAssembly *ass;
7233         MonoDomain *domain;
7234
7235         ass = decode_assemblyid (p, &p, end, &domain, &err);
7236         if (err)
7237                 return err;
7238
7239         switch (command) {
7240         case CMD_ASSEMBLY_GET_LOCATION: {
7241                 buffer_add_string (buf, mono_image_get_filename (ass->image));
7242                 break;                  
7243         }
7244         case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7245                 guint32 token;
7246                 MonoMethod *m;
7247
7248                 if (ass->image->dynamic) {
7249                         buffer_add_id (buf, 0);
7250                 } else {
7251                         token = mono_image_get_entry_point (ass->image);
7252                         if (token == 0) {
7253                                 buffer_add_id (buf, 0);
7254                         } else {
7255                                 m = mono_get_method (ass->image, token, NULL);
7256                                 buffer_add_methodid (buf, domain, m);
7257                         }
7258                 }
7259                 break;                  
7260         }
7261         case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7262                 buffer_add_moduleid (buf, domain, ass->image);
7263                 break;
7264         }
7265         case CMD_ASSEMBLY_GET_OBJECT: {
7266                 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7267                 buffer_add_objid (buf, o);
7268                 break;
7269         }
7270         case CMD_ASSEMBLY_GET_TYPE: {
7271                 char *s = decode_string (p, &p, end);
7272                 gboolean ignorecase = decode_byte (p, &p, end);
7273                 MonoTypeNameParse info;
7274                 MonoType *t;
7275                 gboolean type_resolve, res;
7276                 MonoDomain *d = mono_domain_get ();
7277
7278                 /* This is needed to be able to find referenced assemblies */
7279                 res = mono_domain_set (domain, FALSE);
7280                 g_assert (res);
7281
7282                 if (!mono_reflection_parse_type (s, &info)) {
7283                         t = NULL;
7284                 } else {
7285                         if (info.assembly.name)
7286                                 NOT_IMPLEMENTED;
7287                         t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7288                 }
7289                 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7290                 mono_reflection_free_type_info (&info);
7291                 g_free (s);
7292
7293                 mono_domain_set (d, TRUE);
7294
7295                 break;
7296         }
7297         case CMD_ASSEMBLY_GET_NAME: {
7298                 gchar *name;
7299                 MonoAssembly *mass = ass;
7300
7301                 name = g_strdup_printf (
7302                   "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7303                   mass->aname.name,
7304                   mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7305                   mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7306                   mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7307                   (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7308
7309                 buffer_add_string (buf, name);
7310                 g_free (name);
7311                 break;
7312         }
7313         default:
7314                 return ERR_NOT_IMPLEMENTED;
7315         }
7316
7317         return ERR_NONE;
7318 }
7319
7320 static ErrorCode
7321 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7322 {
7323         int err;
7324         MonoDomain *domain;
7325
7326         switch (command) {
7327         case CMD_MODULE_GET_INFO: {
7328                 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7329                 char *basename;
7330
7331                 basename = g_path_get_basename (image->name);
7332                 buffer_add_string (buf, basename); // name
7333                 buffer_add_string (buf, image->module_name); // scopename
7334                 buffer_add_string (buf, image->name); // fqname
7335                 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7336                 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7337                 g_free (basename);
7338                 break;                  
7339         }
7340         default:
7341                 return ERR_NOT_IMPLEMENTED;
7342         }
7343
7344         return ERR_NONE;
7345 }
7346
7347 static void
7348 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7349 {
7350         if (val && val->vtable->klass == mono_defaults.monotype_class) {
7351                 /* Special case these so the client doesn't have to handle Type objects */
7352                 
7353                 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7354                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7355         } else if (MONO_TYPE_IS_REFERENCE (t))
7356                 buffer_add_value (buf, t, &val, domain);
7357         else
7358                 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7359 }
7360
7361 static void
7362 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7363 {
7364         int i, j;
7365         int nattrs = 0;
7366
7367         if (!cinfo) {
7368                 buffer_add_int (buf, 0);
7369                 return;
7370         }
7371
7372         for (i = 0; i < cinfo->num_attrs; ++i) {
7373                 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7374                         nattrs ++;
7375         }
7376         buffer_add_int (buf, nattrs);
7377
7378         for (i = 0; i < cinfo->num_attrs; ++i) {
7379                 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7380                 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7381                         MonoArray *typed_args, *named_args;
7382                         MonoType *t;
7383                         CattrNamedArg *arginfo;
7384                         MonoError error;
7385
7386                         mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7387                         g_assert (mono_error_ok (&error));
7388
7389                         buffer_add_methodid (buf, domain, attr->ctor);
7390
7391                         /* Ctor args */
7392                         if (typed_args) {
7393                                 buffer_add_int (buf, mono_array_length (typed_args));
7394                                 for (j = 0; j < mono_array_length (typed_args); ++j) {
7395                                         MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7396
7397                                         t = mono_method_signature (attr->ctor)->params [j];
7398
7399                                         buffer_add_cattr_arg (buf, t, domain, val);
7400                                 }
7401                         } else {
7402                                 buffer_add_int (buf, 0);
7403                         }
7404
7405                         /* Named args */
7406                         if (named_args) {
7407                                 buffer_add_int (buf, mono_array_length (named_args));
7408
7409                                 for (j = 0; j < mono_array_length (named_args); ++j) {
7410                                         MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7411
7412                                         if (arginfo [j].prop) {
7413                                                 buffer_add_byte (buf, 0x54);
7414                                                 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7415                                         } else if (arginfo [j].field) {
7416                                                 buffer_add_byte (buf, 0x53);
7417                                                 buffer_add_fieldid (buf, domain, arginfo [j].field);
7418                                         } else {
7419                                                 g_assert_not_reached ();
7420                                         }
7421
7422                                         buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7423                                 }
7424                         } else {
7425                                 buffer_add_int (buf, 0);
7426                         }
7427                 }
7428         }
7429 }
7430
7431 /* FIXME: Code duplication with icall.c */
7432 static void
7433 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7434 {
7435         int i;
7436         MonoClass *ic;
7437
7438         mono_class_setup_interfaces (klass, error);
7439         if (!mono_error_ok (error))
7440                 return;
7441
7442         for (i = 0; i < klass->interface_count; i++) {
7443                 ic = klass->interfaces [i];
7444                 g_hash_table_insert (ifaces, ic, ic);
7445
7446                 collect_interfaces (ic, ifaces, error);
7447                 if (!mono_error_ok (error))
7448                         return;
7449         }
7450 }
7451
7452 static ErrorCode
7453 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7454 {
7455         MonoClass *nested;
7456         MonoType *type;
7457         gpointer iter;
7458         guint8 b;
7459         int err, nnested;
7460         char *name;
7461
7462         switch (command) {
7463         case CMD_TYPE_GET_INFO: {
7464                 buffer_add_string (buf, klass->name_space);
7465                 buffer_add_string (buf, klass->name);
7466                 // FIXME: byref
7467                 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7468                 buffer_add_string (buf, name);
7469                 g_free (name);
7470                 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7471                 buffer_add_moduleid (buf, domain, klass->image);
7472                 buffer_add_typeid (buf, domain, klass->parent);
7473                 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7474                         buffer_add_typeid (buf, domain, klass->element_class);
7475                 else
7476                         buffer_add_id (buf, 0);
7477                 buffer_add_int (buf, klass->type_token);
7478                 buffer_add_byte (buf, klass->rank);
7479                 buffer_add_int (buf, klass->flags);
7480                 b = 0;
7481                 type = &klass->byval_arg;
7482                 // FIXME: Can't decide whenever a class represents a byref type
7483                 if (FALSE)
7484                         b |= (1 << 0);
7485                 if (type->type == MONO_TYPE_PTR)
7486                         b |= (1 << 1);
7487                 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7488                         b |= (1 << 2);
7489                 if (type->type == MONO_TYPE_VALUETYPE)
7490                         b |= (1 << 3);
7491                 if (klass->enumtype)
7492                         b |= (1 << 4);
7493                 if (klass->generic_container)
7494                         b |= (1 << 5);
7495                 if (klass->generic_container || klass->generic_class)
7496                         b |= (1 << 6);
7497                 buffer_add_byte (buf, b);
7498                 nnested = 0;
7499                 iter = NULL;
7500                 while ((nested = mono_class_get_nested_types (klass, &iter)))
7501                         nnested ++;
7502                 buffer_add_int (buf, nnested);
7503                 iter = NULL;
7504                 while ((nested = mono_class_get_nested_types (klass, &iter)))
7505                         buffer_add_typeid (buf, domain, nested);
7506                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7507                         if (klass->generic_container)
7508                                 buffer_add_typeid (buf, domain, klass);
7509                         else if (klass->generic_class)
7510                                 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7511                         else
7512                                 buffer_add_id (buf, 0);
7513                 }
7514                 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7515                         int count, i;
7516
7517                         if (klass->generic_class) {
7518                                 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7519
7520                                 count = inst->type_argc;
7521                                 buffer_add_int (buf, count);
7522                                 for (i = 0; i < count; i++)
7523                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7524                         } else if (klass->generic_container) {
7525                                 MonoGenericContainer *container = klass->generic_container;
7526                                 MonoClass *pklass;
7527
7528                                 count = container->type_argc;
7529                                 buffer_add_int (buf, count);
7530                                 for (i = 0; i < count; i++) {
7531                                         pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7532                                         buffer_add_typeid (buf, domain, pklass);
7533                                 }
7534                         } else {
7535                                 buffer_add_int (buf, 0);
7536                         }
7537                 }
7538                 break;
7539         }
7540         case CMD_TYPE_GET_METHODS: {
7541                 int nmethods;
7542                 int i = 0;
7543                 gpointer iter = NULL;
7544                 MonoMethod *m;
7545
7546                 mono_class_setup_methods (klass);
7547
7548                 nmethods = mono_class_num_methods (klass);
7549
7550                 buffer_add_int (buf, nmethods);
7551
7552                 while ((m = mono_class_get_methods (klass, &iter))) {
7553                         buffer_add_methodid (buf, domain, m);
7554                         i ++;
7555                 }
7556                 g_assert (i == nmethods);
7557                 break;
7558         }
7559         case CMD_TYPE_GET_FIELDS: {
7560                 int nfields;
7561                 int i = 0;
7562                 gpointer iter = NULL;
7563                 MonoClassField *f;
7564
7565                 nfields = mono_class_num_fields (klass);
7566
7567                 buffer_add_int (buf, nfields);
7568
7569                 while ((f = mono_class_get_fields (klass, &iter))) {
7570                         buffer_add_fieldid (buf, domain, f);
7571                         buffer_add_string (buf, f->name);
7572                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7573                         buffer_add_int (buf, f->type->attrs);
7574                         i ++;
7575                 }
7576                 g_assert (i == nfields);
7577                 break;
7578         }
7579         case CMD_TYPE_GET_PROPERTIES: {
7580                 int nprops;
7581                 int i = 0;
7582                 gpointer iter = NULL;
7583                 MonoProperty *p;
7584
7585                 nprops = mono_class_num_properties (klass);
7586
7587                 buffer_add_int (buf, nprops);
7588
7589                 while ((p = mono_class_get_properties (klass, &iter))) {
7590                         buffer_add_propertyid (buf, domain, p);
7591                         buffer_add_string (buf, p->name);
7592                         buffer_add_methodid (buf, domain, p->get);
7593                         buffer_add_methodid (buf, domain, p->set);
7594                         buffer_add_int (buf, p->attrs);
7595                         i ++;
7596                 }
7597                 g_assert (i == nprops);
7598                 break;
7599         }
7600         case CMD_TYPE_GET_CATTRS: {
7601                 MonoClass *attr_klass;
7602                 MonoCustomAttrInfo *cinfo;
7603
7604                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7605                 /* attr_klass can be NULL */
7606                 if (err)
7607                         return err;
7608
7609                 cinfo = mono_custom_attrs_from_class (klass);
7610
7611                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7612                 break;
7613         }
7614         case CMD_TYPE_GET_FIELD_CATTRS: {
7615                 MonoClass *attr_klass;
7616                 MonoCustomAttrInfo *cinfo;
7617                 MonoClassField *field;
7618
7619                 field = decode_fieldid (p, &p, end, NULL, &err);
7620                 if (err)
7621                         return err;
7622                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7623                 if (err)
7624                         return err;
7625
7626                 cinfo = mono_custom_attrs_from_field (klass, field);
7627
7628                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7629                 break;
7630         }
7631         case CMD_TYPE_GET_PROPERTY_CATTRS: {
7632                 MonoClass *attr_klass;
7633                 MonoCustomAttrInfo *cinfo;
7634                 MonoProperty *prop;
7635
7636                 prop = decode_propertyid (p, &p, end, NULL, &err);
7637                 if (err)
7638                         return err;
7639                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7640                 if (err)
7641                         return err;
7642
7643                 cinfo = mono_custom_attrs_from_property (klass, prop);
7644
7645                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7646                 break;
7647         }
7648         case CMD_TYPE_GET_VALUES:
7649         case CMD_TYPE_GET_VALUES_2: {
7650                 guint8 *val;
7651                 MonoClassField *f;
7652                 MonoVTable *vtable;
7653                 MonoClass *k;
7654                 int len, i;
7655                 gboolean found;
7656                 MonoThread *thread_obj;
7657                 MonoInternalThread *thread = NULL;
7658                 guint32 special_static_type;
7659
7660                 if (command == CMD_TYPE_GET_VALUES_2) {
7661                         int objid = decode_objid (p, &p, end);
7662                         int err;
7663
7664                         err = get_object (objid, (MonoObject**)&thread_obj);
7665                         if (err)
7666                                 return err;
7667
7668                         thread = THREAD_TO_INTERNAL (thread_obj);
7669                 }
7670
7671                 len = decode_int (p, &p, end);
7672                 for (i = 0; i < len; ++i) {
7673                         f = decode_fieldid (p, &p, end, NULL, &err);
7674                         if (err)
7675                                 return err;
7676
7677                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7678                                 return ERR_INVALID_FIELDID;
7679                         special_static_type = mono_class_field_get_special_static_type (f);
7680                         if (special_static_type != SPECIAL_STATIC_NONE) {
7681                                 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7682                                         return ERR_INVALID_FIELDID;
7683                         }
7684
7685                         /* Check that the field belongs to the object */
7686                         found = FALSE;
7687                         for (k = klass; k; k = k->parent) {
7688                                 if (k == f->parent) {
7689                                         found = TRUE;
7690                                         break;
7691                                 }
7692                         }
7693                         if (!found)
7694                                 return ERR_INVALID_FIELDID;
7695
7696                         vtable = mono_class_vtable (domain, f->parent);
7697                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7698                         mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7699                         buffer_add_value (buf, f->type, val, domain);
7700                         g_free (val);
7701                 }
7702                 break;
7703         }
7704         case CMD_TYPE_SET_VALUES: {
7705                 guint8 *val;
7706                 MonoClassField *f;
7707                 MonoVTable *vtable;
7708                 MonoClass *k;
7709                 int len, i;
7710                 gboolean found;
7711
7712                 len = decode_int (p, &p, end);
7713                 for (i = 0; i < len; ++i) {
7714                         f = decode_fieldid (p, &p, end, NULL, &err);
7715                         if (err)
7716                                 return err;
7717
7718                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7719                                 return ERR_INVALID_FIELDID;
7720                         if (mono_class_field_is_special_static (f))
7721                                 return ERR_INVALID_FIELDID;
7722
7723                         /* Check that the field belongs to the object */
7724                         found = FALSE;
7725                         for (k = klass; k; k = k->parent) {
7726                                 if (k == f->parent) {
7727                                         found = TRUE;
7728                                         break;
7729                                 }
7730                         }
7731                         if (!found)
7732                                 return ERR_INVALID_FIELDID;
7733
7734                         // FIXME: Check for literal/const
7735
7736                         vtable = mono_class_vtable (domain, f->parent);
7737                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7738                         err = decode_value (f->type, domain, val, p, &p, end);
7739                         if (err) {
7740                                 g_free (val);
7741                                 return err;
7742                         }
7743                         if (MONO_TYPE_IS_REFERENCE (f->type))
7744                                 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7745                         else
7746                                 mono_field_static_set_value (vtable, f, val);
7747                         g_free (val);
7748                 }
7749                 break;
7750         }
7751         case CMD_TYPE_GET_OBJECT: {
7752                 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7753                 buffer_add_objid (buf, o);
7754                 break;
7755         }
7756         case CMD_TYPE_GET_SOURCE_FILES:
7757         case CMD_TYPE_GET_SOURCE_FILES_2: {
7758                 char *source_file, *base;
7759                 GPtrArray *files;
7760                 int i;
7761
7762                 files = get_source_files_for_type (klass);
7763
7764                 buffer_add_int (buf, files->len);
7765                 for (i = 0; i < files->len; ++i) {
7766                         source_file = g_ptr_array_index (files, i);
7767                         if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7768                                 buffer_add_string (buf, source_file);
7769                         } else {
7770                                 base = g_path_get_basename (source_file);
7771                                 buffer_add_string (buf, base);
7772                                 g_free (base);
7773                         }
7774                         g_free (source_file);
7775                 }
7776                 g_ptr_array_free (files, TRUE);
7777                 break;
7778         }
7779         case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7780                 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7781
7782                 if (err)
7783                         return err;
7784                 if (mono_class_is_assignable_from (klass, oklass))
7785                         buffer_add_byte (buf, 1);
7786                 else
7787                         buffer_add_byte (buf, 0);
7788                 break;
7789         }
7790         case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7791                 char *name = decode_string (p, &p, end);
7792                 int i, flags = decode_int (p, &p, end);
7793                 MonoException *ex = NULL;
7794                 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7795
7796                 if (!array)
7797                         return ERR_LOADER_ERROR;
7798                 buffer_add_int (buf, array->len);
7799                 for (i = 0; i < array->len; ++i) {
7800                         MonoMethod *method = g_ptr_array_index (array, i);
7801                         buffer_add_methodid (buf, domain, method);
7802                 }
7803
7804                 g_ptr_array_free (array, TRUE);
7805                 g_free (name);
7806                 break;
7807         }
7808         case CMD_TYPE_GET_INTERFACES: {
7809                 MonoClass *parent;
7810                 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7811                 MonoError error;
7812                 MonoClass *tclass, *iface;
7813                 GHashTableIter iter;
7814
7815                 tclass = klass;
7816
7817                 for (parent = tclass; parent; parent = parent->parent) {
7818                         mono_class_setup_interfaces (parent, &error);
7819                         if (!mono_error_ok (&error))
7820                                 return ERR_LOADER_ERROR;
7821                         collect_interfaces (parent, iface_hash, &error);
7822                         if (!mono_error_ok (&error))
7823                                 return ERR_LOADER_ERROR;
7824                 }
7825
7826                 buffer_add_int (buf, g_hash_table_size (iface_hash));
7827
7828                 g_hash_table_iter_init (&iter, iface_hash);
7829                 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7830                         buffer_add_typeid (buf, domain, iface);
7831                 g_hash_table_destroy (iface_hash);
7832                 break;
7833         }
7834         case CMD_TYPE_GET_INTERFACE_MAP: {
7835                 int tindex, ioffset;
7836                 gboolean variance_used;
7837                 MonoClass *iclass;
7838                 int len, nmethods, i;
7839                 gpointer iter;
7840                 MonoMethod *method;
7841
7842                 len = decode_int (p, &p, end);
7843                 mono_class_setup_vtable (klass);
7844
7845                 for (tindex = 0; tindex < len; ++tindex) {
7846                         iclass = decode_typeid (p, &p, end, NULL, &err);
7847                         if (err)
7848                                 return err;
7849
7850                         ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7851                         if (ioffset == -1)
7852                                 return ERR_INVALID_ARGUMENT;
7853
7854                         nmethods = mono_class_num_methods (iclass);
7855                         buffer_add_int (buf, nmethods);
7856
7857                         iter = NULL;
7858                         while ((method = mono_class_get_methods (iclass, &iter))) {
7859                                 buffer_add_methodid (buf, domain, method);
7860                         }
7861                         for (i = 0; i < nmethods; ++i)
7862                                 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7863                 }
7864                 break;
7865         }
7866         case CMD_TYPE_IS_INITIALIZED: {
7867                 MonoVTable *vtable = mono_class_vtable (domain, klass);
7868
7869                 if (vtable)
7870                         buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7871                 else
7872                         buffer_add_int (buf, 0);
7873                 break;
7874         }
7875         default:
7876                 return ERR_NOT_IMPLEMENTED;
7877         }
7878
7879         return ERR_NONE;
7880 }
7881
7882 static ErrorCode
7883 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7884 {
7885         MonoClass *klass;
7886         MonoDomain *old_domain;
7887         MonoDomain *domain;
7888         int err;
7889
7890         klass = decode_typeid (p, &p, end, &domain, &err);
7891         if (err)
7892                 return err;
7893
7894         old_domain = mono_domain_get ();
7895
7896         mono_domain_set (domain, TRUE);
7897
7898         err = type_commands_internal (command, klass, domain, p, end, buf);
7899
7900         mono_domain_set (old_domain, TRUE);
7901
7902         return err;
7903 }
7904
7905 static ErrorCode
7906 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7907 {
7908         MonoMethodHeader *header;
7909         int err;
7910
7911         switch (command) {
7912         case CMD_METHOD_GET_NAME: {
7913                 buffer_add_string (buf, method->name);
7914                 break;                  
7915         }
7916         case CMD_METHOD_GET_DECLARING_TYPE: {
7917                 buffer_add_typeid (buf, domain, method->klass);
7918                 break;
7919         }
7920         case CMD_METHOD_GET_DEBUG_INFO: {
7921                 MonoDebugMethodInfo *minfo;
7922                 char *source_file;
7923                 int i, j, n_il_offsets;
7924                 int *il_offsets;
7925                 int *line_numbers;
7926                 int *column_numbers;
7927                 int *source_files;
7928                 GPtrArray *source_file_list;
7929
7930                 header = mono_method_get_header (method);
7931                 if (!header) {
7932                         buffer_add_int (buf, 0);
7933                         buffer_add_string (buf, "");
7934                         buffer_add_int (buf, 0);
7935                         break;
7936                 }
7937
7938                 minfo = mono_debug_lookup_method (method);
7939                 if (!minfo) {
7940                         buffer_add_int (buf, header->code_size);
7941                         buffer_add_string (buf, "");
7942                         buffer_add_int (buf, 0);
7943                         mono_metadata_free_mh (header);
7944                         break;
7945                 }
7946
7947                 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7948                 buffer_add_int (buf, header->code_size);
7949                 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7950                         buffer_add_int (buf, source_file_list->len);
7951                         for (i = 0; i < source_file_list->len; ++i) {
7952                                 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7953                                 buffer_add_string (buf, sinfo->source_file);
7954                                 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7955                                         for (j = 0; j < 16; ++j)
7956                                                 buffer_add_byte (buf, sinfo->hash [j]);
7957                                 }
7958                         }
7959                 } else {
7960                         buffer_add_string (buf, source_file);
7961                 }
7962                 buffer_add_int (buf, n_il_offsets);
7963                 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method,  TRUE)));
7964                 for (i = 0; i < n_il_offsets; ++i) {
7965                         const char *srcfile = "";
7966
7967                         if (source_files [i] != -1) {
7968                                 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7969                                 srcfile = sinfo->source_file;
7970                         }
7971                         DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7972                         buffer_add_int (buf, il_offsets [i]);
7973                         buffer_add_int (buf, line_numbers [i]);
7974                         if (CHECK_PROTOCOL_VERSION (2, 13))
7975                                 buffer_add_int (buf, source_files [i]);
7976                         if (CHECK_PROTOCOL_VERSION (2, 19))
7977                                 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7978                 }
7979                 g_free (source_file);
7980                 g_free (il_offsets);
7981                 g_free (line_numbers);
7982                 g_free (source_files);
7983                 g_ptr_array_free (source_file_list, TRUE);
7984                 mono_metadata_free_mh (header);
7985                 break;
7986         }
7987         case CMD_METHOD_GET_PARAM_INFO: {
7988                 MonoMethodSignature *sig = mono_method_signature (method);
7989                 guint32 i;
7990                 char **names;
7991
7992                 /* FIXME: mono_class_from_mono_type () and byrefs */
7993
7994                 /* FIXME: Use a smaller encoding */
7995                 buffer_add_int (buf, sig->call_convention);
7996                 buffer_add_int (buf, sig->param_count);
7997                 buffer_add_int (buf, sig->generic_param_count);
7998                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7999                 for (i = 0; i < sig->param_count; ++i) {
8000                         /* FIXME: vararg */
8001                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8002                 }
8003
8004                 /* Emit parameter names */
8005                 names = g_new (char *, sig->param_count);
8006                 mono_method_get_param_names (method, (const char **) names);
8007                 for (i = 0; i < sig->param_count; ++i)
8008                         buffer_add_string (buf, names [i]);
8009                 g_free (names);
8010
8011                 break;
8012         }
8013         case CMD_METHOD_GET_LOCALS_INFO: {
8014                 int i, j, num_locals;
8015                 MonoDebugLocalsInfo *locals;
8016
8017                 header = mono_method_get_header (method);
8018                 if (!header)
8019                         return ERR_INVALID_ARGUMENT;
8020
8021                 buffer_add_int (buf, header->num_locals);
8022
8023                 /* Types */
8024                 for (i = 0; i < header->num_locals; ++i)
8025                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8026
8027                 /* Names */
8028                 locals = mono_debug_lookup_locals (method);
8029                 if (locals)
8030                         num_locals = locals->num_locals;
8031                 else
8032                         num_locals = 0;
8033                 for (i = 0; i < header->num_locals; ++i) {
8034                         for (j = 0; j < num_locals; ++j)
8035                                 if (locals->locals [j].index == i)
8036                                         break;
8037                         if (j < num_locals)
8038                                 buffer_add_string (buf, locals->locals [j].name);
8039                         else
8040                                 buffer_add_string (buf, "");
8041                 }
8042
8043                 /* Scopes */
8044                 for (i = 0; i < header->num_locals; ++i) {
8045                         for (j = 0; j < num_locals; ++j)
8046                                 if (locals->locals [j].index == i)
8047                                         break;
8048                         if (j < num_locals && locals->locals [j].block) {
8049                                 buffer_add_int (buf, locals->locals [j].block->start_offset);
8050                                 buffer_add_int (buf, locals->locals [j].block->end_offset);
8051                         } else {
8052                                 buffer_add_int (buf, 0);
8053                                 buffer_add_int (buf, header->code_size);
8054                         }
8055                 }
8056                 mono_metadata_free_mh (header);
8057
8058                 if (locals)
8059                         mono_debug_symfile_free_locals (locals);
8060
8061                 break;
8062         }
8063         case CMD_METHOD_GET_INFO:
8064                 buffer_add_int (buf, method->flags);
8065                 buffer_add_int (buf, method->iflags);
8066                 buffer_add_int (buf, method->token);
8067                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8068                         guint8 attrs = 0;
8069                         if (method->is_generic)
8070                                 attrs |= (1 << 0);
8071                         if (mono_method_signature (method)->generic_param_count)
8072                                 attrs |= (1 << 1);
8073                         buffer_add_byte (buf, attrs);
8074                         if (method->is_generic || method->is_inflated) {
8075                                 MonoMethod *result;
8076
8077                                 if (method->is_generic) {
8078                                         result = method;
8079                                 } else {
8080                                         MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8081                                         
8082                                         result = imethod->declaring;
8083                                         if (imethod->context.class_inst) {
8084                                                 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8085                                                 /*Generic methods gets the context of the GTD.*/
8086                                                 if (mono_class_get_context (klass))
8087                                                         result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8088                                         }
8089                                 }
8090
8091                                 buffer_add_methodid (buf, domain, result);
8092                         } else {
8093                                 buffer_add_id (buf, 0);
8094                         }
8095                         if (CHECK_PROTOCOL_VERSION (2, 15)) {
8096                                 if (mono_method_signature (method)->generic_param_count) {
8097                                         int count, i;
8098
8099                                         if (method->is_inflated) {
8100                                                 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8101                                                 if (inst) {
8102                                                         count = inst->type_argc;
8103                                                         buffer_add_int (buf, count);
8104
8105                                                         for (i = 0; i < count; i++)
8106                                                                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8107                                                 } else {
8108                                                         buffer_add_int (buf, 0);
8109                                                 }
8110                                         } else if (method->is_generic) {
8111                                                 MonoGenericContainer *container = mono_method_get_generic_container (method);
8112
8113                                                 count = mono_method_signature (method)->generic_param_count;
8114                                                 buffer_add_int (buf, count);
8115                                                 for (i = 0; i < count; i++) {
8116                                                         MonoGenericParam *param = mono_generic_container_get_param (container, i);
8117                                                         MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8118                                                         buffer_add_typeid (buf, domain, pklass);
8119                                                 }
8120                                         } else {
8121                                                 buffer_add_int (buf, 0);
8122                                         }
8123                                 } else {
8124                                         buffer_add_int (buf, 0);
8125                                 }
8126                         }
8127                 }
8128                 break;
8129         case CMD_METHOD_GET_BODY: {
8130                 int i;
8131
8132                 header = mono_method_get_header (method);
8133                 if (!header) {
8134                         buffer_add_int (buf, 0);
8135
8136                         if (CHECK_PROTOCOL_VERSION (2, 18))
8137                                 buffer_add_int (buf, 0);
8138                 } else {
8139                         buffer_add_int (buf, header->code_size);
8140                         for (i = 0; i < header->code_size; ++i)
8141                                 buffer_add_byte (buf, header->code [i]);
8142
8143                         if (CHECK_PROTOCOL_VERSION (2, 18)) {
8144                                 buffer_add_int (buf, header->num_clauses);
8145                                 for (i = 0; i < header->num_clauses; ++i) {
8146                                         MonoExceptionClause *clause = &header->clauses [i];
8147
8148                                         buffer_add_int (buf, clause->flags);
8149                                         buffer_add_int (buf, clause->try_offset);
8150                                         buffer_add_int (buf, clause->try_len);
8151                                         buffer_add_int (buf, clause->handler_offset);
8152                                         buffer_add_int (buf, clause->handler_len);
8153                                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8154                                                 buffer_add_typeid (buf, domain, clause->data.catch_class);
8155                                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8156                                                 buffer_add_int (buf, clause->data.filter_offset);
8157                                 }
8158                         }
8159
8160                         mono_metadata_free_mh (header);
8161                 }
8162
8163                 break;
8164         }
8165         case CMD_METHOD_RESOLVE_TOKEN: {
8166                 guint32 token = decode_int (p, &p, end);
8167
8168                 // FIXME: Generics
8169                 switch (mono_metadata_token_code (token)) {
8170                 case MONO_TOKEN_STRING: {
8171                         MonoString *s;
8172                         char *s2;
8173
8174                         s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8175                         g_assert (s);
8176
8177                         s2 = mono_string_to_utf8 (s);
8178
8179                         buffer_add_byte (buf, TOKEN_TYPE_STRING);
8180                         buffer_add_string (buf, s2);
8181                         g_free (s2);
8182                         break;
8183                 }
8184                 default: {
8185                         gpointer val;
8186                         MonoClass *handle_class;
8187
8188                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8189                                 val = mono_method_get_wrapper_data (method, token);
8190                                 handle_class = mono_method_get_wrapper_data (method, token + 1);
8191
8192                                 if (handle_class == NULL) {
8193                                         // Can't figure out the token type
8194                                         buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8195                                         break;
8196                                 }
8197                         } else {
8198                                 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8199                                 g_assert (val);
8200                         }
8201
8202                         if (handle_class == mono_defaults.typehandle_class) {
8203                                 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8204                                 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8205                                         buffer_add_typeid (buf, domain, (MonoClass *) val);
8206                                 else
8207                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8208                         } else if (handle_class == mono_defaults.fieldhandle_class) {
8209                                 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8210                                 buffer_add_fieldid (buf, domain, val);
8211                         } else if (handle_class == mono_defaults.methodhandle_class) {
8212                                 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8213                                 buffer_add_methodid (buf, domain, val);
8214                         } else if (handle_class == mono_defaults.string_class) {
8215                                 char *s;
8216
8217                                 s = mono_string_to_utf8 (val);
8218                                 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8219                                 buffer_add_string (buf, s);
8220                                 g_free (s);
8221                         } else {
8222                                 g_assert_not_reached ();
8223                         }
8224                         break;
8225                 }
8226                 }
8227                 break;
8228         }
8229         case CMD_METHOD_GET_CATTRS: {
8230                 MonoClass *attr_klass;
8231                 MonoCustomAttrInfo *cinfo;
8232
8233                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8234                 /* attr_klass can be NULL */
8235                 if (err)
8236                         return err;
8237
8238                 cinfo = mono_custom_attrs_from_method (method);
8239
8240                 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8241                 break;
8242         }
8243         case CMD_METHOD_MAKE_GENERIC_METHOD: {
8244                 MonoType **type_argv;
8245                 int i, type_argc;
8246                 MonoDomain *d;
8247                 MonoClass *klass;
8248                 MonoGenericInst *ginst;
8249                 MonoGenericContext tmp_context;
8250                 MonoMethod *inflated;
8251
8252                 type_argc = decode_int (p, &p, end);
8253                 type_argv = g_new0 (MonoType*, type_argc);
8254                 for (i = 0; i < type_argc; ++i) {
8255                         klass = decode_typeid (p, &p, end, &d, &err);
8256                         if (err) {
8257                                 g_free (type_argv);
8258                                 return err;
8259                         }
8260                         if (domain != d) {
8261                                 g_free (type_argv);
8262                                 return ERR_INVALID_ARGUMENT;
8263                         }
8264                         type_argv [i] = &klass->byval_arg;
8265                 }
8266                 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8267                 g_free (type_argv);
8268                 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8269                 tmp_context.method_inst = ginst;
8270
8271                 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8272                 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8273                         return ERR_INVALID_ARGUMENT;
8274                 buffer_add_methodid (buf, domain, inflated);
8275                 break;
8276         }
8277         default:
8278                 return ERR_NOT_IMPLEMENTED;
8279         }
8280
8281         return ERR_NONE;
8282 }
8283
8284 static ErrorCode
8285 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8286 {
8287         int err;
8288         MonoDomain *old_domain;
8289         MonoDomain *domain;
8290         MonoMethod *method;
8291
8292         method = decode_methodid (p, &p, end, &domain, &err);
8293         if (err)
8294                 return err;
8295
8296         old_domain = mono_domain_get ();
8297
8298         mono_domain_set (domain, TRUE);
8299
8300         err = method_commands_internal (command, method, domain, p, end, buf);
8301
8302         mono_domain_set (old_domain, TRUE);
8303
8304         return err;
8305 }
8306
8307 static ErrorCode
8308 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8309 {
8310         int objid = decode_objid (p, &p, end);
8311         int err;
8312         MonoThread *thread_obj;
8313         MonoInternalThread *thread;
8314
8315         err = get_object (objid, (MonoObject**)&thread_obj);
8316         if (err)
8317                 return err;
8318
8319         thread = THREAD_TO_INTERNAL (thread_obj);
8320            
8321         switch (command) {
8322         case CMD_THREAD_GET_NAME: {
8323                 guint32 name_len;
8324                 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8325
8326                 if (!s) {
8327                         buffer_add_int (buf, 0);
8328                 } else {
8329                         char *name;
8330                         glong len;
8331
8332                         name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8333                         g_assert (name);
8334                         buffer_add_int (buf, len);
8335                         buffer_add_data (buf, (guint8*)name, len);
8336                         g_free (s);
8337                 }
8338                 break;
8339         }
8340         case CMD_THREAD_GET_FRAME_INFO: {
8341                 DebuggerTlsData *tls;
8342                 int i, start_frame, length;
8343
8344                 // Wait for suspending if it already started
8345                 // FIXME: Races with suspend_count
8346                 while (!is_suspended ()) {
8347                         if (suspend_count)
8348                                 wait_for_suspend ();
8349                 }
8350                 /*
8351                 if (suspend_count)
8352                         wait_for_suspend ();
8353                 if (!is_suspended ())
8354                         return ERR_NOT_SUSPENDED;
8355                 */
8356
8357                 start_frame = decode_int (p, &p, end);
8358                 length = decode_int (p, &p, end);
8359
8360                 if (start_frame != 0 || length != -1)
8361                         return ERR_NOT_IMPLEMENTED;
8362
8363                 mono_loader_lock ();
8364                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8365                 mono_loader_unlock ();
8366                 g_assert (tls);
8367
8368                 compute_frame_info (thread, tls);
8369
8370                 buffer_add_int (buf, tls->frame_count);
8371                 for (i = 0; i < tls->frame_count; ++i) {
8372                         buffer_add_int (buf, tls->frames [i]->id);
8373                         buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8374                         buffer_add_int (buf, tls->frames [i]->il_offset);
8375                         /*
8376                          * Instead of passing the frame type directly to the client, we associate
8377                          * it with the previous frame using a set of flags. This avoids lots of
8378                          * conditional code in the client, since a frame whose type isn't 
8379                          * FRAME_TYPE_MANAGED has no method, location, etc.
8380                          */
8381                         buffer_add_byte (buf, tls->frames [i]->flags);
8382                 }
8383
8384                 break;
8385         }
8386         case CMD_THREAD_GET_STATE:
8387                 buffer_add_int (buf, thread->state);
8388                 break;
8389         case CMD_THREAD_GET_INFO:
8390                 buffer_add_byte (buf, thread->threadpool_thread);
8391                 break;
8392         case CMD_THREAD_GET_ID:
8393                 buffer_add_long (buf, (guint64)(gsize)thread);
8394                 break;
8395         case CMD_THREAD_GET_TID:
8396                 buffer_add_long (buf, (guint64)thread->tid);
8397                 break;
8398         default:
8399                 return ERR_NOT_IMPLEMENTED;
8400         }
8401
8402         return ERR_NONE;
8403 }
8404
8405 static ErrorCode
8406 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8407 {
8408         int objid;
8409         int err;
8410         MonoThread *thread_obj;
8411         MonoInternalThread *thread;
8412         int pos, i, len, frame_idx;
8413         DebuggerTlsData *tls;
8414         StackFrame *frame;
8415         MonoDebugMethodJitInfo *jit;
8416         MonoDebugVarInfo *var;
8417         MonoMethodSignature *sig;
8418         gssize id;
8419         MonoMethodHeader *header;
8420
8421         objid = decode_objid (p, &p, end);
8422         err = get_object (objid, (MonoObject**)&thread_obj);
8423         if (err)
8424                 return err;
8425
8426         thread = THREAD_TO_INTERNAL (thread_obj);
8427
8428         id = decode_id (p, &p, end);
8429
8430         mono_loader_lock ();
8431         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8432         mono_loader_unlock ();
8433         g_assert (tls);
8434
8435         for (i = 0; i < tls->frame_count; ++i) {
8436                 if (tls->frames [i]->id == id)
8437                         break;
8438         }
8439         if (i == tls->frame_count)
8440                 return ERR_INVALID_FRAMEID;
8441
8442         frame_idx = i;
8443         frame = tls->frames [frame_idx];
8444
8445         if (!frame->has_ctx)
8446                 return ERR_ABSENT_INFORMATION;
8447
8448         if (!frame->jit) {
8449                 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8450                 if (!frame->jit && frame->api_method->is_inflated)
8451                         frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8452                 if (!frame->jit) {
8453                         char *s;
8454
8455                         /* This could happen for aot images with no jit debug info */
8456                         s = mono_method_full_name (frame->api_method, TRUE);
8457                         DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8458                         g_free (s);
8459                         return ERR_ABSENT_INFORMATION;
8460                 }
8461         }
8462         jit = frame->jit;
8463
8464         sig = mono_method_signature (frame->actual_method);
8465
8466         if (!get_seq_points (frame->domain, frame->actual_method))
8467                 /*
8468                  * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8469                  */
8470                 return ERR_ABSENT_INFORMATION;
8471
8472         switch (command) {
8473         case CMD_STACK_FRAME_GET_VALUES: {
8474                 len = decode_int (p, &p, end);
8475                 header = mono_method_get_header (frame->actual_method);
8476
8477                 for (i = 0; i < len; ++i) {
8478                         pos = decode_int (p, &p, end);
8479
8480                         if (pos < 0) {
8481                                 pos = - pos - 1;
8482
8483                                 g_assert (pos >= 0 && pos < jit->num_params);
8484
8485                                 var = &jit->params [pos];
8486
8487                                 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8488                         } else {
8489                                 g_assert (pos >= 0 && pos < jit->num_locals);
8490
8491                                 var = &jit->locals [pos];
8492                                 
8493                                 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8494                         }
8495                 }
8496                 mono_metadata_free_mh (header);
8497                 break;
8498         }
8499         case CMD_STACK_FRAME_GET_THIS: {
8500                 if (frame->api_method->klass->valuetype) {
8501                         if (!sig->hasthis) {
8502                                 MonoObject *p = NULL;
8503                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8504                         } else {
8505                                 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8506                         }
8507                 } else {
8508                         if (!sig->hasthis) {
8509                                 MonoObject *p = NULL;
8510                                 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8511                         } else {
8512                                 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8513                         }
8514                 }
8515                 break;
8516         }
8517         case CMD_STACK_FRAME_SET_VALUES: {
8518                 guint8 *val_buf;
8519                 MonoType *t;
8520                 MonoDebugVarInfo *var;
8521
8522                 len = decode_int (p, &p, end);
8523                 header = mono_method_get_header (frame->actual_method);
8524
8525                 for (i = 0; i < len; ++i) {
8526                         pos = decode_int (p, &p, end);
8527
8528                         if (pos < 0) {
8529                                 pos = - pos - 1;
8530
8531                                 g_assert (pos >= 0 && pos < jit->num_params);
8532
8533                                 t = sig->params [pos];
8534                                 var = &jit->params [pos];
8535                         } else {
8536                                 g_assert (pos >= 0 && pos < jit->num_locals);
8537
8538                                 t = header->locals [pos];
8539                                 var = &jit->locals [pos];
8540                         }
8541
8542                         if (MONO_TYPE_IS_REFERENCE (t))
8543                                 val_buf = g_alloca (sizeof (MonoObject*));
8544                         else
8545                                 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8546                         err = decode_value (t, frame->domain, val_buf, p, &p, end);
8547                         if (err)
8548                                 return err;
8549
8550                         set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8551                 }
8552                 mono_metadata_free_mh (header);
8553                 break;
8554         }
8555         default:
8556                 return ERR_NOT_IMPLEMENTED;
8557         }
8558
8559         return ERR_NONE;
8560 }
8561
8562 static ErrorCode
8563 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8564 {
8565         MonoArray *arr;
8566         int objid, err, index, len, i, esize;
8567         gpointer elem;
8568
8569         objid = decode_objid (p, &p, end);
8570         err = get_object (objid, (MonoObject**)&arr);
8571         if (err)
8572                 return err;
8573
8574         switch (command) {
8575         case CMD_ARRAY_REF_GET_LENGTH:
8576                 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8577                 if (!arr->bounds) {
8578                         buffer_add_int (buf, arr->max_length);
8579                         buffer_add_int (buf, 0);
8580                 } else {
8581                         for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8582                                 buffer_add_int (buf, arr->bounds [i].length);
8583                                 buffer_add_int (buf, arr->bounds [i].lower_bound);
8584                         }
8585                 }
8586                 break;
8587         case CMD_ARRAY_REF_GET_VALUES:
8588                 index = decode_int (p, &p, end);
8589                 len = decode_int (p, &p, end);
8590
8591                 g_assert (index >= 0 && len >= 0);
8592                 // Reordered to avoid integer overflow
8593                 g_assert (!(index > arr->max_length - len));
8594
8595                 esize = mono_array_element_size (arr->obj.vtable->klass);
8596                 for (i = index; i < index + len; ++i) {
8597                         elem = (gpointer*)((char*)arr->vector + (i * esize));
8598                         buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8599                 }
8600                 break;
8601         case CMD_ARRAY_REF_SET_VALUES:
8602                 index = decode_int (p, &p, end);
8603                 len = decode_int (p, &p, end);
8604
8605                 g_assert (index >= 0 && len >= 0);
8606                 // Reordered to avoid integer overflow
8607                 g_assert (!(index > arr->max_length - len));
8608
8609                 esize = mono_array_element_size (arr->obj.vtable->klass);
8610                 for (i = index; i < index + len; ++i) {
8611                         elem = (gpointer*)((char*)arr->vector + (i * esize));
8612
8613                         decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8614                 }
8615                 break;
8616         default:
8617                 return ERR_NOT_IMPLEMENTED;
8618         }
8619
8620         return ERR_NONE;
8621 }
8622
8623 static ErrorCode
8624 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8625 {
8626         int objid, err;
8627         MonoString *str;
8628         char *s;
8629         int i, index, length;
8630         gunichar2 *c;
8631
8632         objid = decode_objid (p, &p, end);
8633         err = get_object (objid, (MonoObject**)&str);
8634         if (err)
8635                 return err;
8636
8637         switch (command) {
8638         case CMD_STRING_REF_GET_VALUE:
8639                 s = mono_string_to_utf8 (str);
8640                 buffer_add_string (buf, s);
8641                 g_free (s);
8642                 break;
8643         case CMD_STRING_REF_GET_LENGTH:
8644                 buffer_add_long (buf, mono_string_length (str));
8645                 break;
8646         case CMD_STRING_REF_GET_CHARS:
8647                 index = decode_long (p, &p, end);
8648                 length = decode_long (p, &p, end);
8649                 if (index > mono_string_length (str) - length)
8650                         return ERR_INVALID_ARGUMENT;
8651                 c = mono_string_chars (str) + index;
8652                 for (i = 0; i < length; ++i)
8653                         buffer_add_short (buf, c [i]);
8654                 break;
8655         default:
8656                 return ERR_NOT_IMPLEMENTED;
8657         }
8658
8659         return ERR_NONE;
8660 }
8661
8662 static ErrorCode
8663 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8664 {
8665         int objid, err;
8666         MonoObject *obj;
8667         int len, i;
8668         MonoClassField *f;
8669         MonoClass *k;
8670         gboolean found;
8671
8672         if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8673                 objid = decode_objid (p, &p, end);
8674                 err = get_object (objid, &obj);
8675                 if (err)
8676                         buffer_add_int (buf, 1);
8677                 else
8678                         buffer_add_int (buf, 0);
8679                 return 0;
8680         }
8681
8682         objid = decode_objid (p, &p, end);
8683         err = get_object (objid, &obj);
8684         if (err)
8685                 return err;
8686
8687         switch (command) {
8688         case CMD_OBJECT_REF_GET_TYPE:
8689                 /* This handles transparent proxies too */
8690                 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8691                 break;
8692         case CMD_OBJECT_REF_GET_VALUES:
8693                 len = decode_int (p, &p, end);
8694
8695                 for (i = 0; i < len; ++i) {
8696                         MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8697                         if (err)
8698                                 return err;
8699
8700                         /* Check that the field belongs to the object */
8701                         found = FALSE;
8702                         for (k = obj->vtable->klass; k; k = k->parent) {
8703                                 if (k == f->parent) {
8704                                         found = TRUE;
8705                                         break;
8706                                 }
8707                         }
8708                         if (!found)
8709                                 return ERR_INVALID_FIELDID;
8710
8711                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8712                                 guint8 *val;
8713                                 MonoVTable *vtable;
8714
8715                                 if (mono_class_field_is_special_static (f))
8716                                         return ERR_INVALID_FIELDID;
8717
8718                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8719                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8720                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8721                                 mono_field_static_get_value (vtable, f, val);
8722                                 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8723                                 g_free (val);
8724                         } else {
8725                                 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8726                         }
8727                 }
8728                 break;
8729         case CMD_OBJECT_REF_SET_VALUES:
8730                 len = decode_int (p, &p, end);
8731
8732                 for (i = 0; i < len; ++i) {
8733                         f = decode_fieldid (p, &p, end, NULL, &err);
8734                         if (err)
8735                                 return err;
8736
8737                         /* Check that the field belongs to the object */
8738                         found = FALSE;
8739                         for (k = obj->vtable->klass; k; k = k->parent) {
8740                                 if (k == f->parent) {
8741                                         found = TRUE;
8742                                         break;
8743                                 }
8744                         }
8745                         if (!found)
8746                                 return ERR_INVALID_FIELDID;
8747
8748                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8749                                 guint8 *val;
8750                                 MonoVTable *vtable;
8751
8752                                 if (mono_class_field_is_special_static (f))
8753                                         return ERR_INVALID_FIELDID;
8754
8755                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8756                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8757
8758                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8759                                 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8760                                 if (err) {
8761                                         g_free (val);
8762                                         return err;
8763                                 }
8764                                 mono_field_static_set_value (vtable, f, val);
8765                                 g_free (val);
8766                         } else {
8767                                 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8768                                 if (err)
8769                                         return err;
8770                         }
8771                 }
8772                 break;
8773         case CMD_OBJECT_REF_GET_ADDRESS:
8774                 buffer_add_long (buf, (gssize)obj);
8775                 break;
8776         case CMD_OBJECT_REF_GET_DOMAIN:
8777                 buffer_add_domainid (buf, obj->vtable->domain);
8778                 break;
8779         case CMD_OBJECT_REF_GET_INFO:
8780                 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8781                 buffer_add_domainid (buf, obj->vtable->domain);
8782                 break;
8783         default:
8784                 return ERR_NOT_IMPLEMENTED;
8785         }
8786
8787         return ERR_NONE;
8788 }
8789
8790 static const char*
8791 command_set_to_string (CommandSet command_set)
8792 {
8793         switch (command_set) {
8794         case CMD_SET_VM:
8795                 return "VM";
8796         case CMD_SET_OBJECT_REF:
8797                 return "OBJECT_REF";
8798         case CMD_SET_STRING_REF:
8799                 return "STRING_REF"; 
8800         case CMD_SET_THREAD:
8801                 return "THREAD"; 
8802         case CMD_SET_ARRAY_REF:
8803                 return "ARRAY_REF"; 
8804         case CMD_SET_EVENT_REQUEST:
8805                 return "EVENT_REQUEST"; 
8806         case CMD_SET_STACK_FRAME:
8807                 return "STACK_FRAME"; 
8808         case CMD_SET_APPDOMAIN:
8809                 return "APPDOMAIN"; 
8810         case CMD_SET_ASSEMBLY:
8811                 return "ASSEMBLY"; 
8812         case CMD_SET_METHOD:
8813                 return "METHOD"; 
8814         case CMD_SET_TYPE:
8815                 return "TYPE"; 
8816         case CMD_SET_MODULE:
8817                 return "MODULE"; 
8818         case CMD_SET_EVENT:
8819                 return "EVENT"; 
8820         default:
8821                 return "";
8822         }
8823 }
8824
8825 static const char* vm_cmds_str [] = {
8826         "VERSION",
8827         "ALL_THREADS",
8828         "SUSPEND",
8829         "RESUME",
8830         "EXIT",
8831         "DISPOSE",
8832         "INVOKE_METHOD",
8833         "SET_PROTOCOL_VERSION",
8834         "ABORT_INVOKE",
8835         "SET_KEEPALIVE"
8836         "GET_TYPES_FOR_SOURCE_FILE",
8837         "GET_TYPES",
8838         "INVOKE_METHODS"
8839 };
8840
8841 static const char* thread_cmds_str[] = {
8842         "GET_FRAME_INFO",
8843         "GET_NAME",
8844         "GET_STATE",
8845         "GET_INFO",
8846         "GET_ID",
8847         "GET_TID"
8848 };
8849
8850 static const char* event_cmds_str[] = {
8851         "REQUEST_SET",
8852         "REQUEST_CLEAR",
8853         "REQUEST_CLEAR_ALL_BREAKPOINTS"
8854 };
8855
8856 static const char* appdomain_cmds_str[] = {
8857         "GET_ROOT_DOMAIN",
8858         "GET_FRIENDLY_NAME",
8859         "GET_ASSEMBLIES",
8860         "GET_ENTRY_ASSEMBLY",
8861         "CREATE_STRING",
8862         "GET_CORLIB",
8863         "CREATE_BOXED_VALUE"
8864 };
8865
8866 static const char* assembly_cmds_str[] = {
8867         "GET_LOCATION",
8868         "GET_ENTRY_POINT",
8869         "GET_MANIFEST_MODULE",
8870         "GET_OBJECT",
8871         "GET_TYPE",
8872         "GET_NAME"
8873 };
8874
8875 static const char* module_cmds_str[] = {
8876         "GET_INFO",
8877 };
8878
8879 static const char* method_cmds_str[] = {
8880         "GET_NAME",
8881         "GET_DECLARING_TYPE",
8882         "GET_DEBUG_INFO",
8883         "GET_PARAM_INFO",
8884         "GET_LOCALS_INFO",
8885         "GET_INFO",
8886         "GET_BODY",
8887         "RESOLVE_TOKEN",
8888         "GET_CATTRS ",
8889         "MAKE_GENERIC_METHOD"
8890 };
8891
8892 static const char* type_cmds_str[] = {
8893         "GET_INFO",
8894         "GET_METHODS",
8895         "GET_FIELDS",
8896         "GET_VALUES",
8897         "GET_OBJECT",
8898         "GET_SOURCE_FILES",
8899         "SET_VALUES",
8900         "IS_ASSIGNABLE_FROM",
8901         "GET_PROPERTIES ",
8902         "GET_CATTRS",
8903         "GET_FIELD_CATTRS",
8904         "GET_PROPERTY_CATTRS",
8905         "GET_SOURCE_FILES_2",
8906         "GET_VALUES_2",
8907         "GET_METHODS_BY_NAME_FLAGS",
8908         "GET_INTERFACES",
8909         "GET_INTERFACE_MAP",
8910         "IS_INITIALIZED"
8911 };
8912
8913 static const char* stack_frame_cmds_str[] = {
8914         "GET_VALUES",
8915         "GET_THIS",
8916         "SET_VALUES"
8917 };
8918
8919 static const char* array_cmds_str[] = {
8920         "GET_LENGTH",
8921         "GET_VALUES",
8922         "SET_VALUES",
8923 };
8924
8925 static const char* string_cmds_str[] = {
8926         "GET_VALUE",
8927         "GET_LENGTH",
8928         "GET_CHARS"
8929 };
8930
8931 static const char* object_cmds_str[] = {
8932         "GET_TYPE",
8933         "GET_VALUES",
8934         "IS_COLLECTED",
8935         "GET_ADDRESS",
8936         "GET_DOMAIN",
8937         "SET_VALUES",
8938         "GET_INFO",
8939 };
8940
8941 static const char*
8942 cmd_to_string (CommandSet set, int command)
8943 {
8944         const char **cmds;
8945         int cmds_len = 0;
8946
8947         switch (set) {
8948         case CMD_SET_VM:
8949                 cmds = vm_cmds_str;
8950                 cmds_len = G_N_ELEMENTS (vm_cmds_str);
8951                 break;
8952         case CMD_SET_OBJECT_REF:
8953                 cmds = object_cmds_str;
8954                 cmds_len = G_N_ELEMENTS (object_cmds_str);
8955                 break;
8956         case CMD_SET_STRING_REF:
8957                 cmds = string_cmds_str;
8958                 cmds_len = G_N_ELEMENTS (string_cmds_str);
8959                 break;
8960         case CMD_SET_THREAD:
8961                 cmds = thread_cmds_str;
8962                 cmds_len = G_N_ELEMENTS (thread_cmds_str);
8963                 break;
8964         case CMD_SET_ARRAY_REF:
8965                 cmds = array_cmds_str;
8966                 cmds_len = G_N_ELEMENTS (array_cmds_str);
8967                 break;
8968         case CMD_SET_EVENT_REQUEST:
8969                 cmds = event_cmds_str;
8970                 cmds_len = G_N_ELEMENTS (event_cmds_str);
8971                 break;
8972         case CMD_SET_STACK_FRAME:
8973                 cmds = stack_frame_cmds_str;
8974                 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
8975                 break;
8976         case CMD_SET_APPDOMAIN:
8977                 cmds = appdomain_cmds_str;
8978                 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
8979                 break;
8980         case CMD_SET_ASSEMBLY:
8981                 cmds = assembly_cmds_str;
8982                 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
8983                 break;
8984         case CMD_SET_METHOD:
8985                 cmds = method_cmds_str;
8986                 cmds_len = G_N_ELEMENTS (method_cmds_str);
8987                 break;
8988         case CMD_SET_TYPE:
8989                 cmds = type_cmds_str;
8990                 cmds_len = G_N_ELEMENTS (type_cmds_str);
8991                 break;
8992         case CMD_SET_MODULE:
8993                 cmds = module_cmds_str;
8994                 cmds_len = G_N_ELEMENTS (module_cmds_str);
8995                 break;
8996         case CMD_SET_EVENT:
8997                 cmds = event_cmds_str;
8998                 cmds_len = G_N_ELEMENTS (event_cmds_str);
8999                 break;
9000         default:
9001                 break;
9002         }
9003         if (command > 0 && command <= cmds_len)
9004                 return cmds [command - 1];
9005         else
9006                 return NULL;
9007 }
9008
9009 static gboolean
9010 wait_for_attach (void)
9011 {
9012 #ifndef DISABLE_SOCKET_TRANSPORT
9013         if (listen_fd == -1) {
9014                 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9015                 return FALSE;
9016         }
9017
9018         /* Block and wait for client connection */
9019         conn_fd = socket_transport_accept (listen_fd);
9020         DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9021         if (conn_fd == -1) {
9022                 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9023                 return FALSE;
9024         }
9025 #else
9026         g_assert_not_reached ();
9027 #endif
9028
9029         /* Handshake */
9030         disconnected = !transport_handshake ();
9031         if (disconnected) {
9032                 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9033                 return FALSE;
9034         }
9035         
9036         return TRUE;
9037 }
9038
9039 /*
9040  * debugger_thread:
9041  *
9042  *   This thread handles communication with the debugger client using a JDWP
9043  * like protocol.
9044  */
9045 static guint32 WINAPI
9046 debugger_thread (void *arg)
9047 {
9048         int res, len, id, flags, command_set = 0, command = 0;
9049         guint8 header [HEADER_LENGTH];
9050         guint8 *data, *p, *end;
9051         Buffer buf;
9052         ErrorCode err;
9053         gboolean no_reply;
9054         gboolean attach_failed = FALSE;
9055
9056         DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9057
9058         debugger_thread_id = GetCurrentThreadId ();
9059
9060         mono_jit_thread_attach (mono_get_root_domain ());
9061
9062         mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9063
9064         mono_set_is_debugger_attached (TRUE);
9065         
9066         if (agent_config.defer) {
9067                 if (!wait_for_attach ()) {
9068                         DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9069                         attach_failed = TRUE; // Don't abort process when we can't listen
9070                 } else {
9071                         /* Send start event to client */
9072                         process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9073                 }
9074         }
9075         
9076         while (!attach_failed) {
9077                 res = transport_recv (header, HEADER_LENGTH);
9078
9079                 /* This will break if the socket is closed during shutdown too */
9080                 if (res != HEADER_LENGTH) {
9081                         DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9082                         break;
9083                 }
9084
9085                 p = header;
9086                 end = header + HEADER_LENGTH;
9087
9088                 len = decode_int (p, &p, end);
9089                 id = decode_int (p, &p, end);
9090                 flags = decode_byte (p, &p, end);
9091                 command_set = decode_byte (p, &p, end);
9092                 command = decode_byte (p, &p, end);
9093
9094                 g_assert (flags == 0);
9095
9096                 if (log_level) {
9097                         const char *cmd_str;
9098                         char cmd_num [256];
9099
9100                         cmd_str = cmd_to_string (command_set, command);
9101                         if (!cmd_str) {
9102                                 sprintf (cmd_num, "%d", command);
9103                                 cmd_str = cmd_num;
9104                         }
9105                         
9106                         DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d].\n", command_set_to_string (command_set), cmd_str, id));
9107                 }
9108
9109                 data = g_malloc (len - HEADER_LENGTH);
9110                 if (len - HEADER_LENGTH > 0)
9111                 {
9112                         res = transport_recv (data, len - HEADER_LENGTH);
9113                         if (res != len - HEADER_LENGTH) {
9114                                 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9115                                 break;
9116                         }
9117                 }
9118
9119                 p = data;
9120                 end = data + (len - HEADER_LENGTH);
9121
9122                 buffer_init (&buf, 128);
9123
9124                 err = ERR_NONE;
9125                 no_reply = FALSE;
9126
9127                 /* Process the request */
9128                 switch (command_set) {
9129                 case CMD_SET_VM:
9130                         err = vm_commands (command, id, p, end, &buf);
9131                         if (!err && command == CMD_VM_INVOKE_METHOD)
9132                                 /* Sent after the invoke is complete */
9133                                 no_reply = TRUE;
9134                         break;
9135                 case CMD_SET_EVENT_REQUEST:
9136                         err = event_commands (command, p, end, &buf);
9137                         break;
9138                 case CMD_SET_APPDOMAIN:
9139                         err = domain_commands (command, p, end, &buf);
9140                         break;
9141                 case CMD_SET_ASSEMBLY:
9142                         err = assembly_commands (command, p, end, &buf);
9143                         break;
9144                 case CMD_SET_MODULE:
9145                         err = module_commands (command, p, end, &buf);
9146                         break;
9147                 case CMD_SET_TYPE:
9148                         err = type_commands (command, p, end, &buf);
9149                         break;
9150                 case CMD_SET_METHOD:
9151                         err = method_commands (command, p, end, &buf);
9152                         break;
9153                 case CMD_SET_THREAD:
9154                         err = thread_commands (command, p, end, &buf);
9155                         break;
9156                 case CMD_SET_STACK_FRAME:
9157                         err = frame_commands (command, p, end, &buf);
9158                         break;
9159                 case CMD_SET_ARRAY_REF:
9160                         err = array_commands (command, p, end, &buf);
9161                         break;
9162                 case CMD_SET_STRING_REF:
9163                         err = string_commands (command, p, end, &buf);
9164                         break;
9165                 case CMD_SET_OBJECT_REF:
9166                         err = object_commands (command, p, end, &buf);
9167                         break;
9168                 default:
9169                         err = ERR_NOT_IMPLEMENTED;
9170                 }               
9171
9172                 if (!no_reply)
9173                         send_reply_packet (id, err, &buf);
9174
9175                 g_free (data);
9176                 buffer_free (&buf);
9177
9178                 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9179                         break;
9180         }
9181
9182         mono_set_is_debugger_attached (FALSE);
9183         
9184         mono_mutex_lock (&debugger_thread_exited_mutex);
9185         debugger_thread_exited = TRUE;
9186         mono_cond_signal (&debugger_thread_exited_cond);
9187         mono_mutex_unlock (&debugger_thread_exited_mutex);
9188
9189         DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9190         
9191         if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9192                 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9193                 start_debugger_thread ();
9194         }
9195         
9196         return 0;
9197 }
9198
9199 #else /* DISABLE_DEBUGGER_AGENT */
9200
9201 void
9202 mono_debugger_agent_parse_options (char *options)
9203 {
9204         g_error ("This runtime is configured with the debugger agent disabled.");
9205 }
9206
9207 void
9208 mono_debugger_agent_init (void)
9209 {
9210 }
9211
9212 void
9213 mono_debugger_agent_breakpoint_hit (void *sigctx)
9214 {
9215 }
9216
9217 void
9218 mono_debugger_agent_single_step_event (void *sigctx)
9219 {
9220 }
9221
9222 void
9223 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9224 {
9225 }
9226
9227 gboolean
9228 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9229 {
9230         return FALSE;
9231 }
9232
9233 void
9234 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9235                                                                           MonoContext *catch_ctx)
9236 {
9237 }
9238
9239 void
9240 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9241 {
9242 }
9243
9244 void
9245 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9246 {
9247 }
9248
9249 void
9250 mono_debugger_agent_user_break (void)
9251 {
9252         G_BREAKPOINT ();
9253 }
9254
9255 void
9256 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9257 {
9258 }
9259
9260 gboolean
9261 mono_debugger_agent_debug_log_is_enabled (void)
9262 {
9263         return FALSE;
9264 }
9265
9266 #endif
9267