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