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