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