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