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