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