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