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