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