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