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