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