Merge pull request #3547 from cmp-/remove-obsolete-stack-checks-win32
[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 43
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 gsize 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, 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 NULL;
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         if (!obj)
2032                 return 0;
2033         else
2034                 return get_objref (obj)->id;
2035 }
2036
2037 /*
2038  * Set OBJ to the object identified by OBJID.
2039  * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2040  * collected.
2041  */
2042 static ErrorCode
2043 get_object_allow_null (int objid, MonoObject **obj)
2044 {
2045         ObjRef *ref;
2046
2047         if (objid == 0) {
2048                 *obj = NULL;
2049                 return ERR_NONE;
2050         }
2051
2052         if (!objrefs)
2053                 return ERR_INVALID_OBJECT;
2054
2055         mono_loader_lock ();
2056
2057         ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2058
2059         if (ref) {
2060                 *obj = mono_gchandle_get_target (ref->handle);
2061                 mono_loader_unlock ();
2062                 if (!(*obj))
2063                         return ERR_INVALID_OBJECT;
2064                 return ERR_NONE;
2065         } else {
2066                 mono_loader_unlock ();
2067                 return ERR_INVALID_OBJECT;
2068         }
2069 }
2070
2071 static ErrorCode
2072 get_object (int objid, MonoObject **obj)
2073 {
2074         ErrorCode err = get_object_allow_null (objid, obj);
2075
2076         if (err != ERR_NONE)
2077                 return err;
2078         if (!(*obj))
2079                 return ERR_INVALID_OBJECT;
2080         return ERR_NONE;
2081 }
2082
2083 static inline int
2084 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2085 {
2086         return decode_id (buf, endbuf, limit);
2087 }
2088
2089 static inline void
2090 buffer_add_objid (Buffer *buf, MonoObject *o)
2091 {
2092         buffer_add_id (buf, get_objid (o));
2093 }
2094
2095 /*
2096  * IDS
2097  */
2098
2099 typedef enum {
2100         ID_ASSEMBLY = 0,
2101         ID_MODULE = 1,
2102         ID_TYPE = 2,
2103         ID_METHOD = 3,
2104         ID_FIELD = 4,
2105         ID_DOMAIN = 5,
2106         ID_PROPERTY = 6,
2107         ID_NUM
2108 } IdType;
2109
2110 /*
2111  * Represents a runtime structure accessible to the debugger client
2112  */
2113 typedef struct {
2114         /* Unique id used in the wire protocol */
2115         int id;
2116         /* Domain of the runtime structure, NULL if the domain was unloaded */
2117         MonoDomain *domain;
2118         union {
2119                 gpointer val;
2120                 MonoClass *klass;
2121                 MonoMethod *method;
2122                 MonoImage *image;
2123                 MonoAssembly *assembly;
2124                 MonoClassField *field;
2125                 MonoDomain *domain;
2126                 MonoProperty *property;
2127         } data;
2128 } Id;
2129
2130 typedef struct {
2131         /* Maps runtime structure -> Id */
2132         /* Protected by the dbg lock */
2133         GHashTable *val_to_id [ID_NUM];
2134         /* Classes whose class load event has been sent */
2135         /* Protected by the loader lock */
2136         GHashTable *loaded_classes;
2137         /* Maps MonoClass->GPtrArray of file names */
2138         GHashTable *source_files;
2139         /* Maps source file basename -> GSList of classes */
2140         GHashTable *source_file_to_class;
2141         /* Same with ignore-case */
2142         GHashTable *source_file_to_class_ignorecase;
2143 } AgentDomainInfo;
2144
2145 /* Maps id -> Id */
2146 /* Protected by the dbg lock */
2147 static GPtrArray *ids [ID_NUM];
2148
2149 static void
2150 ids_init (void)
2151 {
2152         int i;
2153
2154         for (i = 0; i < ID_NUM; ++i)
2155                 ids [i] = g_ptr_array_new ();
2156 }
2157
2158 static void
2159 ids_cleanup (void)
2160 {
2161         int i, j;
2162
2163         for (i = 0; i < ID_NUM; ++i) {
2164                 if (ids [i]) {
2165                         for (j = 0; j < ids [i]->len; ++j)
2166                                 g_free (g_ptr_array_index (ids [i], j));
2167                         g_ptr_array_free (ids [i], TRUE);
2168                 }
2169                 ids [i] = NULL;
2170         }
2171 }
2172
2173 void
2174 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2175 {
2176         AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2177         int i, j;
2178         GHashTableIter iter;
2179         GPtrArray *file_names;
2180         char *basename;
2181         GSList *l;
2182
2183         if (info) {
2184                 for (i = 0; i < ID_NUM; ++i)
2185                         if (info->val_to_id [i])
2186                                 g_hash_table_destroy (info->val_to_id [i]);
2187                 g_hash_table_destroy (info->loaded_classes);
2188
2189                 g_hash_table_iter_init (&iter, info->source_files);
2190                 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2191                         for (i = 0; i < file_names->len; ++i)
2192                                 g_free (g_ptr_array_index (file_names, i));
2193                         g_ptr_array_free (file_names, TRUE);
2194                 }
2195
2196                 g_hash_table_iter_init (&iter, info->source_file_to_class);
2197                 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2198                         g_free (basename);
2199                         g_slist_free (l);
2200                 }
2201
2202                 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2203                 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2204                         g_free (basename);
2205                         g_slist_free (l);
2206                 }
2207
2208                 g_free (info);
2209         }
2210
2211         domain_jit_info (domain)->agent_info = NULL;
2212
2213         /* Clear ids referencing structures in the domain */
2214         dbg_lock ();
2215         for (i = 0; i < ID_NUM; ++i) {
2216                 if (ids [i]) {
2217                         for (j = 0; j < ids [i]->len; ++j) {
2218                                 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2219                                 if (id->domain == domain)
2220                                         id->domain = NULL;
2221                         }
2222                 }
2223         }
2224         dbg_unlock ();
2225
2226         mono_loader_lock ();
2227         g_hash_table_remove (domains, domain);
2228         mono_loader_unlock ();
2229 }
2230
2231 static AgentDomainInfo*
2232 get_agent_domain_info (MonoDomain *domain)
2233 {
2234         AgentDomainInfo *info = NULL;
2235
2236         mono_domain_lock (domain);
2237
2238         info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2239         if (!info) {
2240                 info = g_new0 (AgentDomainInfo, 1);
2241                 domain_jit_info (domain)->agent_info = info;
2242                 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2243                 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2244                 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2245                 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2246         }
2247
2248         mono_domain_unlock (domain);
2249
2250         return info;
2251 }
2252
2253 static int
2254 get_id (MonoDomain *domain, IdType type, gpointer val)
2255 {
2256         Id *id;
2257         AgentDomainInfo *info;
2258
2259         if (val == NULL)
2260                 return 0;
2261
2262         info = get_agent_domain_info (domain);
2263
2264         dbg_lock ();
2265
2266         if (info->val_to_id [type] == NULL)
2267                 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2268
2269         id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2270         if (id) {
2271                 dbg_unlock ();
2272                 return id->id;
2273         }
2274
2275         id = g_new0 (Id, 1);
2276         /* Reserve id 0 */
2277         id->id = ids [type]->len + 1;
2278         id->domain = domain;
2279         id->data.val = val;
2280
2281         g_hash_table_insert (info->val_to_id [type], val, id);
2282         g_ptr_array_add (ids [type], id);
2283
2284         dbg_unlock ();
2285
2286         return id->id;
2287 }
2288
2289 static inline gpointer
2290 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2291 {
2292         Id *res;
2293
2294         int id = decode_id (buf, endbuf, limit);
2295
2296         *err = ERR_NONE;
2297         if (domain)
2298                 *domain = NULL;
2299
2300         if (id == 0)
2301                 return NULL;
2302
2303         // FIXME: error handling
2304         dbg_lock ();
2305         g_assert (id > 0 && id <= ids [type]->len);
2306
2307         res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2308         dbg_unlock ();
2309
2310         if (res->domain == NULL) {
2311                 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2312                 *err = ERR_UNLOADED;
2313                 return NULL;
2314         }
2315
2316         if (domain)
2317                 *domain = res->domain;
2318
2319         return res->data.val;
2320 }
2321
2322 static inline int
2323 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2324 {
2325         int id = get_id (domain, type, val);
2326
2327         buffer_add_id (buf, id);
2328         return id;
2329 }
2330
2331 static inline MonoClass*
2332 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2333 {
2334         MonoClass *klass;
2335
2336         klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2337         if (G_UNLIKELY (log_level >= 2) && klass) {
2338                 char *s;
2339
2340                 s = mono_type_full_name (&klass->byval_arg);
2341                 DEBUG_PRINTF (2, "[dbg]   recv class [%s]\n", s);
2342                 g_free (s);
2343         }
2344         return klass;
2345 }
2346
2347 static inline MonoAssembly*
2348 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2349 {
2350         return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2351 }
2352
2353 static inline MonoImage*
2354 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2355 {
2356         return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2357 }
2358
2359 static inline MonoMethod*
2360 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2361 {
2362         MonoMethod *m;
2363
2364         m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2365         if (G_UNLIKELY (log_level >= 2) && m) {
2366                 char *s;
2367
2368                 s = mono_method_full_name (m, TRUE);
2369                 DEBUG_PRINTF (2, "[dbg]   recv method [%s]\n", s);
2370                 g_free (s);
2371         }
2372         return m;
2373 }
2374
2375 static inline MonoClassField*
2376 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2377 {
2378         return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2379 }
2380
2381 static inline MonoDomain*
2382 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2383 {
2384         return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2385 }
2386
2387 static inline MonoProperty*
2388 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2389 {
2390         return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2391 }
2392
2393 static inline void
2394 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2395 {
2396         buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2397         if (G_UNLIKELY (log_level >= 2) && klass) {
2398                 char *s;
2399
2400                 s = mono_type_full_name (&klass->byval_arg);
2401                 if (is_debugger_thread ())
2402                         DEBUG_PRINTF (2, "[dbg]   send class [%s]\n", s);
2403                 else
2404                         DEBUG_PRINTF (2, "[%p]   send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2405                 g_free (s);
2406         }
2407 }
2408
2409 static inline void
2410 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2411 {
2412         buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2413         if (G_UNLIKELY (log_level >= 2) && method) {
2414                 char *s;
2415
2416                 s = mono_method_full_name (method, 1);
2417                 DEBUG_PRINTF (2, "[dbg]   send method [%s]\n", s);
2418                 g_free (s);
2419         }
2420 }
2421
2422 static inline void
2423 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2424 {
2425         int id;
2426
2427         id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2428         if (G_UNLIKELY (log_level >= 2) && assembly)
2429                 DEBUG_PRINTF (2, "[dbg]   send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2430 }
2431
2432 static inline void
2433 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2434 {
2435         buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2436 }
2437
2438 static inline void
2439 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2440 {
2441         buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2442 }
2443
2444 static inline void
2445 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2446 {
2447         buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2448 }
2449
2450 static inline void
2451 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2452 {
2453         buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2454 }
2455
2456 static void invoke_method (void);
2457
2458 /*
2459  * SUSPEND/RESUME
2460  */
2461
2462 /*
2463  * save_thread_context:
2464  *
2465  *   Set CTX as the current threads context which is used for computing stack traces.
2466  * This function is signal-safe.
2467  */
2468 static void
2469 save_thread_context (MonoContext *ctx)
2470 {
2471         DebuggerTlsData *tls;
2472
2473         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2474         g_assert (tls);
2475
2476         if (ctx)
2477                 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2478         else
2479                 mono_thread_state_init_from_current (&tls->context);
2480 }
2481
2482 /* Number of threads suspended */
2483 /* 
2484  * If this is equal to the size of thread_to_tls, the runtime is considered
2485  * suspended.
2486  */
2487 static gint32 threads_suspend_count;
2488
2489 static MonoCoopMutex suspend_mutex;
2490
2491 /* Cond variable used to wait for suspend_count becoming 0 */
2492 static MonoCoopCond suspend_cond;
2493
2494 /* Semaphore used to wait for a thread becoming suspended */
2495 static MonoCoopSem suspend_sem;
2496
2497 static void
2498 suspend_init (void)
2499 {
2500         mono_coop_mutex_init (&suspend_mutex);
2501         mono_coop_cond_init (&suspend_cond);    
2502         mono_coop_sem_init (&suspend_sem, 0);
2503 }
2504
2505 typedef struct
2506 {
2507         StackFrameInfo last_frame;
2508         gboolean last_frame_set;
2509         MonoContext ctx;
2510         gpointer lmf;
2511         MonoDomain *domain;
2512 } GetLastFrameUserData;
2513
2514 static gboolean
2515 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2516 {
2517         GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2518
2519         if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2520                 return FALSE;
2521
2522         if (!data->last_frame_set) {
2523                 /* Store the last frame */
2524                 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2525                 data->last_frame_set = TRUE;
2526                 return FALSE;
2527         } else {
2528                 /* Store the context/lmf for the frame above the last frame */
2529                 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2530                 data->lmf = info->lmf;
2531                 data->domain = info->domain;
2532                 return TRUE;
2533         }
2534 }
2535
2536 static void
2537 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2538 {
2539         memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2540
2541         to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2542         to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2543         to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2544         to->valid = TRUE;
2545 }
2546
2547 /*
2548  * thread_interrupt:
2549  *
2550  *   Process interruption of a thread. This should be signal safe.
2551  *
2552  * This always runs in the debugger thread.
2553  */
2554 static void
2555 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2556 {
2557         gpointer ip;
2558         MonoNativeThreadId tid;
2559
2560         g_assert (info);
2561
2562         ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2563         tid = mono_thread_info_get_tid (info);
2564
2565         // FIXME: Races when the thread leaves managed code before hitting a single step
2566         // event.
2567
2568         if (ji && !ji->is_trampoline) {
2569                 /* Running managed code, will be suspended by the single step code */
2570                 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2571         } else {
2572                 /* 
2573                  * Running native code, will be suspended when it returns to/enters 
2574                  * managed code. Treat it as already suspended.
2575                  * This might interrupt the code in process_single_step_inner (), we use the
2576                  * tls->suspending flag to avoid races when that happens.
2577                  */
2578                 if (!tls->suspended && !tls->suspending) {
2579                         GetLastFrameUserData data;
2580
2581                         // FIXME: printf is not signal safe, but this is only used during
2582                         // debugger debugging
2583                         if (ip)
2584                                 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2585                         //save_thread_context (&ctx);
2586
2587                         if (!tls->thread)
2588                                 /* Already terminated */
2589                                 return;
2590
2591                         /*
2592                          * We are in a difficult position: we want to be able to provide stack
2593                          * traces for this thread, but we can't use the current ctx+lmf, since
2594                          * the thread is still running, so it might return to managed code,
2595                          * making these invalid.
2596                          * So we start a stack walk and save the first frame, along with the
2597                          * parent frame's ctx+lmf. This (hopefully) works because the thread will be 
2598                          * suspended when it returns to managed code, so the parent's ctx should
2599                          * remain valid.
2600                          */
2601                         data.last_frame_set = FALSE;
2602                         mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2603                         if (data.last_frame_set) {
2604                                 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2605
2606                                 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2607
2608                                 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2609                                 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2610                         } else {
2611                                 tls->async_state.valid = FALSE;
2612                         }
2613
2614                         mono_memory_barrier ();
2615
2616                         tls->suspended = TRUE;
2617                         mono_coop_sem_post (&suspend_sem);
2618                 }
2619         }
2620 }
2621
2622 /*
2623  * reset_native_thread_suspend_state:
2624  * 
2625  *   Reset the suspended flag and state on native threads
2626  */
2627 static void
2628 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2629 {
2630         DebuggerTlsData *tls = (DebuggerTlsData *)value;
2631
2632         if (!tls->really_suspended && tls->suspended) {
2633                 tls->suspended = FALSE;
2634                 /*
2635                  * The thread might still be running if it was executing native code, so the state won't be invalided by
2636                  * suspend_current ().
2637                  */
2638                 tls->context.valid = FALSE;
2639                 tls->async_state.valid = FALSE;
2640                 invalidate_frames (tls);
2641         }
2642 }
2643
2644 typedef struct {
2645         DebuggerTlsData *tls;
2646         gboolean valid_info;
2647 } InterruptData;
2648
2649 static SuspendThreadResult
2650 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2651 {
2652         InterruptData *data = (InterruptData *)user_data;
2653         MonoJitInfo *ji;
2654
2655         data->valid_info = TRUE;
2656         ji = mono_jit_info_table_find_internal (
2657                         (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2658                         (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2659                         TRUE,
2660                         TRUE);
2661
2662         /* This is signal safe */
2663         thread_interrupt (data->tls, info, ji);
2664         return MonoResumeThread;
2665 }
2666
2667 /*
2668  * notify_thread:
2669  *
2670  *   Notify a thread that it needs to suspend.
2671  */
2672 static void
2673 notify_thread (gpointer key, gpointer value, gpointer user_data)
2674 {
2675         MonoInternalThread *thread = (MonoInternalThread *)key;
2676         DebuggerTlsData *tls = (DebuggerTlsData *)value;
2677         MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2678
2679         if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2680                 return;
2681
2682         DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2683
2684         /* This is _not_ equivalent to mono_thread_internal_abort () */
2685         InterruptData interrupt_data = { 0 };
2686         interrupt_data.tls = tls;
2687
2688         mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2689         if (!interrupt_data.valid_info) {
2690                 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2691                 /* 
2692                  * Attached thread which died without detaching.
2693                  */
2694                 tls->terminated = TRUE;
2695         }
2696 }
2697
2698 static void
2699 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2700 {
2701         guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2702         MonoJitInfo *ji;
2703         MonoMethod *method;
2704
2705         if (mono_loader_lock_is_owned_by_self ()) {
2706                 /*
2707                  * Shortcut for the check in suspend_current (). This speeds up processing
2708                  * when executing long running code inside the loader lock, i.e. assembly load
2709                  * hooks.
2710                  */
2711                 return;
2712         }
2713
2714         if (is_debugger_thread ())
2715                 return;
2716
2717         /* Prevent races with mono_debugger_agent_thread_interrupt () */
2718         if (suspend_count - tls->resume_count > 0)
2719                 tls->suspending = TRUE;
2720
2721         DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2722
2723         if (suspend_count - tls->resume_count == 0) {
2724                 /* 
2725                  * We are executing a single threaded invoke but the single step for 
2726                  * suspending is still active.
2727                  * FIXME: This slows down single threaded invokes.
2728                  */
2729                 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2730                 return;
2731         }
2732
2733         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2734
2735         /* Can't suspend in these methods */
2736         method = jinfo_get_method (ji);
2737         if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2738                 return;
2739
2740         save_thread_context (ctx);
2741
2742         suspend_current ();
2743 }
2744
2745 /*
2746  * suspend_vm:
2747  *
2748  * Increase the suspend count of the VM. While the suspend count is greater 
2749  * than 0, runtime threads are suspended at certain points during execution.
2750  */
2751 static void
2752 suspend_vm (void)
2753 {
2754         mono_loader_lock ();
2755
2756         mono_coop_mutex_lock (&suspend_mutex);
2757
2758         suspend_count ++;
2759
2760         DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2761
2762         if (suspend_count == 1) {
2763                 // FIXME: Is it safe to call this inside the lock ?
2764                 start_single_stepping ();
2765                 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2766         }
2767
2768         mono_coop_mutex_unlock (&suspend_mutex);
2769
2770         if (suspend_count == 1)
2771                 /*
2772                  * Suspend creation of new threadpool threads, since they cannot run
2773                  */
2774                 mono_threadpool_ms_suspend ();
2775
2776         mono_loader_unlock ();
2777 }
2778
2779 /*
2780  * resume_vm:
2781  *
2782  * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2783  * are resumed.
2784  */
2785 static void
2786 resume_vm (void)
2787 {
2788         g_assert (is_debugger_thread ());
2789
2790         mono_loader_lock ();
2791
2792         mono_coop_mutex_lock (&suspend_mutex);
2793
2794         g_assert (suspend_count > 0);
2795         suspend_count --;
2796
2797         DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2798
2799         if (suspend_count == 0) {
2800                 // FIXME: Is it safe to call this inside the lock ?
2801                 stop_single_stepping ();
2802                 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2803         }
2804
2805         /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2806         mono_coop_cond_broadcast (&suspend_cond);
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         DebuggerTlsData *tls;
2826
2827         g_assert (is_debugger_thread ());
2828
2829         mono_loader_lock ();
2830
2831         tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2832         g_assert (tls);
2833
2834         mono_coop_mutex_lock (&suspend_mutex);
2835
2836         g_assert (suspend_count > 0);
2837
2838         DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2839
2840         tls->resume_count += suspend_count;
2841
2842         /* 
2843          * Signal suspend_count without decreasing suspend_count, the threads will wake up
2844          * but only the one whose resume_count field is > 0 will be resumed.
2845          */
2846         mono_coop_cond_broadcast (&suspend_cond);
2847
2848         mono_coop_mutex_unlock (&suspend_mutex);
2849         //g_assert (err == 0);
2850
2851         mono_loader_unlock ();
2852 }
2853
2854 static void
2855 free_frames (StackFrame **frames, int nframes)
2856 {
2857         int i;
2858
2859         for (i = 0; i < nframes; ++i) {
2860                 if (frames [i]->jit)
2861                         mono_debug_free_method_jit_info (frames [i]->jit);
2862                 g_free (frames [i]);
2863         }
2864         g_free (frames);
2865 }
2866
2867 static void
2868 invalidate_frames (DebuggerTlsData *tls)
2869 {
2870         if (!tls)
2871                 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2872         g_assert (tls);
2873
2874         free_frames (tls->frames, tls->frame_count);
2875         tls->frame_count = 0;
2876         tls->frames = NULL;
2877
2878         free_frames (tls->restore_frames, tls->restore_frame_count);
2879         tls->restore_frame_count = 0;
2880         tls->restore_frames = NULL;
2881 }
2882
2883 /*
2884  * suspend_current:
2885  *
2886  *   Suspend the current thread until the runtime is resumed. If the thread has a 
2887  * pending invoke, then the invoke is executed before this function returns. 
2888  */
2889 static void
2890 suspend_current (void)
2891 {
2892         DebuggerTlsData *tls;
2893
2894         g_assert (!is_debugger_thread ());
2895
2896         if (mono_loader_lock_is_owned_by_self ()) {
2897                 /*
2898                  * If we own the loader mutex, can't suspend until we release it, since the
2899                  * whole runtime can deadlock otherwise.
2900                  */
2901                 return;
2902         }
2903
2904         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2905         g_assert (tls);
2906
2907         mono_coop_mutex_lock (&suspend_mutex);
2908
2909         tls->suspending = FALSE;
2910         tls->really_suspended = TRUE;
2911
2912         if (!tls->suspended) {
2913                 tls->suspended = TRUE;
2914                 mono_coop_sem_post (&suspend_sem);
2915         }
2916
2917         DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2918
2919         while (suspend_count - tls->resume_count > 0) {
2920                 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2921         }
2922
2923         tls->suspended = FALSE;
2924         tls->really_suspended = FALSE;
2925
2926         threads_suspend_count --;
2927
2928         mono_coop_mutex_unlock (&suspend_mutex);
2929
2930         DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2931
2932         if (tls->pending_invoke) {
2933                 /* Save the original context */
2934                 tls->pending_invoke->has_ctx = TRUE;
2935                 tls->pending_invoke->ctx = tls->context.ctx;
2936
2937                 invoke_method ();
2938         }
2939
2940         /* The frame info becomes invalid after a resume */
2941         tls->context.valid = FALSE;
2942         tls->async_state.valid = FALSE;
2943         invalidate_frames (tls);
2944 }
2945
2946 static void
2947 count_thread (gpointer key, gpointer value, gpointer user_data)
2948 {
2949         DebuggerTlsData *tls = (DebuggerTlsData *)value;
2950
2951         if (!tls->suspended && !tls->terminated)
2952                 *(int*)user_data = *(int*)user_data + 1;
2953 }
2954
2955 static int
2956 count_threads_to_wait_for (void)
2957 {
2958         int count = 0;
2959
2960         mono_loader_lock ();
2961         mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2962         mono_loader_unlock ();
2963
2964         return count;
2965 }       
2966
2967 /*
2968  * wait_for_suspend:
2969  *
2970  *   Wait until the runtime is completely suspended.
2971  */
2972 static void
2973 wait_for_suspend (void)
2974 {
2975         int nthreads, nwait, err;
2976         gboolean waited = FALSE;
2977
2978         // FIXME: Threads starting/stopping ?
2979         mono_loader_lock ();
2980         nthreads = mono_g_hash_table_size (thread_to_tls);
2981         mono_loader_unlock ();
2982
2983         while (TRUE) {
2984                 nwait = count_threads_to_wait_for ();
2985                 if (nwait) {
2986                         DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2987                         err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2988                         g_assert (err == 0);
2989                         waited = TRUE;
2990                 } else {
2991                         break;
2992                 }
2993         }
2994
2995         if (waited)
2996                 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
2997 }
2998
2999 /*
3000  * is_suspended:
3001  *
3002  *   Return whenever the runtime is suspended.
3003  */
3004 static gboolean
3005 is_suspended (void)
3006 {
3007         return count_threads_to_wait_for () == 0;
3008 }
3009
3010 static void
3011 no_seq_points_found (MonoMethod *method, int offset)
3012 {
3013         /*
3014          * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3015          */
3016         printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3017 }
3018
3019 typedef struct {
3020         DebuggerTlsData *tls;
3021         GSList *frames;
3022 } ComputeFramesUserData;
3023
3024 static gboolean
3025 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3026 {
3027         ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3028         StackFrame *frame;
3029         MonoMethod *method, *actual_method, *api_method;
3030         SeqPoint sp;
3031         int flags = 0;
3032
3033         if (info->type != FRAME_TYPE_MANAGED) {
3034                 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3035                         /* Mark the last frame as an invoke frame */
3036                         if (ud->frames)
3037                                 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3038                 }
3039                 return FALSE;
3040         }
3041
3042         if (info->ji)
3043                 method = jinfo_get_method (info->ji);
3044         else
3045                 method = info->method;
3046         actual_method = info->actual_method;
3047         api_method = method;
3048
3049         if (!method)
3050                 return FALSE;
3051
3052         if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3053                 return FALSE;
3054
3055         if (info->il_offset == -1) {
3056                 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3057                 if (ud->frames == NULL) {
3058                         if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3059                                 info->il_offset = sp.il_offset;
3060                 }
3061                 if (info->il_offset == -1)
3062                         info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3063         }
3064
3065         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);
3066
3067         if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3068                 if (!CHECK_PROTOCOL_VERSION (2, 17))
3069                         /* Older clients can't handle this flag */
3070                         return FALSE;
3071                 api_method = mono_marshal_method_from_wrapper (method);
3072                 if (!api_method)
3073                         return FALSE;
3074                 actual_method = api_method;
3075                 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3076         }
3077
3078         frame = g_new0 (StackFrame, 1);
3079         frame->method = method;
3080         frame->actual_method = actual_method;
3081         frame->api_method = api_method;
3082         frame->il_offset = info->il_offset;
3083         frame->native_offset = info->native_offset;
3084         frame->flags = flags;
3085         frame->ji = info->ji;
3086         if (info->reg_locations)
3087                 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3088         if (ctx) {
3089                 frame->ctx = *ctx;
3090                 frame->has_ctx = TRUE;
3091         }
3092         frame->domain = info->domain;
3093
3094         ud->frames = g_slist_append (ud->frames, frame);
3095
3096         return FALSE;
3097 }
3098
3099 static gboolean
3100 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3101 {
3102         ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3103
3104         /*
3105          * 'tls->filter_ctx' is the location of the throw site.
3106          *
3107          * mono_walk_stack() will never actually hit the throw site, but unwind
3108          * directly from the filter to the call site; we abort stack unwinding here
3109          * once this happens and resume from the throw site.
3110          */
3111
3112         if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3113                 return TRUE;
3114
3115         return process_frame (info, ctx, user_data);
3116 }
3117
3118 /*
3119  * Return a malloc-ed list of StackFrame structures.
3120  */
3121 static StackFrame**
3122 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3123 {
3124         ComputeFramesUserData user_data;
3125         MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3126         StackFrame **res;
3127         int i, nframes;
3128         GSList *l;
3129
3130         user_data.tls = tls;
3131         user_data.frames = NULL;
3132
3133         mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3134
3135         nframes = g_slist_length (user_data.frames);
3136         res = g_new0 (StackFrame*, nframes);
3137         l = user_data.frames;
3138         for (i = 0; i < nframes; ++i) {
3139                 res [i] = (StackFrame *)l->data;
3140                 l = l->next;
3141         }
3142         *out_nframes = nframes;
3143
3144         return res;
3145 }
3146
3147 static void
3148 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3149 {
3150         ComputeFramesUserData user_data;
3151         GSList *tmp;
3152         int i, findex, new_frame_count;
3153         StackFrame **new_frames, *f;
3154         MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3155
3156         // FIXME: Locking on tls
3157         if (tls->frames && tls->frames_up_to_date)
3158                 return;
3159
3160         DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3161
3162         user_data.tls = tls;
3163         user_data.frames = NULL;
3164         if (tls->terminated) {
3165                 tls->frame_count = 0;
3166                 return;
3167         } if (!tls->really_suspended && tls->async_state.valid) {
3168                 /* Have to use the state saved by the signal handler */
3169                 process_frame (&tls->async_last_frame, NULL, &user_data);
3170                 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3171         } else if (tls->filter_state.valid) {
3172                 /*
3173                  * We are inside an exception filter.
3174                  *
3175                  * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3176                  */
3177                 if (tls->context.valid)
3178                         mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3179                 /*
3180                  * After that, we resume unwinding from the location where the exception has been thrown.
3181                  */
3182                 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3183         } else if (tls->context.valid) {
3184                 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3185         } else {
3186                 // FIXME:
3187                 tls->frame_count = 0;
3188                 return;
3189         }
3190
3191         new_frame_count = g_slist_length (user_data.frames);
3192         new_frames = g_new0 (StackFrame*, new_frame_count);
3193         findex = 0;
3194         for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3195                 f = (StackFrame *)tmp->data;
3196
3197                 /* 
3198                  * Reuse the id for already existing stack frames, so invokes don't invalidate
3199                  * the still valid stack frames.
3200                  */
3201                 for (i = 0; i < tls->frame_count; ++i) {
3202                         if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3203                                 f->id = tls->frames [i]->id;
3204                                 break;
3205                         }
3206                 }
3207
3208                 if (i >= tls->frame_count)
3209                         f->id = InterlockedIncrement (&frame_id);
3210
3211                 new_frames [findex ++] = f;
3212         }
3213
3214         g_slist_free (user_data.frames);
3215
3216         invalidate_frames (tls);
3217
3218         tls->frames = new_frames;
3219         tls->frame_count = new_frame_count;
3220         tls->frames_up_to_date = TRUE;
3221 }
3222
3223 /*
3224  * GHFunc to emit an appdomain creation event
3225  * @param key Don't care
3226  * @param value A loaded appdomain
3227  * @param user_data Don't care
3228  */
3229 static void
3230 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3231 {
3232         process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3233         g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3234 }
3235
3236 /*
3237  * GHFunc to emit a thread start event
3238  * @param key A thread id
3239  * @param value A thread object
3240  * @param user_data Don't care
3241  */
3242 static void
3243 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3244 {
3245         if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3246                 process_profiler_event (EVENT_KIND_THREAD_START, value);
3247 }
3248
3249 /*
3250  * GFunc to emit an assembly load event
3251  * @param value A loaded assembly
3252  * @param user_data Don't care
3253  */
3254 static void
3255 emit_assembly_load (gpointer value, gpointer user_data)
3256 {
3257         process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3258 }
3259
3260 /*
3261  * GFunc to emit a type load event
3262  * @param value A loaded type
3263  * @param user_data Don't care
3264  */
3265 static void
3266 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3267 {
3268         process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3269 }
3270
3271 static char*
3272 strdup_tolower (char *s)
3273 {
3274         char *s2, *p;
3275
3276         s2 = g_strdup (s);
3277         for (p = s2; *p; ++p)
3278                 *p = tolower (*p);
3279         return s2;
3280 }
3281
3282 /*
3283  * Same as g_path_get_basename () but handles windows paths as well,
3284  * which can occur in .mdb files created by pdb2mdb.
3285  */
3286 static char*
3287 dbg_path_get_basename (const char *filename)
3288 {
3289         char *r;
3290
3291         if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3292                 return g_path_get_basename (filename);
3293
3294         /* From gpath.c */
3295
3296         /* No separator -> filename */
3297         r = strrchr (filename, '\\');
3298         if (r == NULL)
3299                 return g_strdup (filename);
3300
3301         /* Trailing slash, remove component */
3302         if (r [1] == 0){
3303                 char *copy = g_strdup (filename);
3304                 copy [r-filename] = 0;
3305                 r = strrchr (copy, '\\');
3306
3307                 if (r == NULL){
3308                         g_free (copy);
3309                         return g_strdup ("/");
3310                 }
3311                 r = g_strdup (&r[1]);
3312                 g_free (copy);
3313                 return r;
3314         }
3315
3316         return g_strdup (&r[1]);
3317 }
3318
3319 static void
3320 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3321 {
3322         static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3323         MonoError error;
3324         MonoCustomAttrInfo *ainfo;
3325
3326         if (ji->dbg_attrs_inited)
3327                 return;
3328
3329         if (!hidden_klass)
3330                 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3331
3332         if (!step_through_klass)
3333                 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3334
3335         if (!non_user_klass)
3336                 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3337
3338         ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3339         mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3340         if (ainfo) {
3341                 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3342                         ji->dbg_hidden = TRUE;
3343                 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3344                         ji->dbg_step_through = TRUE;
3345                 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3346                         ji->dbg_non_user_code = TRUE;
3347                 mono_custom_attrs_free (ainfo);
3348         }
3349
3350         ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3351         mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3352         if (ainfo) {
3353                 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3354                         ji->dbg_step_through = TRUE;
3355                 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3356                         ji->dbg_non_user_code = TRUE;
3357                 mono_custom_attrs_free (ainfo);
3358         }
3359
3360         mono_memory_barrier ();
3361         ji->dbg_attrs_inited = TRUE;
3362 }
3363
3364 /*
3365  * EVENT HANDLING
3366  */
3367
3368 /*
3369  * create_event_list:
3370  *
3371  *   Return a list of event request ids matching EVENT, starting from REQS, which
3372  * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3373  * policy.
3374  * We return request ids, instead of requests, to simplify threading, since 
3375  * requests could be deleted anytime when the loader lock is not held.
3376  * LOCKING: Assumes the loader lock is held.
3377  */
3378 static GSList*
3379 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3380 {
3381         int i, j;
3382         GSList *events = NULL;
3383
3384         *suspend_policy = SUSPEND_POLICY_NONE;
3385
3386         if (!reqs)
3387                 reqs = event_requests;
3388
3389         if (!reqs)
3390                 return NULL;
3391
3392         for (i = 0; i < reqs->len; ++i) {
3393                 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3394                 if (req->event_kind == event) {
3395                         gboolean filtered = FALSE;
3396
3397                         /* Apply filters */
3398                         for (j = 0; j < req->nmodifiers; ++j) {
3399                                 Modifier *mod = &req->modifiers [j];
3400
3401                                 if (mod->kind == MOD_KIND_COUNT) {
3402                                         filtered = TRUE;
3403                                         if (mod->data.count > 0) {
3404                                                 if (mod->data.count > 0) {
3405                                                         mod->data.count --;
3406                                                         if (mod->data.count == 0)
3407                                                                 filtered = FALSE;
3408                                                 }
3409                                         }
3410                                 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3411                                         if (mod->data.thread != mono_thread_internal_current ())
3412                                                 filtered = TRUE;
3413                                 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3414                                         if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3415                                                 filtered = TRUE;
3416                                         if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3417                                                 filtered = TRUE;
3418                                         if (ei->caught && !mod->caught)
3419                                                 filtered = TRUE;
3420                                         if (!ei->caught && !mod->uncaught)
3421                                                 filtered = TRUE;
3422                                 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3423                                         int k;
3424                                         gboolean found = FALSE;
3425                                         MonoAssembly **assemblies = mod->data.assemblies;
3426
3427                                         if (assemblies) {
3428                                                 for (k = 0; assemblies [k]; ++k)
3429                                                         if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3430                                                                 found = TRUE;
3431                                         }
3432                                         if (!found)
3433                                                 filtered = TRUE;
3434                                 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3435                                         gpointer iter = NULL;
3436                                         MonoMethod *method;
3437                                         MonoDebugSourceInfo *sinfo;
3438                                         char *source_file, *s;
3439                                         gboolean found = FALSE;
3440                                         int i;
3441                                         GPtrArray *source_file_list;
3442
3443                                         while ((method = mono_class_get_methods (ei->klass, &iter))) {
3444                                                 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3445
3446                                                 if (minfo) {
3447                                                         mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3448                                                         for (i = 0; i < source_file_list->len; ++i) {
3449                                                                 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3450                                                                 /*
3451                                                                  * Do a case-insesitive match by converting the file name to
3452                                                                  * lowercase.
3453                                                                  */
3454                                                                 s = strdup_tolower (sinfo->source_file);
3455                                                                 if (g_hash_table_lookup (mod->data.source_files, s))
3456                                                                         found = TRUE;
3457                                                                 else {
3458                                                                         char *s2 = dbg_path_get_basename (sinfo->source_file);
3459                                                                         char *s3 = strdup_tolower (s2);
3460
3461                                                                         if (g_hash_table_lookup (mod->data.source_files, s3))
3462                                                                                 found = TRUE;
3463                                                                         g_free (s2);
3464                                                                         g_free (s3);
3465                                                                 }
3466                                                                 g_free (s);
3467                                                         }
3468                                                         g_ptr_array_free (source_file_list, TRUE);
3469                                                 }
3470                                         }
3471                                         if (!found)
3472                                                 filtered = TRUE;
3473                                 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3474                                         char *s;
3475
3476                                         s = mono_type_full_name (&ei->klass->byval_arg);
3477                                         if (!g_hash_table_lookup (mod->data.type_names, s))
3478                                                 filtered = TRUE;
3479                                         g_free (s);
3480                                 } else if (mod->kind == MOD_KIND_STEP) {
3481                                         if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3482                                                 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3483                                                 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3484                                                 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3485                                                 filtered = TRUE;
3486                                         if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3487                                                 init_jit_info_dbg_attrs (ji);
3488                                                 if (ji->dbg_hidden)
3489                                                         filtered = TRUE;
3490                                         }
3491                                         if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3492                                                 init_jit_info_dbg_attrs (ji);
3493                                                 if (ji->dbg_step_through)
3494                                                         filtered = TRUE;
3495                                         }
3496                                         if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3497                                                 init_jit_info_dbg_attrs (ji);
3498                                                 if (ji->dbg_non_user_code)
3499                                                         filtered = TRUE;
3500                                         }
3501                                 }
3502                         }
3503
3504                         if (!filtered) {
3505                                 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3506                                 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3507                         }
3508                 }
3509         }
3510
3511         /* Send a VM START/DEATH event by default */
3512         if (event == EVENT_KIND_VM_START)
3513                 events = g_slist_append (events, GINT_TO_POINTER (0));
3514         if (event == EVENT_KIND_VM_DEATH)
3515                 events = g_slist_append (events, GINT_TO_POINTER (0));
3516
3517         return events;
3518 }
3519
3520 static G_GNUC_UNUSED const char*
3521 event_to_string (EventKind event)
3522 {
3523         switch (event) {
3524         case EVENT_KIND_VM_START: return "VM_START";
3525         case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3526         case EVENT_KIND_THREAD_START: return "THREAD_START";
3527         case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3528         case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3529         case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3530         case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3531         case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3532         case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3533         case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3534         case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3535         case EVENT_KIND_STEP: return "STEP";
3536         case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3537         case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3538         case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3539         case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3540         case EVENT_KIND_USER_LOG: return "USER_LOG";
3541         default:
3542                 g_assert_not_reached ();
3543                 return "";
3544         }
3545 }
3546
3547 /*
3548  * process_event:
3549  *
3550  *   Send an event to the client, suspending the vm if needed.
3551  * LOCKING: Since this can suspend the calling thread, no locks should be held
3552  * by the caller.
3553  * The EVENTS list is freed by this function.
3554  */
3555 static void
3556 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3557 {
3558         Buffer buf;
3559         GSList *l;
3560         MonoDomain *domain = mono_domain_get ();
3561         MonoThread *thread = NULL;
3562         MonoObject *keepalive_obj = NULL;
3563         gboolean send_success = FALSE;
3564         static int ecount;
3565         int nevents;
3566
3567         if (!inited) {
3568                 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3569                 return;
3570         }
3571
3572         if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3573                 // FIXME: We miss those events
3574                 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3575                 return;
3576         }
3577
3578         if (vm_death_event_sent) {
3579                 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3580                 return;
3581         }
3582
3583         if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3584                 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3585                 return;
3586         }
3587
3588         if (disconnected) {
3589                 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3590                 return;
3591         }
3592
3593         if (event == EVENT_KIND_KEEPALIVE)
3594                 suspend_policy = SUSPEND_POLICY_NONE;
3595         else {
3596                 if (events == NULL)
3597                         return;
3598
3599                 if (agent_config.defer) {
3600                         /* Make sure the thread id is always set when doing deferred debugging */
3601                         if (is_debugger_thread ()) {
3602                                 /* Don't suspend on events from the debugger thread */
3603                                 suspend_policy = SUSPEND_POLICY_NONE;
3604                                 thread = mono_thread_get_main ();
3605                         }
3606                         else thread = mono_thread_current ();
3607                 } else {
3608                         if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3609                                 // FIXME: Send these with a NULL thread, don't suspend the current thread
3610                                 return;
3611                 }
3612         }
3613
3614         nevents = g_slist_length (events);
3615         buffer_init (&buf, 128);
3616         buffer_add_byte (&buf, suspend_policy);
3617         buffer_add_int (&buf, nevents);
3618
3619         for (l = events; l; l = l->next) {
3620                 buffer_add_byte (&buf, event); // event kind
3621                 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3622
3623                 ecount ++;
3624
3625                 if (event == EVENT_KIND_VM_DEATH) {
3626                         thread = NULL;
3627                 } else {
3628                         if (!thread)
3629                                 thread = mono_thread_current ();
3630
3631                         if (event == EVENT_KIND_VM_START && arg != NULL)
3632                                 thread = (MonoThread *)arg;
3633                 }
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, NULL);
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                 MonoError oerror;
4324
4325                 /* Might be AOTed code */
4326                 mono_class_init (method->klass);
4327                 code = mono_aot_get_method_checked (domain, method, &oerror);
4328                 g_assert (code);
4329                 mono_error_assert_ok (&oerror);
4330                 ji = mono_jit_info_table_find (domain, (char *)code);
4331                 g_assert (ji);
4332         }
4333         g_assert (code);
4334
4335         insert_breakpoint (seq_points, domain, ji, bp, error);
4336 }
4337
4338 static void
4339 clear_breakpoint (MonoBreakpoint *bp);
4340
4341 /*
4342  * set_breakpoint:
4343  *
4344  *   Set a breakpoint at IL_OFFSET in METHOD.
4345  * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4346  * METHOD can also be a generic method definition, in which case a breakpoint
4347  * is placed in all instances of the method.
4348  * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4349  * inserted.
4350  */
4351 static MonoBreakpoint*
4352 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4353 {
4354         MonoBreakpoint *bp;
4355         GHashTableIter iter, iter2;
4356         MonoDomain *domain;
4357         MonoMethod *m;
4358         MonoSeqPointInfo *seq_points;
4359         GPtrArray *methods;
4360         GPtrArray *method_domains;
4361         GPtrArray *method_seq_points;
4362         int i;
4363
4364         if (error)
4365                 mono_error_init (error);
4366
4367         // FIXME:
4368         // - suspend/resume the vm to prevent code patching problems
4369         // - multiple breakpoints on the same location
4370         // - dynamic methods
4371         // - races
4372
4373         bp = g_new0 (MonoBreakpoint, 1);
4374         bp->method = method;
4375         bp->il_offset = il_offset;
4376         bp->req = req;
4377         bp->children = g_ptr_array_new ();
4378
4379         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);
4380
4381         methods = g_ptr_array_new ();
4382         method_domains = g_ptr_array_new ();
4383         method_seq_points = g_ptr_array_new ();
4384
4385         mono_loader_lock ();
4386         g_hash_table_iter_init (&iter, domains);
4387         while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4388                 mono_domain_lock (domain);
4389                 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4390                 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4391                         if (bp_matches_method (bp, m)) {
4392                                 /* Save the info locally to simplify the code inside the domain lock */
4393                                 g_ptr_array_add (methods, m);
4394                                 g_ptr_array_add (method_domains, domain);
4395                                 g_ptr_array_add (method_seq_points, seq_points);
4396                         }
4397                 }
4398                 mono_domain_unlock (domain);
4399         }
4400
4401         for (i = 0; i < methods->len; ++i) {
4402                 m = (MonoMethod *)g_ptr_array_index (methods, i);
4403                 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4404                 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4405                 set_bp_in_method (domain, m, seq_points, bp, error);
4406         }
4407
4408         g_ptr_array_add (breakpoints, bp);
4409         mono_loader_unlock ();
4410
4411         g_ptr_array_free (methods, TRUE);
4412         g_ptr_array_free (method_domains, TRUE);
4413         g_ptr_array_free (method_seq_points, TRUE);
4414
4415         if (error && !mono_error_ok (error)) {
4416                 clear_breakpoint (bp);
4417                 return NULL;
4418         }
4419
4420         return bp;
4421 }
4422
4423 static void
4424 clear_breakpoint (MonoBreakpoint *bp)
4425 {
4426         int i;
4427
4428         // FIXME: locking, races
4429         for (i = 0; i < bp->children->len; ++i) {
4430                 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4431
4432                 remove_breakpoint (inst);
4433
4434                 g_free (inst);
4435         }
4436
4437         mono_loader_lock ();
4438         g_ptr_array_remove (breakpoints, bp);
4439         mono_loader_unlock ();
4440
4441         g_ptr_array_free (bp->children, TRUE);
4442         g_free (bp);
4443 }
4444
4445 static void
4446 breakpoints_cleanup (void)
4447 {
4448         int i;
4449
4450         mono_loader_lock ();
4451         i = 0;
4452         while (i < event_requests->len) {
4453                 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4454
4455                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4456                         clear_breakpoint ((MonoBreakpoint *)req->info);
4457                         g_ptr_array_remove_index_fast (event_requests, i);
4458                         g_free (req);
4459                 } else {
4460                         i ++;
4461                 }
4462         }
4463
4464         for (i = 0; i < breakpoints->len; ++i)
4465                 g_free (g_ptr_array_index (breakpoints, i));
4466
4467         g_ptr_array_free (breakpoints, TRUE);
4468         g_hash_table_destroy (bp_locs);
4469
4470         breakpoints = NULL;
4471         bp_locs = NULL;
4472
4473         mono_loader_unlock ();
4474 }
4475
4476 /*
4477  * clear_breakpoints_for_domain:
4478  *
4479  *   Clear breakpoint instances which reference DOMAIN.
4480  */
4481 static void
4482 clear_breakpoints_for_domain (MonoDomain *domain)
4483 {
4484         int i, j;
4485
4486         /* This could be called after shutdown */
4487         if (!breakpoints)
4488                 return;
4489
4490         mono_loader_lock ();
4491         for (i = 0; i < breakpoints->len; ++i) {
4492                 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4493
4494                 j = 0;
4495                 while (j < bp->children->len) {
4496                         BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4497
4498                         if (inst->domain == domain) {
4499                                 remove_breakpoint (inst);
4500
4501                                 g_free (inst);
4502
4503                                 g_ptr_array_remove_index_fast (bp->children, j);
4504                         } else {
4505                                 j ++;
4506                         }
4507                 }
4508         }
4509         mono_loader_unlock ();
4510 }
4511
4512 /*
4513  * ss_calculate_framecount:
4514  *
4515  * Ensure DebuggerTlsData fields are filled out.
4516  */
4517 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4518 {
4519         if (!tls->context.valid)
4520                 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4521         compute_frame_info (tls->thread, tls);
4522 }
4523
4524 /*
4525  * ss_update:
4526  *
4527  * Return FALSE if single stepping needs to continue.
4528  */
4529 static gboolean
4530 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4531 {
4532         MonoDebugMethodInfo *minfo;
4533         MonoDebugSourceLocation *loc = NULL;
4534         gboolean hit = TRUE;
4535         MonoMethod *method;
4536
4537         if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4538                 /*
4539                  * These seq points are inserted by the JIT after calls, step over needs to skip them.
4540                  */
4541                 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);
4542                 return FALSE;
4543         }
4544
4545         if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit) {
4546                 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4547
4548                 ss_calculate_framecount (tls, ctx);
4549
4550                 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4551                 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4552                 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4553                 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4554                         /* Hit the breakpoint in a recursive call, don't halt */
4555                         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");
4556                         return FALSE;
4557                 }
4558         }
4559
4560         if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4561                 method = jinfo_get_method (ji);
4562                 ss_calculate_framecount (tls, ctx);
4563                 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4564                         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);
4565                         return FALSE;
4566                 }
4567         }
4568
4569         if (req->size != STEP_SIZE_LINE)
4570                 return TRUE;
4571
4572         /* Have to check whenever a different source line was reached */
4573         method = jinfo_get_method (ji);
4574         minfo = mono_debug_lookup_method (method);
4575
4576         if (minfo)
4577                 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4578
4579         if (!loc) {
4580                 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);
4581                 ss_req->last_method = method;
4582                 hit = FALSE;
4583         } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4584                 ss_calculate_framecount (tls, ctx);
4585                 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4586                         DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4587                         hit = FALSE;
4588                 }
4589         }
4590                                 
4591         if (loc) {
4592                 ss_req->last_method = method;
4593                 ss_req->last_line = loc->row;
4594                 mono_debug_free_source_location (loc);
4595         }
4596
4597         return hit;
4598 }
4599
4600 static gboolean
4601 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4602 {
4603         return bp->method && bp->method->klass->image->assembly == assembly;
4604 }
4605
4606 static void
4607 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4608 {
4609         MonoJitInfo *ji;
4610         guint8 *ip;
4611         int i, j, suspend_policy;
4612         guint32 native_offset;
4613         MonoBreakpoint *bp;
4614         BreakpointInstance *inst;
4615         GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4616         GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4617         EventKind kind = EVENT_KIND_BREAKPOINT;
4618         MonoContext *ctx = &tls->restore_state.ctx;
4619         MonoMethod *method;
4620         MonoSeqPointInfo *info;
4621         SeqPoint sp;
4622         gboolean found_sp;
4623
4624         // FIXME: Speed this up
4625
4626         ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4627         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4628         g_assert (ji && !ji->is_trampoline);
4629         method = jinfo_get_method (ji);
4630
4631         /* Compute the native offset of the breakpoint from the ip */
4632         native_offset = ip - (guint8*)ji->code_start;   
4633
4634         /* 
4635          * Skip the instruction causing the breakpoint signal.
4636          */
4637         if (from_signal)
4638                 mono_arch_skip_breakpoint (ctx, ji);
4639
4640         if (method->wrapper_type || tls->disable_breakpoints)
4641                 return;
4642
4643         bp_reqs = g_ptr_array_new ();
4644         ss_reqs = g_ptr_array_new ();
4645         ss_reqs_orig = g_ptr_array_new ();
4646
4647         mono_loader_lock ();
4648
4649         /*
4650          * The ip points to the instruction causing the breakpoint event, which is after
4651          * the offset recorded in the seq point map, so find the prev seq point before ip.
4652          */
4653         found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4654
4655         if (!found_sp)
4656                 no_seq_points_found (method, native_offset);
4657
4658         g_assert (found_sp);
4659
4660         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);
4661
4662         bp = NULL;
4663         for (i = 0; i < breakpoints->len; ++i) {
4664                 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4665
4666                 if (!bp->method)
4667                         continue;
4668
4669                 for (j = 0; j < bp->children->len; ++j) {
4670                         inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4671                         if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4672                                 if (bp->req->event_kind == EVENT_KIND_STEP) {
4673                                         g_ptr_array_add (ss_reqs_orig, bp->req);
4674                                 } else {
4675                                         g_ptr_array_add (bp_reqs, bp->req);
4676                                 }
4677                         }
4678                 }
4679         }
4680         if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4681                 /* Maybe a method entry/exit event */
4682                 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4683                         kind = EVENT_KIND_METHOD_ENTRY;
4684                 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4685                         kind = EVENT_KIND_METHOD_EXIT;
4686         }
4687
4688         /* Process single step requests */
4689         for (i = 0; i < ss_reqs_orig->len; ++i) {
4690                 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4691                 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4692                 gboolean hit;
4693
4694                 if (mono_thread_internal_current () != ss_req->thread)
4695                         continue;
4696
4697                 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4698                 if (hit)
4699                         g_ptr_array_add (ss_reqs, req);
4700
4701                 /* Start single stepping again from the current sequence point */
4702                 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4703         }
4704         
4705         if (ss_reqs->len > 0)
4706                 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4707         if (bp_reqs->len > 0)
4708                 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4709         if (kind != EVENT_KIND_BREAKPOINT)
4710                 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4711
4712         mono_loader_unlock ();
4713
4714         g_ptr_array_free (bp_reqs, TRUE);
4715         g_ptr_array_free (ss_reqs, TRUE);
4716
4717         /* 
4718          * FIXME: The first event will suspend, so the second will only be sent after the
4719          * resume.
4720          */
4721         if (ss_events)
4722                 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4723         if (bp_events)
4724                 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4725         if (enter_leave_events)
4726                 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4727 }
4728
4729 /* Process a breakpoint/single step event after resuming from a signal handler */
4730 static void
4731 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4732 {
4733         DebuggerTlsData *tls;
4734         MonoThreadUnwindState orig_restore_state;
4735         MonoContext ctx;
4736
4737         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4738         /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4739         memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4740         mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4741
4742         func (tls, TRUE);
4743
4744         /* This is called when resuming from a signal handler, so it shouldn't return */
4745         memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4746         memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4747         mono_restore_context (&ctx);
4748         g_assert_not_reached ();
4749 }
4750
4751 static void
4752 process_breakpoint (void)
4753 {
4754         process_signal_event (process_breakpoint_inner);
4755 }
4756
4757 static void
4758 resume_from_signal_handler (void *sigctx, void *func)
4759 {
4760         DebuggerTlsData *tls;
4761         MonoContext ctx;
4762
4763         /* Save the original context in TLS */
4764         // FIXME: This might not work on an altstack ?
4765         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4766         if (!tls)
4767                 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4768         g_assert (tls);
4769
4770         // FIXME: MonoContext usually doesn't include the fp registers, so these are 
4771         // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4772         // clob:c could be added to op_seq_point.
4773
4774         mono_sigctx_to_monoctx (sigctx, &ctx);
4775         memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4776 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4777         mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4778 #else
4779         MONO_CONTEXT_SET_IP (&ctx, func);
4780 #endif
4781         mono_monoctx_to_sigctx (&ctx, sigctx);
4782
4783 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4784         mono_ppc_set_func_into_sigctx (sigctx, func);
4785 #endif
4786 }
4787
4788 void
4789 mono_debugger_agent_breakpoint_hit (void *sigctx)
4790 {
4791         /*
4792          * We are called from a signal handler, and running code there causes all kinds of
4793          * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4794          * So set up the signal context to return to the real breakpoint handler function.
4795          */
4796         resume_from_signal_handler (sigctx, process_breakpoint);
4797 }
4798
4799 static gboolean
4800 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4801 {
4802         if (frame->managed) {
4803                 *(MonoContext*)data = *ctx;
4804
4805                 return TRUE;
4806         } else {
4807                 return FALSE;
4808         }
4809 }
4810
4811 /*
4812  * Called by System.Diagnostics.Debugger:Break ().
4813  */
4814 void
4815 mono_debugger_agent_user_break (void)
4816 {
4817         if (agent_config.enabled) {
4818                 MonoContext ctx;
4819                 int suspend_policy;
4820                 GSList *events;
4821
4822                 /* Obtain a context */
4823                 MONO_CONTEXT_SET_IP (&ctx, NULL);
4824                 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
4825                 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4826
4827                 mono_loader_lock ();
4828                 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4829                 mono_loader_unlock ();
4830
4831                 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4832         } else if (debug_options.native_debugger_break) {
4833                 G_BREAKPOINT ();
4834         }
4835 }
4836
4837 static const char*
4838 ss_depth_to_string (StepDepth depth)
4839 {
4840         switch (depth) {
4841         case STEP_DEPTH_OVER:
4842                 return "over";
4843         case STEP_DEPTH_OUT:
4844                 return "out";
4845         case STEP_DEPTH_INTO:
4846                 return "into";
4847         default:
4848                 g_assert_not_reached ();
4849                 return NULL;
4850         }
4851 }
4852
4853 static void
4854 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4855 {
4856         MonoJitInfo *ji;
4857         guint8 *ip;
4858         GPtrArray *reqs;
4859         int il_offset, suspend_policy;
4860         MonoDomain *domain;
4861         GSList *events;
4862         MonoContext *ctx = &tls->restore_state.ctx;
4863         MonoMethod *method;
4864         SeqPoint sp;
4865         MonoSeqPointInfo *info;
4866
4867         ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4868
4869         /* Skip the instruction causing the single step */
4870         if (from_signal)
4871                 mono_arch_skip_single_step (ctx);
4872
4873         if (suspend_count > 0) {
4874                 /* Fastpath during invokes, see in process_suspend () */
4875                 if (suspend_count - tls->resume_count == 0)
4876                         return;
4877                 process_suspend (tls, ctx);
4878                 return;
4879         }
4880
4881         if (!ss_req)
4882                 // FIXME: A suspend race
4883                 return;
4884
4885         if (mono_thread_internal_current () != ss_req->thread)
4886                 return;
4887
4888         if (log_level > 0) {
4889                 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4890
4891                 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);
4892         }
4893
4894         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4895         g_assert (ji && !ji->is_trampoline);
4896         method = jinfo_get_method (ji);
4897         g_assert (method);
4898
4899         if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4900                 return;
4901
4902         /* 
4903          * FIXME:
4904          * Stopping in memset makes half-initialized vtypes visible.
4905          * Stopping in memcpy makes half-copied vtypes visible.
4906          */
4907         if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4908                 return;
4909
4910         /*
4911          * The ip points to the instruction causing the single step event, which is before
4912          * the offset recorded in the seq point map, so find the next seq point after ip.
4913          */
4914         if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4915                 return;
4916
4917         il_offset = sp.il_offset;
4918
4919         if (!ss_update (ss_req, ji, &sp, tls, ctx))
4920                 return;
4921
4922         /* Start single stepping again from the current sequence point */
4923         ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4924
4925         if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4926                 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4927                 !strcmp (method->name, ".cctor"))
4928                 return;
4929
4930         // FIXME: Has to lock earlier
4931
4932         reqs = g_ptr_array_new ();
4933
4934         mono_loader_lock ();
4935
4936         g_ptr_array_add (reqs, ss_req->req);
4937
4938         events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4939
4940         g_ptr_array_free (reqs, TRUE);
4941
4942         mono_loader_unlock ();
4943
4944         process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4945 }
4946
4947 static void
4948 process_single_step (void)
4949 {
4950         process_signal_event (process_single_step_inner);
4951 }
4952
4953 /*
4954  * mono_debugger_agent_single_step_event:
4955  *
4956  *   Called from a signal handler to handle a single step event.
4957  */
4958 void
4959 mono_debugger_agent_single_step_event (void *sigctx)
4960 {
4961         /* Resume to process_single_step through the signal context */
4962
4963         // FIXME: Since step out/over is implemented using step in, the step in case should
4964         // be as fast as possible. Move the relevant code from process_single_step_inner ()
4965         // here
4966
4967         if (is_debugger_thread ()) {
4968                 /* 
4969                  * This could happen despite our best effors when the runtime calls 
4970                  * assembly/type resolve hooks.
4971                  * FIXME: Breakpoints too.
4972                  */
4973                 MonoContext ctx;
4974
4975                 mono_sigctx_to_monoctx (sigctx, &ctx);
4976                 mono_arch_skip_single_step (&ctx);
4977                 mono_monoctx_to_sigctx (&ctx, sigctx);
4978                 return;
4979         }
4980
4981         resume_from_signal_handler (sigctx, process_single_step);
4982 }
4983
4984 void
4985 debugger_agent_single_step_from_context (MonoContext *ctx)
4986 {
4987         DebuggerTlsData *tls;
4988         MonoThreadUnwindState orig_restore_state;
4989
4990         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4991         /* Fastpath during invokes, see in process_suspend () */
4992         if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4993                 return;
4994
4995         if (is_debugger_thread ())
4996                 return;
4997
4998         g_assert (tls);
4999
5000         /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5001         memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5002         mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5003         memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5004
5005         process_single_step_inner (tls, FALSE);
5006
5007         memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5008         memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5009 }
5010
5011 void
5012 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5013 {
5014         DebuggerTlsData *tls;
5015         MonoThreadUnwindState orig_restore_state;
5016         guint8 *orig_ip;
5017
5018         if (is_debugger_thread ())
5019                 return;
5020
5021         orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5022         MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5023
5024         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5025         g_assert (tls);
5026         memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5027         mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5028         memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5029
5030         process_breakpoint_inner (tls, FALSE);
5031
5032         memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5033         memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5034         if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5035                 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5036 }
5037
5038 /*
5039  * start_single_stepping:
5040  *
5041  *   Turn on single stepping. Can be called multiple times, for example,
5042  * by a single step event request + a suspend.
5043  */
5044 static void
5045 start_single_stepping (void)
5046 {
5047 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5048         int val = InterlockedIncrement (&ss_count);
5049
5050         if (val == 1)
5051                 mono_arch_start_single_stepping ();
5052 #else
5053         g_assert_not_reached ();
5054 #endif
5055 }
5056
5057 static void
5058 stop_single_stepping (void)
5059 {
5060 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5061         int val = InterlockedDecrement (&ss_count);
5062
5063         if (val == 0)
5064                 mono_arch_stop_single_stepping ();
5065 #else
5066         g_assert_not_reached ();
5067 #endif
5068 }
5069
5070 /*
5071  * ss_stop:
5072  *
5073  *   Stop the single stepping operation given by SS_REQ.
5074  */
5075 static void
5076 ss_stop (SingleStepReq *ss_req)
5077 {
5078         if (ss_req->bps) {
5079                 GSList *l;
5080
5081                 for (l = ss_req->bps; l; l = l->next) {
5082                         clear_breakpoint ((MonoBreakpoint *)l->data);
5083                 }
5084                 g_slist_free (ss_req->bps);
5085                 ss_req->bps = NULL;
5086         }
5087
5088         if (ss_req->global) {
5089                 stop_single_stepping ();
5090                 ss_req->global = FALSE;
5091         }
5092 }
5093
5094 /*
5095  * ss_bp_is_unique:
5096  *
5097  * Reject breakpoint if it is a duplicate of one already in list or hash table.
5098  */
5099 static gboolean
5100 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5101 {
5102         if (ss_req_bp_cache) {
5103                 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5104                 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5105         }
5106         for (GSList *l = bps; l; l = l->next) {
5107                 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5108                 if (bp->method == method && bp->il_offset == il_offset)
5109                         return FALSE;
5110         }
5111         return TRUE;
5112 }
5113
5114 /*
5115  * ss_bp_eq:
5116  *
5117  * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5118  */
5119 static gint
5120 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5121 {
5122         const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5123         const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5124         return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5125 }
5126
5127 /*
5128  * ss_bp_eq:
5129  *
5130  * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5131  */
5132 static guint
5133 ss_bp_hash (gconstpointer data)
5134 {
5135         const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5136         guint hash = (guint) (uintptr_t) s->method;
5137         hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5138         hash ^= ((guint)s->il_offset) >> 16;
5139         return hash;
5140 }
5141
5142 #define MAX_LINEAR_SCAN_BPS 7
5143
5144 /*
5145  * ss_bp_add_one:
5146  *
5147  * Create a new breakpoint and add it to a step request.
5148  * Will adjust the bp count and cache used by ss_start.
5149  */
5150 static void
5151 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5152                   MonoMethod *method, guint32 il_offset)
5153 {
5154         // This list is getting too long, switch to using the hash table
5155         if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5156                 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5157                 for (GSList *l = ss_req->bps; l; l = l->next)
5158                         g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5159         }
5160
5161         if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5162                 // Create and add breakpoint
5163                 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5164                 ss_req->bps = g_slist_append (ss_req->bps, bp);
5165                 if (*ss_req_bp_cache)
5166                         g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5167                 (*ss_req_bp_count)++;
5168         } else {
5169                 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);
5170         }
5171 }
5172
5173 /*
5174  * ss_start:
5175  *
5176  *   Start the single stepping operation given by SS_REQ from the sequence point SP.
5177  * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5178  * belong to the same thread as CTX.
5179  * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5180  */
5181 static void
5182 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5183                   gboolean step_to_catch, StackFrame **frames, int nframes)
5184 {
5185         int i, j, frame_index;
5186         SeqPoint *next_sp, *parent_sp = NULL;
5187         SeqPoint local_sp, local_parent_sp;
5188         gboolean found_sp;
5189         MonoSeqPointInfo *parent_info;
5190         MonoMethod *parent_sp_method = NULL;
5191         gboolean enable_global = FALSE;
5192
5193         // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5194         // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5195         int ss_req_bp_count = g_slist_length (ss_req->bps);
5196         GHashTable *ss_req_bp_cache = NULL;
5197
5198         /* Stop the previous operation */
5199         ss_stop (ss_req);
5200
5201         /*
5202          * Implement single stepping using breakpoints if possible.
5203          */
5204         if (step_to_catch) {
5205                 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5206         } else {
5207                 frame_index = 1;
5208
5209                 if (ctx && !frames) {
5210                         /* Need parent frames */
5211                         if (!tls->context.valid)
5212                                 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5213                         compute_frame_info (tls->thread, tls);
5214                         frames = tls->frames;
5215                         nframes = tls->frame_count;
5216                 }
5217
5218                 /*
5219                  * Find the first sequence point in the current or in a previous frame which
5220                  * is not the last in its method.
5221                  */
5222                 if (ss_req->depth == STEP_DEPTH_OUT) {
5223                         /* Ignore seq points in current method */
5224                         while (frame_index < nframes) {
5225                                 StackFrame *frame = frames [frame_index];
5226
5227                                 method = frame->method;
5228                                 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5229                                 sp = (found_sp)? &local_sp : NULL;
5230                                 frame_index ++;
5231                                 if (sp && sp->next_len != 0)
5232                                         break;
5233                         }
5234                         // There could be method calls before the next seq point in the caller when using nested calls
5235                         //enable_global = TRUE;
5236                 } else {
5237                         if (sp && sp->next_len == 0) {
5238                                 sp = NULL;
5239                                 while (frame_index < nframes) {
5240                                         StackFrame *frame = frames [frame_index];
5241
5242                                         method = frame->method;
5243                                         found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5244                                         sp = (found_sp)? &local_sp : NULL;
5245                                         if (sp && sp->next_len != 0)
5246                                                 break;
5247                                         sp = NULL;
5248                                         frame_index ++;
5249                                 }
5250                         } else {
5251                                 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5252                                 while (frame_index < nframes) {
5253                                         StackFrame *frame = frames [frame_index];
5254
5255                                         parent_sp_method = frame->method;
5256                                         found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5257                                         parent_sp = found_sp ? &local_parent_sp : NULL;
5258                                         if (found_sp && parent_sp->next_len != 0)
5259                                                 break;
5260                                         parent_sp = NULL;
5261                                         frame_index ++;
5262                                 }
5263                         }
5264                 }
5265
5266                 if (sp && sp->next_len > 0) {
5267                         SeqPoint* next = g_new(SeqPoint, sp->next_len);
5268
5269                         mono_seq_point_init_next (info, *sp, next);
5270                         for (i = 0; i < sp->next_len; i++) {
5271                                 next_sp = &next[i];
5272
5273                                 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5274                         }
5275                         g_free (next);
5276                 }
5277
5278                 if (parent_sp) {
5279                         SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5280
5281                         mono_seq_point_init_next (parent_info, *parent_sp, next);
5282                         for (i = 0; i < parent_sp->next_len; i++) {
5283                                 next_sp = &next[i];
5284
5285                                 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5286                         }
5287                         g_free (next);
5288                 }
5289
5290                 if (ss_req->nframes == 0)
5291                         ss_req->nframes = nframes;
5292
5293                 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5294                         DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5295                         /*
5296                          * This is needed since if we leave managed code, and later return to it, step over
5297                          * is not going to stop.
5298                          * This approach is a bit ugly, since we change the step depth, but it only affects
5299                          * clients who reuse the same step request, and only in this special case.
5300                          */
5301                         ss_req->depth = STEP_DEPTH_INTO;
5302                 }
5303
5304                 if (ss_req->depth == STEP_DEPTH_OVER) {
5305                         /* Need to stop in catch clauses as well */
5306                         for (i = 0; i < nframes; ++i) {
5307                                 StackFrame *frame = frames [i];
5308
5309                                 if (frame->ji) {
5310                                         MonoJitInfo *jinfo = frame->ji;
5311                                         for (j = 0; j < jinfo->num_clauses; ++j) {
5312                                                 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5313
5314                                                 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);
5315                                                 sp = (found_sp)? &local_sp : NULL;
5316
5317                                                 if (found_sp)
5318                                                         ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, sp->il_offset);
5319                                         }
5320                                 }
5321                         }
5322                 }
5323
5324                 if (ss_req->depth == STEP_DEPTH_INTO) {
5325                         /* Enable global stepping so we stop at method entry too */
5326                         enable_global = TRUE;
5327                 }
5328
5329                 /*
5330                  * The ctx/frame info computed above will become invalid when we continue.
5331                  */
5332                 tls->context.valid = FALSE;
5333                 tls->async_state.valid = FALSE;
5334                 invalidate_frames (tls);
5335         }
5336
5337         if (enable_global) {
5338                 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5339                 ss_req->global = TRUE;
5340                 start_single_stepping ();
5341         } else if (!ss_req->bps) {
5342                 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5343                 ss_req->global = TRUE;
5344                 start_single_stepping ();
5345         } else {
5346                 ss_req->global = FALSE;
5347         }
5348
5349         if (ss_req_bp_cache)
5350                 g_hash_table_destroy (ss_req_bp_cache);
5351 }
5352
5353 /*
5354  * Start single stepping of thread THREAD
5355  */
5356 static ErrorCode
5357 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5358 {
5359         DebuggerTlsData *tls;
5360         MonoSeqPointInfo *info = NULL;
5361         SeqPoint *sp = NULL;
5362         SeqPoint local_sp;
5363         gboolean found_sp;
5364         MonoMethod *method = NULL;
5365         MonoDebugMethodInfo *minfo;
5366         gboolean step_to_catch = FALSE;
5367         gboolean set_ip = FALSE;
5368         StackFrame **frames = NULL;
5369         int nframes = 0;
5370
5371         if (suspend_count == 0)
5372                 return ERR_NOT_SUSPENDED;
5373
5374         wait_for_suspend ();
5375
5376         // FIXME: Multiple requests
5377         if (ss_req) {
5378                 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5379                 return ERR_NOT_IMPLEMENTED;
5380         }
5381
5382         DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5383
5384         ss_req = g_new0 (SingleStepReq, 1);
5385         ss_req->req = req;
5386         ss_req->thread = thread;
5387         ss_req->size = size;
5388         ss_req->depth = depth;
5389         ss_req->filter = filter;
5390         req->info = ss_req;
5391
5392         mono_loader_lock ();
5393         tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5394         mono_loader_unlock ();
5395         g_assert (tls);
5396         g_assert (tls->context.valid);
5397
5398         if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5399                 /*
5400                  * Need to start single stepping from restore_state and not from the current state
5401                  */
5402                 set_ip = TRUE;
5403                 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5404         }
5405
5406         ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5407
5408         if (tls->catch_state.valid) {
5409                 gboolean res;
5410                 StackFrameInfo frame;
5411                 MonoContext new_ctx;
5412                 MonoLMF *lmf = NULL;
5413
5414                 /*
5415                  * We are stopped at a throw site. Stepping should go to the catch site.
5416                  */
5417
5418                 /* Find the the jit info for the catch context */
5419                 res = mono_find_jit_info_ext (
5420                         (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5421                         (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5422                         NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5423                 g_assert (res);
5424                 g_assert (frame.type == FRAME_TYPE_MANAGED);
5425
5426                 /*
5427                  * Find the seq point corresponding to the landing site ip, which is the first seq
5428                  * point after ip.
5429                  */
5430                 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5431                 sp = (found_sp)? &local_sp : NULL;
5432                 if (!sp)
5433                         no_seq_points_found (frame.method, frame.native_offset);
5434                 g_assert (sp);
5435
5436                 method = frame.method;
5437
5438                 step_to_catch = TRUE;
5439                 /* This make sure the seq point is not skipped by process_single_step () */
5440                 ss_req->last_sp = NULL;
5441         }
5442
5443         if (!step_to_catch) {
5444                 StackFrame *frame = NULL;
5445
5446                 if (set_ip) {
5447                         if (frames && nframes)
5448                                 frame = frames [0];
5449                 } else {
5450                         compute_frame_info (thread, tls);
5451
5452                         if (tls->frame_count)
5453                                 frame = tls->frames [0];
5454                 }
5455
5456                 if (ss_req->size == STEP_SIZE_LINE) {
5457                         if (frame) {
5458                                 ss_req->last_method = frame->method;
5459                                 ss_req->last_line = -1;
5460
5461                                 minfo = mono_debug_lookup_method (frame->method);
5462                                 if (minfo && frame->il_offset != -1) {
5463                                         MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5464
5465                                         if (loc) {
5466                                                 ss_req->last_line = loc->row;
5467                                                 g_free (loc);
5468                                         }
5469                                 }
5470                         }
5471                 }
5472
5473                 if (frame) {
5474                         if (!method && frame->il_offset != -1) {
5475                                 /* FIXME: Sort the table and use a binary search */
5476                                 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5477                                 sp = (found_sp)? &local_sp : NULL;
5478                                 if (!sp)
5479                                         no_seq_points_found (frame->method, frame->native_offset);
5480                                 g_assert (sp);
5481                                 method = frame->method;
5482                         }
5483                 }
5484         }
5485
5486         ss_req->start_method = method;
5487
5488         ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5489
5490         if (frames)
5491                 free_frames (frames, nframes);
5492
5493         return ERR_NONE;
5494 }
5495
5496 static void
5497 ss_destroy (SingleStepReq *req)
5498 {
5499         // FIXME: Locking
5500         g_assert (ss_req == req);
5501
5502         ss_stop (ss_req);
5503
5504         g_free (ss_req);
5505         ss_req = NULL;
5506 }
5507
5508 static void
5509 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5510 {
5511         GSList *l;
5512         gboolean found = TRUE;
5513
5514         while (found) {
5515                 found = FALSE;
5516                 for (l = ss_req->bps; l; l = l->next) {
5517                         if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5518                                 clear_breakpoint ((MonoBreakpoint *)l->data);
5519                                 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5520                                 found = TRUE;
5521                                 break;
5522                         }
5523                 }
5524         }
5525 }
5526
5527 /*
5528  * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5529  */
5530 void
5531 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5532 {
5533         MonoError error;
5534         int suspend_policy;
5535         GSList *events;
5536         EventInfo ei;
5537
5538         if (!agent_config.enabled)
5539                 return;
5540
5541         mono_loader_lock ();
5542         events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5543         mono_loader_unlock ();
5544
5545         ei.level = level;
5546         ei.category = NULL;
5547         if (category) {
5548                 ei.category = mono_string_to_utf8_checked (category, &error);
5549                 mono_error_cleanup (&error);
5550         }
5551         ei.message = NULL;
5552         if (message) {
5553                 ei.message = mono_string_to_utf8_checked (message, &error);
5554                 mono_error_cleanup  (&error);
5555         }
5556
5557         process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5558
5559         g_free (ei.category);
5560         g_free (ei.message);
5561 }
5562
5563 gboolean
5564 mono_debugger_agent_debug_log_is_enabled (void)
5565 {
5566         /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5567         return agent_config.enabled;
5568 }
5569
5570 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5571 void
5572 mono_debugger_agent_unhandled_exception (MonoException *exc)
5573 {
5574         int suspend_policy;
5575         GSList *events;
5576         EventInfo ei;
5577
5578         if (!inited)
5579                 return;
5580
5581         memset (&ei, 0, sizeof (EventInfo));
5582         ei.exc = (MonoObject*)exc;
5583
5584         mono_loader_lock ();
5585         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5586         mono_loader_unlock ();
5587
5588         process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5589 }
5590 #endif
5591
5592 void
5593 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx, 
5594                                       MonoContext *catch_ctx)
5595 {
5596         int i, j, suspend_policy;
5597         GSList *events;
5598         MonoJitInfo *ji, *catch_ji;
5599         EventInfo ei;
5600         DebuggerTlsData *tls = NULL;
5601
5602         if (thread_to_tls != NULL) {
5603                 MonoInternalThread *thread = mono_thread_internal_current ();
5604
5605                 mono_loader_lock ();
5606                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5607                 mono_loader_unlock ();
5608
5609                 if (tls && tls->abort_requested)
5610                         return;
5611                 if (tls && tls->disable_breakpoints)
5612                         return;
5613         }
5614
5615         memset (&ei, 0, sizeof (EventInfo));
5616
5617         /* Just-In-Time debugging */
5618         if (!catch_ctx) {
5619                 if (agent_config.onuncaught && !inited) {
5620                         finish_agent_init (FALSE);
5621
5622                         /*
5623                          * Send an unsolicited EXCEPTION event with a dummy request id.
5624                          */
5625                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5626                         ei.exc = (MonoObject*)exc;
5627                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5628                         return;
5629                 }
5630         } else if (agent_config.onthrow && !inited) {
5631                 GSList *l;
5632                 gboolean found = FALSE;
5633
5634                 for (l = agent_config.onthrow; l; l = l->next) {
5635                         char *ex_type = (char *)l->data;
5636                         char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5637
5638                         if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5639                                 found = TRUE;
5640
5641                         g_free (f);
5642                 }
5643
5644                 if (found) {
5645                         finish_agent_init (FALSE);
5646
5647                         /*
5648                          * Send an unsolicited EXCEPTION event with a dummy request id.
5649                          */
5650                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5651                         ei.exc = (MonoObject*)exc;
5652                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5653                         return;
5654                 }
5655         }
5656
5657         if (!inited)
5658                 return;
5659
5660         ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5661         if (catch_ctx)
5662                 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5663         else
5664                 catch_ji = NULL;
5665
5666         ei.exc = (MonoObject*)exc;
5667         ei.caught = catch_ctx != NULL;
5668
5669         mono_loader_lock ();
5670
5671         /* Treat exceptions which are caught in non-user code as unhandled */
5672         for (i = 0; i < event_requests->len; ++i) {
5673                 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5674                 if (req->event_kind != EVENT_KIND_EXCEPTION)
5675                         continue;
5676
5677                 for (j = 0; j < req->nmodifiers; ++j) {
5678                         Modifier *mod = &req->modifiers [j];
5679
5680                         if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5681                                 int k;
5682                                 gboolean found = FALSE;
5683                                 MonoAssembly **assemblies = mod->data.assemblies;
5684
5685                                 if (assemblies) {
5686                                         for (k = 0; assemblies [k]; ++k)
5687                                                 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5688                                                         found = TRUE;
5689                                 }
5690                                 if (!found)
5691                                         ei.caught = FALSE;
5692                         }
5693                 }
5694         }
5695
5696         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5697         mono_loader_unlock ();
5698
5699         if (tls && ei.caught && catch_ctx) {
5700                 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5701                 tls->catch_state.ctx = *catch_ctx;
5702                 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5703                 tls->catch_state.valid = TRUE;
5704         }
5705
5706         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5707
5708         if (tls)
5709                 tls->catch_state.valid = FALSE;
5710 }
5711
5712 void
5713 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5714 {
5715         DebuggerTlsData *tls;
5716
5717         if (!inited)
5718                 return;
5719
5720         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5721         if (!tls)
5722                 return;
5723
5724         /*
5725          * We're about to invoke an exception filter during the first pass of exception handling.
5726          *
5727          * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5728          * 'orig_ctx' is the context where the exception has been thrown.
5729          *
5730          *
5731          * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5732          *
5733          * If we're stopped in Filter(), normal stack unwinding would first unwind to
5734          * the call site (line 37) and then continue to Main(), but it would never
5735          * include the throw site (line 32).
5736          *
5737          * Since exception filters are invoked during the first pass of exception handling,
5738          * the stack frames of the throw site are still intact, so we should include them
5739          * in a stack trace.
5740          *
5741          * We do this here by saving the context of the throw site in 'tls->filter_state'.
5742          *
5743          * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5744          * but report the location of the 'throw' to the user.
5745          *
5746          */
5747
5748         g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5749 }
5750
5751 void
5752 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5753 {
5754         DebuggerTlsData *tls;
5755
5756         if (!inited)
5757                 return;
5758
5759         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5760         if (!tls)
5761                 return;
5762
5763         tls->filter_state.valid = FALSE;
5764 }
5765
5766 /*
5767  * buffer_add_value_full:
5768  *
5769  *   Add the encoding of the value at ADDR described by T to the buffer.
5770  * AS_VTYPE determines whenever to treat primitive types as primitive types or
5771  * vtypes.
5772  */
5773 static void
5774 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5775                                            gboolean as_vtype, GHashTable *parent_vtypes)
5776 {
5777         MonoObject *obj;
5778         gboolean boxed_vtype = FALSE;
5779
5780         if (t->byref) {
5781                 if (!(*(void**)addr)) {
5782                         /* This can happen with compiler generated locals */
5783                         //printf ("%s\n", mono_type_full_name (t));
5784                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5785                         return;
5786                 }
5787                 g_assert (*(void**)addr);
5788                 addr = *(void**)addr;
5789         }
5790
5791         if (as_vtype) {
5792                 switch (t->type) {
5793                 case MONO_TYPE_BOOLEAN:
5794                 case MONO_TYPE_I1:
5795                 case MONO_TYPE_U1:
5796                 case MONO_TYPE_CHAR:
5797                 case MONO_TYPE_I2:
5798                 case MONO_TYPE_U2:
5799                 case MONO_TYPE_I4:
5800                 case MONO_TYPE_U4:
5801                 case MONO_TYPE_R4:
5802                 case MONO_TYPE_I8:
5803                 case MONO_TYPE_U8:
5804                 case MONO_TYPE_R8:
5805                 case MONO_TYPE_I:
5806                 case MONO_TYPE_U:
5807                 case MONO_TYPE_PTR:
5808                         goto handle_vtype;
5809                         break;
5810                 default:
5811                         break;
5812                 }
5813         }
5814
5815         switch (t->type) {
5816         case MONO_TYPE_VOID:
5817                 buffer_add_byte (buf, t->type);
5818                 break;
5819         case MONO_TYPE_BOOLEAN:
5820         case MONO_TYPE_I1:
5821         case MONO_TYPE_U1:
5822                 buffer_add_byte (buf, t->type);
5823                 buffer_add_int (buf, *(gint8*)addr);
5824                 break;
5825         case MONO_TYPE_CHAR:
5826         case MONO_TYPE_I2:
5827         case MONO_TYPE_U2:
5828                 buffer_add_byte (buf, t->type);
5829                 buffer_add_int (buf, *(gint16*)addr);
5830                 break;
5831         case MONO_TYPE_I4:
5832         case MONO_TYPE_U4:
5833         case MONO_TYPE_R4:
5834                 buffer_add_byte (buf, t->type);
5835                 buffer_add_int (buf, *(gint32*)addr);
5836                 break;
5837         case MONO_TYPE_I8:
5838         case MONO_TYPE_U8:
5839         case MONO_TYPE_R8:
5840                 buffer_add_byte (buf, t->type);
5841                 buffer_add_long (buf, *(gint64*)addr);
5842                 break;
5843         case MONO_TYPE_I:
5844         case MONO_TYPE_U:
5845                 /* Treat it as a vtype */
5846                 goto handle_vtype;
5847         case MONO_TYPE_PTR: {
5848                 gssize val = *(gssize*)addr;
5849                 
5850                 buffer_add_byte (buf, t->type);
5851                 buffer_add_long (buf, val);
5852                 break;
5853         }
5854         handle_ref:
5855         case MONO_TYPE_STRING:
5856         case MONO_TYPE_SZARRAY:
5857         case MONO_TYPE_OBJECT:
5858         case MONO_TYPE_CLASS:
5859         case MONO_TYPE_ARRAY:
5860                 obj = *(MonoObject**)addr;
5861
5862                 if (!obj) {
5863                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5864                 } else {
5865                         if (obj->vtable->klass->valuetype) {
5866                                 t = &obj->vtable->klass->byval_arg;
5867                                 addr = mono_object_unbox (obj);
5868                                 boxed_vtype = TRUE;
5869                                 goto handle_vtype;
5870                         } else if (obj->vtable->klass->rank) {
5871                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5872                         } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5873                                 buffer_add_byte (buf, MONO_TYPE_CLASS);
5874                         } else {
5875                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5876                         }
5877                         buffer_add_objid (buf, obj);
5878                 }
5879                 break;
5880         handle_vtype:
5881         case MONO_TYPE_VALUETYPE:
5882         case MONO_TYPE_TYPEDBYREF: {
5883                 int nfields;
5884                 gpointer iter;
5885                 MonoClassField *f;
5886                 MonoClass *klass = mono_class_from_mono_type (t);
5887                 int vtype_index;
5888
5889                 if (boxed_vtype) {
5890                         /*
5891                          * Handle boxed vtypes recursively referencing themselves using fields.
5892                          */
5893                         if (!parent_vtypes)
5894                                 parent_vtypes = g_hash_table_new (NULL, NULL);
5895                         vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5896                         if (vtype_index) {
5897                                 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5898                                         buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5899                                         buffer_add_int (buf, vtype_index - 1);
5900                                 } else {
5901                                         /* The client can't handle PARENT_VTYPE */
5902                                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5903                                 }
5904                                 break;
5905                         } else {
5906                                 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5907                         }
5908                 }
5909
5910                 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5911                 buffer_add_byte (buf, klass->enumtype);
5912                 buffer_add_typeid (buf, domain, klass);
5913
5914                 nfields = 0;
5915                 iter = NULL;
5916                 while ((f = mono_class_get_fields (klass, &iter))) {
5917                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5918                                 continue;
5919                         if (mono_field_is_deleted (f))
5920                                 continue;
5921                         nfields ++;
5922                 }
5923                 buffer_add_int (buf, nfields);
5924
5925                 iter = NULL;
5926                 while ((f = mono_class_get_fields (klass, &iter))) {
5927                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5928                                 continue;
5929                         if (mono_field_is_deleted (f))
5930                                 continue;
5931                         buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5932                 }
5933
5934                 if (boxed_vtype) {
5935                         g_hash_table_remove (parent_vtypes, addr);
5936                         if (g_hash_table_size (parent_vtypes) == 0) {
5937                                 g_hash_table_destroy (parent_vtypes);
5938                                 parent_vtypes = NULL;
5939                         }
5940                 }
5941                 break;
5942         }
5943         case MONO_TYPE_GENERICINST:
5944                 if (mono_type_generic_inst_is_valuetype (t)) {
5945                         goto handle_vtype;
5946                 } else {
5947                         goto handle_ref;
5948                 }
5949                 break;
5950         default:
5951                 NOT_IMPLEMENTED;
5952         }
5953 }
5954
5955 static void
5956 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5957 {
5958         buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5959 }
5960
5961 static gboolean
5962 obj_is_of_type (MonoObject *obj, MonoType *t)
5963 {
5964         MonoClass *klass = obj->vtable->klass;
5965         if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5966                 if (mono_class_is_transparent_proxy (klass)) {
5967                         klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5968                         if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5969                                 return TRUE;
5970                         }
5971                 }
5972                 return FALSE;
5973         }
5974         return TRUE;
5975 }
5976
5977 static ErrorCode
5978 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5979
5980 static ErrorCode
5981 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5982 {
5983         gboolean is_enum;
5984         MonoClass *klass;
5985         MonoClassField *f;
5986         int nfields;
5987         gpointer iter = NULL;
5988         MonoDomain *d;
5989         ErrorCode err;
5990
5991         is_enum = decode_byte (buf, &buf, limit);
5992         /* Enums are sent as a normal vtype */
5993         if (is_enum)
5994                 return ERR_NOT_IMPLEMENTED;
5995         klass = decode_typeid (buf, &buf, limit, &d, &err);
5996         if (err != ERR_NONE)
5997                 return err;
5998
5999         if (t && klass != mono_class_from_mono_type (t)) {
6000                 char *name = mono_type_full_name (t);
6001                 char *name2 = mono_type_full_name (&klass->byval_arg);
6002                 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6003                 g_free (name);
6004                 g_free (name2);
6005                 return ERR_INVALID_ARGUMENT;
6006         }
6007
6008         nfields = decode_int (buf, &buf, limit);
6009         while ((f = mono_class_get_fields (klass, &iter))) {
6010                 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6011                         continue;
6012                 if (mono_field_is_deleted (f))
6013                         continue;
6014                 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6015                 if (err != ERR_NONE)
6016                         return err;
6017                 nfields --;
6018         }
6019         g_assert (nfields == 0);
6020
6021         *endbuf = buf;
6022
6023         return ERR_NONE;
6024 }
6025
6026 static ErrorCode
6027 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6028 {
6029         ErrorCode err;
6030
6031         if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6032                 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6033                 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6034                 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6035                 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6036                 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6037                 char *name = mono_type_full_name (t);
6038                 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6039                 g_free (name);
6040                 return ERR_INVALID_ARGUMENT;
6041         }
6042
6043         switch (t->type) {
6044         case MONO_TYPE_BOOLEAN:
6045                 *(guint8*)addr = decode_int (buf, &buf, limit);
6046                 break;
6047         case MONO_TYPE_CHAR:
6048                 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6049                 break;
6050         case MONO_TYPE_I1:
6051                 *(gint8*)addr = decode_int (buf, &buf, limit);
6052                 break;
6053         case MONO_TYPE_U1:
6054                 *(guint8*)addr = decode_int (buf, &buf, limit);
6055                 break;
6056         case MONO_TYPE_I2:
6057                 *(gint16*)addr = decode_int (buf, &buf, limit);
6058                 break;
6059         case MONO_TYPE_U2:
6060                 *(guint16*)addr = decode_int (buf, &buf, limit);
6061                 break;
6062         case MONO_TYPE_I4:
6063                 *(gint32*)addr = decode_int (buf, &buf, limit);
6064                 break;
6065         case MONO_TYPE_U4:
6066                 *(guint32*)addr = decode_int (buf, &buf, limit);
6067                 break;
6068         case MONO_TYPE_I8:
6069                 *(gint64*)addr = decode_long (buf, &buf, limit);
6070                 break;
6071         case MONO_TYPE_U8:
6072                 *(guint64*)addr = decode_long (buf, &buf, limit);
6073                 break;
6074         case MONO_TYPE_R4:
6075                 *(guint32*)addr = decode_int (buf, &buf, limit);
6076                 break;
6077         case MONO_TYPE_R8:
6078                 *(guint64*)addr = decode_long (buf, &buf, limit);
6079                 break;
6080         case MONO_TYPE_PTR:
6081                 /* We send these as I8, so we get them back as such */
6082                 g_assert (type == MONO_TYPE_I8);
6083                 *(gssize*)addr = decode_long (buf, &buf, limit);
6084                 break;
6085         case MONO_TYPE_GENERICINST:
6086                 if (MONO_TYPE_ISSTRUCT (t)) {
6087                         /* The client sends these as a valuetype */
6088                         goto handle_vtype;
6089                 } else {
6090                         goto handle_ref;
6091                 }
6092                 break;
6093         case MONO_TYPE_I:
6094         case MONO_TYPE_U:
6095                 /* We send these as vtypes, so we get them back as such */
6096                 g_assert (type == MONO_TYPE_VALUETYPE);
6097                 /* Fall through */
6098                 handle_vtype:
6099         case MONO_TYPE_VALUETYPE:
6100                 if (type == MONO_TYPE_OBJECT) {
6101                         /* Boxed vtype */
6102                         int objid = decode_objid (buf, &buf, limit);
6103                         ErrorCode err;
6104                         MonoObject *obj;
6105
6106                         err = get_object (objid, (MonoObject**)&obj);
6107                         if (err != ERR_NONE)
6108                                 return err;
6109                         if (!obj)
6110                                 return ERR_INVALID_ARGUMENT;
6111                         if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6112                                 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6113                                 return ERR_INVALID_ARGUMENT;
6114                         }
6115                         memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6116                 } else {
6117                         err = decode_vtype (t, domain, addr, buf, &buf, limit);
6118                         if (err != ERR_NONE)
6119                                 return err;
6120                 }
6121                 break;
6122         handle_ref:
6123         default:
6124                 if (MONO_TYPE_IS_REFERENCE (t)) {
6125                         if (type == MONO_TYPE_OBJECT) {
6126                                 int objid = decode_objid (buf, &buf, limit);
6127                                 ErrorCode err;
6128                                 MonoObject *obj;
6129
6130                                 err = get_object (objid, (MonoObject**)&obj);
6131                                 if (err != ERR_NONE)
6132                                         return err;
6133
6134                                 if (obj) {
6135                                         if (!obj_is_of_type (obj, t)) {
6136                                                 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6137                                                 return ERR_INVALID_ARGUMENT;
6138                                         }
6139                                 }
6140                                 if (obj && obj->vtable->domain != domain)
6141                                         return ERR_INVALID_ARGUMENT;
6142
6143                                 mono_gc_wbarrier_generic_store (addr, obj);
6144                         } else if (type == VALUE_TYPE_ID_NULL) {
6145                                 *(MonoObject**)addr = NULL;
6146                         } else if (type == MONO_TYPE_VALUETYPE) {
6147                                 MonoError error;
6148                                 guint8 *buf2;
6149                                 gboolean is_enum;
6150                                 MonoClass *klass;
6151                                 MonoDomain *d;
6152                                 guint8 *vtype_buf;
6153                                 int vtype_buf_size;
6154
6155                                 /* This can happen when round-tripping boxed vtypes */
6156                                 /*
6157                                  * Obtain vtype class.
6158                                  * Same as the beginning of the handle_vtype case above.
6159                                  */
6160                                 buf2 = buf;
6161                                 is_enum = decode_byte (buf, &buf, limit);
6162                                 if (is_enum)
6163                                         return ERR_NOT_IMPLEMENTED;
6164                                 klass = decode_typeid (buf, &buf, limit, &d, &err);
6165                                 if (err != ERR_NONE)
6166                                         return err;
6167
6168                                 /* Decode the vtype into a temporary buffer, then box it. */
6169                                 vtype_buf_size = mono_class_value_size (klass, NULL);
6170                                 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6171                                 g_assert (vtype_buf);
6172
6173                                 buf = buf2;
6174                                 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6175                                 if (err != ERR_NONE) {
6176                                         g_free (vtype_buf);
6177                                         return err;
6178                                 }
6179                                 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6180                                 mono_error_cleanup (&error);
6181                                 g_free (vtype_buf);
6182                         } else {
6183                                 char *name = mono_type_full_name (t);
6184                                 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6185                                 g_free (name);
6186                                 return ERR_INVALID_ARGUMENT;
6187                         }
6188                 } else {
6189                         NOT_IMPLEMENTED;
6190                 }
6191                 break;
6192         }
6193
6194         *endbuf = buf;
6195
6196         return ERR_NONE;
6197 }
6198
6199 static ErrorCode
6200 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6201 {
6202         MonoError error;
6203         ErrorCode err;
6204         int type = decode_byte (buf, &buf, limit);
6205
6206         if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6207                 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6208                 guint8 *nullable_buf;
6209
6210                 /*
6211                  * First try decoding it as a Nullable`1
6212                  */
6213                 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6214                 if (err == ERR_NONE)
6215                         return err;
6216
6217                 /*
6218                  * Then try decoding as a primitive value or null.
6219                  */
6220                 if (targ->type == type) {
6221                         nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6222                         err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6223                         if (err != ERR_NONE) {
6224                                 g_free (nullable_buf);
6225                                 return err;
6226                         }
6227                         MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6228                         if (!is_ok (&error)) {
6229                                 mono_error_cleanup (&error);
6230                                 return ERR_INVALID_OBJECT;
6231                         }
6232                         mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6233                         g_free (nullable_buf);
6234                         *endbuf = buf;
6235                         return ERR_NONE;
6236                 } else if (type == VALUE_TYPE_ID_NULL) {
6237                         mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6238                         *endbuf = buf;
6239                         return ERR_NONE;
6240                 }
6241         }
6242
6243         return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6244 }
6245
6246 static void
6247 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6248 {
6249         guint32 flags;
6250         int reg;
6251         guint8 *addr, *gaddr;
6252         mgreg_t reg_val;
6253
6254         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6255         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6256
6257         switch (flags) {
6258         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6259                 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6260
6261                 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL);
6262                 break;
6263         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6264                 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6265                 addr += (gint32)var->offset;
6266
6267                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6268
6269                 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6270                 break;
6271         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6272                 NOT_IMPLEMENTED;
6273                 break;
6274         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6275         case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6276                 /* Same as regoffset, but with an indirection */
6277                 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6278                 addr += (gint32)var->offset;
6279
6280                 gaddr = (guint8 *)*(gpointer*)addr;
6281                 g_assert (gaddr);
6282                 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6283                 break;
6284         case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6285                 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6286                 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6287                 MonoGSharedVtMethodRuntimeInfo *info;
6288                 guint8 *locals;
6289                 int idx;
6290
6291                 idx = reg;
6292
6293                 g_assert (info_var);
6294                 g_assert (locals_var);
6295
6296                 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6297                 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6298                 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6299                         addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6300                         addr += (gint32)info_var->offset;
6301                         info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6302                 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6303                         info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6304                 } else {
6305                         g_assert_not_reached ();
6306                 }
6307                 g_assert (info);
6308
6309                 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6310                 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6311                 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6312                         addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6313                         addr += (gint32)locals_var->offset;
6314                         locals = (guint8 *)*(gpointer*)addr;
6315                 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6316                         locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6317                 } else {
6318                         g_assert_not_reached ();
6319                 }
6320                 g_assert (locals);
6321
6322                 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6323
6324                 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6325                 break;
6326         }
6327
6328         default:
6329                 g_assert_not_reached ();
6330         }
6331 }
6332
6333 static void
6334 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6335 {
6336         guint32 flags;
6337         int reg, size;
6338         guint8 *addr, *gaddr;
6339
6340         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6341         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6342
6343         if (MONO_TYPE_IS_REFERENCE (t))
6344                 size = sizeof (gpointer);
6345         else
6346                 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6347
6348         switch (flags) {
6349         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6350 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6351                 mgreg_t v;
6352                 gboolean is_signed = FALSE;
6353
6354                 if (t->byref) {
6355                         addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6356
6357                         if (addr) {
6358                                 // FIXME: Write barriers
6359                                 mono_gc_memmove_atomic (addr, val, size);
6360                         }
6361                         break;
6362                 }
6363
6364                 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6365                         is_signed = TRUE;
6366
6367                 switch (size) {
6368                 case 1:
6369                         v = is_signed ? *(gint8*)val : *(guint8*)val;
6370                         break;
6371                 case 2:
6372                         v = is_signed ? *(gint16*)val : *(guint16*)val;
6373                         break;
6374                 case 4:
6375                         v = is_signed ? *(gint32*)val : *(guint32*)val;
6376                         break;
6377                 case 8:
6378                         v = is_signed ? *(gint64*)val : *(guint64*)val;
6379                         break;
6380                 default:
6381                         g_assert_not_reached ();
6382                 }
6383
6384                 /* Set value on the stack or in the return ctx */
6385                 if (reg_locations [reg]) {
6386                         /* Saved on the stack */
6387                         DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6388                         *(reg_locations [reg]) = v;
6389                 } else {
6390                         /* Not saved yet */
6391                         DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6392                         mono_arch_context_set_int_reg (restore_ctx, reg, v);
6393                 }                       
6394
6395                 // FIXME: Move these to mono-context.h/c.
6396                 mono_arch_context_set_int_reg (ctx, reg, v);
6397 #else
6398                 // FIXME: Can't set registers, so we disable linears
6399                 NOT_IMPLEMENTED;
6400 #endif
6401                 break;
6402         }
6403         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6404                 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6405                 addr += (gint32)var->offset;
6406
6407                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6408
6409                 if (t->byref) {
6410                         addr = *(guint8**)addr;
6411
6412                         if (!addr)
6413                                 break;
6414                 }
6415                         
6416                 // FIXME: Write barriers
6417                 mono_gc_memmove_atomic (addr, val, size);
6418                 break;
6419         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6420                 /* Same as regoffset, but with an indirection */
6421                 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6422                 addr += (gint32)var->offset;
6423
6424                 gaddr = (guint8 *)*(gpointer*)addr;
6425                 g_assert (gaddr);
6426                 // FIXME: Write barriers
6427                 mono_gc_memmove_atomic (gaddr, val, size);
6428                 break;
6429         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6430                 NOT_IMPLEMENTED;
6431                 break;
6432         default:
6433                 g_assert_not_reached ();
6434         }
6435 }
6436
6437 static void
6438 clear_event_request (int req_id, int etype)
6439 {
6440         int i;
6441
6442         mono_loader_lock ();
6443         for (i = 0; i < event_requests->len; ++i) {
6444                 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6445
6446                 if (req->id == req_id && req->event_kind == etype) {
6447                         if (req->event_kind == EVENT_KIND_BREAKPOINT)
6448                                 clear_breakpoint ((MonoBreakpoint *)req->info);
6449                         if (req->event_kind == EVENT_KIND_STEP)
6450                                 ss_destroy ((SingleStepReq *)req->info);
6451                         if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6452                                 clear_breakpoint ((MonoBreakpoint *)req->info);
6453                         if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6454                                 clear_breakpoint ((MonoBreakpoint *)req->info);
6455                         g_ptr_array_remove_index_fast (event_requests, i);
6456                         g_free (req);
6457                         break;
6458                 }
6459         }
6460         mono_loader_unlock ();
6461 }
6462
6463 static void
6464 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6465 {
6466         int i;
6467
6468         if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6469                 m->kind = MOD_KIND_NONE;
6470         if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6471                 int count = 0, match_count = 0, pos;
6472                 MonoAssembly **newassemblies;
6473
6474                 for (i = 0; m->data.assemblies [i]; ++i) {
6475                         count ++;
6476                         if (m->data.assemblies [i] == assembly)
6477                                 match_count ++;
6478                 }
6479
6480                 if (match_count) {
6481                         newassemblies = g_new0 (MonoAssembly*, count - match_count);
6482
6483                         pos = 0;
6484                         for (i = 0; i < count; ++i)
6485                                 if (m->data.assemblies [i] != assembly)
6486                                         newassemblies [pos ++] = m->data.assemblies [i];
6487                         g_assert (pos == count - match_count);
6488                         g_free (m->data.assemblies);
6489                         m->data.assemblies = newassemblies;
6490                 }
6491         }
6492 }
6493
6494 static void
6495 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6496 {
6497         int i;
6498
6499         for (i = 0; i < req->nmodifiers; ++i) {
6500                 Modifier *m = &req->modifiers [i];
6501
6502                 clear_assembly_from_modifier (req, m, assembly);
6503         }
6504 }
6505
6506 /*
6507  * clear_event_requests_for_assembly:
6508  *
6509  *   Clear all events requests which reference ASSEMBLY.
6510  */
6511 static void
6512 clear_event_requests_for_assembly (MonoAssembly *assembly)
6513 {
6514         int i;
6515         gboolean found;
6516
6517         mono_loader_lock ();
6518         found = TRUE;
6519         while (found) {
6520                 found = FALSE;
6521                 for (i = 0; i < event_requests->len; ++i) {
6522                         EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6523
6524                         clear_assembly_from_modifiers (req, assembly);
6525
6526                         if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6527                                 clear_event_request (req->id, req->event_kind);
6528                                 found = TRUE;
6529                                 break;
6530                         }
6531
6532                         if (req->event_kind == EVENT_KIND_STEP)
6533                                 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6534                 }
6535         }
6536         mono_loader_unlock ();
6537 }
6538
6539 /*
6540  * type_comes_from_assembly:
6541  *
6542  *   GHRFunc that returns TRUE if klass comes from assembly
6543  */
6544 static gboolean
6545 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6546 {
6547         return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6548 }
6549
6550 /*
6551  * clear_types_for_assembly:
6552  *
6553  *   Clears types from loaded_classes for a given assembly
6554  */
6555 static void
6556 clear_types_for_assembly (MonoAssembly *assembly)
6557 {
6558         MonoDomain *domain = mono_domain_get ();
6559         AgentDomainInfo *info = NULL;
6560
6561         if (!domain || !domain_jit_info (domain))
6562                 /* Can happen during shutdown */
6563                 return;
6564
6565         info = get_agent_domain_info (domain);
6566
6567         mono_loader_lock ();
6568         g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6569         mono_loader_unlock ();
6570 }
6571
6572 static void
6573 add_thread (gpointer key, gpointer value, gpointer user_data)
6574 {
6575         MonoInternalThread *thread = (MonoInternalThread *)value;
6576         Buffer *buf = (Buffer *)user_data;
6577
6578         buffer_add_objid (buf, (MonoObject*)thread);
6579 }
6580
6581 static ErrorCode
6582 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6583 {
6584         MonoError error;
6585         guint8 *end = invoke->endp;
6586         MonoMethod *m;
6587         int i, nargs;
6588         ErrorCode err;
6589         MonoMethodSignature *sig;
6590         guint8 **arg_buf;
6591         void **args;
6592         MonoObject *this_arg, *res, *exc;
6593         MonoDomain *domain;
6594         guint8 *this_buf;
6595 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6596         MonoLMFExt ext;
6597 #endif
6598         MonoStopwatch watch;
6599
6600         if (invoke->method) {
6601                 /* 
6602                  * Invoke this method directly, currently only Environment.Exit () is supported.
6603                  */
6604                 this_arg = NULL;
6605                 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>");
6606
6607                 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6608                 mono_error_assert_ok (&error);
6609
6610                 g_assert_not_reached ();
6611         }
6612
6613         m = decode_methodid (p, &p, end, &domain, &err);
6614         if (err != ERR_NONE)
6615                 return err;
6616         sig = mono_method_signature (m);
6617
6618         if (m->klass->valuetype)
6619                 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6620         else
6621                 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6622         if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6623                 /* Should be null */
6624                 int type = decode_byte (p, &p, end);
6625                 if (type != VALUE_TYPE_ID_NULL) {
6626                         DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6627                         return ERR_INVALID_ARGUMENT;
6628                 }
6629                 memset (this_buf, 0, mono_class_instance_size (m->klass));
6630         } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6631                         /* Could be null */
6632                         guint8 *tmp_p;
6633
6634                         int type = decode_byte (p, &tmp_p, end);
6635                         if (type == VALUE_TYPE_ID_NULL) {
6636                                 memset (this_buf, 0, mono_class_instance_size (m->klass));
6637                                 p = tmp_p;
6638                         } else {
6639                                 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6640                                 if (err != ERR_NONE)
6641                                         return err;
6642                         }
6643         } else {
6644                 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6645                 if (err != ERR_NONE)
6646                         return err;
6647         }
6648
6649         if (!m->klass->valuetype)
6650                 this_arg = *(MonoObject**)this_buf;
6651         else
6652                 this_arg = NULL;
6653
6654         if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6655                 if (!this_arg) {
6656                         DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6657                         return ERR_INVALID_ARGUMENT;
6658                 }
6659                 m = mono_object_get_virtual_method (this_arg, m);
6660                 /* Transform this to the format the rest of the code expects it to be */
6661                 if (m->klass->valuetype) {
6662                         this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6663                         memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6664                 }
6665         } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6666                 if (!this_arg) {
6667                         DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6668                         return ERR_INVALID_ARGUMENT;
6669                 }
6670                 m = mono_object_get_virtual_method (this_arg, m);
6671                 if (m->klass->valuetype) {
6672                         this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6673                         memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6674                 }
6675         }
6676
6677         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>");
6678
6679         if (this_arg && this_arg->vtable->domain != domain)
6680                 NOT_IMPLEMENTED;
6681
6682         if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6683                 if (!strcmp (m->name, ".ctor")) {
6684                         if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6685                                 return ERR_INVALID_ARGUMENT;
6686                         else {
6687                                 MonoError error;
6688                                 this_arg = mono_object_new_checked (domain, m->klass, &error);
6689                                 mono_error_assert_ok (&error);
6690                         }
6691                 } else {
6692                         return ERR_INVALID_ARGUMENT;
6693                 }
6694         }
6695
6696         if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6697                 return ERR_INVALID_ARGUMENT;
6698
6699         nargs = decode_int (p, &p, end);
6700         if (nargs != sig->param_count)
6701                 return ERR_INVALID_ARGUMENT;
6702         /* Use alloca to get gc tracking */
6703         arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6704         memset (arg_buf, 0, nargs * sizeof (gpointer));
6705         args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6706         for (i = 0; i < nargs; ++i) {
6707                 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6708                         err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6709                         if (err != ERR_NONE)
6710                                 break;
6711                         if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6712                                 NOT_IMPLEMENTED;
6713
6714                         if (sig->params [i]->byref) {
6715                                 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6716                                 *(gpointer*)arg_buf [i] = args [i];
6717                                 args [i] = arg_buf [i];
6718                         }
6719                 } else {
6720                         arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6721                         err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6722                         if (err != ERR_NONE)
6723                                 break;
6724                         args [i] = arg_buf [i];
6725                 }
6726         }
6727
6728         if (i < nargs)
6729                 return err;
6730
6731         if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6732                 tls->disable_breakpoints = TRUE;
6733         else
6734                 tls->disable_breakpoints = FALSE;
6735
6736         /* 
6737          * Add an LMF frame to link the stack frames on the invoke method with our caller.
6738          */
6739 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6740         if (invoke->has_ctx) {
6741                 MonoLMF **lmf_addr;
6742
6743                 lmf_addr = mono_get_lmf_addr ();
6744
6745                 /* Setup our lmf */
6746                 memset (&ext, 0, sizeof (ext));
6747                 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6748
6749                 ext.debugger_invoke = TRUE;
6750                 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6751
6752                 mono_set_lmf ((MonoLMF*)&ext);
6753         }
6754 #endif
6755
6756         mono_stopwatch_start (&watch);
6757         res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
6758         if (exc == NULL && !mono_error_ok (&error)) {
6759                 exc = (MonoObject*) mono_error_convert_to_exception (&error);
6760         } else {
6761                 mono_error_cleanup (&error); /* FIXME report error */
6762         }
6763         mono_stopwatch_stop (&watch);
6764         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));
6765         if (exc) {
6766                 buffer_add_byte (buf, 0);
6767                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6768         } else {
6769                 gboolean out_this = FALSE;
6770                 gboolean out_args = FALSE;
6771
6772                 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6773                         out_this = TRUE;
6774                 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6775                         out_args = TRUE;
6776                 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6777                 if (sig->ret->type == MONO_TYPE_VOID) {
6778                         if (!strcmp (m->name, ".ctor")) {
6779                                 if (!m->klass->valuetype)
6780                                         buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6781                                 else
6782                                         buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6783                         } else {
6784                                 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6785                         }
6786                 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6787                         buffer_add_value (buf, sig->ret, &res, domain);
6788                 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6789                         if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6790                                 MonoClass *k = mono_class_from_mono_type (sig->ret);
6791                                 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6792
6793                                 g_assert (nullable_buf);
6794                                 mono_nullable_init (nullable_buf, res, k);
6795                                 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6796                         } else {
6797                                 g_assert (res);
6798                                 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6799                         }
6800                 } else {
6801                         NOT_IMPLEMENTED;
6802                 }
6803                 if (out_this)
6804                         /* Return the new value of the receiver after the call */
6805                         buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6806                 if (out_args) {
6807                         buffer_add_int (buf, nargs);
6808                         for (i = 0; i < nargs; ++i) {
6809                                 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6810                                         buffer_add_value (buf, sig->params [i], &args [i], domain);
6811                                 else if (sig->params [i]->byref)
6812                                         /* add_value () does an indirection */
6813                                         buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6814                                 else
6815                                         buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6816                         }
6817                 }
6818         }
6819
6820         tls->disable_breakpoints = FALSE;
6821
6822 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6823         if (invoke->has_ctx)
6824                 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
6825 #endif
6826
6827         *endp = p;
6828         // FIXME: byref arguments
6829         // FIXME: varargs
6830         return ERR_NONE;
6831 }
6832
6833 /*
6834  * invoke_method:
6835  *
6836  *   Invoke the method given by tls->pending_invoke in the current thread.
6837  */
6838 static void
6839 invoke_method (void)
6840 {
6841         DebuggerTlsData *tls;
6842         InvokeData *invoke;
6843         int id;
6844         int i, mindex;
6845         ErrorCode err;
6846         Buffer buf;
6847         MonoContext restore_ctx;
6848         guint8 *p;
6849
6850         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6851         g_assert (tls);
6852
6853         /*
6854          * Store the `InvokeData *' in `tls->invoke' until we're done with
6855          * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6856          */
6857
6858         mono_loader_lock ();
6859
6860         invoke = tls->pending_invoke;
6861         g_assert (invoke);
6862         tls->pending_invoke = NULL;
6863
6864         invoke->last_invoke = tls->invoke;
6865         tls->invoke = invoke;
6866
6867         mono_loader_unlock ();
6868
6869         tls->frames_up_to_date = FALSE;
6870
6871         id = invoke->id;
6872
6873         p = invoke->p;
6874         err = ERR_NONE;
6875         for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6876                 buffer_init (&buf, 128);
6877
6878                 if (err) {
6879                         /* Fail the other invokes as well */
6880                 } else {
6881                         err = do_invoke_method (tls, &buf, invoke, p, &p);
6882                 }
6883
6884                 if (tls->abort_requested) {
6885                         if (CHECK_PROTOCOL_VERSION (2, 42))
6886                                 err = ERR_INVOKE_ABORTED;
6887                 }
6888
6889                 /* Start suspending before sending the reply */
6890                 if (mindex == invoke->nmethods - 1) {
6891                         if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6892                                 for (i = 0; i < invoke->suspend_count; ++i)
6893                                         suspend_vm ();
6894                         }
6895                 }
6896
6897                 send_reply_packet (id, err, &buf);
6898         
6899                 buffer_free (&buf);
6900         }
6901
6902         memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6903
6904         if (invoke->has_ctx)
6905                 save_thread_context (&restore_ctx);
6906
6907         if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6908                 g_assert (tls->resume_count);
6909                 tls->resume_count -= invoke->suspend_count;
6910         }
6911
6912         DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6913
6914         /*
6915          * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6916          *
6917          * It is possible that mono_thread_internal_abort () was called
6918          * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6919          * because we reset the abort here.
6920          */
6921
6922         mono_loader_lock ();
6923
6924         if (tls->abort_requested)
6925                 mono_thread_internal_reset_abort (tls->thread);
6926
6927         tls->invoke = tls->invoke->last_invoke;
6928         tls->abort_requested = FALSE;
6929
6930         mono_loader_unlock ();
6931
6932         g_free (invoke->p);
6933         g_free (invoke);
6934
6935         suspend_current ();
6936 }
6937
6938 static gboolean
6939 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6940 {
6941         MonoThread *thread = (MonoThread *)value;
6942         DebuggerTlsData *tls;
6943         gboolean res;
6944
6945         mono_loader_lock ();
6946         tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6947         g_assert (tls);
6948         res = tls->really_suspended;
6949         mono_loader_unlock ();
6950
6951         return res;
6952 }
6953
6954 static GPtrArray*
6955 get_source_files_for_type (MonoClass *klass)
6956 {
6957         gpointer iter = NULL;
6958         MonoMethod *method;
6959         MonoDebugSourceInfo *sinfo;
6960         GPtrArray *files;
6961         int i, j;
6962
6963         files = g_ptr_array_new ();
6964
6965         while ((method = mono_class_get_methods (klass, &iter))) {
6966                 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6967                 GPtrArray *source_file_list;
6968
6969                 if (minfo) {
6970                         mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6971                         for (j = 0; j < source_file_list->len; ++j) {
6972                                 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6973                                 for (i = 0; i < files->len; ++i)
6974                                         if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6975                                                 break;
6976                                 if (i == files->len)
6977                                         g_ptr_array_add (files, g_strdup (sinfo->source_file));
6978                         }
6979                         g_ptr_array_free (source_file_list, TRUE);
6980                 }
6981         }
6982
6983         return files;
6984 }
6985
6986 static ErrorCode
6987 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6988 {
6989         switch (command) {
6990         case CMD_VM_VERSION: {
6991                 char *build_info, *version;
6992
6993                 build_info = mono_get_runtime_build_info ();
6994                 version = g_strdup_printf ("mono %s", build_info);
6995
6996                 buffer_add_string (buf, version); /* vm version */
6997                 buffer_add_int (buf, MAJOR_VERSION);
6998                 buffer_add_int (buf, MINOR_VERSION);
6999                 g_free (build_info);
7000                 g_free (version);
7001                 break;
7002         }
7003         case CMD_VM_SET_PROTOCOL_VERSION: {
7004                 major_version = decode_int (p, &p, end);
7005                 minor_version = decode_int (p, &p, end);
7006                 protocol_version_set = TRUE;
7007                 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7008                 break;
7009         }
7010         case CMD_VM_ALL_THREADS: {
7011                 // FIXME: Domains
7012                 mono_loader_lock ();
7013                 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7014                 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7015                 mono_loader_unlock ();
7016                 break;
7017         }
7018         case CMD_VM_SUSPEND:
7019                 suspend_vm ();
7020                 wait_for_suspend ();
7021                 break;
7022         case CMD_VM_RESUME:
7023                 if (suspend_count == 0)
7024                         return ERR_NOT_SUSPENDED;
7025                 resume_vm ();
7026                 clear_suspended_objs ();
7027                 break;
7028         case CMD_VM_DISPOSE:
7029                 /* Clear all event requests */
7030                 mono_loader_lock ();
7031                 while (event_requests->len > 0) {
7032                         EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7033
7034                         clear_event_request (req->id, req->event_kind);
7035                 }
7036                 mono_loader_unlock ();
7037
7038                 while (suspend_count > 0)
7039                         resume_vm ();
7040                 disconnected = TRUE;
7041                 vm_start_event_sent = FALSE;
7042                 break;
7043         case CMD_VM_EXIT: {
7044                 MonoInternalThread *thread;
7045                 DebuggerTlsData *tls;
7046 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7047                 MonoClass *env_class;
7048 #endif
7049                 MonoMethod *exit_method = NULL;
7050                 gpointer *args;
7051                 int exit_code;
7052
7053                 exit_code = decode_int (p, &p, end);
7054
7055                 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7056
7057                 /* Have to send a reply before exiting */
7058                 send_reply_packet (id, 0, buf);
7059
7060                 /* Clear all event requests */
7061                 mono_loader_lock ();
7062                 while (event_requests->len > 0) {
7063                         EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7064
7065                         clear_event_request (req->id, req->event_kind);
7066                 }
7067                 mono_loader_unlock ();
7068
7069                 /*
7070                  * The JDWP documentation says that the shutdown is not orderly. It doesn't
7071                  * specify whenever a VM_DEATH event is sent. We currently do an orderly
7072                  * shutdown by hijacking a thread to execute Environment.Exit (). This is
7073                  * better than doing the shutdown ourselves, since it avoids various races.
7074                  */
7075
7076                 suspend_vm ();
7077                 wait_for_suspend ();
7078
7079 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7080                 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7081                 if (env_class)
7082                         exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7083 #endif
7084
7085                 mono_loader_lock ();
7086                 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7087                 mono_loader_unlock ();
7088
7089                 if (thread && exit_method) {
7090                         mono_loader_lock ();
7091                         tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7092                         mono_loader_unlock ();
7093
7094                         args = g_new0 (gpointer, 1);
7095                         args [0] = g_malloc (sizeof (int));
7096                         *(int*)(args [0]) = exit_code;
7097
7098                         tls->pending_invoke = g_new0 (InvokeData, 1);
7099                         tls->pending_invoke->method = exit_method;
7100                         tls->pending_invoke->args = args;
7101                         tls->pending_invoke->nmethods = 1;
7102
7103                         while (suspend_count > 0)
7104                                 resume_vm ();
7105                 } else {
7106                         /* 
7107                          * No thread found, do it ourselves.
7108                          * FIXME: This can race with normal shutdown etc.
7109                          */
7110                         while (suspend_count > 0)
7111                                 resume_vm ();
7112
7113                         if (!mono_runtime_try_shutdown ())
7114                                 break;
7115
7116                         mono_environment_exitcode_set (exit_code);
7117
7118                         /* Suspend all managed threads since the runtime is going away */
7119                         DEBUG_PRINTF (1, "Suspending all threads...\n");
7120                         mono_thread_suspend_all_other_threads ();
7121                         DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7122                         mono_runtime_quit ();
7123                         transport_close2 ();
7124                         DEBUG_PRINTF (1, "Exiting...\n");
7125
7126                         exit (exit_code);
7127                 }
7128                 break;
7129         }               
7130         case CMD_VM_INVOKE_METHOD:
7131         case CMD_VM_INVOKE_METHODS: {
7132                 int objid = decode_objid (p, &p, end);
7133                 MonoThread *thread;
7134                 DebuggerTlsData *tls;
7135                 int i, count, flags, nmethods;
7136                 ErrorCode err;
7137
7138                 err = get_object (objid, (MonoObject**)&thread);
7139                 if (err != ERR_NONE)
7140                         return err;
7141
7142                 flags = decode_int (p, &p, end);
7143
7144                 if (command == CMD_VM_INVOKE_METHODS)
7145                         nmethods = decode_int (p, &p, end);
7146                 else
7147                         nmethods = 1;
7148
7149                 // Wait for suspending if it already started
7150                 if (suspend_count)
7151                         wait_for_suspend ();
7152                 if (!is_suspended ())
7153                         return ERR_NOT_SUSPENDED;
7154
7155                 mono_loader_lock ();
7156                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7157                 mono_loader_unlock ();
7158                 g_assert (tls);
7159
7160                 if (!tls->really_suspended)
7161                         /* The thread is still running native code, can't do invokes */
7162                         return ERR_NOT_SUSPENDED;
7163
7164                 /* 
7165                  * Store the invoke data into tls, the thread will execute it after it is
7166                  * resumed.
7167                  */
7168                 if (tls->pending_invoke)
7169                         return ERR_NOT_SUSPENDED;
7170                 tls->pending_invoke = g_new0 (InvokeData, 1);
7171                 tls->pending_invoke->id = id;
7172                 tls->pending_invoke->flags = flags;
7173                 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7174                 memcpy (tls->pending_invoke->p, p, end - p);
7175                 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7176                 tls->pending_invoke->suspend_count = suspend_count;
7177                 tls->pending_invoke->nmethods = nmethods;
7178
7179                 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7180                         resume_thread (THREAD_TO_INTERNAL (thread));
7181                 }
7182                 else {
7183                         count = suspend_count;
7184                         for (i = 0; i < count; ++i)
7185                                 resume_vm ();
7186                 }
7187                 break;
7188         }
7189         case CMD_VM_ABORT_INVOKE: {
7190                 int objid = decode_objid (p, &p, end);
7191                 MonoThread *thread;
7192                 DebuggerTlsData *tls;
7193                 int invoke_id;
7194                 ErrorCode err;
7195
7196                 err = get_object (objid, (MonoObject**)&thread);
7197                 if (err != ERR_NONE)
7198                         return err;
7199
7200                 invoke_id = decode_int (p, &p, end);
7201
7202                 mono_loader_lock ();
7203                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7204                 g_assert (tls);
7205
7206                 if (tls->abort_requested) {
7207                         DEBUG_PRINTF (1, "Abort already requested.\n");
7208                         mono_loader_unlock ();
7209                         break;
7210                 }
7211
7212                 /*
7213                  * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7214                  * actually the correct invocation.
7215                  *
7216                  * Careful, we do not stop the thread that's doing the invocation, so we can't
7217                  * inspect its stack.  However, invoke_method() also acquires the loader lock
7218                  * when it's done, so we're safe here.
7219                  *
7220                  */
7221
7222                 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7223                         mono_loader_unlock ();
7224                         return ERR_NO_INVOCATION;
7225                 }
7226
7227                 tls->abort_requested = TRUE;
7228
7229                 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7230                 mono_loader_unlock ();
7231                 break;
7232         }
7233
7234         case CMD_VM_SET_KEEPALIVE: {
7235                 int timeout = decode_int (p, &p, end);
7236                 agent_config.keepalive = timeout;
7237                 // FIXME:
7238 #ifndef DISABLE_SOCKET_TRANSPORT
7239                 set_keepalive ();
7240 #else
7241                 NOT_IMPLEMENTED;
7242 #endif
7243                 break;
7244         }
7245         case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7246                 GHashTableIter iter, kiter;
7247                 MonoDomain *domain;
7248                 MonoClass *klass;
7249                 GPtrArray *files;
7250                 int i;
7251                 char *fname, *basename;
7252                 gboolean ignore_case;
7253                 GSList *class_list, *l;
7254                 GPtrArray *res_classes, *res_domains;
7255
7256                 fname = decode_string (p, &p, end);
7257                 ignore_case = decode_byte (p, &p, end);
7258
7259                 basename = dbg_path_get_basename (fname);
7260
7261                 res_classes = g_ptr_array_new ();
7262                 res_domains = g_ptr_array_new ();
7263
7264                 mono_loader_lock ();
7265                 g_hash_table_iter_init (&iter, domains);
7266                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7267                         AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7268
7269                         /* Update 'source_file_to_class' cache */
7270                         g_hash_table_iter_init (&kiter, info->loaded_classes);
7271                         while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7272                                 if (!g_hash_table_lookup (info->source_files, klass)) {
7273                                         files = get_source_files_for_type (klass);
7274                                         g_hash_table_insert (info->source_files, klass, files);
7275
7276                                         for (i = 0; i < files->len; ++i) {
7277                                                 char *s = (char *)g_ptr_array_index (files, i);
7278                                                 char *s2 = dbg_path_get_basename (s);
7279                                                 char *s3;
7280
7281                                                 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7282                                                 if (!class_list) {
7283                                                         class_list = g_slist_prepend (class_list, klass);
7284                                                         g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7285                                                 } else {
7286                                                         class_list = g_slist_prepend (class_list, klass);
7287                                                         g_hash_table_insert (info->source_file_to_class, s2, class_list);
7288                                                 }
7289
7290                                                 /* The _ignorecase hash contains the lowercase path */
7291                                                 s3 = strdup_tolower (s2);
7292                                                 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7293                                                 if (!class_list) {
7294                                                         class_list = g_slist_prepend (class_list, klass);
7295                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7296                                                 } else {
7297                                                         class_list = g_slist_prepend (class_list, klass);
7298                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7299                                                 }
7300
7301                                                 g_free (s2);
7302                                                 g_free (s3);
7303                                         }
7304                                 }
7305                         }
7306
7307                         if (ignore_case) {
7308                                 char *s;
7309
7310                                 s = strdup_tolower (basename);
7311                                 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7312                                 g_free (s);
7313                         } else {
7314                                 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7315                         }
7316
7317                         for (l = class_list; l; l = l->next) {
7318                                 klass = (MonoClass *)l->data;
7319
7320                                 g_ptr_array_add (res_classes, klass);
7321                                 g_ptr_array_add (res_domains, domain);
7322                         }
7323                 }
7324                 mono_loader_unlock ();
7325
7326                 g_free (fname);
7327                 g_free (basename);
7328
7329                 buffer_add_int (buf, res_classes->len);
7330                 for (i = 0; i < res_classes->len; ++i)
7331                         buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7332                 g_ptr_array_free (res_classes, TRUE);
7333                 g_ptr_array_free (res_domains, TRUE);
7334                 break;
7335         }
7336         case CMD_VM_GET_TYPES: {
7337                 GHashTableIter iter;
7338                 MonoDomain *domain;
7339                 int i;
7340                 char *name;
7341                 gboolean ignore_case;
7342                 GPtrArray *res_classes, *res_domains;
7343                 MonoTypeNameParse info;
7344
7345                 name = decode_string (p, &p, end);
7346                 ignore_case = decode_byte (p, &p, end);
7347
7348                 if (!mono_reflection_parse_type (name, &info)) {
7349                         g_free (name);
7350                         mono_reflection_free_type_info (&info);
7351                         return ERR_INVALID_ARGUMENT;
7352                 }
7353
7354                 res_classes = g_ptr_array_new ();
7355                 res_domains = g_ptr_array_new ();
7356
7357                 mono_loader_lock ();
7358                 g_hash_table_iter_init (&iter, domains);
7359                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7360                         MonoAssembly *ass;
7361                         gboolean type_resolve;
7362                         MonoType *t;
7363                         GSList *tmp;
7364
7365                         mono_domain_assemblies_lock (domain);
7366                         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7367                                 ass = (MonoAssembly *)tmp->data;
7368
7369                                 if (ass->image) {
7370                                         MonoError error;
7371                                         type_resolve = TRUE;
7372                                         /* FIXME really okay to call while holding locks? */
7373                                         t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7374                                         mono_error_cleanup (&error); 
7375                                         if (t) {
7376                                                 g_ptr_array_add (res_classes, mono_type_get_class (t));
7377                                                 g_ptr_array_add (res_domains, domain);
7378                                         }
7379                                 }
7380                         }
7381                         mono_domain_assemblies_unlock (domain);
7382                 }
7383                 mono_loader_unlock ();
7384
7385                 g_free (name);
7386                 mono_reflection_free_type_info (&info);
7387
7388                 buffer_add_int (buf, res_classes->len);
7389                 for (i = 0; i < res_classes->len; ++i)
7390                         buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7391                 g_ptr_array_free (res_classes, TRUE);
7392                 g_ptr_array_free (res_domains, TRUE);
7393                 break;
7394         }
7395         case CMD_VM_START_BUFFERING:
7396         case CMD_VM_STOP_BUFFERING:
7397                 /* Handled in the main loop */
7398                 break;
7399         default:
7400                 return ERR_NOT_IMPLEMENTED;
7401         }
7402
7403         return ERR_NONE;
7404 }
7405
7406 static ErrorCode
7407 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7408 {
7409         ErrorCode err;
7410         MonoError error;
7411
7412         switch (command) {
7413         case CMD_EVENT_REQUEST_SET: {
7414                 EventRequest *req;
7415                 int i, event_kind, suspend_policy, nmodifiers;
7416                 ModifierKind mod;
7417                 MonoMethod *method;
7418                 long location = 0;
7419                 MonoThread *step_thread;
7420                 int step_thread_id = 0;
7421                 StepDepth depth = STEP_DEPTH_INTO;
7422                 StepSize size = STEP_SIZE_MIN;
7423                 StepFilter filter = STEP_FILTER_NONE;
7424                 MonoDomain *domain;
7425                 Modifier *modifier;
7426
7427                 event_kind = decode_byte (p, &p, end);
7428                 suspend_policy = decode_byte (p, &p, end);
7429                 nmodifiers = decode_byte (p, &p, end);
7430
7431                 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7432                 req->id = InterlockedIncrement (&event_request_id);
7433                 req->event_kind = event_kind;
7434                 req->suspend_policy = suspend_policy;
7435                 req->nmodifiers = nmodifiers;
7436
7437                 method = NULL;
7438                 for (i = 0; i < nmodifiers; ++i) {
7439                         mod = (ModifierKind)decode_byte (p, &p, end);
7440
7441                         req->modifiers [i].kind = mod;
7442                         if (mod == MOD_KIND_COUNT) {
7443                                 req->modifiers [i].data.count = decode_int (p, &p, end);
7444                         } else if (mod == MOD_KIND_LOCATION_ONLY) {
7445                                 method = decode_methodid (p, &p, end, &domain, &err);
7446                                 if (err != ERR_NONE)
7447                                         return err;
7448                                 location = decode_long (p, &p, end);
7449                         } else if (mod == MOD_KIND_STEP) {
7450                                 step_thread_id = decode_id (p, &p, end);
7451                                 size = (StepSize)decode_int (p, &p, end);
7452                                 depth = (StepDepth)decode_int (p, &p, end);
7453                                 if (CHECK_PROTOCOL_VERSION (2, 16))
7454                                         filter = (StepFilter)decode_int (p, &p, end);
7455                                 req->modifiers [i].data.filter = filter;
7456                                 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7457                                         /* Treat STEP_THOUGH the same as HIDDEN */
7458                                         req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7459                         } else if (mod == MOD_KIND_THREAD_ONLY) {
7460                                 int id = decode_id (p, &p, end);
7461
7462                                 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7463                                 if (err != ERR_NONE) {
7464                                         g_free (req);
7465                                         return err;
7466                                 }
7467                         } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7468                                 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7469
7470                                 if (err != ERR_NONE)
7471                                         return err;
7472                                 req->modifiers [i].caught = decode_byte (p, &p, end);
7473                                 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7474                                 if (CHECK_PROTOCOL_VERSION (2, 25))
7475                                         req->modifiers [i].subclasses = decode_byte (p, &p, end);
7476                                 else
7477                                         req->modifiers [i].subclasses = TRUE;
7478                                 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" : "");
7479                                 if (exc_class) {
7480                                         req->modifiers [i].data.exc_class = exc_class;
7481
7482                                         if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7483                                                 g_free (req);
7484                                                 return ERR_INVALID_ARGUMENT;
7485                                         }
7486                                 }
7487                         } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7488                                 int n = decode_int (p, &p, end);
7489                                 int j;
7490
7491                                 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7492                                 for (j = 0; j < n; ++j) {
7493                                         req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7494                                         if (err != ERR_NONE) {
7495                                                 g_free (req->modifiers [i].data.assemblies);
7496                                                 return err;
7497                                         }
7498                                 }
7499                         } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7500                                 int n = decode_int (p, &p, end);
7501                                 int j;
7502
7503                                 modifier = &req->modifiers [i];
7504                                 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7505                                 for (j = 0; j < n; ++j) {
7506                                         char *s = decode_string (p, &p, end);
7507                                         char *s2;
7508
7509                                         if (s) {
7510                                                 s2 = strdup_tolower (s);
7511                                                 g_hash_table_insert (modifier->data.source_files, s2, s2);
7512                                                 g_free (s);
7513                                         }
7514                                 }
7515                         } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7516                                 int n = decode_int (p, &p, end);
7517                                 int j;
7518
7519                                 modifier = &req->modifiers [i];
7520                                 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7521                                 for (j = 0; j < n; ++j) {
7522                                         char *s = decode_string (p, &p, end);
7523
7524                                         if (s)
7525                                                 g_hash_table_insert (modifier->data.type_names, s, s);
7526                                 }
7527                         } else {
7528                                 g_free (req);
7529                                 return ERR_NOT_IMPLEMENTED;
7530                         }
7531                 }
7532
7533                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7534                         g_assert (method);
7535
7536                         req->info = set_breakpoint (method, location, req, &error);
7537                         if (!mono_error_ok (&error)) {
7538                                 g_free (req);
7539                                 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7540                                 mono_error_cleanup (&error);
7541                                 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7542                         }
7543                 } else if (req->event_kind == EVENT_KIND_STEP) {
7544                         g_assert (step_thread_id);
7545
7546                         err = get_object (step_thread_id, (MonoObject**)&step_thread);
7547                         if (err != ERR_NONE) {
7548                                 g_free (req);
7549                                 return err;
7550                         }
7551
7552                         err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7553                         if (err != ERR_NONE) {
7554                                 g_free (req);
7555                                 return err;
7556                         }
7557                 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7558                         req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7559                 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7560                         req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7561                 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7562                 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7563                 } else {
7564                         if (req->nmodifiers) {
7565                                 g_free (req);
7566                                 return ERR_NOT_IMPLEMENTED;
7567                         }
7568                 }
7569
7570                 mono_loader_lock ();
7571                 g_ptr_array_add (event_requests, req);
7572                 
7573                 if (agent_config.defer) {
7574                         /* Transmit cached data to the client on receipt of the event request */
7575                         switch (req->event_kind) {
7576                         case EVENT_KIND_APPDOMAIN_CREATE:
7577                                 /* Emit load events for currently loaded domains */
7578                                 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7579                                 break;
7580                         case EVENT_KIND_ASSEMBLY_LOAD:
7581                                 /* Emit load events for currently loaded assemblies */
7582                                 mono_assembly_foreach (emit_assembly_load, NULL);
7583                                 break;
7584                         case EVENT_KIND_THREAD_START:
7585                                 /* Emit start events for currently started threads */
7586                                 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7587                                 break;
7588                         case EVENT_KIND_TYPE_LOAD:
7589                                 /* Emit type load events for currently loaded types */
7590                                 mono_domain_foreach (send_types_for_domain, NULL);
7591                                 break;
7592                         default:
7593                                 break;
7594                         }
7595                 }
7596                 mono_loader_unlock ();
7597
7598                 buffer_add_int (buf, req->id);
7599                 break;
7600         }
7601         case CMD_EVENT_REQUEST_CLEAR: {
7602                 int etype = decode_byte (p, &p, end);
7603                 int req_id = decode_int (p, &p, end);
7604
7605                 // FIXME: Make a faster mapping from req_id to request
7606                 mono_loader_lock ();
7607                 clear_event_request (req_id, etype);
7608                 mono_loader_unlock ();
7609                 break;
7610         }
7611         case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7612                 int i;
7613
7614                 mono_loader_lock ();
7615                 i = 0;
7616                 while (i < event_requests->len) {
7617                         EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7618
7619                         if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7620                                 clear_breakpoint ((MonoBreakpoint *)req->info);
7621
7622                                 g_ptr_array_remove_index_fast (event_requests, i);
7623                                 g_free (req);
7624                         } else {
7625                                 i ++;
7626                         }
7627                 }
7628                 mono_loader_unlock ();
7629                 break;
7630         }
7631         default:
7632                 return ERR_NOT_IMPLEMENTED;
7633         }
7634
7635         return ERR_NONE;
7636 }
7637
7638 static ErrorCode
7639 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7640 {
7641         ErrorCode err;
7642         MonoDomain *domain;
7643
7644         switch (command) {
7645         case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7646                 buffer_add_domainid (buf, mono_get_root_domain ());
7647                 break;
7648         }
7649         case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7650                 domain = decode_domainid (p, &p, end, NULL, &err);
7651                 if (err != ERR_NONE)
7652                         return err;
7653                 buffer_add_string (buf, domain->friendly_name);
7654                 break;
7655         }
7656         case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7657                 GSList *tmp;
7658                 MonoAssembly *ass;
7659                 int count;
7660
7661                 domain = decode_domainid (p, &p, end, NULL, &err);
7662                 if (err != ERR_NONE)
7663                         return err;
7664                 mono_loader_lock ();
7665                 count = 0;
7666                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7667                         count ++;
7668                 }
7669                 buffer_add_int (buf, count);
7670                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7671                         ass = (MonoAssembly *)tmp->data;
7672                         buffer_add_assemblyid (buf, domain, ass);
7673                 }
7674                 mono_loader_unlock ();
7675                 break;
7676         }
7677         case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7678                 domain = decode_domainid (p, &p, end, NULL, &err);
7679                 if (err != ERR_NONE)
7680                         return err;
7681
7682                 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7683                 break;
7684         }
7685         case CMD_APPDOMAIN_GET_CORLIB: {
7686                 domain = decode_domainid (p, &p, end, NULL, &err);
7687                 if (err != ERR_NONE)
7688                         return err;
7689
7690                 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7691                 break;
7692         }
7693         case CMD_APPDOMAIN_CREATE_STRING: {
7694                 char *s;
7695                 MonoString *o;
7696
7697                 domain = decode_domainid (p, &p, end, NULL, &err);
7698                 if (err != ERR_NONE)
7699                         return err;
7700                 s = decode_string (p, &p, end);
7701
7702                 o = mono_string_new (domain, s);
7703                 buffer_add_objid (buf, (MonoObject*)o);
7704                 break;
7705         }
7706         case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7707                 MonoError error;
7708                 MonoClass *klass;
7709                 MonoDomain *domain2;
7710                 MonoObject *o;
7711
7712                 domain = decode_domainid (p, &p, end, NULL, &err);
7713                 if (err != ERR_NONE)
7714                         return err;
7715                 klass = decode_typeid (p, &p, end, &domain2, &err);
7716                 if (err != ERR_NONE)
7717                         return err;
7718
7719                 // FIXME:
7720                 g_assert (domain == domain2);
7721
7722                 o = mono_object_new_checked (domain, klass, &error);
7723                 mono_error_assert_ok (&error);
7724
7725                 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7726                 if (err != ERR_NONE)
7727                         return err;
7728
7729                 buffer_add_objid (buf, o);
7730                 break;
7731         }
7732         default:
7733                 return ERR_NOT_IMPLEMENTED;
7734         }
7735
7736         return ERR_NONE;
7737 }
7738
7739 static ErrorCode
7740 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7741 {
7742         ErrorCode err;
7743         MonoAssembly *ass;
7744         MonoDomain *domain;
7745
7746         ass = decode_assemblyid (p, &p, end, &domain, &err);
7747         if (err != ERR_NONE)
7748                 return err;
7749
7750         switch (command) {
7751         case CMD_ASSEMBLY_GET_LOCATION: {
7752                 buffer_add_string (buf, mono_image_get_filename (ass->image));
7753                 break;                  
7754         }
7755         case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7756                 guint32 token;
7757                 MonoMethod *m;
7758
7759                 if (ass->image->dynamic) {
7760                         buffer_add_id (buf, 0);
7761                 } else {
7762                         token = mono_image_get_entry_point (ass->image);
7763                         if (token == 0) {
7764                                 buffer_add_id (buf, 0);
7765                         } else {
7766                                 MonoError error;
7767                                 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
7768                                 if (!m)
7769                                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7770                                 buffer_add_methodid (buf, domain, m);
7771                         }
7772                 }
7773                 break;                  
7774         }
7775         case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7776                 buffer_add_moduleid (buf, domain, ass->image);
7777                 break;
7778         }
7779         case CMD_ASSEMBLY_GET_OBJECT: {
7780                 MonoError error;
7781                 MonoObject *o = (MonoObject*)mono_assembly_get_object_checked (domain, ass, &error);
7782                 if (!o) {
7783                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7784                         return ERR_INVALID_OBJECT;
7785                 }
7786                 buffer_add_objid (buf, o);
7787                 break;
7788         }
7789         case CMD_ASSEMBLY_GET_TYPE: {
7790                 MonoError error;
7791                 char *s = decode_string (p, &p, end);
7792                 gboolean ignorecase = decode_byte (p, &p, end);
7793                 MonoTypeNameParse info;
7794                 MonoType *t;
7795                 gboolean type_resolve, res;
7796                 MonoDomain *d = mono_domain_get ();
7797
7798                 /* This is needed to be able to find referenced assemblies */
7799                 res = mono_domain_set (domain, FALSE);
7800                 g_assert (res);
7801
7802                 if (!mono_reflection_parse_type (s, &info)) {
7803                         t = NULL;
7804                 } else {
7805                         if (info.assembly.name)
7806                                 NOT_IMPLEMENTED;
7807                         t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
7808                         if (!is_ok (&error)) {
7809                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7810                                 mono_reflection_free_type_info (&info);
7811                                 g_free (s);
7812                                 return ERR_INVALID_ARGUMENT;
7813                         }
7814                 }
7815                 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7816                 mono_reflection_free_type_info (&info);
7817                 g_free (s);
7818
7819                 mono_domain_set (d, TRUE);
7820
7821                 break;
7822         }
7823         case CMD_ASSEMBLY_GET_NAME: {
7824                 gchar *name;
7825                 MonoAssembly *mass = ass;
7826
7827                 name = g_strdup_printf (
7828                   "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7829                   mass->aname.name,
7830                   mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7831                   mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7832                   mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7833                   (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7834
7835                 buffer_add_string (buf, name);
7836                 g_free (name);
7837                 break;
7838         }
7839         default:
7840                 return ERR_NOT_IMPLEMENTED;
7841         }
7842
7843         return ERR_NONE;
7844 }
7845
7846 static ErrorCode
7847 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7848 {
7849         ErrorCode err;
7850         MonoDomain *domain;
7851
7852         switch (command) {
7853         case CMD_MODULE_GET_INFO: {
7854                 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7855                 char *basename;
7856
7857                 basename = g_path_get_basename (image->name);
7858                 buffer_add_string (buf, basename); // name
7859                 buffer_add_string (buf, image->module_name); // scopename
7860                 buffer_add_string (buf, image->name); // fqname
7861                 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7862                 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7863                 g_free (basename);
7864                 break;                  
7865         }
7866         default:
7867                 return ERR_NOT_IMPLEMENTED;
7868         }
7869
7870         return ERR_NONE;
7871 }
7872
7873 static ErrorCode
7874 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7875 {
7876         ErrorCode err;
7877         MonoDomain *domain;
7878
7879         switch (command) {
7880         case CMD_FIELD_GET_INFO: {
7881                 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7882
7883                 buffer_add_string (buf, f->name);
7884                 buffer_add_typeid (buf, domain, f->parent);
7885                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7886                 buffer_add_int (buf, f->type->attrs);
7887                 break;
7888         }
7889         default:
7890                 return ERR_NOT_IMPLEMENTED;
7891         }
7892
7893         return ERR_NONE;
7894 }
7895
7896 static void
7897 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7898 {
7899         if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7900                 /* Special case these so the client doesn't have to handle Type objects */
7901                 
7902                 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7903                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7904         } else if (MONO_TYPE_IS_REFERENCE (t))
7905                 buffer_add_value (buf, t, &val, domain);
7906         else
7907                 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7908 }
7909
7910 static ErrorCode
7911 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7912 {
7913         int i, j;
7914         int nattrs = 0;
7915
7916         if (!cinfo) {
7917                 buffer_add_int (buf, 0);
7918                 return ERR_NONE;
7919         }
7920
7921         for (i = 0; i < cinfo->num_attrs; ++i) {
7922                 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7923                         nattrs ++;
7924         }
7925         buffer_add_int (buf, nattrs);
7926
7927         for (i = 0; i < cinfo->num_attrs; ++i) {
7928                 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7929                 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7930                         MonoArray *typed_args, *named_args;
7931                         MonoType *t;
7932                         CattrNamedArg *arginfo = NULL;
7933                         MonoError error;
7934
7935                         mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7936                         if (!mono_error_ok (&error)) {
7937                                 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7938                                 mono_error_cleanup (&error);
7939                                 return ERR_LOADER_ERROR;
7940                         }
7941
7942                         buffer_add_methodid (buf, domain, attr->ctor);
7943
7944                         /* Ctor args */
7945                         if (typed_args) {
7946                                 buffer_add_int (buf, mono_array_length (typed_args));
7947                                 for (j = 0; j < mono_array_length (typed_args); ++j) {
7948                                         MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7949
7950                                         t = mono_method_signature (attr->ctor)->params [j];
7951
7952                                         buffer_add_cattr_arg (buf, t, domain, val);
7953                                 }
7954                         } else {
7955                                 buffer_add_int (buf, 0);
7956                         }
7957
7958                         /* Named args */
7959                         if (named_args) {
7960                                 buffer_add_int (buf, mono_array_length (named_args));
7961
7962                                 for (j = 0; j < mono_array_length (named_args); ++j) {
7963                                         MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7964
7965                                         if (arginfo [j].prop) {
7966                                                 buffer_add_byte (buf, 0x54);
7967                                                 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7968                                         } else if (arginfo [j].field) {
7969                                                 buffer_add_byte (buf, 0x53);
7970                                                 buffer_add_fieldid (buf, domain, arginfo [j].field);
7971                                         } else {
7972                                                 g_assert_not_reached ();
7973                                         }
7974
7975                                         buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7976                                 }
7977                         } else {
7978                                 buffer_add_int (buf, 0);
7979                         }
7980                         g_free (arginfo);
7981                 }
7982         }
7983
7984         return ERR_NONE;
7985 }
7986
7987 /* FIXME: Code duplication with icall.c */
7988 static void
7989 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7990 {
7991         int i;
7992         MonoClass *ic;
7993
7994         mono_class_setup_interfaces (klass, error);
7995         if (!mono_error_ok (error))
7996                 return;
7997
7998         for (i = 0; i < klass->interface_count; i++) {
7999                 ic = klass->interfaces [i];
8000                 g_hash_table_insert (ifaces, ic, ic);
8001
8002                 collect_interfaces (ic, ifaces, error);
8003                 if (!mono_error_ok (error))
8004                         return;
8005         }
8006 }
8007
8008 static ErrorCode
8009 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8010 {
8011         MonoError error;
8012         MonoClass *nested;
8013         MonoType *type;
8014         gpointer iter;
8015         guint8 b;
8016         int nnested;
8017         ErrorCode err;
8018         char *name;
8019
8020         switch (command) {
8021         case CMD_TYPE_GET_INFO: {
8022                 buffer_add_string (buf, klass->name_space);
8023                 buffer_add_string (buf, klass->name);
8024                 // FIXME: byref
8025                 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8026                 buffer_add_string (buf, name);
8027                 g_free (name);
8028                 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8029                 buffer_add_moduleid (buf, domain, klass->image);
8030                 buffer_add_typeid (buf, domain, klass->parent);
8031                 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8032                         buffer_add_typeid (buf, domain, klass->element_class);
8033                 else
8034                         buffer_add_id (buf, 0);
8035                 buffer_add_int (buf, klass->type_token);
8036                 buffer_add_byte (buf, klass->rank);
8037                 buffer_add_int (buf, klass->flags);
8038                 b = 0;
8039                 type = &klass->byval_arg;
8040                 // FIXME: Can't decide whenever a class represents a byref type
8041                 if (FALSE)
8042                         b |= (1 << 0);
8043                 if (type->type == MONO_TYPE_PTR)
8044                         b |= (1 << 1);
8045                 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8046                         b |= (1 << 2);
8047                 if (type->type == MONO_TYPE_VALUETYPE)
8048                         b |= (1 << 3);
8049                 if (klass->enumtype)
8050                         b |= (1 << 4);
8051                 if (klass->generic_container)
8052                         b |= (1 << 5);
8053                 if (klass->generic_container || klass->generic_class)
8054                         b |= (1 << 6);
8055                 buffer_add_byte (buf, b);
8056                 nnested = 0;
8057                 iter = NULL;
8058                 while ((nested = mono_class_get_nested_types (klass, &iter)))
8059                         nnested ++;
8060                 buffer_add_int (buf, nnested);
8061                 iter = NULL;
8062                 while ((nested = mono_class_get_nested_types (klass, &iter)))
8063                         buffer_add_typeid (buf, domain, nested);
8064                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8065                         if (klass->generic_container)
8066                                 buffer_add_typeid (buf, domain, klass);
8067                         else if (klass->generic_class)
8068                                 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
8069                         else
8070                                 buffer_add_id (buf, 0);
8071                 }
8072                 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8073                         int count, i;
8074
8075                         if (klass->generic_class) {
8076                                 MonoGenericInst *inst = klass->generic_class->context.class_inst;
8077
8078                                 count = inst->type_argc;
8079                                 buffer_add_int (buf, count);
8080                                 for (i = 0; i < count; i++)
8081                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8082                         } else if (klass->generic_container) {
8083                                 MonoGenericContainer *container = klass->generic_container;
8084                                 MonoClass *pklass;
8085
8086                                 count = container->type_argc;
8087                                 buffer_add_int (buf, count);
8088                                 for (i = 0; i < count; i++) {
8089                                         pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8090                                         buffer_add_typeid (buf, domain, pklass);
8091                                 }
8092                         } else {
8093                                 buffer_add_int (buf, 0);
8094                         }
8095                 }
8096                 break;
8097         }
8098         case CMD_TYPE_GET_METHODS: {
8099                 int nmethods;
8100                 int i = 0;
8101                 gpointer iter = NULL;
8102                 MonoMethod *m;
8103
8104                 mono_class_setup_methods (klass);
8105
8106                 nmethods = mono_class_num_methods (klass);
8107
8108                 buffer_add_int (buf, nmethods);
8109
8110                 while ((m = mono_class_get_methods (klass, &iter))) {
8111                         buffer_add_methodid (buf, domain, m);
8112                         i ++;
8113                 }
8114                 g_assert (i == nmethods);
8115                 break;
8116         }
8117         case CMD_TYPE_GET_FIELDS: {
8118                 int nfields;
8119                 int i = 0;
8120                 gpointer iter = NULL;
8121                 MonoClassField *f;
8122
8123                 nfields = mono_class_num_fields (klass);
8124
8125                 buffer_add_int (buf, nfields);
8126
8127                 while ((f = mono_class_get_fields (klass, &iter))) {
8128                         buffer_add_fieldid (buf, domain, f);
8129                         buffer_add_string (buf, f->name);
8130                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8131                         buffer_add_int (buf, f->type->attrs);
8132                         i ++;
8133                 }
8134                 g_assert (i == nfields);
8135                 break;
8136         }
8137         case CMD_TYPE_GET_PROPERTIES: {
8138                 int nprops;
8139                 int i = 0;
8140                 gpointer iter = NULL;
8141                 MonoProperty *p;
8142
8143                 nprops = mono_class_num_properties (klass);
8144
8145                 buffer_add_int (buf, nprops);
8146
8147                 while ((p = mono_class_get_properties (klass, &iter))) {
8148                         buffer_add_propertyid (buf, domain, p);
8149                         buffer_add_string (buf, p->name);
8150                         buffer_add_methodid (buf, domain, p->get);
8151                         buffer_add_methodid (buf, domain, p->set);
8152                         buffer_add_int (buf, p->attrs);
8153                         i ++;
8154                 }
8155                 g_assert (i == nprops);
8156                 break;
8157         }
8158         case CMD_TYPE_GET_CATTRS: {
8159                 MonoClass *attr_klass;
8160                 MonoCustomAttrInfo *cinfo;
8161
8162                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8163                 /* attr_klass can be NULL */
8164                 if (err != ERR_NONE)
8165                         return err;
8166
8167                 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8168                 if (!is_ok (&error)) {
8169                         mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8170                         return ERR_LOADER_ERROR;
8171                 }
8172
8173                 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8174                 if (err != ERR_NONE)
8175                         return err;
8176                 break;
8177         }
8178         case CMD_TYPE_GET_FIELD_CATTRS: {
8179                 MonoClass *attr_klass;
8180                 MonoCustomAttrInfo *cinfo;
8181                 MonoClassField *field;
8182
8183                 field = decode_fieldid (p, &p, end, NULL, &err);
8184                 if (err != ERR_NONE)
8185                         return err;
8186                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8187                 if (err != ERR_NONE)
8188                         return err;
8189
8190                 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8191                 if (!is_ok (&error)) {
8192                         mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8193                         return ERR_LOADER_ERROR;
8194                 }
8195
8196                 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8197                 if (err != ERR_NONE)
8198                         return err;
8199                 break;
8200         }
8201         case CMD_TYPE_GET_PROPERTY_CATTRS: {
8202                 MonoClass *attr_klass;
8203                 MonoCustomAttrInfo *cinfo;
8204                 MonoProperty *prop;
8205
8206                 prop = decode_propertyid (p, &p, end, NULL, &err);
8207                 if (err != ERR_NONE)
8208                         return err;
8209                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8210                 if (err != ERR_NONE)
8211                         return err;
8212
8213                 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8214                 if (!is_ok (&error)) {
8215                         mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8216                         return ERR_LOADER_ERROR;
8217                 }
8218
8219                 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8220                 if (err != ERR_NONE)
8221                         return err;
8222                 break;
8223         }
8224         case CMD_TYPE_GET_VALUES:
8225         case CMD_TYPE_GET_VALUES_2: {
8226                 guint8 *val;
8227                 MonoClassField *f;
8228                 MonoVTable *vtable;
8229                 MonoClass *k;
8230                 int len, i;
8231                 gboolean found;
8232                 MonoThread *thread_obj;
8233                 MonoInternalThread *thread = NULL;
8234                 guint32 special_static_type;
8235
8236                 if (command == CMD_TYPE_GET_VALUES_2) {
8237                         int objid = decode_objid (p, &p, end);
8238                         ErrorCode err;
8239
8240                         err = get_object (objid, (MonoObject**)&thread_obj);
8241                         if (err != ERR_NONE)
8242                                 return err;
8243
8244                         thread = THREAD_TO_INTERNAL (thread_obj);
8245                 }
8246
8247                 len = decode_int (p, &p, end);
8248                 for (i = 0; i < len; ++i) {
8249                         f = decode_fieldid (p, &p, end, NULL, &err);
8250                         if (err != ERR_NONE)
8251                                 return err;
8252
8253                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8254                                 return ERR_INVALID_FIELDID;
8255                         special_static_type = mono_class_field_get_special_static_type (f);
8256                         if (special_static_type != SPECIAL_STATIC_NONE) {
8257                                 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8258                                         return ERR_INVALID_FIELDID;
8259                         }
8260
8261                         /* Check that the field belongs to the object */
8262                         found = FALSE;
8263                         for (k = klass; k; k = k->parent) {
8264                                 if (k == f->parent) {
8265                                         found = TRUE;
8266                                         break;
8267                                 }
8268                         }
8269                         if (!found)
8270                                 return ERR_INVALID_FIELDID;
8271
8272                         vtable = mono_class_vtable (domain, f->parent);
8273                         val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8274                         mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8275                         if (!is_ok (&error))
8276                                 return ERR_INVALID_FIELDID;
8277                         buffer_add_value (buf, f->type, val, domain);
8278                         g_free (val);
8279                 }
8280                 break;
8281         }
8282         case CMD_TYPE_SET_VALUES: {
8283                 guint8 *val;
8284                 MonoClassField *f;
8285                 MonoVTable *vtable;
8286                 MonoClass *k;
8287                 int len, i;
8288                 gboolean found;
8289
8290                 len = decode_int (p, &p, end);
8291                 for (i = 0; i < len; ++i) {
8292                         f = decode_fieldid (p, &p, end, NULL, &err);
8293                         if (err != ERR_NONE)
8294                                 return err;
8295
8296                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8297                                 return ERR_INVALID_FIELDID;
8298                         if (mono_class_field_is_special_static (f))
8299                                 return ERR_INVALID_FIELDID;
8300
8301                         /* Check that the field belongs to the object */
8302                         found = FALSE;
8303                         for (k = klass; k; k = k->parent) {
8304                                 if (k == f->parent) {
8305                                         found = TRUE;
8306                                         break;
8307                                 }
8308                         }
8309                         if (!found)
8310                                 return ERR_INVALID_FIELDID;
8311
8312                         // FIXME: Check for literal/const
8313
8314                         vtable = mono_class_vtable (domain, f->parent);
8315                         val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8316                         err = decode_value (f->type, domain, val, p, &p, end);
8317                         if (err != ERR_NONE) {
8318                                 g_free (val);
8319                                 return err;
8320                         }
8321                         if (MONO_TYPE_IS_REFERENCE (f->type))
8322                                 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8323                         else
8324                                 mono_field_static_set_value (vtable, f, val);
8325                         g_free (val);
8326                 }
8327                 break;
8328         }
8329         case CMD_TYPE_GET_OBJECT: {
8330                 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8331                 if (!mono_error_ok (&error)) {
8332                         mono_error_cleanup (&error);
8333                         return ERR_INVALID_OBJECT;
8334                 }
8335                 buffer_add_objid (buf, o);
8336                 break;
8337         }
8338         case CMD_TYPE_GET_SOURCE_FILES:
8339         case CMD_TYPE_GET_SOURCE_FILES_2: {
8340                 char *source_file, *base;
8341                 GPtrArray *files;
8342                 int i;
8343
8344                 files = get_source_files_for_type (klass);
8345
8346                 buffer_add_int (buf, files->len);
8347                 for (i = 0; i < files->len; ++i) {
8348                         source_file = (char *)g_ptr_array_index (files, i);
8349                         if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8350                                 buffer_add_string (buf, source_file);
8351                         } else {
8352                                 base = dbg_path_get_basename (source_file);
8353                                 buffer_add_string (buf, base);
8354                                 g_free (base);
8355                         }
8356                         g_free (source_file);
8357                 }
8358                 g_ptr_array_free (files, TRUE);
8359                 break;
8360         }
8361         case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8362                 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8363
8364                 if (err != ERR_NONE)
8365                         return err;
8366                 if (mono_class_is_assignable_from (klass, oklass))
8367                         buffer_add_byte (buf, 1);
8368                 else
8369                         buffer_add_byte (buf, 0);
8370                 break;
8371         }
8372         case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8373                 char *name = decode_string (p, &p, end);
8374                 int i, flags = decode_int (p, &p, end);
8375                 MonoError error;
8376                 GPtrArray *array;
8377
8378                 mono_error_init (&error);
8379                 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8380                 if (!is_ok (&error)) {
8381                         mono_error_cleanup (&error);
8382                         return ERR_LOADER_ERROR;
8383                 }
8384                 buffer_add_int (buf, array->len);
8385                 for (i = 0; i < array->len; ++i) {
8386                         MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8387                         buffer_add_methodid (buf, domain, method);
8388                 }
8389
8390                 g_ptr_array_free (array, TRUE);
8391                 g_free (name);
8392                 break;
8393         }
8394         case CMD_TYPE_GET_INTERFACES: {
8395                 MonoClass *parent;
8396                 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8397                 MonoClass *tclass, *iface;
8398                 GHashTableIter iter;
8399
8400                 tclass = klass;
8401
8402                 for (parent = tclass; parent; parent = parent->parent) {
8403                         mono_class_setup_interfaces (parent, &error);
8404                         if (!mono_error_ok (&error))
8405                                 return ERR_LOADER_ERROR;
8406                         collect_interfaces (parent, iface_hash, &error);
8407                         if (!mono_error_ok (&error))
8408                                 return ERR_LOADER_ERROR;
8409                 }
8410
8411                 buffer_add_int (buf, g_hash_table_size (iface_hash));
8412
8413                 g_hash_table_iter_init (&iter, iface_hash);
8414                 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8415                         buffer_add_typeid (buf, domain, iface);
8416                 g_hash_table_destroy (iface_hash);
8417                 break;
8418         }
8419         case CMD_TYPE_GET_INTERFACE_MAP: {
8420                 int tindex, ioffset;
8421                 gboolean variance_used;
8422                 MonoClass *iclass;
8423                 int len, nmethods, i;
8424                 gpointer iter;
8425                 MonoMethod *method;
8426
8427                 len = decode_int (p, &p, end);
8428                 mono_class_setup_vtable (klass);
8429
8430                 for (tindex = 0; tindex < len; ++tindex) {
8431                         iclass = decode_typeid (p, &p, end, NULL, &err);
8432                         if (err != ERR_NONE)
8433                                 return err;
8434
8435                         ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8436                         if (ioffset == -1)
8437                                 return ERR_INVALID_ARGUMENT;
8438
8439                         nmethods = mono_class_num_methods (iclass);
8440                         buffer_add_int (buf, nmethods);
8441
8442                         iter = NULL;
8443                         while ((method = mono_class_get_methods (iclass, &iter))) {
8444                                 buffer_add_methodid (buf, domain, method);
8445                         }
8446                         for (i = 0; i < nmethods; ++i)
8447                                 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8448                 }
8449                 break;
8450         }
8451         case CMD_TYPE_IS_INITIALIZED: {
8452                 MonoVTable *vtable = mono_class_vtable (domain, klass);
8453
8454                 if (vtable)
8455                         buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8456                 else
8457                         buffer_add_int (buf, 0);
8458                 break;
8459         }
8460         case CMD_TYPE_CREATE_INSTANCE: {
8461                 MonoError error;
8462                 MonoObject *obj;
8463
8464                 obj = mono_object_new_checked (domain, klass, &error);
8465                 mono_error_assert_ok (&error);
8466                 buffer_add_objid (buf, obj);
8467                 break;
8468         }
8469         default:
8470                 return ERR_NOT_IMPLEMENTED;
8471         }
8472
8473         return ERR_NONE;
8474 }
8475
8476 static ErrorCode
8477 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8478 {
8479         MonoClass *klass;
8480         MonoDomain *old_domain;
8481         MonoDomain *domain;
8482         ErrorCode err;
8483
8484         klass = decode_typeid (p, &p, end, &domain, &err);
8485         if (err != ERR_NONE)
8486                 return err;
8487
8488         old_domain = mono_domain_get ();
8489
8490         mono_domain_set (domain, TRUE);
8491
8492         err = type_commands_internal (command, klass, domain, p, end, buf);
8493
8494         mono_domain_set (old_domain, TRUE);
8495
8496         return err;
8497 }
8498
8499 static ErrorCode
8500 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8501 {
8502         MonoMethodHeader *header;
8503         ErrorCode err;
8504
8505         switch (command) {
8506         case CMD_METHOD_GET_NAME: {
8507                 buffer_add_string (buf, method->name);
8508                 break;                  
8509         }
8510         case CMD_METHOD_GET_DECLARING_TYPE: {
8511                 buffer_add_typeid (buf, domain, method->klass);
8512                 break;
8513         }
8514         case CMD_METHOD_GET_DEBUG_INFO: {
8515                 MonoError error;
8516                 MonoDebugMethodInfo *minfo;
8517                 char *source_file;
8518                 int i, j, n_il_offsets;
8519                 int *source_files;
8520                 GPtrArray *source_file_list;
8521                 MonoSymSeqPoint *sym_seq_points;
8522
8523                 header = mono_method_get_header_checked (method, &error);
8524                 if (!header) {
8525                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
8526                         buffer_add_int (buf, 0);
8527                         buffer_add_string (buf, "");
8528                         buffer_add_int (buf, 0);
8529                         break;
8530                 }
8531
8532                 minfo = mono_debug_lookup_method (method);
8533                 if (!minfo) {
8534                         buffer_add_int (buf, header->code_size);
8535                         buffer_add_string (buf, "");
8536                         buffer_add_int (buf, 0);
8537                         mono_metadata_free_mh (header);
8538                         break;
8539                 }
8540
8541                 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8542                 buffer_add_int (buf, header->code_size);
8543                 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8544                         buffer_add_int (buf, source_file_list->len);
8545                         for (i = 0; i < source_file_list->len; ++i) {
8546                                 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8547                                 buffer_add_string (buf, sinfo->source_file);
8548                                 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8549                                         for (j = 0; j < 16; ++j)
8550                                                 buffer_add_byte (buf, sinfo->hash [j]);
8551                                 }
8552                         }
8553                 } else {
8554                         buffer_add_string (buf, source_file);
8555                 }
8556                 buffer_add_int (buf, n_il_offsets);
8557                 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method,  TRUE));
8558                 for (i = 0; i < n_il_offsets; ++i) {
8559                         MonoSymSeqPoint *sp = &sym_seq_points [i];
8560                         const char *srcfile = "";
8561
8562                         if (source_files [i] != -1) {
8563                                 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8564                                 srcfile = sinfo->source_file;
8565                         }
8566                         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);
8567                         buffer_add_int (buf, sp->il_offset);
8568                         buffer_add_int (buf, sp->line);
8569                         if (CHECK_PROTOCOL_VERSION (2, 13))
8570                                 buffer_add_int (buf, source_files [i]);
8571                         if (CHECK_PROTOCOL_VERSION (2, 19))
8572                                 buffer_add_int (buf, sp->column);
8573                         if (CHECK_PROTOCOL_VERSION (2, 32)) {
8574                                 buffer_add_int (buf, sp->end_line);
8575                                 buffer_add_int (buf, sp->end_column);
8576                         }
8577                 }
8578                 g_free (source_file);
8579                 g_free (source_files);
8580                 g_free (sym_seq_points);
8581                 g_ptr_array_free (source_file_list, TRUE);
8582                 mono_metadata_free_mh (header);
8583                 break;
8584         }
8585         case CMD_METHOD_GET_PARAM_INFO: {
8586                 MonoMethodSignature *sig = mono_method_signature (method);
8587                 guint32 i;
8588                 char **names;
8589
8590                 /* FIXME: mono_class_from_mono_type () and byrefs */
8591
8592                 /* FIXME: Use a smaller encoding */
8593                 buffer_add_int (buf, sig->call_convention);
8594                 buffer_add_int (buf, sig->param_count);
8595                 buffer_add_int (buf, sig->generic_param_count);
8596                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8597                 for (i = 0; i < sig->param_count; ++i) {
8598                         /* FIXME: vararg */
8599                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8600                 }
8601
8602                 /* Emit parameter names */
8603                 names = g_new (char *, sig->param_count);
8604                 mono_method_get_param_names (method, (const char **) names);
8605                 for (i = 0; i < sig->param_count; ++i)
8606                         buffer_add_string (buf, names [i]);
8607                 g_free (names);
8608
8609                 break;
8610         }
8611         case CMD_METHOD_GET_LOCALS_INFO: {
8612                 MonoError error;
8613                 int i, num_locals;
8614                 MonoDebugLocalsInfo *locals;
8615                 int *locals_map = NULL;
8616
8617                 header = mono_method_get_header_checked (method, &error);
8618                 if (!header) {
8619                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
8620                         return ERR_INVALID_ARGUMENT;
8621                 }
8622
8623                 locals = mono_debug_lookup_locals (method);
8624                 if (!locals) {
8625                         if (CHECK_PROTOCOL_VERSION (2, 43)) {
8626                                 /* Scopes */
8627                                 buffer_add_int (buf, 1);
8628                                 buffer_add_int (buf, 0);
8629                                 buffer_add_int (buf, header->code_size);
8630                         }
8631                         buffer_add_int (buf, header->num_locals);
8632                         /* Types */
8633                         for (i = 0; i < header->num_locals; ++i) {
8634                                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8635                         }
8636                         /* Names */
8637                         for (i = 0; i < header->num_locals; ++i) {
8638                                 char lname [128];
8639                                 sprintf (lname, "V_%d", i);
8640                                 buffer_add_string (buf, lname);
8641                         }
8642                         /* Scopes */
8643                         for (i = 0; i < header->num_locals; ++i) {
8644                                 buffer_add_int (buf, 0);
8645                                 buffer_add_int (buf, header->code_size);
8646                         }
8647                 } else {
8648                         if (CHECK_PROTOCOL_VERSION (2, 43)) {
8649                                 /* Scopes */
8650                                 buffer_add_int (buf, locals->num_blocks);
8651                                 int last_start = 0;
8652                                 for (i = 0; i < locals->num_blocks; ++i) {
8653                                         buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8654                                         buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8655                                         last_start = locals->code_blocks [i].start_offset;
8656                                 }
8657                         }
8658
8659                         num_locals = locals->num_locals;
8660                         buffer_add_int (buf, num_locals);
8661
8662                         /* Types */
8663                         for (i = 0; i < num_locals; ++i) {
8664                                 g_assert (locals->locals [i].index < header->num_locals);
8665                                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8666                         }
8667                         /* Names */
8668                         for (i = 0; i < num_locals; ++i)
8669                                 buffer_add_string (buf, locals->locals [i].name);
8670                         /* Scopes */
8671                         for (i = 0; i < num_locals; ++i) {
8672                                 if (locals->locals [i].block) {
8673                                         buffer_add_int (buf, locals->locals [i].block->start_offset);
8674                                         buffer_add_int (buf, locals->locals [i].block->end_offset);
8675                                 } else {
8676                                         buffer_add_int (buf, 0);
8677                                         buffer_add_int (buf, header->code_size);
8678                                 }
8679                         }
8680                 }
8681                 mono_metadata_free_mh (header);
8682
8683                 if (locals)
8684                         mono_debug_free_locals (locals);
8685                 g_free (locals_map);
8686
8687                 break;
8688         }
8689         case CMD_METHOD_GET_INFO:
8690                 buffer_add_int (buf, method->flags);
8691                 buffer_add_int (buf, method->iflags);
8692                 buffer_add_int (buf, method->token);
8693                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8694                         guint8 attrs = 0;
8695                         if (method->is_generic)
8696                                 attrs |= (1 << 0);
8697                         if (mono_method_signature (method)->generic_param_count)
8698                                 attrs |= (1 << 1);
8699                         buffer_add_byte (buf, attrs);
8700                         if (method->is_generic || method->is_inflated) {
8701                                 MonoMethod *result;
8702
8703                                 if (method->is_generic) {
8704                                         result = method;
8705                                 } else {
8706                                         MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8707                                         
8708                                         result = imethod->declaring;
8709                                         if (imethod->context.class_inst) {
8710                                                 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8711                                                 /*Generic methods gets the context of the GTD.*/
8712                                                 if (mono_class_get_context (klass)) {
8713                                                         MonoError error;
8714                                                         result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8715                                                         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8716                                                 }
8717                                         }
8718                                 }
8719
8720                                 buffer_add_methodid (buf, domain, result);
8721                         } else {
8722                                 buffer_add_id (buf, 0);
8723                         }
8724                         if (CHECK_PROTOCOL_VERSION (2, 15)) {
8725                                 if (mono_method_signature (method)->generic_param_count) {
8726                                         int count, i;
8727
8728                                         if (method->is_inflated) {
8729                                                 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8730                                                 if (inst) {
8731                                                         count = inst->type_argc;
8732                                                         buffer_add_int (buf, count);
8733
8734                                                         for (i = 0; i < count; i++)
8735                                                                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8736                                                 } else {
8737                                                         buffer_add_int (buf, 0);
8738                                                 }
8739                                         } else if (method->is_generic) {
8740                                                 MonoGenericContainer *container = mono_method_get_generic_container (method);
8741
8742                                                 count = mono_method_signature (method)->generic_param_count;
8743                                                 buffer_add_int (buf, count);
8744                                                 for (i = 0; i < count; i++) {
8745                                                         MonoGenericParam *param = mono_generic_container_get_param (container, i);
8746                                                         MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
8747                                                         buffer_add_typeid (buf, domain, pklass);
8748                                                 }
8749                                         } else {
8750                                                 buffer_add_int (buf, 0);
8751                                         }
8752                                 } else {
8753                                         buffer_add_int (buf, 0);
8754                                 }
8755                         }
8756                 }
8757                 break;
8758         case CMD_METHOD_GET_BODY: {
8759                 MonoError error;
8760                 int i;
8761
8762                 header = mono_method_get_header_checked (method, &error);
8763                 if (!header) {
8764                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
8765                         buffer_add_int (buf, 0);
8766
8767                         if (CHECK_PROTOCOL_VERSION (2, 18))
8768                                 buffer_add_int (buf, 0);
8769                 } else {
8770                         buffer_add_int (buf, header->code_size);
8771                         for (i = 0; i < header->code_size; ++i)
8772                                 buffer_add_byte (buf, header->code [i]);
8773
8774                         if (CHECK_PROTOCOL_VERSION (2, 18)) {
8775                                 buffer_add_int (buf, header->num_clauses);
8776                                 for (i = 0; i < header->num_clauses; ++i) {
8777                                         MonoExceptionClause *clause = &header->clauses [i];
8778
8779                                         buffer_add_int (buf, clause->flags);
8780                                         buffer_add_int (buf, clause->try_offset);
8781                                         buffer_add_int (buf, clause->try_len);
8782                                         buffer_add_int (buf, clause->handler_offset);
8783                                         buffer_add_int (buf, clause->handler_len);
8784                                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8785                                                 buffer_add_typeid (buf, domain, clause->data.catch_class);
8786                                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8787                                                 buffer_add_int (buf, clause->data.filter_offset);
8788                                 }
8789                         }
8790
8791                         mono_metadata_free_mh (header);
8792                 }
8793
8794                 break;
8795         }
8796         case CMD_METHOD_RESOLVE_TOKEN: {
8797                 guint32 token = decode_int (p, &p, end);
8798
8799                 // FIXME: Generics
8800                 switch (mono_metadata_token_code (token)) {
8801                 case MONO_TOKEN_STRING: {
8802                         MonoError error;
8803                         MonoString *s;
8804                         char *s2;
8805
8806                         s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
8807                         mono_error_assert_ok (&error); /* FIXME don't swallow the error */
8808
8809                         s2 = mono_string_to_utf8_checked (s, &error);
8810                         mono_error_assert_ok (&error);
8811
8812                         buffer_add_byte (buf, TOKEN_TYPE_STRING);
8813                         buffer_add_string (buf, s2);
8814                         g_free (s2);
8815                         break;
8816                 }
8817                 default: {
8818                         MonoError error;
8819                         gpointer val;
8820                         MonoClass *handle_class;
8821
8822                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8823                                 val = mono_method_get_wrapper_data (method, token);
8824                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8825
8826                                 if (handle_class == NULL) {
8827                                         // Can't figure out the token type
8828                                         buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8829                                         break;
8830                                 }
8831                         } else {
8832                                 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8833                                 if (!val)
8834                                         g_error ("Could not load token due to %s", mono_error_get_message (&error));
8835                         }
8836
8837                         if (handle_class == mono_defaults.typehandle_class) {
8838                                 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8839                                 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8840                                         buffer_add_typeid (buf, domain, (MonoClass *) val);
8841                                 else
8842                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8843                         } else if (handle_class == mono_defaults.fieldhandle_class) {
8844                                 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8845                                 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8846                         } else if (handle_class == mono_defaults.methodhandle_class) {
8847                                 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8848                                 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8849                         } else if (handle_class == mono_defaults.string_class) {
8850                                 char *s;
8851
8852                                 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
8853                                 mono_error_assert_ok (&error);
8854                                 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8855                                 buffer_add_string (buf, s);
8856                                 g_free (s);
8857                         } else {
8858                                 g_assert_not_reached ();
8859                         }
8860                         break;
8861                 }
8862                 }
8863                 break;
8864         }
8865         case CMD_METHOD_GET_CATTRS: {
8866                 MonoError error;
8867                 MonoClass *attr_klass;
8868                 MonoCustomAttrInfo *cinfo;
8869
8870                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8871                 /* attr_klass can be NULL */
8872                 if (err != ERR_NONE)
8873                         return err;
8874
8875                 cinfo = mono_custom_attrs_from_method_checked (method, &error);
8876                 if (!is_ok (&error)) {
8877                         mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8878                         return ERR_LOADER_ERROR;
8879                 }
8880
8881                 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8882                 if (err != ERR_NONE)
8883                         return err;
8884                 break;
8885         }
8886         case CMD_METHOD_MAKE_GENERIC_METHOD: {
8887                 MonoError error;
8888                 MonoType **type_argv;
8889                 int i, type_argc;
8890                 MonoDomain *d;
8891                 MonoClass *klass;
8892                 MonoGenericInst *ginst;
8893                 MonoGenericContext tmp_context;
8894                 MonoMethod *inflated;
8895
8896                 type_argc = decode_int (p, &p, end);
8897                 type_argv = g_new0 (MonoType*, type_argc);
8898                 for (i = 0; i < type_argc; ++i) {
8899                         klass = decode_typeid (p, &p, end, &d, &err);
8900                         if (err != ERR_NONE) {
8901                                 g_free (type_argv);
8902                                 return err;
8903                         }
8904                         if (domain != d) {
8905                                 g_free (type_argv);
8906                                 return ERR_INVALID_ARGUMENT;
8907                         }
8908                         type_argv [i] = &klass->byval_arg;
8909                 }
8910                 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8911                 g_free (type_argv);
8912                 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8913                 tmp_context.method_inst = ginst;
8914
8915                 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8916                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8917                 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8918                         return ERR_INVALID_ARGUMENT;
8919                 buffer_add_methodid (buf, domain, inflated);
8920                 break;
8921         }
8922         default:
8923                 return ERR_NOT_IMPLEMENTED;
8924         }
8925
8926         return ERR_NONE;
8927 }
8928
8929 static ErrorCode
8930 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8931 {
8932         ErrorCode err;
8933         MonoDomain *old_domain;
8934         MonoDomain *domain;
8935         MonoMethod *method;
8936
8937         method = decode_methodid (p, &p, end, &domain, &err);
8938         if (err != ERR_NONE)
8939                 return err;
8940
8941         old_domain = mono_domain_get ();
8942
8943         mono_domain_set (domain, TRUE);
8944
8945         err = method_commands_internal (command, method, domain, p, end, buf);
8946
8947         mono_domain_set (old_domain, TRUE);
8948
8949         return err;
8950 }
8951
8952 static ErrorCode
8953 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8954 {
8955         int objid = decode_objid (p, &p, end);
8956         ErrorCode err;
8957         MonoThread *thread_obj;
8958         MonoInternalThread *thread;
8959
8960         err = get_object (objid, (MonoObject**)&thread_obj);
8961         if (err != ERR_NONE)
8962                 return err;
8963
8964         thread = THREAD_TO_INTERNAL (thread_obj);
8965            
8966         switch (command) {
8967         case CMD_THREAD_GET_NAME: {
8968                 guint32 name_len;
8969                 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8970
8971                 if (!s) {
8972                         buffer_add_int (buf, 0);
8973                 } else {
8974                         char *name;
8975                         glong len;
8976
8977                         name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8978                         g_assert (name);
8979                         buffer_add_int (buf, len);
8980                         buffer_add_data (buf, (guint8*)name, len);
8981                         g_free (s);
8982                 }
8983                 break;
8984         }
8985         case CMD_THREAD_GET_FRAME_INFO: {
8986                 DebuggerTlsData *tls;
8987                 int i, start_frame, length;
8988
8989                 // Wait for suspending if it already started
8990                 // FIXME: Races with suspend_count
8991                 while (!is_suspended ()) {
8992                         if (suspend_count)
8993                                 wait_for_suspend ();
8994                 }
8995                 /*
8996                 if (suspend_count)
8997                         wait_for_suspend ();
8998                 if (!is_suspended ())
8999                         return ERR_NOT_SUSPENDED;
9000                 */
9001
9002                 start_frame = decode_int (p, &p, end);
9003                 length = decode_int (p, &p, end);
9004
9005                 if (start_frame != 0 || length != -1)
9006                         return ERR_NOT_IMPLEMENTED;
9007
9008                 mono_loader_lock ();
9009                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9010                 mono_loader_unlock ();
9011                 g_assert (tls);
9012
9013                 compute_frame_info (thread, tls);
9014
9015                 buffer_add_int (buf, tls->frame_count);
9016                 for (i = 0; i < tls->frame_count; ++i) {
9017                         buffer_add_int (buf, tls->frames [i]->id);
9018                         buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9019                         buffer_add_int (buf, tls->frames [i]->il_offset);
9020                         /*
9021                          * Instead of passing the frame type directly to the client, we associate
9022                          * it with the previous frame using a set of flags. This avoids lots of
9023                          * conditional code in the client, since a frame whose type isn't 
9024                          * FRAME_TYPE_MANAGED has no method, location, etc.
9025                          */
9026                         buffer_add_byte (buf, tls->frames [i]->flags);
9027                 }
9028
9029                 break;
9030         }
9031         case CMD_THREAD_GET_STATE:
9032                 buffer_add_int (buf, thread->state);
9033                 break;
9034         case CMD_THREAD_GET_INFO:
9035                 buffer_add_byte (buf, thread->threadpool_thread);
9036                 break;
9037         case CMD_THREAD_GET_ID:
9038                 buffer_add_long (buf, (guint64)(gsize)thread);
9039                 break;
9040         case CMD_THREAD_GET_TID:
9041                 buffer_add_long (buf, (guint64)thread->tid);
9042                 break;
9043         case CMD_THREAD_SET_IP: {
9044                 DebuggerTlsData *tls;
9045                 MonoMethod *method;
9046                 MonoDomain *domain;
9047                 MonoSeqPointInfo *seq_points;
9048                 SeqPoint sp;
9049                 gboolean found_sp;
9050                 gint64 il_offset;
9051
9052                 method = decode_methodid (p, &p, end, &domain, &err);
9053                 if (err != ERR_NONE)
9054                         return err;
9055                 il_offset = decode_long (p, &p, end);
9056
9057                 while (!is_suspended ()) {
9058                         if (suspend_count)
9059                                 wait_for_suspend ();
9060                 }
9061
9062                 mono_loader_lock ();
9063                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9064                 mono_loader_unlock ();
9065                 g_assert (tls);
9066
9067                 compute_frame_info (thread, tls);
9068                 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9069                         return ERR_INVALID_ARGUMENT;
9070
9071                 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9072
9073                 g_assert (seq_points);
9074
9075                 if (!found_sp)
9076                         return ERR_INVALID_ARGUMENT;
9077
9078                 // FIXME: Check that the ip change is safe
9079
9080                 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);
9081                 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9082                 break;
9083         }
9084         default:
9085                 return ERR_NOT_IMPLEMENTED;
9086         }
9087
9088         return ERR_NONE;
9089 }
9090
9091 static ErrorCode
9092 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9093 {
9094         int objid;
9095         ErrorCode err;
9096         MonoThread *thread_obj;
9097         MonoInternalThread *thread;
9098         int pos, i, len, frame_idx;
9099         DebuggerTlsData *tls;
9100         StackFrame *frame;
9101         MonoDebugMethodJitInfo *jit;
9102         MonoMethodSignature *sig;
9103         gssize id;
9104         MonoMethodHeader *header;
9105
9106         objid = decode_objid (p, &p, end);
9107         err = get_object (objid, (MonoObject**)&thread_obj);
9108         if (err != ERR_NONE)
9109                 return err;
9110
9111         thread = THREAD_TO_INTERNAL (thread_obj);
9112
9113         id = decode_id (p, &p, end);
9114
9115         mono_loader_lock ();
9116         tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9117         mono_loader_unlock ();
9118         g_assert (tls);
9119
9120         for (i = 0; i < tls->frame_count; ++i) {
9121                 if (tls->frames [i]->id == id)
9122                         break;
9123         }
9124         if (i == tls->frame_count)
9125                 return ERR_INVALID_FRAMEID;
9126
9127         frame_idx = i;
9128         frame = tls->frames [frame_idx];
9129
9130         /* This is supported for frames without has_ctx etc. set */
9131         if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9132                 if (CHECK_PROTOCOL_VERSION (2, 38))
9133                         buffer_add_domainid (buf, frame->domain);
9134                 return ERR_NONE;
9135         }
9136
9137         if (!frame->has_ctx)
9138                 return ERR_ABSENT_INFORMATION;
9139
9140         if (!frame->jit) {
9141                 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
9142                 if (!frame->jit && frame->api_method->is_inflated)
9143                         frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
9144                 if (!frame->jit) {
9145                         char *s;
9146
9147                         /* This could happen for aot images with no jit debug info */
9148                         s = mono_method_full_name (frame->api_method, TRUE);
9149                         DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
9150                         g_free (s);
9151                         return ERR_ABSENT_INFORMATION;
9152                 }
9153         }
9154         jit = frame->jit;
9155
9156         sig = mono_method_signature (frame->actual_method);
9157
9158         if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9159                 /*
9160                  * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9161                  */
9162                 return ERR_ABSENT_INFORMATION;
9163
9164         switch (command) {
9165         case CMD_STACK_FRAME_GET_VALUES: {
9166                 MonoError error;
9167                 len = decode_int (p, &p, end);
9168                 header = mono_method_get_header_checked (frame->actual_method, &error);
9169                 mono_error_assert_ok (&error); /* FIXME report error */
9170
9171                 for (i = 0; i < len; ++i) {
9172                         pos = decode_int (p, &p, end);
9173
9174                         if (pos < 0) {
9175                                 pos = - pos - 1;
9176
9177                                 DEBUG_PRINTF (4, "[dbg]   send arg %d.\n", pos);
9178
9179                                 g_assert (pos >= 0 && pos < jit->num_params);
9180
9181                                 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9182                         } else {
9183                                 MonoDebugLocalsInfo *locals;
9184
9185                                 locals = mono_debug_lookup_locals (frame->method);
9186                                 if (locals) {
9187                                         g_assert (pos < locals->num_locals);
9188                                         pos = locals->locals [pos].index;
9189                                         mono_debug_free_locals (locals);
9190                                 }
9191                                 g_assert (pos >= 0 && pos < jit->num_locals);
9192
9193                                 DEBUG_PRINTF (4, "[dbg]   send local %d.\n", pos);
9194
9195                                 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9196                         }
9197                 }
9198                 mono_metadata_free_mh (header);
9199                 break;
9200         }
9201         case CMD_STACK_FRAME_GET_THIS: {
9202                 if (frame->api_method->klass->valuetype) {
9203                         if (!sig->hasthis) {
9204                                 MonoObject *p = NULL;
9205                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9206                         } else {
9207                                 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9208                         }
9209                 } else {
9210                         if (!sig->hasthis) {
9211                                 MonoObject *p = NULL;
9212                                 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9213                         } else {
9214                                 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9215                         }
9216                 }
9217                 break;
9218         }
9219         case CMD_STACK_FRAME_SET_VALUES: {
9220                 MonoError error;
9221                 guint8 *val_buf;
9222                 MonoType *t;
9223                 MonoDebugVarInfo *var;
9224
9225                 len = decode_int (p, &p, end);
9226                 header = mono_method_get_header_checked (frame->actual_method, &error);
9227                 mono_error_assert_ok (&error); /* FIXME report error */
9228
9229                 for (i = 0; i < len; ++i) {
9230                         pos = decode_int (p, &p, end);
9231
9232                         if (pos < 0) {
9233                                 pos = - pos - 1;
9234
9235                                 g_assert (pos >= 0 && pos < jit->num_params);
9236
9237                                 t = sig->params [pos];
9238                                 var = &jit->params [pos];
9239                         } else {
9240                                 MonoDebugLocalsInfo *locals;
9241
9242                                 locals = mono_debug_lookup_locals (frame->method);
9243                                 if (locals) {
9244                                         g_assert (pos < locals->num_locals);
9245                                         pos = locals->locals [pos].index;
9246                                         mono_debug_free_locals (locals);
9247                                 }
9248                                 g_assert (pos >= 0 && pos < jit->num_locals);
9249
9250                                 t = header->locals [pos];
9251                                 var = &jit->locals [pos];
9252                         }
9253
9254                         if (MONO_TYPE_IS_REFERENCE (t))
9255                                 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9256                         else
9257                                 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9258                         err = decode_value (t, frame->domain, val_buf, p, &p, end);
9259                         if (err != ERR_NONE)
9260                                 return err;
9261
9262                         set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9263                 }
9264                 mono_metadata_free_mh (header);
9265                 break;
9266         }
9267         case CMD_STACK_FRAME_GET_DOMAIN: {
9268                 if (CHECK_PROTOCOL_VERSION (2, 38))
9269                         buffer_add_domainid (buf, frame->domain);
9270                 break;
9271         }
9272         default:
9273                 return ERR_NOT_IMPLEMENTED;
9274         }
9275
9276         return ERR_NONE;
9277 }
9278
9279 static ErrorCode
9280 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9281 {
9282         MonoArray *arr;
9283         int objid, index, len, i, esize;
9284         ErrorCode err;
9285         gpointer elem;
9286
9287         objid = decode_objid (p, &p, end);
9288         err = get_object (objid, (MonoObject**)&arr);
9289         if (err != ERR_NONE)
9290                 return err;
9291
9292         switch (command) {
9293         case CMD_ARRAY_REF_GET_LENGTH:
9294                 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9295                 if (!arr->bounds) {
9296                         buffer_add_int (buf, arr->max_length);
9297                         buffer_add_int (buf, 0);
9298                 } else {
9299                         for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9300                                 buffer_add_int (buf, arr->bounds [i].length);
9301                                 buffer_add_int (buf, arr->bounds [i].lower_bound);
9302                         }
9303                 }
9304                 break;
9305         case CMD_ARRAY_REF_GET_VALUES:
9306                 index = decode_int (p, &p, end);
9307                 len = decode_int (p, &p, end);
9308
9309                 g_assert (index >= 0 && len >= 0);
9310                 // Reordered to avoid integer overflow
9311                 g_assert (!(index > arr->max_length - len));
9312
9313                 esize = mono_array_element_size (arr->obj.vtable->klass);
9314                 for (i = index; i < index + len; ++i) {
9315                         elem = (gpointer*)((char*)arr->vector + (i * esize));
9316                         buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9317                 }
9318                 break;
9319         case CMD_ARRAY_REF_SET_VALUES:
9320                 index = decode_int (p, &p, end);
9321                 len = decode_int (p, &p, end);
9322
9323                 g_assert (index >= 0 && len >= 0);
9324                 // Reordered to avoid integer overflow
9325                 g_assert (!(index > arr->max_length - len));
9326
9327                 esize = mono_array_element_size (arr->obj.vtable->klass);
9328                 for (i = index; i < index + len; ++i) {
9329                         elem = (gpointer*)((char*)arr->vector + (i * esize));
9330
9331                         decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9332                 }
9333                 break;
9334         default:
9335                 return ERR_NOT_IMPLEMENTED;
9336         }
9337
9338         return ERR_NONE;
9339 }
9340
9341 static ErrorCode
9342 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9343 {
9344         int objid;
9345         ErrorCode err;
9346         MonoString *str;
9347         char *s;
9348         int i, index, length;
9349         gunichar2 *c;
9350         gboolean use_utf16 = FALSE;
9351
9352         objid = decode_objid (p, &p, end);
9353         err = get_object (objid, (MonoObject**)&str);
9354         if (err != ERR_NONE)
9355                 return err;
9356
9357         switch (command) {
9358         case CMD_STRING_REF_GET_VALUE:
9359                 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9360                         for (i = 0; i < mono_string_length (str); ++i)
9361                                 if (mono_string_chars (str)[i] == 0)
9362                                         use_utf16 = TRUE;
9363                         buffer_add_byte (buf, use_utf16 ? 1 : 0);
9364                 }
9365                 if (use_utf16) {
9366                         buffer_add_int (buf, mono_string_length (str) * 2);
9367                         buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9368                 } else {
9369                         MonoError error;
9370                         s = mono_string_to_utf8_checked (str, &error);
9371                         mono_error_assert_ok (&error);
9372                         buffer_add_string (buf, s);
9373                         g_free (s);
9374                 }
9375                 break;
9376         case CMD_STRING_REF_GET_LENGTH:
9377                 buffer_add_long (buf, mono_string_length (str));
9378                 break;
9379         case CMD_STRING_REF_GET_CHARS:
9380                 index = decode_long (p, &p, end);
9381                 length = decode_long (p, &p, end);
9382                 if (index > mono_string_length (str) - length)
9383                         return ERR_INVALID_ARGUMENT;
9384                 c = mono_string_chars (str) + index;
9385                 for (i = 0; i < length; ++i)
9386                         buffer_add_short (buf, c [i]);
9387                 break;
9388         default:
9389                 return ERR_NOT_IMPLEMENTED;
9390         }
9391
9392         return ERR_NONE;
9393 }
9394
9395 static ErrorCode
9396 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9397 {
9398         MonoError error;
9399         int objid;
9400         ErrorCode err;
9401         MonoObject *obj;
9402         int len, i;
9403         MonoClassField *f;
9404         MonoClass *k;
9405         gboolean found;
9406
9407         if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9408                 objid = decode_objid (p, &p, end);
9409                 err = get_object (objid, &obj);
9410                 if (err != ERR_NONE)
9411                         buffer_add_int (buf, 1);
9412                 else
9413                         buffer_add_int (buf, 0);
9414                 return ERR_NONE;
9415         }
9416
9417         objid = decode_objid (p, &p, end);
9418         err = get_object (objid, &obj);
9419         if (err != ERR_NONE)
9420                 return err;
9421
9422         MonoClass *obj_type;
9423         gboolean remote_obj = FALSE;
9424
9425         obj_type = obj->vtable->klass;
9426         if (mono_class_is_transparent_proxy (obj_type)) {
9427                 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9428                 remote_obj = TRUE;
9429         }
9430
9431         g_assert (obj_type);
9432
9433         switch (command) {
9434         case CMD_OBJECT_REF_GET_TYPE:
9435                 /* This handles transparent proxies too */
9436                 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9437                 break;
9438         case CMD_OBJECT_REF_GET_VALUES:
9439                 len = decode_int (p, &p, end);
9440
9441                 for (i = 0; i < len; ++i) {
9442                         MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9443                         if (err != ERR_NONE)
9444                                 return err;
9445
9446                         /* Check that the field belongs to the object */
9447                         found = FALSE;
9448                         for (k = obj_type; k; k = k->parent) {
9449                                 if (k == f->parent) {
9450                                         found = TRUE;
9451                                         break;
9452                                 }
9453                         }
9454                         if (!found)
9455                                 return ERR_INVALID_FIELDID;
9456
9457                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9458                                 guint8 *val;
9459                                 MonoVTable *vtable;
9460
9461                                 if (mono_class_field_is_special_static (f))
9462                                         return ERR_INVALID_FIELDID;
9463
9464                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9465                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9466                                 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9467                                 mono_field_static_get_value_checked (vtable, f, val, &error);
9468                                 if (!is_ok (&error)) {
9469                                         mono_error_cleanup (&error); /* FIXME report the error */
9470                                         return ERR_INVALID_OBJECT;
9471                                 }
9472                                 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9473                                 g_free (val);
9474                         } else {
9475                                 guint8 *field_value = NULL;
9476
9477                                 if (remote_obj) {
9478 #ifndef DISABLE_REMOTING
9479                                         void *field_storage = NULL;
9480                                         field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9481                                         if (!is_ok (&error)) {
9482                                                 mono_error_cleanup (&error); /* FIXME report the error */
9483                                                 return ERR_INVALID_OBJECT;
9484                                         }
9485 #else
9486                                         g_assert_not_reached ();
9487 #endif
9488                                 } else
9489                                         field_value = (guint8*)obj + f->offset;
9490
9491                                 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9492                         }
9493                 }
9494                 break;
9495         case CMD_OBJECT_REF_SET_VALUES:
9496                 len = decode_int (p, &p, end);
9497
9498                 for (i = 0; i < len; ++i) {
9499                         f = decode_fieldid (p, &p, end, NULL, &err);
9500                         if (err != ERR_NONE)
9501                                 return err;
9502
9503                         /* Check that the field belongs to the object */
9504                         found = FALSE;
9505                         for (k = obj_type; k; k = k->parent) {
9506                                 if (k == f->parent) {
9507                                         found = TRUE;
9508                                         break;
9509                                 }
9510                         }
9511                         if (!found)
9512                                 return ERR_INVALID_FIELDID;
9513
9514                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9515                                 guint8 *val;
9516                                 MonoVTable *vtable;
9517
9518                                 if (mono_class_field_is_special_static (f))
9519                                         return ERR_INVALID_FIELDID;
9520
9521                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9522                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9523
9524                                 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9525                                 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9526                                 if (err != ERR_NONE) {
9527                                         g_free (val);
9528                                         return err;
9529                                 }
9530                                 mono_field_static_set_value (vtable, f, val);
9531                                 g_free (val);
9532                         } else {
9533                                 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9534                                 if (err != ERR_NONE)
9535                                         return err;
9536                         }
9537                 }
9538                 break;
9539         case CMD_OBJECT_REF_GET_ADDRESS:
9540                 buffer_add_long (buf, (gssize)obj);
9541                 break;
9542         case CMD_OBJECT_REF_GET_DOMAIN:
9543                 buffer_add_domainid (buf, obj->vtable->domain);
9544                 break;
9545         case CMD_OBJECT_REF_GET_INFO:
9546                 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9547                 buffer_add_domainid (buf, obj->vtable->domain);
9548                 break;
9549         default:
9550                 return ERR_NOT_IMPLEMENTED;
9551         }
9552
9553         return ERR_NONE;
9554 }
9555
9556 static const char*
9557 command_set_to_string (CommandSet command_set)
9558 {
9559         switch (command_set) {
9560         case CMD_SET_VM:
9561                 return "VM";
9562         case CMD_SET_OBJECT_REF:
9563                 return "OBJECT_REF";
9564         case CMD_SET_STRING_REF:
9565                 return "STRING_REF";
9566         case CMD_SET_THREAD:
9567                 return "THREAD";
9568         case CMD_SET_ARRAY_REF:
9569                 return "ARRAY_REF";
9570         case CMD_SET_EVENT_REQUEST:
9571                 return "EVENT_REQUEST";
9572         case CMD_SET_STACK_FRAME:
9573                 return "STACK_FRAME";
9574         case CMD_SET_APPDOMAIN:
9575                 return "APPDOMAIN";
9576         case CMD_SET_ASSEMBLY:
9577                 return "ASSEMBLY";
9578         case CMD_SET_METHOD:
9579                 return "METHOD";
9580         case CMD_SET_TYPE:
9581                 return "TYPE";
9582         case CMD_SET_MODULE:
9583                 return "MODULE";
9584         case CMD_SET_FIELD:
9585                 return "FIELD";
9586         case CMD_SET_EVENT:
9587                 return "EVENT";
9588         default:
9589                 return "";
9590         }
9591 }
9592
9593 static const char* vm_cmds_str [] = {
9594         "VERSION",
9595         "ALL_THREADS",
9596         "SUSPEND",
9597         "RESUME",
9598         "EXIT",
9599         "DISPOSE",
9600         "INVOKE_METHOD",
9601         "SET_PROTOCOL_VERSION",
9602         "ABORT_INVOKE",
9603         "SET_KEEPALIVE"
9604         "GET_TYPES_FOR_SOURCE_FILE",
9605         "GET_TYPES",
9606         "INVOKE_METHODS"
9607 };
9608
9609 static const char* thread_cmds_str[] = {
9610         "GET_FRAME_INFO",
9611         "GET_NAME",
9612         "GET_STATE",
9613         "GET_INFO",
9614         "GET_ID",
9615         "GET_TID",
9616         "SET_IP"
9617 };
9618
9619 static const char* event_cmds_str[] = {
9620         "REQUEST_SET",
9621         "REQUEST_CLEAR",
9622         "REQUEST_CLEAR_ALL_BREAKPOINTS"
9623 };
9624
9625 static const char* appdomain_cmds_str[] = {
9626         "GET_ROOT_DOMAIN",
9627         "GET_FRIENDLY_NAME",
9628         "GET_ASSEMBLIES",
9629         "GET_ENTRY_ASSEMBLY",
9630         "CREATE_STRING",
9631         "GET_CORLIB",
9632         "CREATE_BOXED_VALUE"
9633 };
9634
9635 static const char* assembly_cmds_str[] = {
9636         "GET_LOCATION",
9637         "GET_ENTRY_POINT",
9638         "GET_MANIFEST_MODULE",
9639         "GET_OBJECT",
9640         "GET_TYPE",
9641         "GET_NAME"
9642 };
9643
9644 static const char* module_cmds_str[] = {
9645         "GET_INFO",
9646 };
9647
9648 static const char* field_cmds_str[] = {
9649         "GET_INFO",
9650 };
9651
9652 static const char* method_cmds_str[] = {
9653         "GET_NAME",
9654         "GET_DECLARING_TYPE",
9655         "GET_DEBUG_INFO",
9656         "GET_PARAM_INFO",
9657         "GET_LOCALS_INFO",
9658         "GET_INFO",
9659         "GET_BODY",
9660         "RESOLVE_TOKEN",
9661         "GET_CATTRS ",
9662         "MAKE_GENERIC_METHOD"
9663 };
9664
9665 static const char* type_cmds_str[] = {
9666         "GET_INFO",
9667         "GET_METHODS",
9668         "GET_FIELDS",
9669         "GET_VALUES",
9670         "GET_OBJECT",
9671         "GET_SOURCE_FILES",
9672         "SET_VALUES",
9673         "IS_ASSIGNABLE_FROM",
9674         "GET_PROPERTIES ",
9675         "GET_CATTRS",
9676         "GET_FIELD_CATTRS",
9677         "GET_PROPERTY_CATTRS",
9678         "GET_SOURCE_FILES_2",
9679         "GET_VALUES_2",
9680         "GET_METHODS_BY_NAME_FLAGS",
9681         "GET_INTERFACES",
9682         "GET_INTERFACE_MAP",
9683         "IS_INITIALIZED"
9684 };
9685
9686 static const char* stack_frame_cmds_str[] = {
9687         "GET_VALUES",
9688         "GET_THIS",
9689         "SET_VALUES",
9690         "GET_DOMAIN",
9691 };
9692
9693 static const char* array_cmds_str[] = {
9694         "GET_LENGTH",
9695         "GET_VALUES",
9696         "SET_VALUES",
9697 };
9698
9699 static const char* string_cmds_str[] = {
9700         "GET_VALUE",
9701         "GET_LENGTH",
9702         "GET_CHARS"
9703 };
9704
9705 static const char* object_cmds_str[] = {
9706         "GET_TYPE",
9707         "GET_VALUES",
9708         "IS_COLLECTED",
9709         "GET_ADDRESS",
9710         "GET_DOMAIN",
9711         "SET_VALUES",
9712         "GET_INFO",
9713 };
9714
9715 static const char*
9716 cmd_to_string (CommandSet set, int command)
9717 {
9718         const char **cmds;
9719         int cmds_len = 0;
9720
9721         switch (set) {
9722         case CMD_SET_VM:
9723                 cmds = vm_cmds_str;
9724                 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9725                 break;
9726         case CMD_SET_OBJECT_REF:
9727                 cmds = object_cmds_str;
9728                 cmds_len = G_N_ELEMENTS (object_cmds_str);
9729                 break;
9730         case CMD_SET_STRING_REF:
9731                 cmds = string_cmds_str;
9732                 cmds_len = G_N_ELEMENTS (string_cmds_str);
9733                 break;
9734         case CMD_SET_THREAD:
9735                 cmds = thread_cmds_str;
9736                 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9737                 break;
9738         case CMD_SET_ARRAY_REF:
9739                 cmds = array_cmds_str;
9740                 cmds_len = G_N_ELEMENTS (array_cmds_str);
9741                 break;
9742         case CMD_SET_EVENT_REQUEST:
9743                 cmds = event_cmds_str;
9744                 cmds_len = G_N_ELEMENTS (event_cmds_str);
9745                 break;
9746         case CMD_SET_STACK_FRAME:
9747                 cmds = stack_frame_cmds_str;
9748                 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9749                 break;
9750         case CMD_SET_APPDOMAIN:
9751                 cmds = appdomain_cmds_str;
9752                 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9753                 break;
9754         case CMD_SET_ASSEMBLY:
9755                 cmds = assembly_cmds_str;
9756                 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9757                 break;
9758         case CMD_SET_METHOD:
9759                 cmds = method_cmds_str;
9760                 cmds_len = G_N_ELEMENTS (method_cmds_str);
9761                 break;
9762         case CMD_SET_TYPE:
9763                 cmds = type_cmds_str;
9764                 cmds_len = G_N_ELEMENTS (type_cmds_str);
9765                 break;
9766         case CMD_SET_MODULE:
9767                 cmds = module_cmds_str;
9768                 cmds_len = G_N_ELEMENTS (module_cmds_str);
9769                 break;
9770         case CMD_SET_FIELD:
9771                 cmds = field_cmds_str;
9772                 cmds_len = G_N_ELEMENTS (field_cmds_str);
9773                 break;
9774         case CMD_SET_EVENT:
9775                 cmds = event_cmds_str;
9776                 cmds_len = G_N_ELEMENTS (event_cmds_str);
9777                 break;
9778         default:
9779                 return NULL;
9780         }
9781         if (command > 0 && command <= cmds_len)
9782                 return cmds [command - 1];
9783         else
9784                 return NULL;
9785 }
9786
9787 static gboolean
9788 wait_for_attach (void)
9789 {
9790 #ifndef DISABLE_SOCKET_TRANSPORT
9791         if (listen_fd == -1) {
9792                 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9793                 return FALSE;
9794         }
9795
9796         /* Block and wait for client connection */
9797         conn_fd = socket_transport_accept (listen_fd);
9798
9799         DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9800         if (conn_fd == -1) {
9801                 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9802                 return FALSE;
9803         }
9804 #else
9805         g_assert_not_reached ();
9806 #endif
9807
9808         /* Handshake */
9809         disconnected = !transport_handshake ();
9810         if (disconnected) {
9811                 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9812                 return FALSE;
9813         }
9814         
9815         return TRUE;
9816 }
9817
9818 /*
9819  * debugger_thread:
9820  *
9821  *   This thread handles communication with the debugger client using a JDWP
9822  * like protocol.
9823  */
9824 static gsize WINAPI
9825 debugger_thread (void *arg)
9826 {
9827         MonoError error;
9828         int res, len, id, flags, command = 0;
9829         CommandSet command_set = (CommandSet)0;
9830         guint8 header [HEADER_LENGTH];
9831         guint8 *data, *p, *end;
9832         Buffer buf;
9833         ErrorCode err;
9834         gboolean no_reply;
9835         gboolean attach_failed = FALSE;
9836
9837         DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9838
9839         debugger_thread_id = mono_native_thread_id_get ();
9840
9841         MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
9842         mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, &error);
9843         mono_error_assert_ok (&error);
9844
9845         thread->internal_thread->state |= ThreadState_Background;
9846         thread->internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9847
9848         if (agent_config.defer) {
9849                 if (!wait_for_attach ()) {
9850                         DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9851                         attach_failed = TRUE; // Don't abort process when we can't listen
9852                 } else {
9853                         mono_set_is_debugger_attached (TRUE);
9854                         /* Send start event to client */
9855                         process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9856                 }
9857         } else {
9858                 mono_set_is_debugger_attached (TRUE);
9859         }
9860         
9861         while (!attach_failed) {
9862                 res = transport_recv (header, HEADER_LENGTH);
9863
9864                 /* This will break if the socket is closed during shutdown too */
9865                 if (res != HEADER_LENGTH) {
9866                         DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9867                         break;
9868                 }
9869
9870                 p = header;
9871                 end = header + HEADER_LENGTH;
9872
9873                 len = decode_int (p, &p, end);
9874                 id = decode_int (p, &p, end);
9875                 flags = decode_byte (p, &p, end);
9876                 command_set = (CommandSet)decode_byte (p, &p, end);
9877                 command = decode_byte (p, &p, end);
9878
9879                 g_assert (flags == 0);
9880
9881                 if (log_level) {
9882                         const char *cmd_str;
9883                         char cmd_num [256];
9884
9885                         cmd_str = cmd_to_string (command_set, command);
9886                         if (!cmd_str) {
9887                                 sprintf (cmd_num, "%d", command);
9888                                 cmd_str = cmd_num;
9889                         }
9890                         
9891                         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);
9892                 }
9893
9894                 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
9895                 if (len - HEADER_LENGTH > 0)
9896                 {
9897                         res = transport_recv (data, len - HEADER_LENGTH);
9898                         if (res != len - HEADER_LENGTH) {
9899                                 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9900                                 break;
9901                         }
9902                 }
9903
9904                 p = data;
9905                 end = data + (len - HEADER_LENGTH);
9906
9907                 buffer_init (&buf, 128);
9908
9909                 err = ERR_NONE;
9910                 no_reply = FALSE;
9911
9912                 /* Process the request */
9913                 switch (command_set) {
9914                 case CMD_SET_VM:
9915                         err = vm_commands (command, id, p, end, &buf);
9916                         if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
9917                                 /* Sent after the invoke is complete */
9918                                 no_reply = TRUE;
9919                         break;
9920                 case CMD_SET_EVENT_REQUEST:
9921                         err = event_commands (command, p, end, &buf);
9922                         break;
9923                 case CMD_SET_APPDOMAIN:
9924                         err = domain_commands (command, p, end, &buf);
9925                         break;
9926                 case CMD_SET_ASSEMBLY:
9927                         err = assembly_commands (command, p, end, &buf);
9928                         break;
9929                 case CMD_SET_MODULE:
9930                         err = module_commands (command, p, end, &buf);
9931                         break;
9932                 case CMD_SET_FIELD:
9933                         err = field_commands (command, p, end, &buf);
9934                         break;
9935                 case CMD_SET_TYPE:
9936                         err = type_commands (command, p, end, &buf);
9937                         break;
9938                 case CMD_SET_METHOD:
9939                         err = method_commands (command, p, end, &buf);
9940                         break;
9941                 case CMD_SET_THREAD:
9942                         err = thread_commands (command, p, end, &buf);
9943                         break;
9944                 case CMD_SET_STACK_FRAME:
9945                         err = frame_commands (command, p, end, &buf);
9946                         break;
9947                 case CMD_SET_ARRAY_REF:
9948                         err = array_commands (command, p, end, &buf);
9949                         break;
9950                 case CMD_SET_STRING_REF:
9951                         err = string_commands (command, p, end, &buf);
9952                         break;
9953                 case CMD_SET_OBJECT_REF:
9954                         err = object_commands (command, p, end, &buf);
9955                         break;
9956                 default:
9957                         err = ERR_NOT_IMPLEMENTED;
9958                 }               
9959
9960                 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9961                         buffer_replies = TRUE;
9962                 }
9963
9964                 if (!no_reply) {
9965                         if (buffer_replies) {
9966                                 buffer_reply_packet (id, err, &buf);
9967                         } else {
9968                                 send_reply_packet (id, err, &buf);
9969                                 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9970                         }
9971                 }
9972
9973                 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9974                         send_buffered_reply_packets ();
9975                         buffer_replies = FALSE;
9976                 }
9977
9978                 g_free (data);
9979                 buffer_free (&buf);
9980
9981                 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9982                         break;
9983         }
9984
9985         mono_set_is_debugger_attached (FALSE);
9986
9987         mono_coop_mutex_lock (&debugger_thread_exited_mutex);
9988         debugger_thread_exited = TRUE;
9989         mono_coop_cond_signal (&debugger_thread_exited_cond);
9990         mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
9991
9992         DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9993         
9994         if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9995                 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9996                 start_debugger_thread ();
9997         }
9998
9999         return 0;
10000 }
10001
10002 #else /* DISABLE_DEBUGGER_AGENT */
10003
10004 void
10005 mono_debugger_agent_parse_options (char *options)
10006 {
10007         g_error ("This runtime is configured with the debugger agent disabled.");
10008 }
10009
10010 void
10011 mono_debugger_agent_init (void)
10012 {
10013 }
10014
10015 void
10016 mono_debugger_agent_breakpoint_hit (void *sigctx)
10017 {
10018 }
10019
10020 void
10021 mono_debugger_agent_single_step_event (void *sigctx)
10022 {
10023 }
10024
10025 void
10026 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10027 {
10028 }
10029
10030 void
10031 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10032                                                                           MonoContext *catch_ctx)
10033 {
10034 }
10035
10036 void
10037 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10038 {
10039 }
10040
10041 void
10042 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10043 {
10044 }
10045
10046 void
10047 mono_debugger_agent_user_break (void)
10048 {
10049         G_BREAKPOINT ();
10050 }
10051
10052 void
10053 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10054 {
10055 }
10056
10057 gboolean
10058 mono_debugger_agent_debug_log_is_enabled (void)
10059 {
10060         return FALSE;
10061 }
10062
10063 void
10064 mono_debugger_agent_unhandled_exception (MonoException *exc)
10065 {
10066         g_assert_not_reached ();
10067 }
10068
10069 void
10070 debugger_agent_single_step_from_context (MonoContext *ctx)
10071 {
10072         g_assert_not_reached ();
10073 }
10074
10075 void
10076 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10077 {
10078         g_assert_not_reached ();
10079 }
10080
10081 #endif