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