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