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