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