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