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