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