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