Merge pull request #2698 from esdrubal/iosxmlarray
[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_checked 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         MonoError error;
3327         MonoCustomAttrInfo *ainfo;
3328
3329         if (ji->dbg_attrs_inited)
3330                 return;
3331
3332         if (!hidden_klass)
3333                 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3334
3335         if (!step_through_klass)
3336                 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3337
3338         if (!non_user_klass)
3339                 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3340
3341         ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3342         mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3343         if (ainfo) {
3344                 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3345                         ji->dbg_hidden = TRUE;
3346                 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3347                         ji->dbg_step_through = TRUE;
3348                 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3349                         ji->dbg_non_user_code = TRUE;
3350                 mono_custom_attrs_free (ainfo);
3351         }
3352
3353         ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3354         mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3355         if (ainfo) {
3356                 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3357                         ji->dbg_step_through = TRUE;
3358                 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3359                         ji->dbg_non_user_code = TRUE;
3360                 mono_custom_attrs_free (ainfo);
3361         }
3362
3363         mono_memory_barrier ();
3364         ji->dbg_attrs_inited = TRUE;
3365 }
3366
3367 /*
3368  * EVENT HANDLING
3369  */
3370
3371 /*
3372  * create_event_list:
3373  *
3374  *   Return a list of event request ids matching EVENT, starting from REQS, which
3375  * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3376  * policy.
3377  * We return request ids, instead of requests, to simplify threading, since 
3378  * requests could be deleted anytime when the loader lock is not held.
3379  * LOCKING: Assumes the loader lock is held.
3380  */
3381 static GSList*
3382 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3383 {
3384         int i, j;
3385         GSList *events = NULL;
3386
3387         *suspend_policy = SUSPEND_POLICY_NONE;
3388
3389         if (!reqs)
3390                 reqs = event_requests;
3391
3392         if (!reqs)
3393                 return NULL;
3394
3395         for (i = 0; i < reqs->len; ++i) {
3396                 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3397                 if (req->event_kind == event) {
3398                         gboolean filtered = FALSE;
3399
3400                         /* Apply filters */
3401                         for (j = 0; j < req->nmodifiers; ++j) {
3402                                 Modifier *mod = &req->modifiers [j];
3403
3404                                 if (mod->kind == MOD_KIND_COUNT) {
3405                                         filtered = TRUE;
3406                                         if (mod->data.count > 0) {
3407                                                 if (mod->data.count > 0) {
3408                                                         mod->data.count --;
3409                                                         if (mod->data.count == 0)
3410                                                                 filtered = FALSE;
3411                                                 }
3412                                         }
3413                                 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3414                                         if (mod->data.thread != mono_thread_internal_current ())
3415                                                 filtered = TRUE;
3416                                 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3417                                         if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3418                                                 filtered = TRUE;
3419                                         if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3420                                                 filtered = TRUE;
3421                                         if (ei->caught && !mod->caught)
3422                                                 filtered = TRUE;
3423                                         if (!ei->caught && !mod->uncaught)
3424                                                 filtered = TRUE;
3425                                 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3426                                         int k;
3427                                         gboolean found = FALSE;
3428                                         MonoAssembly **assemblies = mod->data.assemblies;
3429
3430                                         if (assemblies) {
3431                                                 for (k = 0; assemblies [k]; ++k)
3432                                                         if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3433                                                                 found = TRUE;
3434                                         }
3435                                         if (!found)
3436                                                 filtered = TRUE;
3437                                 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3438                                         gpointer iter = NULL;
3439                                         MonoMethod *method;
3440                                         MonoDebugSourceInfo *sinfo;
3441                                         char *source_file, *s;
3442                                         gboolean found = FALSE;
3443                                         int i;
3444                                         GPtrArray *source_file_list;
3445
3446                                         while ((method = mono_class_get_methods (ei->klass, &iter))) {
3447                                                 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3448
3449                                                 if (minfo) {
3450                                                         mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3451                                                         for (i = 0; i < source_file_list->len; ++i) {
3452                                                                 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3453                                                                 /*
3454                                                                  * Do a case-insesitive match by converting the file name to
3455                                                                  * lowercase.
3456                                                                  */
3457                                                                 s = strdup_tolower (sinfo->source_file);
3458                                                                 if (g_hash_table_lookup (mod->data.source_files, s))
3459                                                                         found = TRUE;
3460                                                                 else {
3461                                                                         char *s2 = dbg_path_get_basename (sinfo->source_file);
3462                                                                         char *s3 = strdup_tolower (s2);
3463
3464                                                                         if (g_hash_table_lookup (mod->data.source_files, s3))
3465                                                                                 found = TRUE;
3466                                                                         g_free (s2);
3467                                                                         g_free (s3);
3468                                                                 }
3469                                                                 g_free (s);
3470                                                         }
3471                                                         g_ptr_array_free (source_file_list, TRUE);
3472                                                 }
3473                                         }
3474                                         if (!found)
3475                                                 filtered = TRUE;
3476                                 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3477                                         char *s;
3478
3479                                         s = mono_type_full_name (&ei->klass->byval_arg);
3480                                         if (!g_hash_table_lookup (mod->data.type_names, s))
3481                                                 filtered = TRUE;
3482                                         g_free (s);
3483                                 } else if (mod->kind == MOD_KIND_STEP) {
3484                                         if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3485                                                 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3486                                                 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3487                                                 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3488                                                 filtered = TRUE;
3489                                         if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3490                                                 init_jit_info_dbg_attrs (ji);
3491                                                 if (ji->dbg_hidden)
3492                                                         filtered = TRUE;
3493                                         }
3494                                         if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3495                                                 init_jit_info_dbg_attrs (ji);
3496                                                 if (ji->dbg_step_through)
3497                                                         filtered = TRUE;
3498                                         }
3499                                         if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3500                                                 init_jit_info_dbg_attrs (ji);
3501                                                 if (ji->dbg_non_user_code)
3502                                                         filtered = TRUE;
3503                                         }
3504                                 }
3505                         }
3506
3507                         if (!filtered) {
3508                                 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3509                                 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3510                         }
3511                 }
3512         }
3513
3514         /* Send a VM START/DEATH event by default */
3515         if (event == EVENT_KIND_VM_START)
3516                 events = g_slist_append (events, GINT_TO_POINTER (0));
3517         if (event == EVENT_KIND_VM_DEATH)
3518                 events = g_slist_append (events, GINT_TO_POINTER (0));
3519
3520         return events;
3521 }
3522
3523 static G_GNUC_UNUSED const char*
3524 event_to_string (EventKind event)
3525 {
3526         switch (event) {
3527         case EVENT_KIND_VM_START: return "VM_START";
3528         case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3529         case EVENT_KIND_THREAD_START: return "THREAD_START";
3530         case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3531         case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3532         case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3533         case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3534         case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3535         case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3536         case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3537         case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3538         case EVENT_KIND_STEP: return "STEP";
3539         case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3540         case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3541         case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3542         case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3543         case EVENT_KIND_USER_LOG: return "USER_LOG";
3544         default:
3545                 g_assert_not_reached ();
3546                 return "";
3547         }
3548 }
3549
3550 /*
3551  * process_event:
3552  *
3553  *   Send an event to the client, suspending the vm if needed.
3554  * LOCKING: Since this can suspend the calling thread, no locks should be held
3555  * by the caller.
3556  * The EVENTS list is freed by this function.
3557  */
3558 static void
3559 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3560 {
3561         Buffer buf;
3562         GSList *l;
3563         MonoDomain *domain = mono_domain_get ();
3564         MonoThread *thread = NULL;
3565         MonoObject *keepalive_obj = NULL;
3566         gboolean send_success = FALSE;
3567         static int ecount;
3568         int nevents;
3569
3570         if (!inited) {
3571                 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3572                 return;
3573         }
3574
3575         if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3576                 // FIXME: We miss those events
3577                 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3578                 return;
3579         }
3580
3581         if (vm_death_event_sent) {
3582                 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3583                 return;
3584         }
3585
3586         if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3587                 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3588                 return;
3589         }
3590
3591         if (disconnected) {
3592                 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3593                 return;
3594         }
3595
3596         if (event == EVENT_KIND_KEEPALIVE)
3597                 suspend_policy = SUSPEND_POLICY_NONE;
3598         else {
3599                 if (events == NULL)
3600                         return;
3601
3602                 if (agent_config.defer) {
3603                         /* Make sure the thread id is always set when doing deferred debugging */
3604                         if (is_debugger_thread ()) {
3605                                 /* Don't suspend on events from the debugger thread */
3606                                 suspend_policy = SUSPEND_POLICY_NONE;
3607                                 thread = mono_thread_get_main ();
3608                         }
3609                         else thread = mono_thread_current ();
3610                 } else {
3611                         if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3612                                 // FIXME: Send these with a NULL thread, don't suspend the current thread
3613                                 return;
3614                 }
3615         }
3616
3617         nevents = g_slist_length (events);
3618         buffer_init (&buf, 128);
3619         buffer_add_byte (&buf, suspend_policy);
3620         buffer_add_int (&buf, nevents);
3621
3622         for (l = events; l; l = l->next) {
3623                 buffer_add_byte (&buf, event); // event kind
3624                 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3625
3626                 ecount ++;
3627
3628                 if (!thread)
3629                         thread = mono_thread_current ();
3630
3631                 if (event == EVENT_KIND_VM_START && arg != NULL)
3632                         thread = (MonoThread *)arg;
3633
3634                 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3635
3636                 switch (event) {
3637                 case EVENT_KIND_THREAD_START:
3638                 case EVENT_KIND_THREAD_DEATH:
3639                         break;
3640                 case EVENT_KIND_APPDOMAIN_CREATE:
3641                 case EVENT_KIND_APPDOMAIN_UNLOAD:
3642                         buffer_add_domainid (&buf, (MonoDomain *)arg);
3643                         break;
3644                 case EVENT_KIND_METHOD_ENTRY:
3645                 case EVENT_KIND_METHOD_EXIT:
3646                         buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3647                         break;
3648                 case EVENT_KIND_ASSEMBLY_LOAD:
3649                         buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3650                         break;
3651                 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3652                         DebuggerTlsData *tls;
3653
3654                         /* The domain the assembly belonged to is not equal to the current domain */
3655                         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3656                         g_assert (tls);
3657                         g_assert (tls->domain_unloading);
3658
3659                         buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3660                         break;
3661                 }
3662                 case EVENT_KIND_TYPE_LOAD:
3663                         buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3664                         break;
3665                 case EVENT_KIND_BREAKPOINT:
3666                 case EVENT_KIND_STEP:
3667                         buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3668                         buffer_add_long (&buf, il_offset);
3669                         break;
3670                 case EVENT_KIND_VM_START:
3671                         buffer_add_domainid (&buf, mono_get_root_domain ());
3672                         break;
3673                 case EVENT_KIND_VM_DEATH:
3674                         if (CHECK_PROTOCOL_VERSION (2, 27))
3675                                 buffer_add_int (&buf, mono_environment_exitcode_get ());
3676                         break;
3677                 case EVENT_KIND_EXCEPTION: {
3678                         EventInfo *ei = (EventInfo *)arg;
3679                         buffer_add_objid (&buf, ei->exc);
3680                         /*
3681                          * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3682                          * later after the suspension. (#12494).
3683                          */
3684                         keepalive_obj = ei->exc;
3685                         break;
3686                 }
3687                 case EVENT_KIND_USER_BREAK:
3688                         break;
3689                 case EVENT_KIND_USER_LOG: {
3690                         EventInfo *ei = (EventInfo *)arg;
3691                         buffer_add_int (&buf, ei->level);
3692                         buffer_add_string (&buf, ei->category ? ei->category : "");
3693                         buffer_add_string (&buf, ei->message ? ei->message : "");
3694                         break;
3695                 }
3696                 case EVENT_KIND_KEEPALIVE:
3697                         suspend_policy = SUSPEND_POLICY_NONE;
3698                         break;
3699                 default:
3700                         g_assert_not_reached ();
3701                 }
3702         }
3703
3704         if (event == EVENT_KIND_VM_START) {
3705                 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3706                 if (!agent_config.defer)
3707                         start_debugger_thread ();
3708         }
3709    
3710         if (event == EVENT_KIND_VM_DEATH) {
3711                 vm_death_event_sent = TRUE;
3712                 suspend_policy = SUSPEND_POLICY_NONE;
3713         }
3714
3715         if (mono_runtime_is_shutting_down ())
3716                 suspend_policy = SUSPEND_POLICY_NONE;
3717
3718         if (suspend_policy != SUSPEND_POLICY_NONE) {
3719                 /* 
3720                  * Save the thread context and start suspending before sending the packet,
3721                  * since we could be receiving the resume request before send_packet ()
3722                  * returns.
3723                  */
3724                 save_thread_context (ctx);
3725                 suspend_vm ();
3726
3727                 if (keepalive_obj)
3728                         /* This will keep this object alive */
3729                         get_objref (keepalive_obj);
3730         }
3731
3732         send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3733
3734         buffer_free (&buf);
3735
3736         g_slist_free (events);
3737         events = NULL;
3738
3739         if (!send_success) {
3740                 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3741                 return;
3742         }
3743         
3744         if (event == EVENT_KIND_VM_START) {
3745                 vm_start_event_sent = TRUE;
3746         }
3747
3748         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);
3749
3750         switch (suspend_policy) {
3751         case SUSPEND_POLICY_NONE:
3752                 break;
3753         case SUSPEND_POLICY_ALL:
3754                 suspend_current ();
3755                 break;
3756         case SUSPEND_POLICY_EVENT_THREAD:
3757                 NOT_IMPLEMENTED;
3758                 break;
3759         default:
3760                 g_assert_not_reached ();
3761         }
3762 }
3763
3764 static void
3765 process_profiler_event (EventKind event, gpointer arg)
3766 {
3767         int suspend_policy;
3768         GSList *events;
3769         EventInfo ei, *ei_arg = NULL;
3770
3771         if (event == EVENT_KIND_TYPE_LOAD) {
3772                 ei.klass = (MonoClass *)arg;
3773                 ei_arg = &ei;
3774         }
3775
3776         mono_loader_lock ();
3777         events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3778         mono_loader_unlock ();
3779
3780         process_event (event, arg, 0, NULL, events, suspend_policy);
3781 }
3782
3783 static void
3784 runtime_initialized (MonoProfiler *prof)
3785 {
3786         process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3787         if (agent_config.defer)
3788                 start_debugger_thread ();
3789 }
3790
3791 static void
3792 runtime_shutdown (MonoProfiler *prof)
3793 {
3794         process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3795
3796         mono_debugger_agent_cleanup ();
3797 }
3798
3799 static void
3800 thread_startup (MonoProfiler *prof, uintptr_t tid)
3801 {
3802         MonoInternalThread *thread = mono_thread_internal_current ();
3803         MonoInternalThread *old_thread;
3804         DebuggerTlsData *tls;
3805
3806         if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3807                 return;
3808
3809         g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3810
3811         mono_loader_lock ();
3812         old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3813         mono_loader_unlock ();
3814         if (old_thread) {
3815                 if (thread == old_thread) {
3816                         /* 
3817                          * For some reason, thread_startup () might be called for the same thread
3818                          * multiple times (attach ?).
3819                          */
3820                         DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3821                         return;
3822                 } else {
3823                         /*
3824                          * thread_end () might not be called for some threads, and the tid could
3825                          * get reused.
3826                          */
3827                         DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3828                         mono_loader_lock ();
3829                         mono_g_hash_table_remove (thread_to_tls, old_thread);
3830                         mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3831                         mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3832                         mono_loader_unlock ();
3833                 }
3834         }
3835
3836         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3837         g_assert (!tls);
3838         // FIXME: Free this somewhere
3839         tls = g_new0 (DebuggerTlsData, 1);
3840         MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3841         tls->thread = thread;
3842         mono_native_tls_set_value (debugger_tls_id, tls);
3843
3844         DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3845
3846         mono_loader_lock ();
3847         mono_g_hash_table_insert (thread_to_tls, thread, tls);
3848         mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3849         mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3850         mono_loader_unlock ();
3851
3852         process_profiler_event (EVENT_KIND_THREAD_START, thread);
3853
3854         /* 
3855          * suspend_vm () could have missed this thread, so wait for a resume.
3856          */
3857         suspend_current ();
3858 }
3859
3860 static void
3861 thread_end (MonoProfiler *prof, uintptr_t tid)
3862 {
3863         MonoInternalThread *thread;
3864         DebuggerTlsData *tls = NULL;
3865
3866         mono_loader_lock ();
3867         thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3868         if (thread) {
3869                 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3870                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3871                 if (tls) {
3872                         /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3873                         tls->terminated = TRUE;
3874                         /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3875                         MONO_GC_UNREGISTER_ROOT (tls->thread);
3876                         tls->thread = NULL;
3877                 }
3878         }
3879         mono_loader_unlock ();
3880
3881         /* We might be called for threads started before we registered the start callback */
3882         if (thread) {
3883                 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3884
3885                 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3886                      && !mono_native_tls_get_value (debugger_tls_id)
3887                 ) {
3888                         /*
3889                          * This can happen on darwin since we deregister threads using pthread dtors.
3890                          * process_profiler_event () and the code it calls cannot handle a null TLS value.
3891                          */
3892                         return;
3893                 }
3894
3895                 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3896         }
3897 }
3898
3899 static void
3900 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3901 {
3902         mono_loader_lock ();
3903         g_hash_table_insert (domains, domain, domain);
3904         mono_loader_unlock ();
3905
3906         process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3907 }
3908
3909 static void
3910 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3911 {
3912         DebuggerTlsData *tls;
3913
3914         /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3915         if (is_debugger_thread ())
3916                 return;
3917
3918         /*
3919          * Remember the currently unloading appdomain as it is needed to generate
3920          * proper ids for unloading assemblies.
3921          */
3922         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3923         g_assert (tls);
3924         tls->domain_unloading = domain;
3925 }
3926
3927 static void
3928 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3929 {
3930         DebuggerTlsData *tls;
3931
3932         if (is_debugger_thread ())
3933                 return;
3934
3935         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3936         g_assert (tls);
3937         tls->domain_unloading = NULL;
3938
3939         clear_breakpoints_for_domain (domain);
3940         
3941         mono_loader_lock ();
3942         /* Invalidate each thread's frame stack */
3943         mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3944         mono_loader_unlock ();
3945         
3946         process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3947 }
3948
3949 /*
3950  * invalidate_each_thread:
3951  *
3952  *   A GHFunc to invalidate frames.
3953  *   value must be a DebuggerTlsData*
3954  */
3955 static void
3956 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3957 {
3958         invalidate_frames ((DebuggerTlsData *)value);
3959 }
3960
3961 static void
3962 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3963 {
3964         /* Sent later in jit_end () */
3965         dbg_lock ();
3966         g_ptr_array_add (pending_assembly_loads, assembly);
3967         dbg_unlock ();
3968 }
3969
3970 static void
3971 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3972 {
3973         if (is_debugger_thread ())
3974                 return;
3975
3976         process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3977
3978         clear_event_requests_for_assembly (assembly);
3979         clear_types_for_assembly (assembly);
3980 }
3981
3982 static void
3983 send_type_load (MonoClass *klass)
3984 {
3985         gboolean type_load = FALSE;
3986         MonoDomain *domain = mono_domain_get ();
3987         AgentDomainInfo *info = NULL;
3988
3989         info = get_agent_domain_info (domain);
3990
3991         mono_loader_lock ();
3992
3993         if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3994                 type_load = TRUE;
3995                 g_hash_table_insert (info->loaded_classes, klass, klass);
3996         }
3997
3998         mono_loader_unlock ();
3999
4000         if (type_load)
4001                 emit_type_load (klass, klass, NULL);
4002 }
4003
4004 /*
4005  * Emit load events for all types currently loaded in the domain.
4006  * Takes the loader and domain locks.
4007  * user_data is unused.
4008  */
4009 static void
4010 send_types_for_domain (MonoDomain *domain, void *user_data)
4011 {
4012         AgentDomainInfo *info = NULL;
4013
4014         info = get_agent_domain_info (domain);
4015         g_assert (info);
4016         
4017         mono_loader_lock ();
4018         g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4019         mono_loader_unlock ();
4020 }
4021
4022 static void
4023 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4024 {
4025         /*
4026          * We emit type load events when the first method of the type is JITted,
4027          * since the class load profiler callbacks might be called with the
4028          * loader lock held. They could also occur in the debugger thread.
4029          * Same for assembly load events.
4030          */
4031         while (TRUE) {
4032                 MonoAssembly *assembly = NULL;
4033
4034                 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4035                 dbg_lock ();
4036                 if (pending_assembly_loads->len > 0) {
4037                         assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4038                         g_ptr_array_remove_index (pending_assembly_loads, 0);
4039                 }
4040                 dbg_unlock ();
4041
4042                 if (assembly) {
4043                         process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4044                 } else {
4045                         break;
4046                 }
4047         }
4048
4049         send_type_load (method->klass);
4050
4051         if (!result)
4052                 add_pending_breakpoints (method, jinfo);
4053 }
4054
4055 /*
4056  * BREAKPOINTS/SINGLE STEPPING
4057  */
4058
4059 /* 
4060  * Contains information about an inserted breakpoint.
4061  */
4062 typedef struct {
4063         long il_offset, native_offset;
4064         guint8 *ip;
4065         MonoJitInfo *ji;
4066         MonoDomain *domain;
4067 } BreakpointInstance;
4068
4069 /*
4070  * Contains generic information about a breakpoint.
4071  */
4072 typedef struct {
4073         /* 
4074          * The method where the breakpoint is placed. Can be NULL in which case it 
4075          * is inserted into every method. This is used to implement method entry/
4076          * exit events. Can be a generic method definition, in which case the
4077          * breakpoint is inserted into every instance.
4078          */
4079         MonoMethod *method;
4080         long il_offset;
4081         EventRequest *req;
4082         /* 
4083          * A list of BreakpointInstance structures describing where the breakpoint
4084          * was inserted. There could be more than one because of 
4085          * generics/appdomains/method entry/exit.
4086          */
4087         GPtrArray *children;
4088 } MonoBreakpoint;
4089
4090 /* List of breakpoints */
4091 /* Protected by the loader lock */
4092 static GPtrArray *breakpoints;
4093 /* Maps breakpoint locations to the number of breakpoints at that location */
4094 static GHashTable *bp_locs;
4095
4096 static void
4097 breakpoints_init (void)
4098 {
4099         breakpoints = g_ptr_array_new ();
4100         bp_locs = g_hash_table_new (NULL, NULL);
4101 }       
4102
4103 /*
4104  * insert_breakpoint:
4105  *
4106  *   Insert the breakpoint described by BP into the method described by
4107  * JI.
4108  */
4109 static void
4110 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4111 {
4112         int count;
4113         BreakpointInstance *inst;
4114         SeqPointIterator it;
4115         gboolean it_has_sp = FALSE;
4116
4117         if (error)
4118                 mono_error_init (error);
4119
4120         mono_seq_point_iterator_init (&it, seq_points);
4121         while (mono_seq_point_iterator_next (&it)) {
4122                 if (it.seq_point.il_offset == bp->il_offset) {
4123                         it_has_sp = TRUE;
4124                         break;
4125                 }
4126         }
4127
4128         if (!it_has_sp) {
4129                 /*
4130                  * The set of IL offsets with seq points doesn't completely match the
4131                  * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4132                  */
4133                 mono_seq_point_iterator_init (&it, seq_points);
4134                 while (mono_seq_point_iterator_next (&it)) {
4135                         if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4136                                 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4137                                 it.seq_point.il_offset + 1 == bp->il_offset) {
4138                                 it_has_sp = TRUE;
4139                                 break;
4140                         }
4141                 }
4142         }
4143
4144         if (!it_has_sp) {
4145                 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4146
4147                 mono_seq_point_iterator_init (&it, seq_points);
4148                 while (mono_seq_point_iterator_next (&it))
4149                         DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4150
4151                 if (error) {
4152                         mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4153                         g_warning ("%s", s);
4154                         g_free (s);
4155                         return;
4156                 } else {
4157                         g_warning ("%s", s);
4158                         g_free (s);
4159                         return;
4160                 }
4161         }
4162
4163         inst = g_new0 (BreakpointInstance, 1);
4164         inst->il_offset = it.seq_point.il_offset;
4165         inst->native_offset = it.seq_point.native_offset;
4166         inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4167         inst->ji = ji;
4168         inst->domain = domain;
4169
4170         mono_loader_lock ();
4171
4172         g_ptr_array_add (bp->children, inst);
4173
4174         mono_loader_unlock ();
4175
4176         dbg_lock ();
4177         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4178         g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4179         dbg_unlock ();
4180
4181         if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4182                 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4183         } else if (count == 0) {
4184 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4185                 mono_arch_set_breakpoint (ji, inst->ip);
4186 #else
4187                 NOT_IMPLEMENTED;
4188 #endif
4189         }
4190
4191         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);
4192 }
4193
4194 static void
4195 remove_breakpoint (BreakpointInstance *inst)
4196 {
4197 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4198         int count;
4199         MonoJitInfo *ji = inst->ji;
4200         guint8 *ip = inst->ip;
4201
4202         dbg_lock ();
4203         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4204         g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4205         dbg_unlock ();
4206
4207         g_assert (count > 0);
4208
4209         if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4210                 mono_arch_clear_breakpoint (ji, ip);
4211                 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4212         }
4213 #else
4214         NOT_IMPLEMENTED;
4215 #endif
4216 }       
4217
4218 /*
4219  * This doesn't take any locks.
4220  */
4221 static inline gboolean
4222 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4223 {
4224         int i;
4225
4226         if (!bp->method)
4227                 return TRUE;
4228         if (method == bp->method)
4229                 return TRUE;
4230         if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4231                 return TRUE;
4232
4233         if (bp->method->is_inflated && method->is_inflated) {
4234                 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4235                 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4236
4237                 /* Open generic methods should match closed generic methods of the same class */
4238                 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4239                         for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4240                                 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4241
4242                                 /* FIXME: Handle !mvar */
4243                                 if (t1->type != MONO_TYPE_MVAR)
4244                                         return FALSE;
4245                         }
4246                         return TRUE;
4247                 }
4248         }
4249
4250         return FALSE;
4251 }
4252
4253 /*
4254  * add_pending_breakpoints:
4255  *
4256  *   Insert pending breakpoints into the newly JITted method METHOD.
4257  */
4258 static void
4259 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4260 {
4261         int i, j;
4262         MonoSeqPointInfo *seq_points;
4263         MonoDomain *domain;
4264         MonoMethod *jmethod;
4265
4266         if (!breakpoints)
4267                 return;
4268
4269         domain = mono_domain_get ();
4270
4271         mono_loader_lock ();
4272
4273         for (i = 0; i < breakpoints->len; ++i) {
4274                 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4275                 gboolean found = FALSE;
4276
4277                 if (!bp_matches_method (bp, method))
4278                         continue;
4279
4280                 for (j = 0; j < bp->children->len; ++j) {
4281                         BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4282
4283                         if (inst->ji == ji)
4284                                 found = TRUE;
4285                 }
4286
4287                 if (!found) {
4288                         MonoMethod *declaring = NULL;
4289
4290                         jmethod = jinfo_get_method (ji);
4291                         if (jmethod->is_inflated)
4292                                 declaring = mono_method_get_declaring_generic_method (jmethod);
4293
4294                         mono_domain_lock (domain);
4295                         seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4296                         if (!seq_points && declaring)
4297                                 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4298                         mono_domain_unlock (domain);
4299                         if (!seq_points)
4300                                 /* Could be AOT code */
4301                                 continue;
4302                         g_assert (seq_points);
4303
4304                         insert_breakpoint (seq_points, domain, ji, bp, NULL);
4305                 }
4306         }
4307
4308         mono_loader_unlock ();
4309 }
4310
4311 static void
4312 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4313 {
4314         gpointer code;
4315         MonoJitInfo *ji;
4316
4317         if (error)
4318                 mono_error_init (error);
4319
4320         code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4321         if (!code) {
4322                 /* Might be AOTed code */
4323                 code = mono_aot_get_method (domain, method);
4324                 g_assert (code);
4325                 ji = mono_jit_info_table_find (domain, (char *)code);
4326                 g_assert (ji);
4327         }
4328         g_assert (code);
4329
4330         insert_breakpoint (seq_points, domain, ji, bp, error);
4331 }
4332
4333 static void
4334 clear_breakpoint (MonoBreakpoint *bp);
4335
4336 /*
4337  * set_breakpoint:
4338  *
4339  *   Set a breakpoint at IL_OFFSET in METHOD.
4340  * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4341  * METHOD can also be a generic method definition, in which case a breakpoint
4342  * is placed in all instances of the method.
4343  * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4344  * inserted.
4345  */
4346 static MonoBreakpoint*
4347 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4348 {
4349         MonoBreakpoint *bp;
4350         GHashTableIter iter, iter2;
4351         MonoDomain *domain;
4352         MonoMethod *m;
4353         MonoSeqPointInfo *seq_points;
4354         GPtrArray *methods;
4355         GPtrArray *method_domains;
4356         GPtrArray *method_seq_points;
4357         int i;
4358
4359         if (error)
4360                 mono_error_init (error);
4361
4362         // FIXME:
4363         // - suspend/resume the vm to prevent code patching problems
4364         // - multiple breakpoints on the same location
4365         // - dynamic methods
4366         // - races
4367
4368         bp = g_new0 (MonoBreakpoint, 1);
4369         bp->method = method;
4370         bp->il_offset = il_offset;
4371         bp->req = req;
4372         bp->children = g_ptr_array_new ();
4373
4374         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);
4375
4376         methods = g_ptr_array_new ();
4377         method_domains = g_ptr_array_new ();
4378         method_seq_points = g_ptr_array_new ();
4379
4380         mono_loader_lock ();
4381         g_hash_table_iter_init (&iter, domains);
4382         while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4383                 mono_domain_lock (domain);
4384                 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4385                 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4386                         if (bp_matches_method (bp, m)) {
4387                                 /* Save the info locally to simplify the code inside the domain lock */
4388                                 g_ptr_array_add (methods, m);
4389                                 g_ptr_array_add (method_domains, domain);
4390                                 g_ptr_array_add (method_seq_points, seq_points);
4391                         }
4392                 }
4393                 mono_domain_unlock (domain);
4394         }
4395
4396         for (i = 0; i < methods->len; ++i) {
4397                 m = (MonoMethod *)g_ptr_array_index (methods, i);
4398                 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4399                 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4400                 set_bp_in_method (domain, m, seq_points, bp, error);
4401         }
4402
4403         g_ptr_array_add (breakpoints, bp);
4404         mono_loader_unlock ();
4405
4406         g_ptr_array_free (methods, TRUE);
4407         g_ptr_array_free (method_domains, TRUE);
4408         g_ptr_array_free (method_seq_points, TRUE);
4409
4410         if (error && !mono_error_ok (error)) {
4411                 clear_breakpoint (bp);
4412                 return NULL;
4413         }
4414
4415         return bp;
4416 }
4417
4418 static void
4419 clear_breakpoint (MonoBreakpoint *bp)
4420 {
4421         int i;
4422
4423         // FIXME: locking, races
4424         for (i = 0; i < bp->children->len; ++i) {
4425                 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4426
4427                 remove_breakpoint (inst);
4428
4429                 g_free (inst);
4430         }
4431
4432         mono_loader_lock ();
4433         g_ptr_array_remove (breakpoints, bp);
4434         mono_loader_unlock ();
4435
4436         g_ptr_array_free (bp->children, TRUE);
4437         g_free (bp);
4438 }
4439
4440 static void
4441 breakpoints_cleanup (void)
4442 {
4443         int i;
4444
4445         mono_loader_lock ();
4446         i = 0;
4447         while (i < event_requests->len) {
4448                 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4449
4450                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4451                         clear_breakpoint ((MonoBreakpoint *)req->info);
4452                         g_ptr_array_remove_index_fast (event_requests, i);
4453                         g_free (req);
4454                 } else {
4455                         i ++;
4456                 }
4457         }
4458
4459         for (i = 0; i < breakpoints->len; ++i)
4460                 g_free (g_ptr_array_index (breakpoints, i));
4461
4462         g_ptr_array_free (breakpoints, TRUE);
4463         g_hash_table_destroy (bp_locs);
4464
4465         breakpoints = NULL;
4466         bp_locs = NULL;
4467
4468         mono_loader_unlock ();
4469 }
4470
4471 /*
4472  * clear_breakpoints_for_domain:
4473  *
4474  *   Clear breakpoint instances which reference DOMAIN.
4475  */
4476 static void
4477 clear_breakpoints_for_domain (MonoDomain *domain)
4478 {
4479         int i, j;
4480
4481         /* This could be called after shutdown */
4482         if (!breakpoints)
4483                 return;
4484
4485         mono_loader_lock ();
4486         for (i = 0; i < breakpoints->len; ++i) {
4487                 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4488
4489                 j = 0;
4490                 while (j < bp->children->len) {
4491                         BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4492
4493                         if (inst->domain == domain) {
4494                                 remove_breakpoint (inst);
4495
4496                                 g_free (inst);
4497
4498                                 g_ptr_array_remove_index_fast (bp->children, j);
4499                         } else {
4500                                 j ++;
4501                         }
4502                 }
4503         }
4504         mono_loader_unlock ();
4505 }
4506
4507 /*
4508  * ss_update:
4509  *
4510  * Return FALSE if single stepping needs to continue.
4511  */
4512 static gboolean
4513 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4514 {
4515         MonoDebugMethodInfo *minfo;
4516         MonoDebugSourceLocation *loc = NULL;
4517         gboolean hit = TRUE;
4518         MonoMethod *method;
4519
4520         if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4521                 /*
4522                  * These seq points are inserted by the JIT after calls, step over needs to skip them.
4523                  */
4524                 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);
4525                 return FALSE;
4526         }
4527
4528         if (req->depth == STEP_DEPTH_OVER && hit) {
4529                 if (!tls->context.valid)
4530                         mono_thread_state_init_from_monoctx (&tls->context, ctx);
4531                 compute_frame_info (tls->thread, tls);
4532                 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4533                         /* Hit the breakpoint in a recursive call */
4534                         DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4535                         return FALSE;
4536                 }
4537         }
4538
4539         if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4540                 method = jinfo_get_method (ji);
4541                 if (!tls->context.valid)
4542                         mono_thread_state_init_from_monoctx (&tls->context, ctx);
4543                 compute_frame_info (tls->thread, tls);
4544                 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4545                         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);
4546                         return FALSE;
4547                 }
4548         }
4549
4550         if (req->size != STEP_SIZE_LINE)
4551                 return TRUE;
4552
4553         /* Have to check whenever a different source line was reached */
4554         method = jinfo_get_method (ji);
4555         minfo = mono_debug_lookup_method (method);
4556
4557         if (minfo)
4558                 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4559
4560         if (!loc) {
4561                 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);
4562                 ss_req->last_method = method;
4563                 hit = FALSE;
4564         } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4565                 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4566                 hit = FALSE;
4567         }
4568                                 
4569         if (loc) {
4570                 ss_req->last_method = method;
4571                 ss_req->last_line = loc->row;
4572                 mono_debug_free_source_location (loc);
4573         }
4574
4575         return hit;
4576 }
4577
4578 static gboolean
4579 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4580 {
4581         return bp->method && bp->method->klass->image->assembly == assembly;
4582 }
4583
4584 static void
4585 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4586 {
4587         MonoJitInfo *ji;
4588         guint8 *ip;
4589         int i, j, suspend_policy;
4590         guint32 native_offset;
4591         MonoBreakpoint *bp;
4592         BreakpointInstance *inst;
4593         GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4594         GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4595         EventKind kind = EVENT_KIND_BREAKPOINT;
4596         MonoContext *ctx = &tls->restore_state.ctx;
4597         MonoMethod *method;
4598         MonoSeqPointInfo *info;
4599         SeqPoint sp;
4600         gboolean found_sp;
4601
4602         // FIXME: Speed this up
4603
4604         ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4605         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4606         g_assert (ji && !ji->is_trampoline);
4607         method = jinfo_get_method (ji);
4608
4609         /* Compute the native offset of the breakpoint from the ip */
4610         native_offset = ip - (guint8*)ji->code_start;   
4611
4612         /* 
4613          * Skip the instruction causing the breakpoint signal.
4614          */
4615         if (from_signal)
4616                 mono_arch_skip_breakpoint (ctx, ji);
4617
4618         if (method->wrapper_type || tls->disable_breakpoints)
4619                 return;
4620
4621         bp_reqs = g_ptr_array_new ();
4622         ss_reqs = g_ptr_array_new ();
4623         ss_reqs_orig = g_ptr_array_new ();
4624
4625         mono_loader_lock ();
4626
4627         /*
4628          * The ip points to the instruction causing the breakpoint event, which is after
4629          * the offset recorded in the seq point map, so find the prev seq point before ip.
4630          */
4631         found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4632
4633         if (!found_sp)
4634                 no_seq_points_found (method, native_offset);
4635
4636         g_assert (found_sp);
4637
4638         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);
4639
4640         bp = NULL;
4641         for (i = 0; i < breakpoints->len; ++i) {
4642                 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4643
4644                 if (!bp->method)
4645                         continue;
4646
4647                 for (j = 0; j < bp->children->len; ++j) {
4648                         inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4649                         if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4650                                 if (bp->req->event_kind == EVENT_KIND_STEP) {
4651                                         g_ptr_array_add (ss_reqs_orig, bp->req);
4652                                 } else {
4653                                         g_ptr_array_add (bp_reqs, bp->req);
4654                                 }
4655                         }
4656                 }
4657         }
4658         if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4659                 /* Maybe a method entry/exit event */
4660                 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4661                         kind = EVENT_KIND_METHOD_ENTRY;
4662                 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4663                         kind = EVENT_KIND_METHOD_EXIT;
4664         }
4665
4666         /* Process single step requests */
4667         for (i = 0; i < ss_reqs_orig->len; ++i) {
4668                 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4669                 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4670                 gboolean hit;
4671
4672                 if (mono_thread_internal_current () != ss_req->thread)
4673                         continue;
4674
4675                 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4676                 if (hit)
4677                         g_ptr_array_add (ss_reqs, req);
4678
4679                 /* Start single stepping again from the current sequence point */
4680                 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4681         }
4682         
4683         if (ss_reqs->len > 0)
4684                 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4685         if (bp_reqs->len > 0)
4686                 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4687         if (kind != EVENT_KIND_BREAKPOINT)
4688                 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4689
4690         mono_loader_unlock ();
4691
4692         g_ptr_array_free (bp_reqs, TRUE);
4693         g_ptr_array_free (ss_reqs, TRUE);
4694
4695         /* 
4696          * FIXME: The first event will suspend, so the second will only be sent after the
4697          * resume.
4698          */
4699         if (ss_events)
4700                 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4701         if (bp_events)
4702                 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4703         if (enter_leave_events)
4704                 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4705 }
4706
4707 /* Process a breakpoint/single step event after resuming from a signal handler */
4708 static void
4709 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4710 {
4711         DebuggerTlsData *tls;
4712         MonoThreadUnwindState orig_restore_state;
4713         MonoContext ctx;
4714
4715         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4716         /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4717         memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4718         mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4719
4720         func (tls, TRUE);
4721
4722         /* This is called when resuming from a signal handler, so it shouldn't return */
4723         memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4724         memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4725         mono_restore_context (&ctx);
4726         g_assert_not_reached ();
4727 }
4728
4729 static void
4730 process_breakpoint (void)
4731 {
4732         process_signal_event (process_breakpoint_inner);
4733 }
4734
4735 static void
4736 resume_from_signal_handler (void *sigctx, void *func)
4737 {
4738         DebuggerTlsData *tls;
4739         MonoContext ctx;
4740
4741         /* Save the original context in TLS */
4742         // FIXME: This might not work on an altstack ?
4743         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4744         if (!tls)
4745                 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4746         g_assert (tls);
4747
4748         // FIXME: MonoContext usually doesn't include the fp registers, so these are 
4749         // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4750         // clob:c could be added to op_seq_point.
4751
4752         mono_sigctx_to_monoctx (sigctx, &ctx);
4753         memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4754 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4755         mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4756 #else
4757         MONO_CONTEXT_SET_IP (&ctx, func);
4758 #endif
4759         mono_monoctx_to_sigctx (&ctx, sigctx);
4760
4761 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4762         mono_ppc_set_func_into_sigctx (sigctx, func);
4763 #endif
4764 }
4765
4766 void
4767 mono_debugger_agent_breakpoint_hit (void *sigctx)
4768 {
4769         /*
4770          * We are called from a signal handler, and running code there causes all kinds of
4771          * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4772          * So set up the signal context to return to the real breakpoint handler function.
4773          */
4774         resume_from_signal_handler (sigctx, process_breakpoint);
4775 }
4776
4777 static gboolean
4778 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4779 {
4780         if (frame->managed) {
4781                 *(MonoContext*)data = *ctx;
4782
4783                 return TRUE;
4784         } else {
4785                 return FALSE;
4786         }
4787 }
4788
4789 /*
4790  * Called by System.Diagnostics.Debugger:Break ().
4791  */
4792 void
4793 mono_debugger_agent_user_break (void)
4794 {
4795         if (agent_config.enabled) {
4796                 MonoContext ctx;
4797                 int suspend_policy;
4798                 GSList *events;
4799
4800                 /* Obtain a context */
4801                 MONO_CONTEXT_SET_IP (&ctx, NULL);
4802                 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
4803                 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4804
4805                 mono_loader_lock ();
4806                 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4807                 mono_loader_unlock ();
4808
4809                 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4810         } else if (debug_options.native_debugger_break) {
4811                 G_BREAKPOINT ();
4812         }
4813 }
4814
4815 static const char*
4816 ss_depth_to_string (StepDepth depth)
4817 {
4818         switch (depth) {
4819         case STEP_DEPTH_OVER:
4820                 return "over";
4821         case STEP_DEPTH_OUT:
4822                 return "out";
4823         case STEP_DEPTH_INTO:
4824                 return "into";
4825         default:
4826                 g_assert_not_reached ();
4827                 return NULL;
4828         }
4829 }
4830
4831 static void
4832 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4833 {
4834         MonoJitInfo *ji;
4835         guint8 *ip;
4836         GPtrArray *reqs;
4837         int il_offset, suspend_policy;
4838         MonoDomain *domain;
4839         GSList *events;
4840         MonoContext *ctx = &tls->restore_state.ctx;
4841         MonoMethod *method;
4842         SeqPoint sp;
4843         MonoSeqPointInfo *info;
4844
4845         ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4846
4847         /* Skip the instruction causing the single step */
4848         if (from_signal)
4849                 mono_arch_skip_single_step (ctx);
4850
4851         if (suspend_count > 0) {
4852                 /* Fastpath during invokes, see in process_suspend () */
4853                 if (suspend_count - tls->resume_count == 0)
4854                         return;
4855                 process_suspend (tls, ctx);
4856                 return;
4857         }
4858
4859         if (!ss_req)
4860                 // FIXME: A suspend race
4861                 return;
4862
4863         if (mono_thread_internal_current () != ss_req->thread)
4864                 return;
4865
4866         if (log_level > 0) {
4867                 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4868
4869                 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);
4870         }
4871
4872         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4873         g_assert (ji && !ji->is_trampoline);
4874         method = jinfo_get_method (ji);
4875         g_assert (method);
4876
4877         if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4878                 return;
4879
4880         /* 
4881          * FIXME:
4882          * Stopping in memset makes half-initialized vtypes visible.
4883          * Stopping in memcpy makes half-copied vtypes visible.
4884          */
4885         if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4886                 return;
4887
4888         /*
4889          * The ip points to the instruction causing the single step event, which is before
4890          * the offset recorded in the seq point map, so find the next seq point after ip.
4891          */
4892         if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4893                 return;
4894
4895         il_offset = sp.il_offset;
4896
4897         if (!ss_update (ss_req, ji, &sp, tls, ctx))
4898                 return;
4899
4900         /* Start single stepping again from the current sequence point */
4901         ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4902
4903         if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4904                 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4905                 !strcmp (method->name, ".cctor"))
4906                 return;
4907
4908         // FIXME: Has to lock earlier
4909
4910         reqs = g_ptr_array_new ();
4911
4912         mono_loader_lock ();
4913
4914         g_ptr_array_add (reqs, ss_req->req);
4915
4916         events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4917
4918         g_ptr_array_free (reqs, TRUE);
4919
4920         mono_loader_unlock ();
4921
4922         process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4923 }
4924
4925 static void
4926 process_single_step (void)
4927 {
4928         process_signal_event (process_single_step_inner);
4929 }
4930
4931 /*
4932  * mono_debugger_agent_single_step_event:
4933  *
4934  *   Called from a signal handler to handle a single step event.
4935  */
4936 void
4937 mono_debugger_agent_single_step_event (void *sigctx)
4938 {
4939         /* Resume to process_single_step through the signal context */
4940
4941         // FIXME: Since step out/over is implemented using step in, the step in case should
4942         // be as fast as possible. Move the relevant code from process_single_step_inner ()
4943         // here
4944
4945         if (is_debugger_thread ()) {
4946                 /* 
4947                  * This could happen despite our best effors when the runtime calls 
4948                  * assembly/type resolve hooks.
4949                  * FIXME: Breakpoints too.
4950                  */
4951                 MonoContext ctx;
4952
4953                 mono_sigctx_to_monoctx (sigctx, &ctx);
4954                 mono_arch_skip_single_step (&ctx);
4955                 mono_monoctx_to_sigctx (&ctx, sigctx);
4956                 return;
4957         }
4958
4959         resume_from_signal_handler (sigctx, process_single_step);
4960 }
4961
4962 void
4963 debugger_agent_single_step_from_context (MonoContext *ctx)
4964 {
4965         DebuggerTlsData *tls;
4966         MonoThreadUnwindState orig_restore_state;
4967
4968         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4969         /* Fastpath during invokes, see in process_suspend () */
4970         if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4971                 return;
4972
4973         if (is_debugger_thread ())
4974                 return;
4975
4976         g_assert (tls);
4977
4978         /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4979         memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4980         mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4981         memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4982
4983         process_single_step_inner (tls, FALSE);
4984
4985         memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4986         memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4987 }
4988
4989 void
4990 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4991 {
4992         DebuggerTlsData *tls;
4993         MonoThreadUnwindState orig_restore_state;
4994         guint8 *orig_ip;
4995
4996         if (is_debugger_thread ())
4997                 return;
4998
4999         orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5000         MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5001
5002         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5003         g_assert (tls);
5004         memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5005         mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5006         memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5007
5008         process_breakpoint_inner (tls, FALSE);
5009
5010         memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5011         memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5012         if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5013                 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5014 }
5015
5016 /*
5017  * start_single_stepping:
5018  *
5019  *   Turn on single stepping. Can be called multiple times, for example,
5020  * by a single step event request + a suspend.
5021  */
5022 static void
5023 start_single_stepping (void)
5024 {
5025 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5026         int val = InterlockedIncrement (&ss_count);
5027
5028         if (val == 1)
5029                 mono_arch_start_single_stepping ();
5030 #else
5031         g_assert_not_reached ();
5032 #endif
5033 }
5034
5035 static void
5036 stop_single_stepping (void)
5037 {
5038 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5039         int val = InterlockedDecrement (&ss_count);
5040
5041         if (val == 0)
5042                 mono_arch_stop_single_stepping ();
5043 #else
5044         g_assert_not_reached ();
5045 #endif
5046 }
5047
5048 /*
5049  * ss_stop:
5050  *
5051  *   Stop the single stepping operation given by SS_REQ.
5052  */
5053 static void
5054 ss_stop (SingleStepReq *ss_req)
5055 {
5056         if (ss_req->bps) {
5057                 GSList *l;
5058
5059                 for (l = ss_req->bps; l; l = l->next) {
5060                         clear_breakpoint ((MonoBreakpoint *)l->data);
5061                 }
5062                 g_slist_free (ss_req->bps);
5063                 ss_req->bps = NULL;
5064         }
5065
5066         if (ss_req->global) {
5067                 stop_single_stepping ();
5068                 ss_req->global = FALSE;
5069         }
5070 }
5071
5072 /*
5073  * ss_start:
5074  *
5075  *   Start the single stepping operation given by SS_REQ from the sequence point SP.
5076  * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5077  * belong to the same thread as CTX.
5078  * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5079  */
5080 static void
5081 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5082                   gboolean step_to_catch, StackFrame **frames, int nframes)
5083 {
5084         int i, j, frame_index;
5085         SeqPoint *next_sp, *parent_sp = NULL;
5086         SeqPoint local_sp, local_parent_sp;
5087         gboolean found_sp;
5088         MonoBreakpoint *bp;
5089         MonoSeqPointInfo *parent_info;
5090         MonoMethod *parent_sp_method = NULL;
5091         gboolean enable_global = FALSE;
5092
5093         /* Stop the previous operation */
5094         ss_stop (ss_req);
5095
5096         /*
5097          * Implement single stepping using breakpoints if possible.
5098          */
5099         if (step_to_catch) {
5100                 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5101                 ss_req->bps = g_slist_append (ss_req->bps, bp);
5102         } else {
5103                 frame_index = 1;
5104
5105                 if (ctx && !frames) {
5106                         /* Need parent frames */
5107                         if (!tls->context.valid)
5108                                 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5109                         compute_frame_info (tls->thread, tls);
5110                         frames = tls->frames;
5111                         nframes = tls->frame_count;
5112                 }
5113
5114                 /*
5115                  * Find the first sequence point in the current or in a previous frame which
5116                  * is not the last in its method.
5117                  */
5118                 if (ss_req->depth == STEP_DEPTH_OUT) {
5119                         /* Ignore seq points in current method */
5120                         while (frame_index < nframes) {
5121                                 StackFrame *frame = frames [frame_index];
5122
5123                                 method = frame->method;
5124                                 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5125                                 sp = (found_sp)? &local_sp : NULL;
5126                                 frame_index ++;
5127                                 if (sp && sp->next_len != 0)
5128                                         break;
5129                         }
5130                         // There could be method calls before the next seq point in the caller when using nested calls
5131                         //enable_global = TRUE;
5132                 } else {
5133                         if (sp && sp->next_len == 0) {
5134                                 sp = NULL;
5135                                 while (frame_index < nframes) {
5136                                         StackFrame *frame = frames [frame_index];
5137
5138                                         method = frame->method;
5139                                         found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5140                                         sp = (found_sp)? &local_sp : NULL;
5141                                         if (sp && sp->next_len != 0)
5142                                                 break;
5143                                         sp = NULL;
5144                                         frame_index ++;
5145                                 }
5146                         } else {
5147                                 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5148                                 while (frame_index < nframes) {
5149                                         StackFrame *frame = frames [frame_index];
5150
5151                                         parent_sp_method = frame->method;
5152                                         found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5153                                         parent_sp = found_sp ? &local_parent_sp : NULL;
5154                                         if (found_sp && parent_sp->next_len != 0)
5155                                                 break;
5156                                         parent_sp = NULL;
5157                                         frame_index ++;
5158                                 }
5159                         }
5160                 }
5161
5162                 if (sp && sp->next_len > 0) {
5163                         SeqPoint* next = g_new(SeqPoint, sp->next_len);
5164
5165                         mono_seq_point_init_next (info, *sp, next);
5166                         for (i = 0; i < sp->next_len; i++) {
5167                                 next_sp = &next[i];
5168
5169                                 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5170                                 ss_req->bps = g_slist_append (ss_req->bps, bp);
5171                         }
5172                         g_free (next);
5173                 }
5174
5175                 if (parent_sp) {
5176                         SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5177
5178                         mono_seq_point_init_next (parent_info, *parent_sp, next);
5179                         for (i = 0; i < parent_sp->next_len; i++) {
5180                                 next_sp = &next[i];
5181
5182                                 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5183                                 ss_req->bps = g_slist_append (ss_req->bps, bp);
5184                         }
5185                         g_free (next);
5186                 }
5187
5188                 if (ss_req->nframes == 0)
5189                         ss_req->nframes = nframes;
5190
5191                 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5192                         DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5193                         /*
5194                          * This is needed since if we leave managed code, and later return to it, step over
5195                          * is not going to stop.
5196                          * This approach is a bit ugly, since we change the step depth, but it only affects
5197                          * clients who reuse the same step request, and only in this special case.
5198                          */
5199                         ss_req->depth = STEP_DEPTH_INTO;
5200                 }
5201
5202                 if (ss_req->depth == STEP_DEPTH_OVER) {
5203                         /* Need to stop in catch clauses as well */
5204                         for (i = 0; i < nframes; ++i) {
5205                                 StackFrame *frame = frames [i];
5206
5207                                 if (frame->ji) {
5208                                         MonoJitInfo *jinfo = frame->ji;
5209                                         for (j = 0; j < jinfo->num_clauses; ++j) {
5210                                                 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5211
5212                                                 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);
5213                                                 sp = (found_sp)? &local_sp : NULL;
5214                                                 if (sp) {
5215                                                         bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5216                                                         ss_req->bps = g_slist_append (ss_req->bps, bp);
5217                                                 }
5218                                         }
5219                                 }
5220                         }
5221                 }
5222
5223                 if (ss_req->depth == STEP_DEPTH_INTO) {
5224                         /* Enable global stepping so we stop at method entry too */
5225                         enable_global = TRUE;
5226                 }
5227
5228                 /*
5229                  * The ctx/frame info computed above will become invalid when we continue.
5230                  */
5231                 tls->context.valid = FALSE;
5232                 tls->async_state.valid = FALSE;
5233                 invalidate_frames (tls);
5234         }
5235
5236         if (enable_global) {
5237                 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5238                 ss_req->global = TRUE;
5239                 start_single_stepping ();
5240         } else if (!ss_req->bps) {
5241                 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5242                 ss_req->global = TRUE;
5243                 start_single_stepping ();
5244         } else {
5245                 ss_req->global = FALSE;
5246         }
5247 }
5248
5249 /*
5250  * Start single stepping of thread THREAD
5251  */
5252 static ErrorCode
5253 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5254 {
5255         DebuggerTlsData *tls;
5256         MonoSeqPointInfo *info = NULL;
5257         SeqPoint *sp = NULL;
5258         SeqPoint local_sp;
5259         gboolean found_sp;
5260         MonoMethod *method = NULL;
5261         MonoDebugMethodInfo *minfo;
5262         gboolean step_to_catch = FALSE;
5263         gboolean set_ip = FALSE;
5264         StackFrame **frames = NULL;
5265         int nframes = 0;
5266
5267         if (suspend_count == 0)
5268                 return ERR_NOT_SUSPENDED;
5269
5270         wait_for_suspend ();
5271
5272         // FIXME: Multiple requests
5273         if (ss_req) {
5274                 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5275                 return ERR_NOT_IMPLEMENTED;
5276         }
5277
5278         DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5279
5280         ss_req = g_new0 (SingleStepReq, 1);
5281         ss_req->req = req;
5282         ss_req->thread = thread;
5283         ss_req->size = size;
5284         ss_req->depth = depth;
5285         ss_req->filter = filter;
5286         req->info = ss_req;
5287
5288         mono_loader_lock ();
5289         tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5290         mono_loader_unlock ();
5291         g_assert (tls);
5292         g_assert (tls->context.valid);
5293
5294         if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5295                 /*
5296                  * Need to start single stepping from restore_state and not from the current state
5297                  */
5298                 set_ip = TRUE;
5299                 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5300         }
5301
5302         ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5303
5304         if (tls->catch_state.valid) {
5305                 gboolean res;
5306                 StackFrameInfo frame;
5307                 MonoContext new_ctx;
5308                 MonoLMF *lmf = NULL;
5309
5310                 /*
5311                  * We are stopped at a throw site. Stepping should go to the catch site.
5312                  */
5313
5314                 /* Find the the jit info for the catch context */
5315                 res = mono_find_jit_info_ext (
5316                         (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5317                         (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5318                         NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5319                 g_assert (res);
5320                 g_assert (frame.type == FRAME_TYPE_MANAGED);
5321
5322                 /*
5323                  * Find the seq point corresponding to the landing site ip, which is the first seq
5324                  * point after ip.
5325                  */
5326                 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5327                 sp = (found_sp)? &local_sp : NULL;
5328                 if (!sp)
5329                         no_seq_points_found (frame.method, frame.native_offset);
5330                 g_assert (sp);
5331
5332                 method = frame.method;
5333
5334                 step_to_catch = TRUE;
5335                 /* This make sure the seq point is not skipped by process_single_step () */
5336                 ss_req->last_sp = NULL;
5337         }
5338
5339         if (!step_to_catch) {
5340                 StackFrame *frame = NULL;
5341
5342                 if (set_ip) {
5343                         if (frames && nframes)
5344                                 frame = frames [0];
5345                 } else {
5346                         compute_frame_info (thread, tls);
5347
5348                         if (tls->frame_count)
5349                                 frame = tls->frames [0];
5350                 }
5351
5352                 if (ss_req->size == STEP_SIZE_LINE) {
5353                         if (frame) {
5354                                 ss_req->last_method = frame->method;
5355                                 ss_req->last_line = -1;
5356
5357                                 minfo = mono_debug_lookup_method (frame->method);
5358                                 if (minfo && frame->il_offset != -1) {
5359                                         MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5360
5361                                         if (loc) {
5362                                                 ss_req->last_line = loc->row;
5363                                                 g_free (loc);
5364                                         }
5365                                 }
5366                         }
5367                 }
5368
5369                 if (frame) {
5370                         if (!method && frame->il_offset != -1) {
5371                                 /* FIXME: Sort the table and use a binary search */
5372                                 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5373                                 sp = (found_sp)? &local_sp : NULL;
5374                                 if (!sp)
5375                                         no_seq_points_found (frame->method, frame->native_offset);
5376                                 g_assert (sp);
5377                                 method = frame->method;
5378                         }
5379                 }
5380         }
5381
5382         ss_req->start_method = method;
5383
5384         ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5385
5386         if (frames)
5387                 free_frames (frames, nframes);
5388
5389         return ERR_NONE;
5390 }
5391
5392 static void
5393 ss_destroy (SingleStepReq *req)
5394 {
5395         // FIXME: Locking
5396         g_assert (ss_req == req);
5397
5398         ss_stop (ss_req);
5399
5400         g_free (ss_req);
5401         ss_req = NULL;
5402 }
5403
5404 static void
5405 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5406 {
5407         GSList *l;
5408         gboolean found = TRUE;
5409
5410         while (found) {
5411                 found = FALSE;
5412                 for (l = ss_req->bps; l; l = l->next) {
5413                         if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5414                                 clear_breakpoint ((MonoBreakpoint *)l->data);
5415                                 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5416                                 found = TRUE;
5417                                 break;
5418                         }
5419                 }
5420         }
5421 }
5422
5423 /*
5424  * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5425  */
5426 void
5427 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5428 {
5429         int suspend_policy;
5430         GSList *events;
5431         EventInfo ei;
5432
5433         if (!agent_config.enabled)
5434                 return;
5435
5436         mono_loader_lock ();
5437         events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5438         mono_loader_unlock ();
5439
5440         ei.level = level;
5441         ei.category = category ? mono_string_to_utf8 (category) : NULL;
5442         ei.message = message ? mono_string_to_utf8 (message) : NULL;
5443
5444         process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5445
5446         g_free (ei.category);
5447         g_free (ei.message);
5448 }
5449
5450 gboolean
5451 mono_debugger_agent_debug_log_is_enabled (void)
5452 {
5453         /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5454         return agent_config.enabled;
5455 }
5456
5457 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5458 void
5459 mono_debugger_agent_unhandled_exception (MonoException *exc)
5460 {
5461         int suspend_policy;
5462         GSList *events;
5463         EventInfo ei;
5464
5465         if (!inited)
5466                 return;
5467
5468         memset (&ei, 0, sizeof (EventInfo));
5469         ei.exc = (MonoObject*)exc;
5470
5471         mono_loader_lock ();
5472         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5473         mono_loader_unlock ();
5474
5475         process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5476 }
5477 #endif
5478
5479 void
5480 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx, 
5481                                       MonoContext *catch_ctx)
5482 {
5483         int i, j, suspend_policy;
5484         GSList *events;
5485         MonoJitInfo *ji, *catch_ji;
5486         EventInfo ei;
5487         DebuggerTlsData *tls = NULL;
5488
5489         if (thread_to_tls != NULL) {
5490                 MonoInternalThread *thread = mono_thread_internal_current ();
5491
5492                 mono_loader_lock ();
5493                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5494                 mono_loader_unlock ();
5495
5496                 if (tls && tls->abort_requested)
5497                         return;
5498                 if (tls && tls->disable_breakpoints)
5499                         return;
5500         }
5501
5502         memset (&ei, 0, sizeof (EventInfo));
5503
5504         /* Just-In-Time debugging */
5505         if (!catch_ctx) {
5506                 if (agent_config.onuncaught && !inited) {
5507                         finish_agent_init (FALSE);
5508
5509                         /*
5510                          * Send an unsolicited EXCEPTION event with a dummy request id.
5511                          */
5512                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5513                         ei.exc = (MonoObject*)exc;
5514                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5515                         return;
5516                 }
5517         } else if (agent_config.onthrow && !inited) {
5518                 GSList *l;
5519                 gboolean found = FALSE;
5520
5521                 for (l = agent_config.onthrow; l; l = l->next) {
5522                         char *ex_type = (char *)l->data;
5523                         char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5524
5525                         if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5526                                 found = TRUE;
5527
5528                         g_free (f);
5529                 }
5530
5531                 if (found) {
5532                         finish_agent_init (FALSE);
5533
5534                         /*
5535                          * Send an unsolicited EXCEPTION event with a dummy request id.
5536                          */
5537                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5538                         ei.exc = (MonoObject*)exc;
5539                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5540                         return;
5541                 }
5542         }
5543
5544         if (!inited)
5545                 return;
5546
5547         ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5548         if (catch_ctx)
5549                 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5550         else
5551                 catch_ji = NULL;
5552
5553         ei.exc = (MonoObject*)exc;
5554         ei.caught = catch_ctx != NULL;
5555
5556         mono_loader_lock ();
5557
5558         /* Treat exceptions which are caught in non-user code as unhandled */
5559         for (i = 0; i < event_requests->len; ++i) {
5560                 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5561                 if (req->event_kind != EVENT_KIND_EXCEPTION)
5562                         continue;
5563
5564                 for (j = 0; j < req->nmodifiers; ++j) {
5565                         Modifier *mod = &req->modifiers [j];
5566
5567                         if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5568                                 int k;
5569                                 gboolean found = FALSE;
5570                                 MonoAssembly **assemblies = mod->data.assemblies;
5571
5572                                 if (assemblies) {
5573                                         for (k = 0; assemblies [k]; ++k)
5574                                                 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5575                                                         found = TRUE;
5576                                 }
5577                                 if (!found)
5578                                         ei.caught = FALSE;
5579                         }
5580                 }
5581         }
5582
5583         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5584         mono_loader_unlock ();
5585
5586         if (tls && ei.caught && catch_ctx) {
5587                 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5588                 tls->catch_state.ctx = *catch_ctx;
5589                 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5590                 tls->catch_state.valid = TRUE;
5591         }
5592
5593         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5594
5595         if (tls)
5596                 tls->catch_state.valid = FALSE;
5597 }
5598
5599 void
5600 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5601 {
5602         DebuggerTlsData *tls;
5603
5604         if (!inited)
5605                 return;
5606
5607         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5608         if (!tls)
5609                 return;
5610
5611         /*
5612          * We're about to invoke an exception filter during the first pass of exception handling.
5613          *
5614          * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5615          * 'orig_ctx' is the context where the exception has been thrown.
5616          *
5617          *
5618          * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5619          *
5620          * If we're stopped in Filter(), normal stack unwinding would first unwind to
5621          * the call site (line 37) and then continue to Main(), but it would never
5622          * include the throw site (line 32).
5623          *
5624          * Since exception filters are invoked during the first pass of exception handling,
5625          * the stack frames of the throw site are still intact, so we should include them
5626          * in a stack trace.
5627          *
5628          * We do this here by saving the context of the throw site in 'tls->filter_state'.
5629          *
5630          * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5631          * but report the location of the 'throw' to the user.
5632          *
5633          */
5634
5635         g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5636 }
5637
5638 void
5639 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5640 {
5641         DebuggerTlsData *tls;
5642
5643         if (!inited)
5644                 return;
5645
5646         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5647         if (!tls)
5648                 return;
5649
5650         tls->filter_state.valid = FALSE;
5651 }
5652
5653 /*
5654  * buffer_add_value_full:
5655  *
5656  *   Add the encoding of the value at ADDR described by T to the buffer.
5657  * AS_VTYPE determines whenever to treat primitive types as primitive types or
5658  * vtypes.
5659  */
5660 static void
5661 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5662                                            gboolean as_vtype, GHashTable *parent_vtypes)
5663 {
5664         MonoObject *obj;
5665         gboolean boxed_vtype = FALSE;
5666
5667         if (t->byref) {
5668                 if (!(*(void**)addr)) {
5669                         /* This can happen with compiler generated locals */
5670                         //printf ("%s\n", mono_type_full_name (t));
5671                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5672                         return;
5673                 }
5674                 g_assert (*(void**)addr);
5675                 addr = *(void**)addr;
5676         }
5677
5678         if (as_vtype) {
5679                 switch (t->type) {
5680                 case MONO_TYPE_BOOLEAN:
5681                 case MONO_TYPE_I1:
5682                 case MONO_TYPE_U1:
5683                 case MONO_TYPE_CHAR:
5684                 case MONO_TYPE_I2:
5685                 case MONO_TYPE_U2:
5686                 case MONO_TYPE_I4:
5687                 case MONO_TYPE_U4:
5688                 case MONO_TYPE_R4:
5689                 case MONO_TYPE_I8:
5690                 case MONO_TYPE_U8:
5691                 case MONO_TYPE_R8:
5692                 case MONO_TYPE_I:
5693                 case MONO_TYPE_U:
5694                 case MONO_TYPE_PTR:
5695                         goto handle_vtype;
5696                         break;
5697                 default:
5698                         break;
5699                 }
5700         }
5701
5702         switch (t->type) {
5703         case MONO_TYPE_VOID:
5704                 buffer_add_byte (buf, t->type);
5705                 break;
5706         case MONO_TYPE_BOOLEAN:
5707         case MONO_TYPE_I1:
5708         case MONO_TYPE_U1:
5709                 buffer_add_byte (buf, t->type);
5710                 buffer_add_int (buf, *(gint8*)addr);
5711                 break;
5712         case MONO_TYPE_CHAR:
5713         case MONO_TYPE_I2:
5714         case MONO_TYPE_U2:
5715                 buffer_add_byte (buf, t->type);
5716                 buffer_add_int (buf, *(gint16*)addr);
5717                 break;
5718         case MONO_TYPE_I4:
5719         case MONO_TYPE_U4:
5720         case MONO_TYPE_R4:
5721                 buffer_add_byte (buf, t->type);
5722                 buffer_add_int (buf, *(gint32*)addr);
5723                 break;
5724         case MONO_TYPE_I8:
5725         case MONO_TYPE_U8:
5726         case MONO_TYPE_R8:
5727                 buffer_add_byte (buf, t->type);
5728                 buffer_add_long (buf, *(gint64*)addr);
5729                 break;
5730         case MONO_TYPE_I:
5731         case MONO_TYPE_U:
5732                 /* Treat it as a vtype */
5733                 goto handle_vtype;
5734         case MONO_TYPE_PTR: {
5735                 gssize val = *(gssize*)addr;
5736                 
5737                 buffer_add_byte (buf, t->type);
5738                 buffer_add_long (buf, val);
5739                 break;
5740         }
5741         handle_ref:
5742         case MONO_TYPE_STRING:
5743         case MONO_TYPE_SZARRAY:
5744         case MONO_TYPE_OBJECT:
5745         case MONO_TYPE_CLASS:
5746         case MONO_TYPE_ARRAY:
5747                 obj = *(MonoObject**)addr;
5748
5749                 if (!obj) {
5750                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5751                 } else {
5752                         if (obj->vtable->klass->valuetype) {
5753                                 t = &obj->vtable->klass->byval_arg;
5754                                 addr = mono_object_unbox (obj);
5755                                 boxed_vtype = TRUE;
5756                                 goto handle_vtype;
5757                         } else if (obj->vtable->klass->rank) {
5758                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5759                         } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5760                                 buffer_add_byte (buf, MONO_TYPE_CLASS);
5761                         } else {
5762                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5763                         }
5764                         buffer_add_objid (buf, obj);
5765                 }
5766                 break;
5767         handle_vtype:
5768         case MONO_TYPE_VALUETYPE:
5769         case MONO_TYPE_TYPEDBYREF: {
5770                 int nfields;
5771                 gpointer iter;
5772                 MonoClassField *f;
5773                 MonoClass *klass = mono_class_from_mono_type (t);
5774                 int vtype_index;
5775
5776                 if (boxed_vtype) {
5777                         /*
5778                          * Handle boxed vtypes recursively referencing themselves using fields.
5779                          */
5780                         if (!parent_vtypes)
5781                                 parent_vtypes = g_hash_table_new (NULL, NULL);
5782                         vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5783                         if (vtype_index) {
5784                                 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5785                                         buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5786                                         buffer_add_int (buf, vtype_index - 1);
5787                                 } else {
5788                                         /* The client can't handle PARENT_VTYPE */
5789                                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5790                                 }
5791                                 break;
5792                         } else {
5793                                 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5794                         }
5795                 }
5796
5797                 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5798                 buffer_add_byte (buf, klass->enumtype);
5799                 buffer_add_typeid (buf, domain, klass);
5800
5801                 nfields = 0;
5802                 iter = NULL;
5803                 while ((f = mono_class_get_fields (klass, &iter))) {
5804                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5805                                 continue;
5806                         if (mono_field_is_deleted (f))
5807                                 continue;
5808                         nfields ++;
5809                 }
5810                 buffer_add_int (buf, nfields);
5811
5812                 iter = NULL;
5813                 while ((f = mono_class_get_fields (klass, &iter))) {
5814                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5815                                 continue;
5816                         if (mono_field_is_deleted (f))
5817                                 continue;
5818                         buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5819                 }
5820
5821                 if (boxed_vtype) {
5822                         g_hash_table_remove (parent_vtypes, addr);
5823                         if (g_hash_table_size (parent_vtypes) == 0) {
5824                                 g_hash_table_destroy (parent_vtypes);
5825                                 parent_vtypes = NULL;
5826                         }
5827                 }
5828                 break;
5829         }
5830         case MONO_TYPE_GENERICINST:
5831                 if (mono_type_generic_inst_is_valuetype (t)) {
5832                         goto handle_vtype;
5833                 } else {
5834                         goto handle_ref;
5835                 }
5836                 break;
5837         default:
5838                 NOT_IMPLEMENTED;
5839         }
5840 }
5841
5842 static void
5843 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5844 {
5845         buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5846 }
5847
5848 static gboolean
5849 obj_is_of_type (MonoObject *obj, MonoType *t)
5850 {
5851         MonoClass *klass = obj->vtable->klass;
5852         if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5853                 if (mono_class_is_transparent_proxy (klass)) {
5854                         klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5855                         if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5856                                 return TRUE;
5857                         }
5858                 }
5859                 return FALSE;
5860         }
5861         return TRUE;
5862 }
5863
5864 static ErrorCode
5865 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5866
5867 static ErrorCode
5868 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5869 {
5870         gboolean is_enum;
5871         MonoClass *klass;
5872         MonoClassField *f;
5873         int nfields;
5874         gpointer iter = NULL;
5875         MonoDomain *d;
5876         ErrorCode err;
5877
5878         is_enum = decode_byte (buf, &buf, limit);
5879         /* Enums are sent as a normal vtype */
5880         if (is_enum)
5881                 return ERR_NOT_IMPLEMENTED;
5882         klass = decode_typeid (buf, &buf, limit, &d, &err);
5883         if (err != ERR_NONE)
5884                 return err;
5885
5886         if (t && klass != mono_class_from_mono_type (t)) {
5887                 char *name = mono_type_full_name (t);
5888                 char *name2 = mono_type_full_name (&klass->byval_arg);
5889                 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5890                 g_free (name);
5891                 g_free (name2);
5892                 return ERR_INVALID_ARGUMENT;
5893         }
5894
5895         nfields = decode_int (buf, &buf, limit);
5896         while ((f = mono_class_get_fields (klass, &iter))) {
5897                 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5898                         continue;
5899                 if (mono_field_is_deleted (f))
5900                         continue;
5901                 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5902                 if (err != ERR_NONE)
5903                         return err;
5904                 nfields --;
5905         }
5906         g_assert (nfields == 0);
5907
5908         *endbuf = buf;
5909
5910         return ERR_NONE;
5911 }
5912
5913 static ErrorCode
5914 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5915 {
5916         ErrorCode err;
5917
5918         if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5919                 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5920                 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5921                 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5922                 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5923                 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5924                 char *name = mono_type_full_name (t);
5925                 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5926                 g_free (name);
5927                 return ERR_INVALID_ARGUMENT;
5928         }
5929
5930         switch (t->type) {
5931         case MONO_TYPE_BOOLEAN:
5932                 *(guint8*)addr = decode_int (buf, &buf, limit);
5933                 break;
5934         case MONO_TYPE_CHAR:
5935                 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5936                 break;
5937         case MONO_TYPE_I1:
5938                 *(gint8*)addr = decode_int (buf, &buf, limit);
5939                 break;
5940         case MONO_TYPE_U1:
5941                 *(guint8*)addr = decode_int (buf, &buf, limit);
5942                 break;
5943         case MONO_TYPE_I2:
5944                 *(gint16*)addr = decode_int (buf, &buf, limit);
5945                 break;
5946         case MONO_TYPE_U2:
5947                 *(guint16*)addr = decode_int (buf, &buf, limit);
5948                 break;
5949         case MONO_TYPE_I4:
5950                 *(gint32*)addr = decode_int (buf, &buf, limit);
5951                 break;
5952         case MONO_TYPE_U4:
5953                 *(guint32*)addr = decode_int (buf, &buf, limit);
5954                 break;
5955         case MONO_TYPE_I8:
5956                 *(gint64*)addr = decode_long (buf, &buf, limit);
5957                 break;
5958         case MONO_TYPE_U8:
5959                 *(guint64*)addr = decode_long (buf, &buf, limit);
5960                 break;
5961         case MONO_TYPE_R4:
5962                 *(guint32*)addr = decode_int (buf, &buf, limit);
5963                 break;
5964         case MONO_TYPE_R8:
5965                 *(guint64*)addr = decode_long (buf, &buf, limit);
5966                 break;
5967         case MONO_TYPE_PTR:
5968                 /* We send these as I8, so we get them back as such */
5969                 g_assert (type == MONO_TYPE_I8);
5970                 *(gssize*)addr = decode_long (buf, &buf, limit);
5971                 break;
5972         case MONO_TYPE_GENERICINST:
5973                 if (MONO_TYPE_ISSTRUCT (t)) {
5974                         /* The client sends these as a valuetype */
5975                         goto handle_vtype;
5976                 } else {
5977                         goto handle_ref;
5978                 }
5979                 break;
5980         case MONO_TYPE_I:
5981         case MONO_TYPE_U:
5982                 /* We send these as vtypes, so we get them back as such */
5983                 g_assert (type == MONO_TYPE_VALUETYPE);
5984                 /* Fall through */
5985                 handle_vtype:
5986         case MONO_TYPE_VALUETYPE:
5987                 if (type == MONO_TYPE_OBJECT) {
5988                         /* Boxed vtype */
5989                         int objid = decode_objid (buf, &buf, limit);
5990                         ErrorCode err;
5991                         MonoObject *obj;
5992
5993                         err = get_object (objid, (MonoObject**)&obj);
5994                         if (err != ERR_NONE)
5995                                 return err;
5996                         if (!obj)
5997                                 return ERR_INVALID_ARGUMENT;
5998                         if (obj->vtable->klass != mono_class_from_mono_type (t)) {
5999                                 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6000                                 return ERR_INVALID_ARGUMENT;
6001                         }
6002                         memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6003                 } else {
6004                         err = decode_vtype (t, domain, addr, buf, &buf, limit);
6005                         if (err != ERR_NONE)
6006                                 return err;
6007                 }
6008                 break;
6009         handle_ref:
6010         default:
6011                 if (MONO_TYPE_IS_REFERENCE (t)) {
6012                         if (type == MONO_TYPE_OBJECT) {
6013                                 int objid = decode_objid (buf, &buf, limit);
6014                                 ErrorCode err;
6015                                 MonoObject *obj;
6016
6017                                 err = get_object (objid, (MonoObject**)&obj);
6018                                 if (err != ERR_NONE)
6019                                         return err;
6020
6021                                 if (obj) {
6022                                         if (!obj_is_of_type (obj, t)) {
6023                                                 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6024                                                 return ERR_INVALID_ARGUMENT;
6025                                         }
6026                                 }
6027                                 if (obj && obj->vtable->domain != domain)
6028                                         return ERR_INVALID_ARGUMENT;
6029
6030                                 mono_gc_wbarrier_generic_store (addr, obj);
6031                         } else if (type == VALUE_TYPE_ID_NULL) {
6032                                 *(MonoObject**)addr = NULL;
6033                         } else if (type == MONO_TYPE_VALUETYPE) {
6034                                 MonoError error;
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_checked (d, klass, vtype_buf, &error);
6067                                 mono_error_cleanup (&error);
6068                                 g_free (vtype_buf);
6069                         } else {
6070                                 char *name = mono_type_full_name (t);
6071                                 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6072                                 g_free (name);
6073                                 return ERR_INVALID_ARGUMENT;
6074                         }
6075                 } else {
6076                         NOT_IMPLEMENTED;
6077                 }
6078                 break;
6079         }
6080
6081         *endbuf = buf;
6082
6083         return ERR_NONE;
6084 }
6085
6086 static ErrorCode
6087 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6088 {
6089         MonoError error;
6090         ErrorCode err;
6091         int type = decode_byte (buf, &buf, limit);
6092
6093         if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6094                 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6095                 guint8 *nullable_buf;
6096
6097                 /*
6098                  * First try decoding it as a Nullable`1
6099                  */
6100                 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6101                 if (err == ERR_NONE)
6102                         return err;
6103
6104                 /*
6105                  * Then try decoding as a primitive value or null.
6106                  */
6107                 if (targ->type == type) {
6108                         nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6109                         err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6110                         if (err != ERR_NONE) {
6111                                 g_free (nullable_buf);
6112                                 return err;
6113                         }
6114                         MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6115                         if (!is_ok (&error)) {
6116                                 mono_error_cleanup (&error);
6117                                 return ERR_INVALID_OBJECT;
6118                         }
6119                         mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6120                         g_free (nullable_buf);
6121                         *endbuf = buf;
6122                         return ERR_NONE;
6123                 } else if (type == VALUE_TYPE_ID_NULL) {
6124                         mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6125                         *endbuf = buf;
6126                         return ERR_NONE;
6127                 }
6128         }
6129
6130         return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6131 }
6132
6133 static void
6134 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6135 {
6136         guint32 flags;
6137         int reg;
6138         guint8 *addr, *gaddr;
6139         mgreg_t reg_val;
6140
6141         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6142         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6143
6144         switch (flags) {
6145         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6146                 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6147
6148                 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL);
6149                 break;
6150         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6151                 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6152                 addr += (gint32)var->offset;
6153
6154                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6155
6156                 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6157                 break;
6158         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6159                 NOT_IMPLEMENTED;
6160                 break;
6161         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6162         case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6163                 /* Same as regoffset, but with an indirection */
6164                 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6165                 addr += (gint32)var->offset;
6166
6167                 gaddr = (guint8 *)*(gpointer*)addr;
6168                 g_assert (gaddr);
6169                 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6170                 break;
6171         case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6172                 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6173                 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6174                 MonoGSharedVtMethodRuntimeInfo *info;
6175                 guint8 *locals;
6176                 int idx;
6177
6178                 idx = reg;
6179
6180                 g_assert (info_var);
6181                 g_assert (locals_var);
6182
6183                 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6184                 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6185                 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6186                         addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6187                         addr += (gint32)info_var->offset;
6188                         info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6189                 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6190                         info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6191                 } else {
6192                         g_assert_not_reached ();
6193                 }
6194                 g_assert (info);
6195
6196                 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6197                 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6198                 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6199                         addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6200                         addr += (gint32)locals_var->offset;
6201                         locals = (guint8 *)*(gpointer*)addr;
6202                 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6203                         locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6204                 } else {
6205                         g_assert_not_reached ();
6206                 }
6207                 g_assert (locals);
6208
6209                 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6210
6211                 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6212                 break;
6213         }
6214
6215         default:
6216                 g_assert_not_reached ();
6217         }
6218 }
6219
6220 static void
6221 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6222 {
6223         guint32 flags;
6224         int reg, size;
6225         guint8 *addr, *gaddr;
6226
6227         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6228         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6229
6230         if (MONO_TYPE_IS_REFERENCE (t))
6231                 size = sizeof (gpointer);
6232         else
6233                 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6234
6235         switch (flags) {
6236         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6237 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6238                 mgreg_t v;
6239                 gboolean is_signed = FALSE;
6240
6241                 if (t->byref) {
6242                         addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6243
6244                         if (addr) {
6245                                 // FIXME: Write barriers
6246                                 mono_gc_memmove_atomic (addr, val, size);
6247                         }
6248                         break;
6249                 }
6250
6251                 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6252                         is_signed = TRUE;
6253
6254                 switch (size) {
6255                 case 1:
6256                         v = is_signed ? *(gint8*)val : *(guint8*)val;
6257                         break;
6258                 case 2:
6259                         v = is_signed ? *(gint16*)val : *(guint16*)val;
6260                         break;
6261                 case 4:
6262                         v = is_signed ? *(gint32*)val : *(guint32*)val;
6263                         break;
6264                 case 8:
6265                         v = is_signed ? *(gint64*)val : *(guint64*)val;
6266                         break;
6267                 default:
6268                         g_assert_not_reached ();
6269                 }
6270
6271                 /* Set value on the stack or in the return ctx */
6272                 if (reg_locations [reg]) {
6273                         /* Saved on the stack */
6274                         DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6275                         *(reg_locations [reg]) = v;
6276                 } else {
6277                         /* Not saved yet */
6278                         DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6279                         mono_arch_context_set_int_reg (restore_ctx, reg, v);
6280                 }                       
6281
6282                 // FIXME: Move these to mono-context.h/c.
6283                 mono_arch_context_set_int_reg (ctx, reg, v);
6284 #else
6285                 // FIXME: Can't set registers, so we disable linears
6286                 NOT_IMPLEMENTED;
6287 #endif
6288                 break;
6289         }
6290         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6291                 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6292                 addr += (gint32)var->offset;
6293
6294                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6295
6296                 if (t->byref) {
6297                         addr = *(guint8**)addr;
6298
6299                         if (!addr)
6300                                 break;
6301                 }
6302                         
6303                 // FIXME: Write barriers
6304                 mono_gc_memmove_atomic (addr, val, size);
6305                 break;
6306         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6307                 /* Same as regoffset, but with an indirection */
6308                 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6309                 addr += (gint32)var->offset;
6310
6311                 gaddr = (guint8 *)*(gpointer*)addr;
6312                 g_assert (gaddr);
6313                 // FIXME: Write barriers
6314                 mono_gc_memmove_atomic (gaddr, val, size);
6315                 break;
6316         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6317                 NOT_IMPLEMENTED;
6318                 break;
6319         default:
6320                 g_assert_not_reached ();
6321         }
6322 }
6323
6324 static void
6325 clear_event_request (int req_id, int etype)
6326 {
6327         int i;
6328
6329         mono_loader_lock ();
6330         for (i = 0; i < event_requests->len; ++i) {
6331                 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6332
6333                 if (req->id == req_id && req->event_kind == etype) {
6334                         if (req->event_kind == EVENT_KIND_BREAKPOINT)
6335                                 clear_breakpoint ((MonoBreakpoint *)req->info);
6336                         if (req->event_kind == EVENT_KIND_STEP)
6337                                 ss_destroy ((SingleStepReq *)req->info);
6338                         if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6339                                 clear_breakpoint ((MonoBreakpoint *)req->info);
6340                         if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6341                                 clear_breakpoint ((MonoBreakpoint *)req->info);
6342                         g_ptr_array_remove_index_fast (event_requests, i);
6343                         g_free (req);
6344                         break;
6345                 }
6346         }
6347         mono_loader_unlock ();
6348 }
6349
6350 static void
6351 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6352 {
6353         int i;
6354
6355         if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6356                 m->kind = MOD_KIND_NONE;
6357         if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6358                 int count = 0, match_count = 0, pos;
6359                 MonoAssembly **newassemblies;
6360
6361                 for (i = 0; m->data.assemblies [i]; ++i) {
6362                         count ++;
6363                         if (m->data.assemblies [i] == assembly)
6364                                 match_count ++;
6365                 }
6366
6367                 if (match_count) {
6368                         newassemblies = g_new0 (MonoAssembly*, count - match_count);
6369
6370                         pos = 0;
6371                         for (i = 0; i < count; ++i)
6372                                 if (m->data.assemblies [i] != assembly)
6373                                         newassemblies [pos ++] = m->data.assemblies [i];
6374                         g_assert (pos == count - match_count);
6375                         g_free (m->data.assemblies);
6376                         m->data.assemblies = newassemblies;
6377                 }
6378         }
6379 }
6380
6381 static void
6382 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6383 {
6384         int i;
6385
6386         for (i = 0; i < req->nmodifiers; ++i) {
6387                 Modifier *m = &req->modifiers [i];
6388
6389                 clear_assembly_from_modifier (req, m, assembly);
6390         }
6391 }
6392
6393 /*
6394  * clear_event_requests_for_assembly:
6395  *
6396  *   Clear all events requests which reference ASSEMBLY.
6397  */
6398 static void
6399 clear_event_requests_for_assembly (MonoAssembly *assembly)
6400 {
6401         int i;
6402         gboolean found;
6403
6404         mono_loader_lock ();
6405         found = TRUE;
6406         while (found) {
6407                 found = FALSE;
6408                 for (i = 0; i < event_requests->len; ++i) {
6409                         EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6410
6411                         clear_assembly_from_modifiers (req, assembly);
6412
6413                         if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6414                                 clear_event_request (req->id, req->event_kind);
6415                                 found = TRUE;
6416                                 break;
6417                         }
6418
6419                         if (req->event_kind == EVENT_KIND_STEP)
6420                                 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6421                 }
6422         }
6423         mono_loader_unlock ();
6424 }
6425
6426 /*
6427  * type_comes_from_assembly:
6428  *
6429  *   GHRFunc that returns TRUE if klass comes from assembly
6430  */
6431 static gboolean
6432 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6433 {
6434         return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6435 }
6436
6437 /*
6438  * clear_types_for_assembly:
6439  *
6440  *   Clears types from loaded_classes for a given assembly
6441  */
6442 static void
6443 clear_types_for_assembly (MonoAssembly *assembly)
6444 {
6445         MonoDomain *domain = mono_domain_get ();
6446         AgentDomainInfo *info = NULL;
6447
6448         if (!domain || !domain_jit_info (domain))
6449                 /* Can happen during shutdown */
6450                 return;
6451
6452         info = get_agent_domain_info (domain);
6453
6454         mono_loader_lock ();
6455         g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6456         mono_loader_unlock ();
6457 }
6458
6459 static void
6460 add_thread (gpointer key, gpointer value, gpointer user_data)
6461 {
6462         MonoInternalThread *thread = (MonoInternalThread *)value;
6463         Buffer *buf = (Buffer *)user_data;
6464
6465         buffer_add_objid (buf, (MonoObject*)thread);
6466 }
6467
6468 static ErrorCode
6469 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6470 {
6471         MonoError error;
6472         guint8 *end = invoke->endp;
6473         MonoMethod *m;
6474         int i, nargs;
6475         ErrorCode err;
6476         MonoMethodSignature *sig;
6477         guint8 **arg_buf;
6478         void **args;
6479         MonoObject *this_arg, *res, *exc;
6480         MonoDomain *domain;
6481         guint8 *this_buf;
6482 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6483         MonoLMFExt ext;
6484 #endif
6485         MonoStopwatch watch;
6486
6487         if (invoke->method) {
6488                 /* 
6489                  * Invoke this method directly, currently only Environment.Exit () is supported.
6490                  */
6491                 this_arg = NULL;
6492                 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>");
6493
6494                 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6495                 mono_error_assert_ok (&error);
6496
6497                 g_assert_not_reached ();
6498         }
6499
6500         m = decode_methodid (p, &p, end, &domain, &err);
6501         if (err != ERR_NONE)
6502                 return err;
6503         sig = mono_method_signature (m);
6504
6505         if (m->klass->valuetype)
6506                 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6507         else
6508                 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6509         if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6510                 /* Should be null */
6511                 int type = decode_byte (p, &p, end);
6512                 if (type != VALUE_TYPE_ID_NULL) {
6513                         DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6514                         return ERR_INVALID_ARGUMENT;
6515                 }
6516                 memset (this_buf, 0, mono_class_instance_size (m->klass));
6517         } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6518                         /* Could be null */
6519                         guint8 *tmp_p;
6520
6521                         int type = decode_byte (p, &tmp_p, end);
6522                         if (type == VALUE_TYPE_ID_NULL) {
6523                                 memset (this_buf, 0, mono_class_instance_size (m->klass));
6524                                 p = tmp_p;
6525                         } else {
6526                                 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6527                                 if (err != ERR_NONE)
6528                                         return err;
6529                         }
6530         } else {
6531                 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6532                 if (err != ERR_NONE)
6533                         return err;
6534         }
6535
6536         if (!m->klass->valuetype)
6537                 this_arg = *(MonoObject**)this_buf;
6538         else
6539                 this_arg = NULL;
6540
6541         if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6542                 if (!this_arg) {
6543                         DEBUG_PRINTF (1, "[%p] Error: Interface method invoked 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                 /* Transform this to the format the rest of the code expects it to be */
6548                 if (m->klass->valuetype) {
6549                         this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6550                         memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6551                 }
6552         } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6553                 if (!this_arg) {
6554                         DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6555                         return ERR_INVALID_ARGUMENT;
6556                 }
6557                 m = mono_object_get_virtual_method (this_arg, m);
6558                 if (m->klass->valuetype) {
6559                         this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6560                         memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6561                 }
6562         }
6563
6564         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>");
6565
6566         if (this_arg && this_arg->vtable->domain != domain)
6567                 NOT_IMPLEMENTED;
6568
6569         if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6570                 if (!strcmp (m->name, ".ctor")) {
6571                         if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6572                                 return ERR_INVALID_ARGUMENT;
6573                         else {
6574                                 MonoError error;
6575                                 this_arg = mono_object_new_checked (domain, m->klass, &error);
6576                                 mono_error_assert_ok (&error);
6577                         }
6578                 } else {
6579                         return ERR_INVALID_ARGUMENT;
6580                 }
6581         }
6582
6583         if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6584                 return ERR_INVALID_ARGUMENT;
6585
6586         nargs = decode_int (p, &p, end);
6587         if (nargs != sig->param_count)
6588                 return ERR_INVALID_ARGUMENT;
6589         /* Use alloca to get gc tracking */
6590         arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6591         memset (arg_buf, 0, nargs * sizeof (gpointer));
6592         args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6593         for (i = 0; i < nargs; ++i) {
6594                 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6595                         err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6596                         if (err != ERR_NONE)
6597                                 break;
6598                         if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6599                                 NOT_IMPLEMENTED;
6600
6601                         if (sig->params [i]->byref) {
6602                                 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6603                                 *(gpointer*)arg_buf [i] = args [i];
6604                                 args [i] = arg_buf [i];
6605                         }
6606                 } else {
6607                         arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6608                         err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6609                         if (err != ERR_NONE)
6610                                 break;
6611                         args [i] = arg_buf [i];
6612                 }
6613         }
6614
6615         if (i < nargs)
6616                 return err;
6617
6618         if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6619                 tls->disable_breakpoints = TRUE;
6620         else
6621                 tls->disable_breakpoints = FALSE;
6622
6623         /* 
6624          * Add an LMF frame to link the stack frames on the invoke method with our caller.
6625          */
6626 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6627         if (invoke->has_ctx) {
6628                 MonoLMF **lmf_addr;
6629
6630                 lmf_addr = mono_get_lmf_addr ();
6631
6632                 /* Setup our lmf */
6633                 memset (&ext, 0, sizeof (ext));
6634                 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6635
6636                 ext.debugger_invoke = TRUE;
6637                 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6638
6639                 mono_set_lmf ((MonoLMF*)&ext);
6640         }
6641 #endif
6642
6643         mono_stopwatch_start (&watch);
6644         res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
6645         if (exc == NULL && !mono_error_ok (&error)) {
6646                 exc = (MonoObject*) mono_error_convert_to_exception (&error);
6647         } else {
6648                 mono_error_cleanup (&error); /* FIXME report error */
6649         }
6650         mono_stopwatch_stop (&watch);
6651         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));
6652         if (exc) {
6653                 buffer_add_byte (buf, 0);
6654                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6655         } else {
6656                 gboolean out_this = FALSE;
6657                 gboolean out_args = FALSE;
6658
6659                 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6660                         out_this = TRUE;
6661                 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6662                         out_args = TRUE;
6663                 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6664                 if (sig->ret->type == MONO_TYPE_VOID) {
6665                         if (!strcmp (m->name, ".ctor")) {
6666                                 if (!m->klass->valuetype)
6667                                         buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6668                                 else
6669                                         buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6670                         } else {
6671                                 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6672                         }
6673                 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6674                         buffer_add_value (buf, sig->ret, &res, domain);
6675                 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6676                         if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6677                                 MonoClass *k = mono_class_from_mono_type (sig->ret);
6678                                 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6679
6680                                 g_assert (nullable_buf);
6681                                 mono_nullable_init (nullable_buf, res, k);
6682                                 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6683                         } else {
6684                                 g_assert (res);
6685                                 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6686                         }
6687                 } else {
6688                         NOT_IMPLEMENTED;
6689                 }
6690                 if (out_this)
6691                         /* Return the new value of the receiver after the call */
6692                         buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6693                 if (out_args) {
6694                         buffer_add_int (buf, nargs);
6695                         for (i = 0; i < nargs; ++i) {
6696                                 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6697                                         buffer_add_value (buf, sig->params [i], &args [i], domain);
6698                                 else if (sig->params [i]->byref)
6699                                         /* add_value () does an indirection */
6700                                         buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6701                                 else
6702                                         buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6703                         }
6704                 }
6705         }
6706
6707         tls->disable_breakpoints = FALSE;
6708
6709 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6710         if (invoke->has_ctx)
6711                 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
6712 #endif
6713
6714         *endp = p;
6715         // FIXME: byref arguments
6716         // FIXME: varargs
6717         return ERR_NONE;
6718 }
6719
6720 /*
6721  * invoke_method:
6722  *
6723  *   Invoke the method given by tls->pending_invoke in the current thread.
6724  */
6725 static void
6726 invoke_method (void)
6727 {
6728         DebuggerTlsData *tls;
6729         InvokeData *invoke;
6730         int id;
6731         int i, mindex;
6732         ErrorCode err;
6733         Buffer buf;
6734         MonoContext restore_ctx;
6735         guint8 *p;
6736
6737         tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6738         g_assert (tls);
6739
6740         /*
6741          * Store the `InvokeData *' in `tls->invoke' until we're done with
6742          * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6743          */
6744
6745         mono_loader_lock ();
6746
6747         invoke = tls->pending_invoke;
6748         g_assert (invoke);
6749         tls->pending_invoke = NULL;
6750
6751         invoke->last_invoke = tls->invoke;
6752         tls->invoke = invoke;
6753
6754         mono_loader_unlock ();
6755
6756         tls->frames_up_to_date = FALSE;
6757
6758         id = invoke->id;
6759
6760         p = invoke->p;
6761         err = ERR_NONE;
6762         for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6763                 buffer_init (&buf, 128);
6764
6765                 if (err) {
6766                         /* Fail the other invokes as well */
6767                 } else {
6768                         err = do_invoke_method (tls, &buf, invoke, p, &p);
6769                 }
6770
6771                 if (tls->abort_requested) {
6772                         if (CHECK_PROTOCOL_VERSION (2, 42))
6773                                 err = ERR_INVOKE_ABORTED;
6774                 }
6775
6776                 /* Start suspending before sending the reply */
6777                 if (mindex == invoke->nmethods - 1) {
6778                         if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6779                                 for (i = 0; i < invoke->suspend_count; ++i)
6780                                         suspend_vm ();
6781                         }
6782                 }
6783
6784                 send_reply_packet (id, err, &buf);
6785         
6786                 buffer_free (&buf);
6787         }
6788
6789         memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6790
6791         if (invoke->has_ctx)
6792                 save_thread_context (&restore_ctx);
6793
6794         if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6795                 g_assert (tls->resume_count);
6796                 tls->resume_count -= invoke->suspend_count;
6797         }
6798
6799         DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6800
6801         /*
6802          * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6803          *
6804          * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6805          * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6806          * because we reset the abort here.
6807          */
6808
6809         mono_loader_lock ();
6810
6811         if (tls->abort_requested)
6812                 mono_thread_internal_reset_abort (tls->thread);
6813
6814         tls->invoke = tls->invoke->last_invoke;
6815         tls->abort_requested = FALSE;
6816
6817         mono_loader_unlock ();
6818
6819         g_free (invoke->p);
6820         g_free (invoke);
6821
6822         suspend_current ();
6823 }
6824
6825 static gboolean
6826 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6827 {
6828         MonoThread *thread = (MonoThread *)value;
6829         DebuggerTlsData *tls;
6830         gboolean res;
6831
6832         mono_loader_lock ();
6833         tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6834         g_assert (tls);
6835         res = tls->really_suspended;
6836         mono_loader_unlock ();
6837
6838         return res;
6839 }
6840
6841 static GPtrArray*
6842 get_source_files_for_type (MonoClass *klass)
6843 {
6844         gpointer iter = NULL;
6845         MonoMethod *method;
6846         MonoDebugSourceInfo *sinfo;
6847         GPtrArray *files;
6848         int i, j;
6849
6850         files = g_ptr_array_new ();
6851
6852         while ((method = mono_class_get_methods (klass, &iter))) {
6853                 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6854                 GPtrArray *source_file_list;
6855
6856                 if (minfo) {
6857                         mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6858                         for (j = 0; j < source_file_list->len; ++j) {
6859                                 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6860                                 for (i = 0; i < files->len; ++i)
6861                                         if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6862                                                 break;
6863                                 if (i == files->len)
6864                                         g_ptr_array_add (files, g_strdup (sinfo->source_file));
6865                         }
6866                         g_ptr_array_free (source_file_list, TRUE);
6867                 }
6868         }
6869
6870         return files;
6871 }
6872
6873 static ErrorCode
6874 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6875 {
6876         switch (command) {
6877         case CMD_VM_VERSION: {
6878                 char *build_info, *version;
6879
6880                 build_info = mono_get_runtime_build_info ();
6881                 version = g_strdup_printf ("mono %s", build_info);
6882
6883                 buffer_add_string (buf, version); /* vm version */
6884                 buffer_add_int (buf, MAJOR_VERSION);
6885                 buffer_add_int (buf, MINOR_VERSION);
6886                 g_free (build_info);
6887                 g_free (version);
6888                 break;
6889         }
6890         case CMD_VM_SET_PROTOCOL_VERSION: {
6891                 major_version = decode_int (p, &p, end);
6892                 minor_version = decode_int (p, &p, end);
6893                 protocol_version_set = TRUE;
6894                 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6895                 break;
6896         }
6897         case CMD_VM_ALL_THREADS: {
6898                 // FIXME: Domains
6899                 mono_loader_lock ();
6900                 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6901                 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6902                 mono_loader_unlock ();
6903                 break;
6904         }
6905         case CMD_VM_SUSPEND:
6906                 suspend_vm ();
6907                 wait_for_suspend ();
6908                 break;
6909         case CMD_VM_RESUME:
6910                 if (suspend_count == 0)
6911                         return ERR_NOT_SUSPENDED;
6912                 resume_vm ();
6913                 clear_suspended_objs ();
6914                 break;
6915         case CMD_VM_DISPOSE:
6916                 /* Clear all event requests */
6917                 mono_loader_lock ();
6918                 while (event_requests->len > 0) {
6919                         EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6920
6921                         clear_event_request (req->id, req->event_kind);
6922                 }
6923                 mono_loader_unlock ();
6924
6925                 while (suspend_count > 0)
6926                         resume_vm ();
6927                 disconnected = TRUE;
6928                 vm_start_event_sent = FALSE;
6929                 break;
6930         case CMD_VM_EXIT: {
6931                 MonoInternalThread *thread;
6932                 DebuggerTlsData *tls;
6933 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6934                 MonoClass *env_class;
6935 #endif
6936                 MonoMethod *exit_method = NULL;
6937                 gpointer *args;
6938                 int exit_code;
6939
6940                 exit_code = decode_int (p, &p, end);
6941
6942                 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6943
6944                 /* Have to send a reply before exiting */
6945                 send_reply_packet (id, 0, buf);
6946
6947                 /* Clear all event requests */
6948                 mono_loader_lock ();
6949                 while (event_requests->len > 0) {
6950                         EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6951
6952                         clear_event_request (req->id, req->event_kind);
6953                 }
6954                 mono_loader_unlock ();
6955
6956                 /*
6957                  * The JDWP documentation says that the shutdown is not orderly. It doesn't
6958                  * specify whenever a VM_DEATH event is sent. We currently do an orderly
6959                  * shutdown by hijacking a thread to execute Environment.Exit (). This is
6960                  * better than doing the shutdown ourselves, since it avoids various races.
6961                  */
6962
6963                 suspend_vm ();
6964                 wait_for_suspend ();
6965
6966 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6967                 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
6968                 if (env_class)
6969                         exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6970 #endif
6971
6972                 mono_loader_lock ();
6973                 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6974                 mono_loader_unlock ();
6975
6976                 if (thread && exit_method) {
6977                         mono_loader_lock ();
6978                         tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6979                         mono_loader_unlock ();
6980
6981                         args = g_new0 (gpointer, 1);
6982                         args [0] = g_malloc (sizeof (int));
6983                         *(int*)(args [0]) = exit_code;
6984
6985                         tls->pending_invoke = g_new0 (InvokeData, 1);
6986                         tls->pending_invoke->method = exit_method;
6987                         tls->pending_invoke->args = args;
6988                         tls->pending_invoke->nmethods = 1;
6989
6990                         while (suspend_count > 0)
6991                                 resume_vm ();
6992                 } else {
6993                         /* 
6994                          * No thread found, do it ourselves.
6995                          * FIXME: This can race with normal shutdown etc.
6996                          */
6997                         while (suspend_count > 0)
6998                                 resume_vm ();
6999
7000                         if (!mono_runtime_try_shutdown ())
7001                                 break;
7002
7003                         mono_environment_exitcode_set (exit_code);
7004
7005                         /* Suspend all managed threads since the runtime is going away */
7006                         DEBUG_PRINTF (1, "Suspending all threads...\n");
7007                         mono_thread_suspend_all_other_threads ();
7008                         DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7009                         mono_runtime_quit ();
7010                         transport_close2 ();
7011                         DEBUG_PRINTF (1, "Exiting...\n");
7012
7013                         exit (exit_code);
7014                 }
7015                 break;
7016         }               
7017         case CMD_VM_INVOKE_METHOD:
7018         case CMD_VM_INVOKE_METHODS: {
7019                 int objid = decode_objid (p, &p, end);
7020                 MonoThread *thread;
7021                 DebuggerTlsData *tls;
7022                 int i, count, flags, nmethods;
7023                 ErrorCode err;
7024
7025                 err = get_object (objid, (MonoObject**)&thread);
7026                 if (err != ERR_NONE)
7027                         return err;
7028
7029                 flags = decode_int (p, &p, end);
7030
7031                 if (command == CMD_VM_INVOKE_METHODS)
7032                         nmethods = decode_int (p, &p, end);
7033                 else
7034                         nmethods = 1;
7035
7036                 // Wait for suspending if it already started
7037                 if (suspend_count)
7038                         wait_for_suspend ();
7039                 if (!is_suspended ())
7040                         return ERR_NOT_SUSPENDED;
7041
7042                 mono_loader_lock ();
7043                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7044                 mono_loader_unlock ();
7045                 g_assert (tls);
7046
7047                 if (!tls->really_suspended)
7048                         /* The thread is still running native code, can't do invokes */
7049                         return ERR_NOT_SUSPENDED;
7050
7051                 /* 
7052                  * Store the invoke data into tls, the thread will execute it after it is
7053                  * resumed.
7054                  */
7055                 if (tls->pending_invoke)
7056                         return ERR_NOT_SUSPENDED;
7057                 tls->pending_invoke = g_new0 (InvokeData, 1);
7058                 tls->pending_invoke->id = id;
7059                 tls->pending_invoke->flags = flags;
7060                 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7061                 memcpy (tls->pending_invoke->p, p, end - p);
7062                 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7063                 tls->pending_invoke->suspend_count = suspend_count;
7064                 tls->pending_invoke->nmethods = nmethods;
7065
7066                 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7067                         resume_thread (THREAD_TO_INTERNAL (thread));
7068                 }
7069                 else {
7070                         count = suspend_count;
7071                         for (i = 0; i < count; ++i)
7072                                 resume_vm ();
7073                 }
7074                 break;
7075         }
7076         case CMD_VM_ABORT_INVOKE: {
7077                 int objid = decode_objid (p, &p, end);
7078                 MonoThread *thread;
7079                 DebuggerTlsData *tls;
7080                 int invoke_id;
7081                 ErrorCode err;
7082
7083                 err = get_object (objid, (MonoObject**)&thread);
7084                 if (err != ERR_NONE)
7085                         return err;
7086
7087                 invoke_id = decode_int (p, &p, end);
7088
7089                 mono_loader_lock ();
7090                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7091                 g_assert (tls);
7092
7093                 if (tls->abort_requested) {
7094                         DEBUG_PRINTF (1, "Abort already requested.\n");
7095                         mono_loader_unlock ();
7096                         break;
7097                 }
7098
7099                 /*
7100                  * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7101                  * actually the correct invocation.
7102                  *
7103                  * Careful, we do not stop the thread that's doing the invocation, so we can't
7104                  * inspect its stack.  However, invoke_method() also acquires the loader lock
7105                  * when it's done, so we're safe here.
7106                  *
7107                  */
7108
7109                 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7110                         mono_loader_unlock ();
7111                         return ERR_NO_INVOCATION;
7112                 }
7113
7114                 tls->abort_requested = TRUE;
7115
7116                 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7117                 mono_loader_unlock ();
7118                 break;
7119         }
7120
7121         case CMD_VM_SET_KEEPALIVE: {
7122                 int timeout = decode_int (p, &p, end);
7123                 agent_config.keepalive = timeout;
7124                 // FIXME:
7125 #ifndef DISABLE_SOCKET_TRANSPORT
7126                 set_keepalive ();
7127 #else
7128                 NOT_IMPLEMENTED;
7129 #endif
7130                 break;
7131         }
7132         case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7133                 GHashTableIter iter, kiter;
7134                 MonoDomain *domain;
7135                 MonoClass *klass;
7136                 GPtrArray *files;
7137                 int i;
7138                 char *fname, *basename;
7139                 gboolean ignore_case;
7140                 GSList *class_list, *l;
7141                 GPtrArray *res_classes, *res_domains;
7142
7143                 fname = decode_string (p, &p, end);
7144                 ignore_case = decode_byte (p, &p, end);
7145
7146                 basename = dbg_path_get_basename (fname);
7147
7148                 res_classes = g_ptr_array_new ();
7149                 res_domains = g_ptr_array_new ();
7150
7151                 mono_loader_lock ();
7152                 g_hash_table_iter_init (&iter, domains);
7153                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7154                         AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7155
7156                         /* Update 'source_file_to_class' cache */
7157                         g_hash_table_iter_init (&kiter, info->loaded_classes);
7158                         while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7159                                 if (!g_hash_table_lookup (info->source_files, klass)) {
7160                                         files = get_source_files_for_type (klass);
7161                                         g_hash_table_insert (info->source_files, klass, files);
7162
7163                                         for (i = 0; i < files->len; ++i) {
7164                                                 char *s = (char *)g_ptr_array_index (files, i);
7165                                                 char *s2 = dbg_path_get_basename (s);
7166                                                 char *s3;
7167
7168                                                 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7169                                                 if (!class_list) {
7170                                                         class_list = g_slist_prepend (class_list, klass);
7171                                                         g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7172                                                 } else {
7173                                                         class_list = g_slist_prepend (class_list, klass);
7174                                                         g_hash_table_insert (info->source_file_to_class, s2, class_list);
7175                                                 }
7176
7177                                                 /* The _ignorecase hash contains the lowercase path */
7178                                                 s3 = strdup_tolower (s2);
7179                                                 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7180                                                 if (!class_list) {
7181                                                         class_list = g_slist_prepend (class_list, klass);
7182                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7183                                                 } else {
7184                                                         class_list = g_slist_prepend (class_list, klass);
7185                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7186                                                 }
7187
7188                                                 g_free (s2);
7189                                                 g_free (s3);
7190                                         }
7191                                 }
7192                         }
7193
7194                         if (ignore_case) {
7195                                 char *s;
7196
7197                                 s = strdup_tolower (basename);
7198                                 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7199                                 g_free (s);
7200                         } else {
7201                                 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7202                         }
7203
7204                         for (l = class_list; l; l = l->next) {
7205                                 klass = (MonoClass *)l->data;
7206
7207                                 g_ptr_array_add (res_classes, klass);
7208                                 g_ptr_array_add (res_domains, domain);
7209                         }
7210                 }
7211                 mono_loader_unlock ();
7212
7213                 g_free (fname);
7214                 g_free (basename);
7215
7216                 buffer_add_int (buf, res_classes->len);
7217                 for (i = 0; i < res_classes->len; ++i)
7218                         buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7219                 g_ptr_array_free (res_classes, TRUE);
7220                 g_ptr_array_free (res_domains, TRUE);
7221                 break;
7222         }
7223         case CMD_VM_GET_TYPES: {
7224                 GHashTableIter iter;
7225                 MonoDomain *domain;
7226                 int i;
7227                 char *name;
7228                 gboolean ignore_case;
7229                 GPtrArray *res_classes, *res_domains;
7230                 MonoTypeNameParse info;
7231
7232                 name = decode_string (p, &p, end);
7233                 ignore_case = decode_byte (p, &p, end);
7234
7235                 if (!mono_reflection_parse_type (name, &info)) {
7236                         g_free (name);
7237                         mono_reflection_free_type_info (&info);
7238                         return ERR_INVALID_ARGUMENT;
7239                 }
7240
7241                 res_classes = g_ptr_array_new ();
7242                 res_domains = g_ptr_array_new ();
7243
7244                 mono_loader_lock ();
7245                 g_hash_table_iter_init (&iter, domains);
7246                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7247                         MonoAssembly *ass;
7248                         gboolean type_resolve;
7249                         MonoType *t;
7250                         GSList *tmp;
7251
7252                         mono_domain_assemblies_lock (domain);
7253                         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7254                                 ass = (MonoAssembly *)tmp->data;
7255
7256                                 if (ass->image) {
7257                                         MonoError error;
7258                                         type_resolve = TRUE;
7259                                         /* FIXME really okay to call while holding locks? */
7260                                         t = mono_reflection_get_type_checked (ass->image, &info, ignore_case, &type_resolve, &error);
7261                                         mono_error_cleanup (&error); 
7262                                         if (t) {
7263                                                 g_ptr_array_add (res_classes, mono_type_get_class (t));
7264                                                 g_ptr_array_add (res_domains, domain);
7265                                         }
7266                                 }
7267                         }
7268                         mono_domain_assemblies_unlock (domain);
7269                 }
7270                 mono_loader_unlock ();
7271
7272                 g_free (name);
7273                 mono_reflection_free_type_info (&info);
7274
7275                 buffer_add_int (buf, res_classes->len);
7276                 for (i = 0; i < res_classes->len; ++i)
7277                         buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7278                 g_ptr_array_free (res_classes, TRUE);
7279                 g_ptr_array_free (res_domains, TRUE);
7280                 break;
7281         }
7282         case CMD_VM_START_BUFFERING:
7283         case CMD_VM_STOP_BUFFERING:
7284                 /* Handled in the main loop */
7285                 break;
7286         default:
7287                 return ERR_NOT_IMPLEMENTED;
7288         }
7289
7290         return ERR_NONE;
7291 }
7292
7293 static ErrorCode
7294 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7295 {
7296         ErrorCode err;
7297         MonoError error;
7298
7299         switch (command) {
7300         case CMD_EVENT_REQUEST_SET: {
7301                 EventRequest *req;
7302                 int i, event_kind, suspend_policy, nmodifiers;
7303                 ModifierKind mod;
7304                 MonoMethod *method;
7305                 long location = 0;
7306                 MonoThread *step_thread;
7307                 int step_thread_id = 0;
7308                 StepDepth depth = STEP_DEPTH_INTO;
7309                 StepSize size = STEP_SIZE_MIN;
7310                 StepFilter filter = STEP_FILTER_NONE;
7311                 MonoDomain *domain;
7312                 Modifier *modifier;
7313
7314                 event_kind = decode_byte (p, &p, end);
7315                 suspend_policy = decode_byte (p, &p, end);
7316                 nmodifiers = decode_byte (p, &p, end);
7317
7318                 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7319                 req->id = InterlockedIncrement (&event_request_id);
7320                 req->event_kind = event_kind;
7321                 req->suspend_policy = suspend_policy;
7322                 req->nmodifiers = nmodifiers;
7323
7324                 method = NULL;
7325                 for (i = 0; i < nmodifiers; ++i) {
7326                         mod = (ModifierKind)decode_byte (p, &p, end);
7327
7328                         req->modifiers [i].kind = mod;
7329                         if (mod == MOD_KIND_COUNT) {
7330                                 req->modifiers [i].data.count = decode_int (p, &p, end);
7331                         } else if (mod == MOD_KIND_LOCATION_ONLY) {
7332                                 method = decode_methodid (p, &p, end, &domain, &err);
7333                                 if (err != ERR_NONE)
7334                                         return err;
7335                                 location = decode_long (p, &p, end);
7336                         } else if (mod == MOD_KIND_STEP) {
7337                                 step_thread_id = decode_id (p, &p, end);
7338                                 size = (StepSize)decode_int (p, &p, end);
7339                                 depth = (StepDepth)decode_int (p, &p, end);
7340                                 if (CHECK_PROTOCOL_VERSION (2, 16))
7341                                         filter = (StepFilter)decode_int (p, &p, end);
7342                                 req->modifiers [i].data.filter = filter;
7343                                 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7344                                         /* Treat STEP_THOUGH the same as HIDDEN */
7345                                         req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7346                         } else if (mod == MOD_KIND_THREAD_ONLY) {
7347                                 int id = decode_id (p, &p, end);
7348
7349                                 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7350                                 if (err != ERR_NONE) {
7351                                         g_free (req);
7352                                         return err;
7353                                 }
7354                         } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7355                                 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7356
7357                                 if (err != ERR_NONE)
7358                                         return err;
7359                                 req->modifiers [i].caught = decode_byte (p, &p, end);
7360                                 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7361                                 if (CHECK_PROTOCOL_VERSION (2, 25))
7362                                         req->modifiers [i].subclasses = decode_byte (p, &p, end);
7363                                 else
7364                                         req->modifiers [i].subclasses = TRUE;
7365                                 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" : "");
7366                                 if (exc_class) {
7367                                         req->modifiers [i].data.exc_class = exc_class;
7368
7369                                         if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7370                                                 g_free (req);
7371                                                 return ERR_INVALID_ARGUMENT;
7372                                         }
7373                                 }
7374                         } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7375                                 int n = decode_int (p, &p, end);
7376                                 int j;
7377
7378                                 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7379                                 for (j = 0; j < n; ++j) {
7380                                         req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7381                                         if (err != ERR_NONE) {
7382                                                 g_free (req->modifiers [i].data.assemblies);
7383                                                 return err;
7384                                         }
7385                                 }
7386                         } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7387                                 int n = decode_int (p, &p, end);
7388                                 int j;
7389
7390                                 modifier = &req->modifiers [i];
7391                                 modifier->data.source_files = 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                                         char *s2;
7395
7396                                         if (s) {
7397                                                 s2 = strdup_tolower (s);
7398                                                 g_hash_table_insert (modifier->data.source_files, s2, s2);
7399                                                 g_free (s);
7400                                         }
7401                                 }
7402                         } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7403                                 int n = decode_int (p, &p, end);
7404                                 int j;
7405
7406                                 modifier = &req->modifiers [i];
7407                                 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7408                                 for (j = 0; j < n; ++j) {
7409                                         char *s = decode_string (p, &p, end);
7410
7411                                         if (s)
7412                                                 g_hash_table_insert (modifier->data.type_names, s, s);
7413                                 }
7414                         } else {
7415                                 g_free (req);
7416                                 return ERR_NOT_IMPLEMENTED;
7417                         }
7418                 }
7419
7420                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7421                         g_assert (method);
7422
7423                         req->info = set_breakpoint (method, location, req, &error);
7424                         if (!mono_error_ok (&error)) {
7425                                 g_free (req);
7426                                 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7427                                 mono_error_cleanup (&error);
7428                                 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7429                         }
7430                 } else if (req->event_kind == EVENT_KIND_STEP) {
7431                         g_assert (step_thread_id);
7432
7433                         err = get_object (step_thread_id, (MonoObject**)&step_thread);
7434                         if (err != ERR_NONE) {
7435                                 g_free (req);
7436                                 return err;
7437                         }
7438
7439                         err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7440                         if (err != ERR_NONE) {
7441                                 g_free (req);
7442                                 return err;
7443                         }
7444                 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7445                         req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7446                 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7447                         req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7448                 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7449                 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7450                 } else {
7451                         if (req->nmodifiers) {
7452                                 g_free (req);
7453                                 return ERR_NOT_IMPLEMENTED;
7454                         }
7455                 }
7456
7457                 mono_loader_lock ();
7458                 g_ptr_array_add (event_requests, req);
7459                 
7460                 if (agent_config.defer) {
7461                         /* Transmit cached data to the client on receipt of the event request */
7462                         switch (req->event_kind) {
7463                         case EVENT_KIND_APPDOMAIN_CREATE:
7464                                 /* Emit load events for currently loaded domains */
7465                                 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7466                                 break;
7467                         case EVENT_KIND_ASSEMBLY_LOAD:
7468                                 /* Emit load events for currently loaded assemblies */
7469                                 mono_assembly_foreach (emit_assembly_load, NULL);
7470                                 break;
7471                         case EVENT_KIND_THREAD_START:
7472                                 /* Emit start events for currently started threads */
7473                                 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7474                                 break;
7475                         case EVENT_KIND_TYPE_LOAD:
7476                                 /* Emit type load events for currently loaded types */
7477                                 mono_domain_foreach (send_types_for_domain, NULL);
7478                                 break;
7479                         default:
7480                                 break;
7481                         }
7482                 }
7483                 mono_loader_unlock ();
7484
7485                 buffer_add_int (buf, req->id);
7486                 break;
7487         }
7488         case CMD_EVENT_REQUEST_CLEAR: {
7489                 int etype = decode_byte (p, &p, end);
7490                 int req_id = decode_int (p, &p, end);
7491
7492                 // FIXME: Make a faster mapping from req_id to request
7493                 mono_loader_lock ();
7494                 clear_event_request (req_id, etype);
7495                 mono_loader_unlock ();
7496                 break;
7497         }
7498         case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7499                 int i;
7500
7501                 mono_loader_lock ();
7502                 i = 0;
7503                 while (i < event_requests->len) {
7504                         EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7505
7506                         if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7507                                 clear_breakpoint ((MonoBreakpoint *)req->info);
7508
7509                                 g_ptr_array_remove_index_fast (event_requests, i);
7510                                 g_free (req);
7511                         } else {
7512                                 i ++;
7513                         }
7514                 }
7515                 mono_loader_unlock ();
7516                 break;
7517         }
7518         default:
7519                 return ERR_NOT_IMPLEMENTED;
7520         }
7521
7522         return ERR_NONE;
7523 }
7524
7525 static ErrorCode
7526 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7527 {
7528         ErrorCode err;
7529         MonoDomain *domain;
7530
7531         switch (command) {
7532         case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7533                 buffer_add_domainid (buf, mono_get_root_domain ());
7534                 break;
7535         }
7536         case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7537                 domain = decode_domainid (p, &p, end, NULL, &err);
7538                 if (err != ERR_NONE)
7539                         return err;
7540                 buffer_add_string (buf, domain->friendly_name);
7541                 break;
7542         }
7543         case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7544                 GSList *tmp;
7545                 MonoAssembly *ass;
7546                 int count;
7547
7548                 domain = decode_domainid (p, &p, end, NULL, &err);
7549                 if (err != ERR_NONE)
7550                         return err;
7551                 mono_loader_lock ();
7552                 count = 0;
7553                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7554                         count ++;
7555                 }
7556                 buffer_add_int (buf, count);
7557                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7558                         ass = (MonoAssembly *)tmp->data;
7559                         buffer_add_assemblyid (buf, domain, ass);
7560                 }
7561                 mono_loader_unlock ();
7562                 break;
7563         }
7564         case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7565                 domain = decode_domainid (p, &p, end, NULL, &err);
7566                 if (err != ERR_NONE)
7567                         return err;
7568
7569                 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7570                 break;
7571         }
7572         case CMD_APPDOMAIN_GET_CORLIB: {
7573                 domain = decode_domainid (p, &p, end, NULL, &err);
7574                 if (err != ERR_NONE)
7575                         return err;
7576
7577                 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7578                 break;
7579         }
7580         case CMD_APPDOMAIN_CREATE_STRING: {
7581                 char *s;
7582                 MonoString *o;
7583
7584                 domain = decode_domainid (p, &p, end, NULL, &err);
7585                 if (err != ERR_NONE)
7586                         return err;
7587                 s = decode_string (p, &p, end);
7588
7589                 o = mono_string_new (domain, s);
7590                 buffer_add_objid (buf, (MonoObject*)o);
7591                 break;
7592         }
7593         case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7594                 MonoError error;
7595                 MonoClass *klass;
7596                 MonoDomain *domain2;
7597                 MonoObject *o;
7598
7599                 domain = decode_domainid (p, &p, end, NULL, &err);
7600                 if (err != ERR_NONE)
7601                         return err;
7602                 klass = decode_typeid (p, &p, end, &domain2, &err);
7603                 if (err != ERR_NONE)
7604                         return err;
7605
7606                 // FIXME:
7607                 g_assert (domain == domain2);
7608
7609                 o = mono_object_new_checked (domain, klass, &error);
7610                 mono_error_assert_ok (&error);
7611
7612                 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7613                 if (err != ERR_NONE)
7614                         return err;
7615
7616                 buffer_add_objid (buf, o);
7617                 break;
7618         }
7619         default:
7620                 return ERR_NOT_IMPLEMENTED;
7621         }
7622
7623         return ERR_NONE;
7624 }
7625
7626 static ErrorCode
7627 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7628 {
7629         ErrorCode err;
7630         MonoAssembly *ass;
7631         MonoDomain *domain;
7632
7633         ass = decode_assemblyid (p, &p, end, &domain, &err);
7634         if (err != ERR_NONE)
7635                 return err;
7636
7637         switch (command) {
7638         case CMD_ASSEMBLY_GET_LOCATION: {
7639                 buffer_add_string (buf, mono_image_get_filename (ass->image));
7640                 break;                  
7641         }
7642         case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7643                 guint32 token;
7644                 MonoMethod *m;
7645
7646                 if (ass->image->dynamic) {
7647                         buffer_add_id (buf, 0);
7648                 } else {
7649                         token = mono_image_get_entry_point (ass->image);
7650                         if (token == 0) {
7651                                 buffer_add_id (buf, 0);
7652                         } else {
7653                                 MonoError error;
7654                                 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
7655                                 if (!m)
7656                                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7657                                 buffer_add_methodid (buf, domain, m);
7658                         }
7659                 }
7660                 break;                  
7661         }
7662         case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7663                 buffer_add_moduleid (buf, domain, ass->image);
7664                 break;
7665         }
7666         case CMD_ASSEMBLY_GET_OBJECT: {
7667                 MonoError error;
7668                 MonoObject *o = (MonoObject*)mono_assembly_get_object_checked (domain, ass, &error);
7669                 if (!o) {
7670                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7671                         return ERR_INVALID_OBJECT;
7672                 }
7673                 buffer_add_objid (buf, o);
7674                 break;
7675         }
7676         case CMD_ASSEMBLY_GET_TYPE: {
7677                 MonoError error;
7678                 char *s = decode_string (p, &p, end);
7679                 gboolean ignorecase = decode_byte (p, &p, end);
7680                 MonoTypeNameParse info;
7681                 MonoType *t;
7682                 gboolean type_resolve, res;
7683                 MonoDomain *d = mono_domain_get ();
7684
7685                 /* This is needed to be able to find referenced assemblies */
7686                 res = mono_domain_set (domain, FALSE);
7687                 g_assert (res);
7688
7689                 if (!mono_reflection_parse_type (s, &info)) {
7690                         t = NULL;
7691                 } else {
7692                         if (info.assembly.name)
7693                                 NOT_IMPLEMENTED;
7694                         t = mono_reflection_get_type_checked (ass->image, &info, ignorecase, &type_resolve, &error);
7695                         if (!is_ok (&error)) {
7696                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7697                                 mono_reflection_free_type_info (&info);
7698                                 g_free (s);
7699                                 return ERR_INVALID_ARGUMENT;
7700                         }
7701                 }
7702                 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7703                 mono_reflection_free_type_info (&info);
7704                 g_free (s);
7705
7706                 mono_domain_set (d, TRUE);
7707
7708                 break;
7709         }
7710         case CMD_ASSEMBLY_GET_NAME: {
7711                 gchar *name;
7712                 MonoAssembly *mass = ass;
7713
7714                 name = g_strdup_printf (
7715                   "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7716                   mass->aname.name,
7717                   mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7718                   mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7719                   mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7720                   (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7721
7722                 buffer_add_string (buf, name);
7723                 g_free (name);
7724                 break;
7725         }
7726         default:
7727                 return ERR_NOT_IMPLEMENTED;
7728         }
7729
7730         return ERR_NONE;
7731 }
7732
7733 static ErrorCode
7734 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7735 {
7736         ErrorCode err;
7737         MonoDomain *domain;
7738
7739         switch (command) {
7740         case CMD_MODULE_GET_INFO: {
7741                 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7742                 char *basename;
7743
7744                 basename = g_path_get_basename (image->name);
7745                 buffer_add_string (buf, basename); // name
7746                 buffer_add_string (buf, image->module_name); // scopename
7747                 buffer_add_string (buf, image->name); // fqname
7748                 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7749                 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7750                 g_free (basename);
7751                 break;                  
7752         }
7753         default:
7754                 return ERR_NOT_IMPLEMENTED;
7755         }
7756
7757         return ERR_NONE;
7758 }
7759
7760 static ErrorCode
7761 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7762 {
7763         ErrorCode err;
7764         MonoDomain *domain;
7765
7766         switch (command) {
7767         case CMD_FIELD_GET_INFO: {
7768                 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7769
7770                 buffer_add_string (buf, f->name);
7771                 buffer_add_typeid (buf, domain, f->parent);
7772                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7773                 buffer_add_int (buf, f->type->attrs);
7774                 break;
7775         }
7776         default:
7777                 return ERR_NOT_IMPLEMENTED;
7778         }
7779
7780         return ERR_NONE;
7781 }
7782
7783 static void
7784 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7785 {
7786         if (val && val->vtable->klass == mono_defaults.monotype_class) {
7787                 /* Special case these so the client doesn't have to handle Type objects */
7788                 
7789                 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7790                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7791         } else if (MONO_TYPE_IS_REFERENCE (t))
7792                 buffer_add_value (buf, t, &val, domain);
7793         else
7794                 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7795 }
7796
7797 static ErrorCode
7798 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7799 {
7800         int i, j;
7801         int nattrs = 0;
7802
7803         if (!cinfo) {
7804                 buffer_add_int (buf, 0);
7805                 return ERR_NONE;
7806         }
7807
7808         for (i = 0; i < cinfo->num_attrs; ++i) {
7809                 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7810                         nattrs ++;
7811         }
7812         buffer_add_int (buf, nattrs);
7813
7814         for (i = 0; i < cinfo->num_attrs; ++i) {
7815                 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7816                 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7817                         MonoArray *typed_args, *named_args;
7818                         MonoType *t;
7819                         CattrNamedArg *arginfo = NULL;
7820                         MonoError error;
7821
7822                         mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7823                         if (!mono_error_ok (&error)) {
7824                                 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7825                                 mono_error_cleanup (&error);
7826                                 return ERR_LOADER_ERROR;
7827                         }
7828
7829                         buffer_add_methodid (buf, domain, attr->ctor);
7830
7831                         /* Ctor args */
7832                         if (typed_args) {
7833                                 buffer_add_int (buf, mono_array_length (typed_args));
7834                                 for (j = 0; j < mono_array_length (typed_args); ++j) {
7835                                         MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7836
7837                                         t = mono_method_signature (attr->ctor)->params [j];
7838
7839                                         buffer_add_cattr_arg (buf, t, domain, val);
7840                                 }
7841                         } else {
7842                                 buffer_add_int (buf, 0);
7843                         }
7844
7845                         /* Named args */
7846                         if (named_args) {
7847                                 buffer_add_int (buf, mono_array_length (named_args));
7848
7849                                 for (j = 0; j < mono_array_length (named_args); ++j) {
7850                                         MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7851
7852                                         if (arginfo [j].prop) {
7853                                                 buffer_add_byte (buf, 0x54);
7854                                                 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7855                                         } else if (arginfo [j].field) {
7856                                                 buffer_add_byte (buf, 0x53);
7857                                                 buffer_add_fieldid (buf, domain, arginfo [j].field);
7858                                         } else {
7859                                                 g_assert_not_reached ();
7860                                         }
7861
7862                                         buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7863                                 }
7864                         } else {
7865                                 buffer_add_int (buf, 0);
7866                         }
7867                         g_free (arginfo);
7868                 }
7869         }
7870
7871         return ERR_NONE;
7872 }
7873
7874 /* FIXME: Code duplication with icall.c */
7875 static void
7876 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7877 {
7878         int i;
7879         MonoClass *ic;
7880
7881         mono_class_setup_interfaces (klass, error);
7882         if (!mono_error_ok (error))
7883                 return;
7884
7885         for (i = 0; i < klass->interface_count; i++) {
7886                 ic = klass->interfaces [i];
7887                 g_hash_table_insert (ifaces, ic, ic);
7888
7889                 collect_interfaces (ic, ifaces, error);
7890                 if (!mono_error_ok (error))
7891                         return;
7892         }
7893 }
7894
7895 static ErrorCode
7896 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7897 {
7898         MonoError error;
7899         MonoClass *nested;
7900         MonoType *type;
7901         gpointer iter;
7902         guint8 b;
7903         int nnested;
7904         ErrorCode err;
7905         char *name;
7906
7907         switch (command) {
7908         case CMD_TYPE_GET_INFO: {
7909                 buffer_add_string (buf, klass->name_space);
7910                 buffer_add_string (buf, klass->name);
7911                 // FIXME: byref
7912                 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7913                 buffer_add_string (buf, name);
7914                 g_free (name);
7915                 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7916                 buffer_add_moduleid (buf, domain, klass->image);
7917                 buffer_add_typeid (buf, domain, klass->parent);
7918                 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7919                         buffer_add_typeid (buf, domain, klass->element_class);
7920                 else
7921                         buffer_add_id (buf, 0);
7922                 buffer_add_int (buf, klass->type_token);
7923                 buffer_add_byte (buf, klass->rank);
7924                 buffer_add_int (buf, klass->flags);
7925                 b = 0;
7926                 type = &klass->byval_arg;
7927                 // FIXME: Can't decide whenever a class represents a byref type
7928                 if (FALSE)
7929                         b |= (1 << 0);
7930                 if (type->type == MONO_TYPE_PTR)
7931                         b |= (1 << 1);
7932                 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7933                         b |= (1 << 2);
7934                 if (type->type == MONO_TYPE_VALUETYPE)
7935                         b |= (1 << 3);
7936                 if (klass->enumtype)
7937                         b |= (1 << 4);
7938                 if (klass->generic_container)
7939                         b |= (1 << 5);
7940                 if (klass->generic_container || klass->generic_class)
7941                         b |= (1 << 6);
7942                 buffer_add_byte (buf, b);
7943                 nnested = 0;
7944                 iter = NULL;
7945                 while ((nested = mono_class_get_nested_types (klass, &iter)))
7946                         nnested ++;
7947                 buffer_add_int (buf, nnested);
7948                 iter = NULL;
7949                 while ((nested = mono_class_get_nested_types (klass, &iter)))
7950                         buffer_add_typeid (buf, domain, nested);
7951                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7952                         if (klass->generic_container)
7953                                 buffer_add_typeid (buf, domain, klass);
7954                         else if (klass->generic_class)
7955                                 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7956                         else
7957                                 buffer_add_id (buf, 0);
7958                 }
7959                 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7960                         int count, i;
7961
7962                         if (klass->generic_class) {
7963                                 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7964
7965                                 count = inst->type_argc;
7966                                 buffer_add_int (buf, count);
7967                                 for (i = 0; i < count; i++)
7968                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7969                         } else if (klass->generic_container) {
7970                                 MonoGenericContainer *container = klass->generic_container;
7971                                 MonoClass *pklass;
7972
7973                                 count = container->type_argc;
7974                                 buffer_add_int (buf, count);
7975                                 for (i = 0; i < count; i++) {
7976                                         pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
7977                                         buffer_add_typeid (buf, domain, pklass);
7978                                 }
7979                         } else {
7980                                 buffer_add_int (buf, 0);
7981                         }
7982                 }
7983                 break;
7984         }
7985         case CMD_TYPE_GET_METHODS: {
7986                 int nmethods;
7987                 int i = 0;
7988                 gpointer iter = NULL;
7989                 MonoMethod *m;
7990
7991                 mono_class_setup_methods (klass);
7992
7993                 nmethods = mono_class_num_methods (klass);
7994
7995                 buffer_add_int (buf, nmethods);
7996
7997                 while ((m = mono_class_get_methods (klass, &iter))) {
7998                         buffer_add_methodid (buf, domain, m);
7999                         i ++;
8000                 }
8001                 g_assert (i == nmethods);
8002                 break;
8003         }
8004         case CMD_TYPE_GET_FIELDS: {
8005                 int nfields;
8006                 int i = 0;
8007                 gpointer iter = NULL;
8008                 MonoClassField *f;
8009
8010                 nfields = mono_class_num_fields (klass);
8011
8012                 buffer_add_int (buf, nfields);
8013
8014                 while ((f = mono_class_get_fields (klass, &iter))) {
8015                         buffer_add_fieldid (buf, domain, f);
8016                         buffer_add_string (buf, f->name);
8017                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8018                         buffer_add_int (buf, f->type->attrs);
8019                         i ++;
8020                 }
8021                 g_assert (i == nfields);
8022                 break;
8023         }
8024         case CMD_TYPE_GET_PROPERTIES: {
8025                 int nprops;
8026                 int i = 0;
8027                 gpointer iter = NULL;
8028                 MonoProperty *p;
8029
8030                 nprops = mono_class_num_properties (klass);
8031
8032                 buffer_add_int (buf, nprops);
8033
8034                 while ((p = mono_class_get_properties (klass, &iter))) {
8035                         buffer_add_propertyid (buf, domain, p);
8036                         buffer_add_string (buf, p->name);
8037                         buffer_add_methodid (buf, domain, p->get);
8038                         buffer_add_methodid (buf, domain, p->set);
8039                         buffer_add_int (buf, p->attrs);
8040                         i ++;
8041                 }
8042                 g_assert (i == nprops);
8043                 break;
8044         }
8045         case CMD_TYPE_GET_CATTRS: {
8046                 MonoClass *attr_klass;
8047                 MonoCustomAttrInfo *cinfo;
8048
8049                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8050                 /* attr_klass can be NULL */
8051                 if (err != ERR_NONE)
8052                         return err;
8053
8054                 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8055                 if (!is_ok (&error)) {
8056                         mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8057                         return ERR_LOADER_ERROR;
8058                 }
8059
8060                 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8061                 if (err != ERR_NONE)
8062                         return err;
8063                 break;
8064         }
8065         case CMD_TYPE_GET_FIELD_CATTRS: {
8066                 MonoClass *attr_klass;
8067                 MonoCustomAttrInfo *cinfo;
8068                 MonoClassField *field;
8069
8070                 field = decode_fieldid (p, &p, end, NULL, &err);
8071                 if (err != ERR_NONE)
8072                         return err;
8073                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8074                 if (err != ERR_NONE)
8075                         return err;
8076
8077                 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8078                 if (!is_ok (&error)) {
8079                         mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8080                         return ERR_LOADER_ERROR;
8081                 }
8082
8083                 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8084                 if (err != ERR_NONE)
8085                         return err;
8086                 break;
8087         }
8088         case CMD_TYPE_GET_PROPERTY_CATTRS: {
8089                 MonoClass *attr_klass;
8090                 MonoCustomAttrInfo *cinfo;
8091                 MonoProperty *prop;
8092
8093                 prop = decode_propertyid (p, &p, end, NULL, &err);
8094                 if (err != ERR_NONE)
8095                         return err;
8096                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8097                 if (err != ERR_NONE)
8098                         return err;
8099
8100                 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8101                 if (!is_ok (&error)) {
8102                         mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8103                         return ERR_LOADER_ERROR;
8104                 }
8105
8106                 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8107                 if (err != ERR_NONE)
8108                         return err;
8109                 break;
8110         }
8111         case CMD_TYPE_GET_VALUES:
8112         case CMD_TYPE_GET_VALUES_2: {
8113                 guint8 *val;
8114                 MonoClassField *f;
8115                 MonoVTable *vtable;
8116                 MonoClass *k;
8117                 int len, i;
8118                 gboolean found;
8119                 MonoThread *thread_obj;
8120                 MonoInternalThread *thread = NULL;
8121                 guint32 special_static_type;
8122
8123                 if (command == CMD_TYPE_GET_VALUES_2) {
8124                         int objid = decode_objid (p, &p, end);
8125                         ErrorCode err;
8126
8127                         err = get_object (objid, (MonoObject**)&thread_obj);
8128                         if (err != ERR_NONE)
8129                                 return err;
8130
8131                         thread = THREAD_TO_INTERNAL (thread_obj);
8132                 }
8133
8134                 len = decode_int (p, &p, end);
8135                 for (i = 0; i < len; ++i) {
8136                         f = decode_fieldid (p, &p, end, NULL, &err);
8137                         if (err != ERR_NONE)
8138                                 return err;
8139
8140                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8141                                 return ERR_INVALID_FIELDID;
8142                         special_static_type = mono_class_field_get_special_static_type (f);
8143                         if (special_static_type != SPECIAL_STATIC_NONE) {
8144                                 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8145                                         return ERR_INVALID_FIELDID;
8146                         }
8147
8148                         /* Check that the field belongs to the object */
8149                         found = FALSE;
8150                         for (k = klass; k; k = k->parent) {
8151                                 if (k == f->parent) {
8152                                         found = TRUE;
8153                                         break;
8154                                 }
8155                         }
8156                         if (!found)
8157                                 return ERR_INVALID_FIELDID;
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                         mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8162                         buffer_add_value (buf, f->type, val, domain);
8163                         g_free (val);
8164                 }
8165                 break;
8166         }
8167         case CMD_TYPE_SET_VALUES: {
8168                 guint8 *val;
8169                 MonoClassField *f;
8170                 MonoVTable *vtable;
8171                 MonoClass *k;
8172                 int len, i;
8173                 gboolean found;
8174
8175                 len = decode_int (p, &p, end);
8176                 for (i = 0; i < len; ++i) {
8177                         f = decode_fieldid (p, &p, end, NULL, &err);
8178                         if (err != ERR_NONE)
8179                                 return err;
8180
8181                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8182                                 return ERR_INVALID_FIELDID;
8183                         if (mono_class_field_is_special_static (f))
8184                                 return ERR_INVALID_FIELDID;
8185
8186                         /* Check that the field belongs to the object */
8187                         found = FALSE;
8188                         for (k = klass; k; k = k->parent) {
8189                                 if (k == f->parent) {
8190                                         found = TRUE;
8191                                         break;
8192                                 }
8193                         }
8194                         if (!found)
8195                                 return ERR_INVALID_FIELDID;
8196
8197                         // FIXME: Check for literal/const
8198
8199                         vtable = mono_class_vtable (domain, f->parent);
8200                         val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8201                         err = decode_value (f->type, domain, val, p, &p, end);
8202                         if (err != ERR_NONE) {
8203                                 g_free (val);
8204                                 return err;
8205                         }
8206                         if (MONO_TYPE_IS_REFERENCE (f->type))
8207                                 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8208                         else
8209                                 mono_field_static_set_value (vtable, f, val);
8210                         g_free (val);
8211                 }
8212                 break;
8213         }
8214         case CMD_TYPE_GET_OBJECT: {
8215                 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8216                 if (!mono_error_ok (&error)) {
8217                         mono_error_cleanup (&error);
8218                         return ERR_INVALID_OBJECT;
8219                 }
8220                 buffer_add_objid (buf, o);
8221                 break;
8222         }
8223         case CMD_TYPE_GET_SOURCE_FILES:
8224         case CMD_TYPE_GET_SOURCE_FILES_2: {
8225                 char *source_file, *base;
8226                 GPtrArray *files;
8227                 int i;
8228
8229                 files = get_source_files_for_type (klass);
8230
8231                 buffer_add_int (buf, files->len);
8232                 for (i = 0; i < files->len; ++i) {
8233                         source_file = (char *)g_ptr_array_index (files, i);
8234                         if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8235                                 buffer_add_string (buf, source_file);
8236                         } else {
8237                                 base = dbg_path_get_basename (source_file);
8238                                 buffer_add_string (buf, base);
8239                                 g_free (base);
8240                         }
8241                         g_free (source_file);
8242                 }
8243                 g_ptr_array_free (files, TRUE);
8244                 break;
8245         }
8246         case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8247                 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8248
8249                 if (err != ERR_NONE)
8250                         return err;
8251                 if (mono_class_is_assignable_from (klass, oklass))
8252                         buffer_add_byte (buf, 1);
8253                 else
8254                         buffer_add_byte (buf, 0);
8255                 break;
8256         }
8257         case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8258                 char *name = decode_string (p, &p, end);
8259                 int i, flags = decode_int (p, &p, end);
8260                 MonoException *ex = NULL;
8261                 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8262
8263                 if (!array)
8264                         return ERR_LOADER_ERROR;
8265                 buffer_add_int (buf, array->len);
8266                 for (i = 0; i < array->len; ++i) {
8267                         MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8268                         buffer_add_methodid (buf, domain, method);
8269                 }
8270
8271                 g_ptr_array_free (array, TRUE);
8272                 g_free (name);
8273                 break;
8274         }
8275         case CMD_TYPE_GET_INTERFACES: {
8276                 MonoClass *parent;
8277                 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8278                 MonoClass *tclass, *iface;
8279                 GHashTableIter iter;
8280
8281                 tclass = klass;
8282
8283                 for (parent = tclass; parent; parent = parent->parent) {
8284                         mono_class_setup_interfaces (parent, &error);
8285                         if (!mono_error_ok (&error))
8286                                 return ERR_LOADER_ERROR;
8287                         collect_interfaces (parent, iface_hash, &error);
8288                         if (!mono_error_ok (&error))
8289                                 return ERR_LOADER_ERROR;
8290                 }
8291
8292                 buffer_add_int (buf, g_hash_table_size (iface_hash));
8293
8294                 g_hash_table_iter_init (&iter, iface_hash);
8295                 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8296                         buffer_add_typeid (buf, domain, iface);
8297                 g_hash_table_destroy (iface_hash);
8298                 break;
8299         }
8300         case CMD_TYPE_GET_INTERFACE_MAP: {
8301                 int tindex, ioffset;
8302                 gboolean variance_used;
8303                 MonoClass *iclass;
8304                 int len, nmethods, i;
8305                 gpointer iter;
8306                 MonoMethod *method;
8307
8308                 len = decode_int (p, &p, end);
8309                 mono_class_setup_vtable (klass);
8310
8311                 for (tindex = 0; tindex < len; ++tindex) {
8312                         iclass = decode_typeid (p, &p, end, NULL, &err);
8313                         if (err != ERR_NONE)
8314                                 return err;
8315
8316                         ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8317                         if (ioffset == -1)
8318                                 return ERR_INVALID_ARGUMENT;
8319
8320                         nmethods = mono_class_num_methods (iclass);
8321                         buffer_add_int (buf, nmethods);
8322
8323                         iter = NULL;
8324                         while ((method = mono_class_get_methods (iclass, &iter))) {
8325                                 buffer_add_methodid (buf, domain, method);
8326                         }
8327                         for (i = 0; i < nmethods; ++i)
8328                                 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8329                 }
8330                 break;
8331         }
8332         case CMD_TYPE_IS_INITIALIZED: {
8333                 MonoVTable *vtable = mono_class_vtable (domain, klass);
8334
8335                 if (vtable)
8336                         buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8337                 else
8338                         buffer_add_int (buf, 0);
8339                 break;
8340         }
8341         case CMD_TYPE_CREATE_INSTANCE: {
8342                 MonoError error;
8343                 MonoObject *obj;
8344
8345                 obj = mono_object_new_checked (domain, klass, &error);
8346                 mono_error_assert_ok (&error);
8347                 buffer_add_objid (buf, obj);
8348                 break;
8349         }
8350         default:
8351                 return ERR_NOT_IMPLEMENTED;
8352         }
8353
8354         return ERR_NONE;
8355 }
8356
8357 static ErrorCode
8358 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8359 {
8360         MonoClass *klass;
8361         MonoDomain *old_domain;
8362         MonoDomain *domain;
8363         ErrorCode err;
8364
8365         klass = decode_typeid (p, &p, end, &domain, &err);
8366         if (err != ERR_NONE)
8367                 return err;
8368
8369         old_domain = mono_domain_get ();
8370
8371         mono_domain_set (domain, TRUE);
8372
8373         err = type_commands_internal (command, klass, domain, p, end, buf);
8374
8375         mono_domain_set (old_domain, TRUE);
8376
8377         return err;
8378 }
8379
8380 static ErrorCode
8381 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8382 {
8383         MonoMethodHeader *header;
8384         ErrorCode err;
8385
8386         switch (command) {
8387         case CMD_METHOD_GET_NAME: {
8388                 buffer_add_string (buf, method->name);
8389                 break;                  
8390         }
8391         case CMD_METHOD_GET_DECLARING_TYPE: {
8392                 buffer_add_typeid (buf, domain, method->klass);
8393                 break;
8394         }
8395         case CMD_METHOD_GET_DEBUG_INFO: {
8396                 MonoError error;
8397                 MonoDebugMethodInfo *minfo;
8398                 char *source_file;
8399                 int i, j, n_il_offsets;
8400                 int *source_files;
8401                 GPtrArray *source_file_list;
8402                 MonoSymSeqPoint *sym_seq_points;
8403
8404                 header = mono_method_get_header_checked (method, &error);
8405                 if (!header) {
8406                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
8407                         buffer_add_int (buf, 0);
8408                         buffer_add_string (buf, "");
8409                         buffer_add_int (buf, 0);
8410                         break;
8411                 }
8412
8413                 minfo = mono_debug_lookup_method (method);
8414                 if (!minfo) {
8415                         buffer_add_int (buf, header->code_size);
8416                         buffer_add_string (buf, "");
8417                         buffer_add_int (buf, 0);
8418                         mono_metadata_free_mh (header);
8419                         break;
8420                 }
8421
8422                 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8423                 buffer_add_int (buf, header->code_size);
8424                 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8425                         buffer_add_int (buf, source_file_list->len);
8426                         for (i = 0; i < source_file_list->len; ++i) {
8427                                 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8428                                 buffer_add_string (buf, sinfo->source_file);
8429                                 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8430                                         for (j = 0; j < 16; ++j)
8431                                                 buffer_add_byte (buf, sinfo->hash [j]);
8432                                 }
8433                         }
8434                 } else {
8435                         buffer_add_string (buf, source_file);
8436                 }
8437                 buffer_add_int (buf, n_il_offsets);
8438                 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method,  TRUE));
8439                 for (i = 0; i < n_il_offsets; ++i) {
8440                         MonoSymSeqPoint *sp = &sym_seq_points [i];
8441                         const char *srcfile = "";
8442
8443                         if (source_files [i] != -1) {
8444                                 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8445                                 srcfile = sinfo->source_file;
8446                         }
8447                         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);
8448                         buffer_add_int (buf, sp->il_offset);
8449                         buffer_add_int (buf, sp->line);
8450                         if (CHECK_PROTOCOL_VERSION (2, 13))
8451                                 buffer_add_int (buf, source_files [i]);
8452                         if (CHECK_PROTOCOL_VERSION (2, 19))
8453                                 buffer_add_int (buf, sp->column);
8454                         if (CHECK_PROTOCOL_VERSION (2, 32)) {
8455                                 buffer_add_int (buf, sp->end_line);
8456                                 buffer_add_int (buf, sp->end_column);
8457                         }
8458                 }
8459                 g_free (source_file);
8460                 g_free (source_files);
8461                 g_free (sym_seq_points);
8462                 g_ptr_array_free (source_file_list, TRUE);
8463                 mono_metadata_free_mh (header);
8464                 break;
8465         }
8466         case CMD_METHOD_GET_PARAM_INFO: {
8467                 MonoMethodSignature *sig = mono_method_signature (method);
8468                 guint32 i;
8469                 char **names;
8470
8471                 /* FIXME: mono_class_from_mono_type () and byrefs */
8472
8473                 /* FIXME: Use a smaller encoding */
8474                 buffer_add_int (buf, sig->call_convention);
8475                 buffer_add_int (buf, sig->param_count);
8476                 buffer_add_int (buf, sig->generic_param_count);
8477                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8478                 for (i = 0; i < sig->param_count; ++i) {
8479                         /* FIXME: vararg */
8480                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8481                 }
8482
8483                 /* Emit parameter names */
8484                 names = g_new (char *, sig->param_count);
8485                 mono_method_get_param_names (method, (const char **) names);
8486                 for (i = 0; i < sig->param_count; ++i)
8487                         buffer_add_string (buf, names [i]);
8488                 g_free (names);
8489
8490                 break;
8491         }
8492         case CMD_METHOD_GET_LOCALS_INFO: {
8493                 MonoError error;
8494                 int i, num_locals;
8495                 MonoDebugLocalsInfo *locals;
8496                 int *locals_map = NULL;
8497
8498                 header = mono_method_get_header_checked (method, &error);
8499                 if (!header) {
8500                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
8501                         return ERR_INVALID_ARGUMENT;
8502                 }
8503
8504                 locals = mono_debug_lookup_locals (method);
8505                 if (!locals) {
8506                         buffer_add_int (buf, header->num_locals);
8507                         /* Types */
8508                         for (i = 0; i < header->num_locals; ++i) {
8509                                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8510                         }
8511                         /* Names */
8512                         for (i = 0; i < header->num_locals; ++i) {
8513                                 char lname [128];
8514                                 sprintf (lname, "V_%d", i);
8515                                 buffer_add_string (buf, lname);
8516                         }
8517                         /* Scopes */
8518                         for (i = 0; i < header->num_locals; ++i) {
8519                                 buffer_add_int (buf, 0);
8520                                 buffer_add_int (buf, header->code_size);
8521                         }
8522                 } else {
8523                         num_locals = locals->num_locals;
8524                         buffer_add_int (buf, num_locals);
8525
8526                         /* Types */
8527                         for (i = 0; i < num_locals; ++i) {
8528                                 g_assert (locals->locals [i].index < header->num_locals);
8529                                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8530                         }
8531                         /* Names */
8532                         for (i = 0; i < num_locals; ++i)
8533                                 buffer_add_string (buf, locals->locals [i].name);
8534                         /* Scopes */
8535                         for (i = 0; i < num_locals; ++i) {
8536                                 if (locals->locals [i].block) {
8537                                         buffer_add_int (buf, locals->locals [i].block->start_offset);
8538                                         buffer_add_int (buf, locals->locals [i].block->end_offset);
8539                                 } else {
8540                                         buffer_add_int (buf, 0);
8541                                         buffer_add_int (buf, header->code_size);
8542                                 }
8543                         }
8544                 }
8545                 mono_metadata_free_mh (header);
8546
8547                 if (locals)
8548                         mono_debug_free_locals (locals);
8549                 g_free (locals_map);
8550
8551                 break;
8552         }
8553         case CMD_METHOD_GET_INFO:
8554                 buffer_add_int (buf, method->flags);
8555                 buffer_add_int (buf, method->iflags);
8556                 buffer_add_int (buf, method->token);
8557                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8558                         guint8 attrs = 0;
8559                         if (method->is_generic)
8560                                 attrs |= (1 << 0);
8561                         if (mono_method_signature (method)->generic_param_count)
8562                                 attrs |= (1 << 1);
8563                         buffer_add_byte (buf, attrs);
8564                         if (method->is_generic || method->is_inflated) {
8565                                 MonoMethod *result;
8566
8567                                 if (method->is_generic) {
8568                                         result = method;
8569                                 } else {
8570                                         MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8571                                         
8572                                         result = imethod->declaring;
8573                                         if (imethod->context.class_inst) {
8574                                                 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8575                                                 /*Generic methods gets the context of the GTD.*/
8576                                                 if (mono_class_get_context (klass)) {
8577                                                         MonoError error;
8578                                                         result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8579                                                         g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8580                                                 }
8581                                         }
8582                                 }
8583
8584                                 buffer_add_methodid (buf, domain, result);
8585                         } else {
8586                                 buffer_add_id (buf, 0);
8587                         }
8588                         if (CHECK_PROTOCOL_VERSION (2, 15)) {
8589                                 if (mono_method_signature (method)->generic_param_count) {
8590                                         int count, i;
8591
8592                                         if (method->is_inflated) {
8593                                                 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8594                                                 if (inst) {
8595                                                         count = inst->type_argc;
8596                                                         buffer_add_int (buf, count);
8597
8598                                                         for (i = 0; i < count; i++)
8599                                                                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8600                                                 } else {
8601                                                         buffer_add_int (buf, 0);
8602                                                 }
8603                                         } else if (method->is_generic) {
8604                                                 MonoGenericContainer *container = mono_method_get_generic_container (method);
8605
8606                                                 count = mono_method_signature (method)->generic_param_count;
8607                                                 buffer_add_int (buf, count);
8608                                                 for (i = 0; i < count; i++) {
8609                                                         MonoGenericParam *param = mono_generic_container_get_param (container, i);
8610                                                         MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
8611                                                         buffer_add_typeid (buf, domain, pklass);
8612                                                 }
8613                                         } else {
8614                                                 buffer_add_int (buf, 0);
8615                                         }
8616                                 } else {
8617                                         buffer_add_int (buf, 0);
8618                                 }
8619                         }
8620                 }
8621                 break;
8622         case CMD_METHOD_GET_BODY: {
8623                 MonoError error;
8624                 int i;
8625
8626                 header = mono_method_get_header_checked (method, &error);
8627                 if (!header) {
8628                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
8629                         buffer_add_int (buf, 0);
8630
8631                         if (CHECK_PROTOCOL_VERSION (2, 18))
8632                                 buffer_add_int (buf, 0);
8633                 } else {
8634                         buffer_add_int (buf, header->code_size);
8635                         for (i = 0; i < header->code_size; ++i)
8636                                 buffer_add_byte (buf, header->code [i]);
8637
8638                         if (CHECK_PROTOCOL_VERSION (2, 18)) {
8639                                 buffer_add_int (buf, header->num_clauses);
8640                                 for (i = 0; i < header->num_clauses; ++i) {
8641                                         MonoExceptionClause *clause = &header->clauses [i];
8642
8643                                         buffer_add_int (buf, clause->flags);
8644                                         buffer_add_int (buf, clause->try_offset);
8645                                         buffer_add_int (buf, clause->try_len);
8646                                         buffer_add_int (buf, clause->handler_offset);
8647                                         buffer_add_int (buf, clause->handler_len);
8648                                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8649                                                 buffer_add_typeid (buf, domain, clause->data.catch_class);
8650                                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8651                                                 buffer_add_int (buf, clause->data.filter_offset);
8652                                 }
8653                         }
8654
8655                         mono_metadata_free_mh (header);
8656                 }
8657
8658                 break;
8659         }
8660         case CMD_METHOD_RESOLVE_TOKEN: {
8661                 guint32 token = decode_int (p, &p, end);
8662
8663                 // FIXME: Generics
8664                 switch (mono_metadata_token_code (token)) {
8665                 case MONO_TOKEN_STRING: {
8666                         MonoString *s;
8667                         char *s2;
8668
8669                         s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8670                         g_assert (s);
8671
8672                         s2 = mono_string_to_utf8 (s);
8673
8674                         buffer_add_byte (buf, TOKEN_TYPE_STRING);
8675                         buffer_add_string (buf, s2);
8676                         g_free (s2);
8677                         break;
8678                 }
8679                 default: {
8680                         gpointer val;
8681                         MonoClass *handle_class;
8682
8683                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8684                                 val = mono_method_get_wrapper_data (method, token);
8685                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8686
8687                                 if (handle_class == NULL) {
8688                                         // Can't figure out the token type
8689                                         buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8690                                         break;
8691                                 }
8692                         } else {
8693                                 MonoError error;
8694                                 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8695                                 if (!val)
8696                                         g_error ("Could not load token due to %s", mono_error_get_message (&error));
8697                         }
8698
8699                         if (handle_class == mono_defaults.typehandle_class) {
8700                                 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8701                                 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8702                                         buffer_add_typeid (buf, domain, (MonoClass *) val);
8703                                 else
8704                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8705                         } else if (handle_class == mono_defaults.fieldhandle_class) {
8706                                 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8707                                 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8708                         } else if (handle_class == mono_defaults.methodhandle_class) {
8709                                 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8710                                 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8711                         } else if (handle_class == mono_defaults.string_class) {
8712                                 char *s;
8713
8714                                 s = mono_string_to_utf8 ((MonoString *)val);
8715                                 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8716                                 buffer_add_string (buf, s);
8717                                 g_free (s);
8718                         } else {
8719                                 g_assert_not_reached ();
8720                         }
8721                         break;
8722                 }
8723                 }
8724                 break;
8725         }
8726         case CMD_METHOD_GET_CATTRS: {
8727                 MonoError error;
8728                 MonoClass *attr_klass;
8729                 MonoCustomAttrInfo *cinfo;
8730
8731                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8732                 /* attr_klass can be NULL */
8733                 if (err != ERR_NONE)
8734                         return err;
8735
8736                 cinfo = mono_custom_attrs_from_method_checked (method, &error);
8737                 if (!is_ok (&error)) {
8738                         mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8739                         return ERR_LOADER_ERROR;
8740                 }
8741
8742                 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8743                 if (err != ERR_NONE)
8744                         return err;
8745                 break;
8746         }
8747         case CMD_METHOD_MAKE_GENERIC_METHOD: {
8748                 MonoError error;
8749                 MonoType **type_argv;
8750                 int i, type_argc;
8751                 MonoDomain *d;
8752                 MonoClass *klass;
8753                 MonoGenericInst *ginst;
8754                 MonoGenericContext tmp_context;
8755                 MonoMethod *inflated;
8756
8757                 type_argc = decode_int (p, &p, end);
8758                 type_argv = g_new0 (MonoType*, type_argc);
8759                 for (i = 0; i < type_argc; ++i) {
8760                         klass = decode_typeid (p, &p, end, &d, &err);
8761                         if (err != ERR_NONE) {
8762                                 g_free (type_argv);
8763                                 return err;
8764                         }
8765                         if (domain != d) {
8766                                 g_free (type_argv);
8767                                 return ERR_INVALID_ARGUMENT;
8768                         }
8769                         type_argv [i] = &klass->byval_arg;
8770                 }
8771                 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8772                 g_free (type_argv);
8773                 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8774                 tmp_context.method_inst = ginst;
8775
8776                 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8777                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8778                 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8779                         return ERR_INVALID_ARGUMENT;
8780                 buffer_add_methodid (buf, domain, inflated);
8781                 break;
8782         }
8783         default:
8784                 return ERR_NOT_IMPLEMENTED;
8785         }
8786
8787         return ERR_NONE;
8788 }
8789
8790 static ErrorCode
8791 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8792 {
8793         ErrorCode err;
8794         MonoDomain *old_domain;
8795         MonoDomain *domain;
8796         MonoMethod *method;
8797
8798         method = decode_methodid (p, &p, end, &domain, &err);
8799         if (err != ERR_NONE)
8800                 return err;
8801
8802         old_domain = mono_domain_get ();
8803
8804         mono_domain_set (domain, TRUE);
8805
8806         err = method_commands_internal (command, method, domain, p, end, buf);
8807
8808         mono_domain_set (old_domain, TRUE);
8809
8810         return err;
8811 }
8812
8813 static ErrorCode
8814 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8815 {
8816         int objid = decode_objid (p, &p, end);
8817         ErrorCode err;
8818         MonoThread *thread_obj;
8819         MonoInternalThread *thread;
8820
8821         err = get_object (objid, (MonoObject**)&thread_obj);
8822         if (err != ERR_NONE)
8823                 return err;
8824
8825         thread = THREAD_TO_INTERNAL (thread_obj);
8826            
8827         switch (command) {
8828         case CMD_THREAD_GET_NAME: {
8829                 guint32 name_len;
8830                 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8831
8832                 if (!s) {
8833                         buffer_add_int (buf, 0);
8834                 } else {
8835                         char *name;
8836                         glong len;
8837
8838                         name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8839                         g_assert (name);
8840                         buffer_add_int (buf, len);
8841                         buffer_add_data (buf, (guint8*)name, len);
8842                         g_free (s);
8843                 }
8844                 break;
8845         }
8846         case CMD_THREAD_GET_FRAME_INFO: {
8847                 DebuggerTlsData *tls;
8848                 int i, start_frame, length;
8849
8850                 // Wait for suspending if it already started
8851                 // FIXME: Races with suspend_count
8852                 while (!is_suspended ()) {
8853                         if (suspend_count)
8854                                 wait_for_suspend ();
8855                 }
8856                 /*
8857                 if (suspend_count)
8858                         wait_for_suspend ();
8859                 if (!is_suspended ())
8860                         return ERR_NOT_SUSPENDED;
8861                 */
8862
8863                 start_frame = decode_int (p, &p, end);
8864                 length = decode_int (p, &p, end);
8865
8866                 if (start_frame != 0 || length != -1)
8867                         return ERR_NOT_IMPLEMENTED;
8868
8869                 mono_loader_lock ();
8870                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8871                 mono_loader_unlock ();
8872                 g_assert (tls);
8873
8874                 compute_frame_info (thread, tls);
8875
8876                 buffer_add_int (buf, tls->frame_count);
8877                 for (i = 0; i < tls->frame_count; ++i) {
8878                         buffer_add_int (buf, tls->frames [i]->id);
8879                         buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8880                         buffer_add_int (buf, tls->frames [i]->il_offset);
8881                         /*
8882                          * Instead of passing the frame type directly to the client, we associate
8883                          * it with the previous frame using a set of flags. This avoids lots of
8884                          * conditional code in the client, since a frame whose type isn't 
8885                          * FRAME_TYPE_MANAGED has no method, location, etc.
8886                          */
8887                         buffer_add_byte (buf, tls->frames [i]->flags);
8888                 }
8889
8890                 break;
8891         }
8892         case CMD_THREAD_GET_STATE:
8893                 buffer_add_int (buf, thread->state);
8894                 break;
8895         case CMD_THREAD_GET_INFO:
8896                 buffer_add_byte (buf, thread->threadpool_thread);
8897                 break;
8898         case CMD_THREAD_GET_ID:
8899                 buffer_add_long (buf, (guint64)(gsize)thread);
8900                 break;
8901         case CMD_THREAD_GET_TID:
8902                 buffer_add_long (buf, (guint64)thread->tid);
8903                 break;
8904         case CMD_THREAD_SET_IP: {
8905                 DebuggerTlsData *tls;
8906                 MonoMethod *method;
8907                 MonoDomain *domain;
8908                 MonoSeqPointInfo *seq_points;
8909                 SeqPoint sp;
8910                 gboolean found_sp;
8911                 gint64 il_offset;
8912
8913                 method = decode_methodid (p, &p, end, &domain, &err);
8914                 if (err != ERR_NONE)
8915                         return err;
8916                 il_offset = decode_long (p, &p, end);
8917
8918                 while (!is_suspended ()) {
8919                         if (suspend_count)
8920                                 wait_for_suspend ();
8921                 }
8922
8923                 mono_loader_lock ();
8924                 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8925                 mono_loader_unlock ();
8926                 g_assert (tls);
8927
8928                 compute_frame_info (thread, tls);
8929                 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8930                         return ERR_INVALID_ARGUMENT;
8931
8932                 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
8933
8934                 g_assert (seq_points);
8935
8936                 if (!found_sp)
8937                         return ERR_INVALID_ARGUMENT;
8938
8939                 // FIXME: Check that the ip change is safe
8940
8941                 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);
8942                 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8943                 break;
8944         }
8945         default:
8946                 return ERR_NOT_IMPLEMENTED;
8947         }
8948
8949         return ERR_NONE;
8950 }
8951
8952 static ErrorCode
8953 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8954 {
8955         int objid;
8956         ErrorCode err;
8957         MonoThread *thread_obj;
8958         MonoInternalThread *thread;
8959         int pos, i, len, frame_idx;
8960         DebuggerTlsData *tls;
8961         StackFrame *frame;
8962         MonoDebugMethodJitInfo *jit;
8963         MonoMethodSignature *sig;
8964         gssize id;
8965         MonoMethodHeader *header;
8966
8967         objid = decode_objid (p, &p, end);
8968         err = get_object (objid, (MonoObject**)&thread_obj);
8969         if (err != ERR_NONE)
8970                 return err;
8971
8972         thread = THREAD_TO_INTERNAL (thread_obj);
8973
8974         id = decode_id (p, &p, end);
8975
8976         mono_loader_lock ();
8977         tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8978         mono_loader_unlock ();
8979         g_assert (tls);
8980
8981         for (i = 0; i < tls->frame_count; ++i) {
8982                 if (tls->frames [i]->id == id)
8983                         break;
8984         }
8985         if (i == tls->frame_count)
8986                 return ERR_INVALID_FRAMEID;
8987
8988         frame_idx = i;
8989         frame = tls->frames [frame_idx];
8990
8991         /* This is supported for frames without has_ctx etc. set */
8992         if (command == CMD_STACK_FRAME_GET_DOMAIN) {
8993                 if (CHECK_PROTOCOL_VERSION (2, 38))
8994                         buffer_add_domainid (buf, frame->domain);
8995                 return ERR_NONE;
8996         }
8997
8998         if (!frame->has_ctx)
8999                 return ERR_ABSENT_INFORMATION;
9000
9001         if (!frame->jit) {
9002                 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
9003                 if (!frame->jit && frame->api_method->is_inflated)
9004                         frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
9005                 if (!frame->jit) {
9006                         char *s;
9007
9008                         /* This could happen for aot images with no jit debug info */
9009                         s = mono_method_full_name (frame->api_method, TRUE);
9010                         DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
9011                         g_free (s);
9012                         return ERR_ABSENT_INFORMATION;
9013                 }
9014         }
9015         jit = frame->jit;
9016
9017         sig = mono_method_signature (frame->actual_method);
9018
9019         if (!mono_get_seq_points (frame->domain, frame->actual_method))
9020                 /*
9021                  * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9022                  */
9023                 return ERR_ABSENT_INFORMATION;
9024
9025         switch (command) {
9026         case CMD_STACK_FRAME_GET_VALUES: {
9027                 MonoError error;
9028                 len = decode_int (p, &p, end);
9029                 header = mono_method_get_header_checked (frame->actual_method, &error);
9030                 mono_error_assert_ok (&error); /* FIXME report error */
9031
9032                 for (i = 0; i < len; ++i) {
9033                         pos = decode_int (p, &p, end);
9034
9035                         if (pos < 0) {
9036                                 pos = - pos - 1;
9037
9038                                 DEBUG_PRINTF (4, "[dbg]   send arg %d.\n", pos);
9039
9040                                 g_assert (pos >= 0 && pos < jit->num_params);
9041
9042                                 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9043                         } else {
9044                                 MonoDebugLocalsInfo *locals;
9045
9046                                 locals = mono_debug_lookup_locals (frame->method);
9047                                 if (locals) {
9048                                         g_assert (pos < locals->num_locals);
9049                                         pos = locals->locals [pos].index;
9050                                         mono_debug_free_locals (locals);
9051                                 }
9052                                 g_assert (pos >= 0 && pos < jit->num_locals);
9053
9054                                 DEBUG_PRINTF (4, "[dbg]   send local %d.\n", pos);
9055
9056                                 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9057                         }
9058                 }
9059                 mono_metadata_free_mh (header);
9060                 break;
9061         }
9062         case CMD_STACK_FRAME_GET_THIS: {
9063                 if (frame->api_method->klass->valuetype) {
9064                         if (!sig->hasthis) {
9065                                 MonoObject *p = NULL;
9066                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9067                         } else {
9068                                 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9069                         }
9070                 } else {
9071                         if (!sig->hasthis) {
9072                                 MonoObject *p = NULL;
9073                                 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9074                         } else {
9075                                 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9076                         }
9077                 }
9078                 break;
9079         }
9080         case CMD_STACK_FRAME_SET_VALUES: {
9081                 MonoError error;
9082                 guint8 *val_buf;
9083                 MonoType *t;
9084                 MonoDebugVarInfo *var;
9085
9086                 len = decode_int (p, &p, end);
9087                 header = mono_method_get_header_checked (frame->actual_method, &error);
9088                 mono_error_assert_ok (&error); /* FIXME report error */
9089
9090                 for (i = 0; i < len; ++i) {
9091                         pos = decode_int (p, &p, end);
9092
9093                         if (pos < 0) {
9094                                 pos = - pos - 1;
9095
9096                                 g_assert (pos >= 0 && pos < jit->num_params);
9097
9098                                 t = sig->params [pos];
9099                                 var = &jit->params [pos];
9100                         } else {
9101                                 MonoDebugLocalsInfo *locals;
9102
9103                                 locals = mono_debug_lookup_locals (frame->method);
9104                                 if (locals) {
9105                                         g_assert (pos < locals->num_locals);
9106                                         pos = locals->locals [pos].index;
9107                                         mono_debug_free_locals (locals);
9108                                 }
9109                                 g_assert (pos >= 0 && pos < jit->num_locals);
9110
9111                                 t = header->locals [pos];
9112                                 var = &jit->locals [pos];
9113                         }
9114
9115                         if (MONO_TYPE_IS_REFERENCE (t))
9116                                 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9117                         else
9118                                 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9119                         err = decode_value (t, frame->domain, val_buf, p, &p, end);
9120                         if (err != ERR_NONE)
9121                                 return err;
9122
9123                         set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9124                 }
9125                 mono_metadata_free_mh (header);
9126                 break;
9127         }
9128         case CMD_STACK_FRAME_GET_DOMAIN: {
9129                 if (CHECK_PROTOCOL_VERSION (2, 38))
9130                         buffer_add_domainid (buf, frame->domain);
9131                 break;
9132         }
9133         default:
9134                 return ERR_NOT_IMPLEMENTED;
9135         }
9136
9137         return ERR_NONE;
9138 }
9139
9140 static ErrorCode
9141 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9142 {
9143         MonoArray *arr;
9144         int objid, index, len, i, esize;
9145         ErrorCode err;
9146         gpointer elem;
9147
9148         objid = decode_objid (p, &p, end);
9149         err = get_object (objid, (MonoObject**)&arr);
9150         if (err != ERR_NONE)
9151                 return err;
9152
9153         switch (command) {
9154         case CMD_ARRAY_REF_GET_LENGTH:
9155                 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9156                 if (!arr->bounds) {
9157                         buffer_add_int (buf, arr->max_length);
9158                         buffer_add_int (buf, 0);
9159                 } else {
9160                         for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9161                                 buffer_add_int (buf, arr->bounds [i].length);
9162                                 buffer_add_int (buf, arr->bounds [i].lower_bound);
9163                         }
9164                 }
9165                 break;
9166         case CMD_ARRAY_REF_GET_VALUES:
9167                 index = decode_int (p, &p, end);
9168                 len = decode_int (p, &p, end);
9169
9170                 g_assert (index >= 0 && len >= 0);
9171                 // Reordered to avoid integer overflow
9172                 g_assert (!(index > arr->max_length - len));
9173
9174                 esize = mono_array_element_size (arr->obj.vtable->klass);
9175                 for (i = index; i < index + len; ++i) {
9176                         elem = (gpointer*)((char*)arr->vector + (i * esize));
9177                         buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9178                 }
9179                 break;
9180         case CMD_ARRAY_REF_SET_VALUES:
9181                 index = decode_int (p, &p, end);
9182                 len = decode_int (p, &p, end);
9183
9184                 g_assert (index >= 0 && len >= 0);
9185                 // Reordered to avoid integer overflow
9186                 g_assert (!(index > arr->max_length - len));
9187
9188                 esize = mono_array_element_size (arr->obj.vtable->klass);
9189                 for (i = index; i < index + len; ++i) {
9190                         elem = (gpointer*)((char*)arr->vector + (i * esize));
9191
9192                         decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9193                 }
9194                 break;
9195         default:
9196                 return ERR_NOT_IMPLEMENTED;
9197         }
9198
9199         return ERR_NONE;
9200 }
9201
9202 static ErrorCode
9203 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9204 {
9205         int objid;
9206         ErrorCode err;
9207         MonoString *str;
9208         char *s;
9209         int i, index, length;
9210         gunichar2 *c;
9211         gboolean use_utf16 = FALSE;
9212
9213         objid = decode_objid (p, &p, end);
9214         err = get_object (objid, (MonoObject**)&str);
9215         if (err != ERR_NONE)
9216                 return err;
9217
9218         switch (command) {
9219         case CMD_STRING_REF_GET_VALUE:
9220                 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9221                         for (i = 0; i < mono_string_length (str); ++i)
9222                                 if (mono_string_chars (str)[i] == 0)
9223                                         use_utf16 = TRUE;
9224                         buffer_add_byte (buf, use_utf16 ? 1 : 0);
9225                 }
9226                 if (use_utf16) {
9227                         buffer_add_int (buf, mono_string_length (str) * 2);
9228                         buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9229                 } else {
9230                         s = mono_string_to_utf8 (str);
9231                         buffer_add_string (buf, s);
9232                         g_free (s);
9233                 }
9234                 break;
9235         case CMD_STRING_REF_GET_LENGTH:
9236                 buffer_add_long (buf, mono_string_length (str));
9237                 break;
9238         case CMD_STRING_REF_GET_CHARS:
9239                 index = decode_long (p, &p, end);
9240                 length = decode_long (p, &p, end);
9241                 if (index > mono_string_length (str) - length)
9242                         return ERR_INVALID_ARGUMENT;
9243                 c = mono_string_chars (str) + index;
9244                 for (i = 0; i < length; ++i)
9245                         buffer_add_short (buf, c [i]);
9246                 break;
9247         default:
9248                 return ERR_NOT_IMPLEMENTED;
9249         }
9250
9251         return ERR_NONE;
9252 }
9253
9254 static ErrorCode
9255 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9256 {
9257         int objid;
9258         ErrorCode err;
9259         MonoObject *obj;
9260         int len, i;
9261         MonoClassField *f;
9262         MonoClass *k;
9263         gboolean found;
9264
9265         if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9266                 objid = decode_objid (p, &p, end);
9267                 err = get_object (objid, &obj);
9268                 if (err != ERR_NONE)
9269                         buffer_add_int (buf, 1);
9270                 else
9271                         buffer_add_int (buf, 0);
9272                 return ERR_NONE;
9273         }
9274
9275         objid = decode_objid (p, &p, end);
9276         err = get_object (objid, &obj);
9277         if (err != ERR_NONE)
9278                 return err;
9279
9280         MonoClass *obj_type;
9281         gboolean remote_obj = FALSE;
9282
9283         obj_type = obj->vtable->klass;
9284         if (mono_class_is_transparent_proxy (obj_type)) {
9285                 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9286                 remote_obj = TRUE;
9287         }
9288
9289         g_assert (obj_type);
9290
9291         switch (command) {
9292         case CMD_OBJECT_REF_GET_TYPE:
9293                 /* This handles transparent proxies too */
9294                 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9295                 break;
9296         case CMD_OBJECT_REF_GET_VALUES:
9297                 len = decode_int (p, &p, end);
9298
9299                 for (i = 0; i < len; ++i) {
9300                         MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9301                         if (err != ERR_NONE)
9302                                 return err;
9303
9304                         /* Check that the field belongs to the object */
9305                         found = FALSE;
9306                         for (k = obj_type; k; k = k->parent) {
9307                                 if (k == f->parent) {
9308                                         found = TRUE;
9309                                         break;
9310                                 }
9311                         }
9312                         if (!found)
9313                                 return ERR_INVALID_FIELDID;
9314
9315                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9316                                 guint8 *val;
9317                                 MonoVTable *vtable;
9318
9319                                 if (mono_class_field_is_special_static (f))
9320                                         return ERR_INVALID_FIELDID;
9321
9322                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9323                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9324                                 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9325                                 mono_field_static_get_value (vtable, f, val);
9326                                 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9327                                 g_free (val);
9328                         } else {
9329                                 guint8 *field_value = NULL;
9330                                 void *field_storage = NULL;
9331
9332                                 if (remote_obj) {
9333 #ifndef DISABLE_REMOTING
9334                                         field_value = mono_load_remote_field(obj, obj_type, f, &field_storage);
9335 #else
9336                                         g_assert_not_reached ();
9337 #endif
9338                                 } else
9339                                         field_value = (guint8*)obj + f->offset;
9340
9341                                 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9342                         }
9343                 }
9344                 break;
9345         case CMD_OBJECT_REF_SET_VALUES:
9346                 len = decode_int (p, &p, end);
9347
9348                 for (i = 0; i < len; ++i) {
9349                         f = decode_fieldid (p, &p, end, NULL, &err);
9350                         if (err != ERR_NONE)
9351                                 return err;
9352
9353                         /* Check that the field belongs to the object */
9354                         found = FALSE;
9355                         for (k = obj_type; k; k = k->parent) {
9356                                 if (k == f->parent) {
9357                                         found = TRUE;
9358                                         break;
9359                                 }
9360                         }
9361                         if (!found)
9362                                 return ERR_INVALID_FIELDID;
9363
9364                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9365                                 guint8 *val;
9366                                 MonoVTable *vtable;
9367
9368                                 if (mono_class_field_is_special_static (f))
9369                                         return ERR_INVALID_FIELDID;
9370
9371                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9372                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9373
9374                                 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9375                                 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9376                                 if (err != ERR_NONE) {
9377                                         g_free (val);
9378                                         return err;
9379                                 }
9380                                 mono_field_static_set_value (vtable, f, val);
9381                                 g_free (val);
9382                         } else {
9383                                 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9384                                 if (err != ERR_NONE)
9385                                         return err;
9386                         }
9387                 }
9388                 break;
9389         case CMD_OBJECT_REF_GET_ADDRESS:
9390                 buffer_add_long (buf, (gssize)obj);
9391                 break;
9392         case CMD_OBJECT_REF_GET_DOMAIN:
9393                 buffer_add_domainid (buf, obj->vtable->domain);
9394                 break;
9395         case CMD_OBJECT_REF_GET_INFO:
9396                 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9397                 buffer_add_domainid (buf, obj->vtable->domain);
9398                 break;
9399         default:
9400                 return ERR_NOT_IMPLEMENTED;
9401         }
9402
9403         return ERR_NONE;
9404 }
9405
9406 static const char*
9407 command_set_to_string (CommandSet command_set)
9408 {
9409         switch (command_set) {
9410         case CMD_SET_VM:
9411                 return "VM";
9412         case CMD_SET_OBJECT_REF:
9413                 return "OBJECT_REF";
9414         case CMD_SET_STRING_REF:
9415                 return "STRING_REF";
9416         case CMD_SET_THREAD:
9417                 return "THREAD";
9418         case CMD_SET_ARRAY_REF:
9419                 return "ARRAY_REF";
9420         case CMD_SET_EVENT_REQUEST:
9421                 return "EVENT_REQUEST";
9422         case CMD_SET_STACK_FRAME:
9423                 return "STACK_FRAME";
9424         case CMD_SET_APPDOMAIN:
9425                 return "APPDOMAIN";
9426         case CMD_SET_ASSEMBLY:
9427                 return "ASSEMBLY";
9428         case CMD_SET_METHOD:
9429                 return "METHOD";
9430         case CMD_SET_TYPE:
9431                 return "TYPE";
9432         case CMD_SET_MODULE:
9433                 return "MODULE";
9434         case CMD_SET_FIELD:
9435                 return "FIELD";
9436         case CMD_SET_EVENT:
9437                 return "EVENT";
9438         default:
9439                 return "";
9440         }
9441 }
9442
9443 static const char* vm_cmds_str [] = {
9444         "VERSION",
9445         "ALL_THREADS",
9446         "SUSPEND",
9447         "RESUME",
9448         "EXIT",
9449         "DISPOSE",
9450         "INVOKE_METHOD",
9451         "SET_PROTOCOL_VERSION",
9452         "ABORT_INVOKE",
9453         "SET_KEEPALIVE"
9454         "GET_TYPES_FOR_SOURCE_FILE",
9455         "GET_TYPES",
9456         "INVOKE_METHODS"
9457 };
9458
9459 static const char* thread_cmds_str[] = {
9460         "GET_FRAME_INFO",
9461         "GET_NAME",
9462         "GET_STATE",
9463         "GET_INFO",
9464         "GET_ID",
9465         "GET_TID",
9466         "SET_IP"
9467 };
9468
9469 static const char* event_cmds_str[] = {
9470         "REQUEST_SET",
9471         "REQUEST_CLEAR",
9472         "REQUEST_CLEAR_ALL_BREAKPOINTS"
9473 };
9474
9475 static const char* appdomain_cmds_str[] = {
9476         "GET_ROOT_DOMAIN",
9477         "GET_FRIENDLY_NAME",
9478         "GET_ASSEMBLIES",
9479         "GET_ENTRY_ASSEMBLY",
9480         "CREATE_STRING",
9481         "GET_CORLIB",
9482         "CREATE_BOXED_VALUE"
9483 };
9484
9485 static const char* assembly_cmds_str[] = {
9486         "GET_LOCATION",
9487         "GET_ENTRY_POINT",
9488         "GET_MANIFEST_MODULE",
9489         "GET_OBJECT",
9490         "GET_TYPE",
9491         "GET_NAME"
9492 };
9493
9494 static const char* module_cmds_str[] = {
9495         "GET_INFO",
9496 };
9497
9498 static const char* field_cmds_str[] = {
9499         "GET_INFO",
9500 };
9501
9502 static const char* method_cmds_str[] = {
9503         "GET_NAME",
9504         "GET_DECLARING_TYPE",
9505         "GET_DEBUG_INFO",
9506         "GET_PARAM_INFO",
9507         "GET_LOCALS_INFO",
9508         "GET_INFO",
9509         "GET_BODY",
9510         "RESOLVE_TOKEN",
9511         "GET_CATTRS ",
9512         "MAKE_GENERIC_METHOD"
9513 };
9514
9515 static const char* type_cmds_str[] = {
9516         "GET_INFO",
9517         "GET_METHODS",
9518         "GET_FIELDS",
9519         "GET_VALUES",
9520         "GET_OBJECT",
9521         "GET_SOURCE_FILES",
9522         "SET_VALUES",
9523         "IS_ASSIGNABLE_FROM",
9524         "GET_PROPERTIES ",
9525         "GET_CATTRS",
9526         "GET_FIELD_CATTRS",
9527         "GET_PROPERTY_CATTRS",
9528         "GET_SOURCE_FILES_2",
9529         "GET_VALUES_2",
9530         "GET_METHODS_BY_NAME_FLAGS",
9531         "GET_INTERFACES",
9532         "GET_INTERFACE_MAP",
9533         "IS_INITIALIZED"
9534 };
9535
9536 static const char* stack_frame_cmds_str[] = {
9537         "GET_VALUES",
9538         "GET_THIS",
9539         "SET_VALUES",
9540         "GET_DOMAIN",
9541 };
9542
9543 static const char* array_cmds_str[] = {
9544         "GET_LENGTH",
9545         "GET_VALUES",
9546         "SET_VALUES",
9547 };
9548
9549 static const char* string_cmds_str[] = {
9550         "GET_VALUE",
9551         "GET_LENGTH",
9552         "GET_CHARS"
9553 };
9554
9555 static const char* object_cmds_str[] = {
9556         "GET_TYPE",
9557         "GET_VALUES",
9558         "IS_COLLECTED",
9559         "GET_ADDRESS",
9560         "GET_DOMAIN",
9561         "SET_VALUES",
9562         "GET_INFO",
9563 };
9564
9565 static const char*
9566 cmd_to_string (CommandSet set, int command)
9567 {
9568         const char **cmds;
9569         int cmds_len = 0;
9570
9571         switch (set) {
9572         case CMD_SET_VM:
9573                 cmds = vm_cmds_str;
9574                 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9575                 break;
9576         case CMD_SET_OBJECT_REF:
9577                 cmds = object_cmds_str;
9578                 cmds_len = G_N_ELEMENTS (object_cmds_str);
9579                 break;
9580         case CMD_SET_STRING_REF:
9581                 cmds = string_cmds_str;
9582                 cmds_len = G_N_ELEMENTS (string_cmds_str);
9583                 break;
9584         case CMD_SET_THREAD:
9585                 cmds = thread_cmds_str;
9586                 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9587                 break;
9588         case CMD_SET_ARRAY_REF:
9589                 cmds = array_cmds_str;
9590                 cmds_len = G_N_ELEMENTS (array_cmds_str);
9591                 break;
9592         case CMD_SET_EVENT_REQUEST:
9593                 cmds = event_cmds_str;
9594                 cmds_len = G_N_ELEMENTS (event_cmds_str);
9595                 break;
9596         case CMD_SET_STACK_FRAME:
9597                 cmds = stack_frame_cmds_str;
9598                 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9599                 break;
9600         case CMD_SET_APPDOMAIN:
9601                 cmds = appdomain_cmds_str;
9602                 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9603                 break;
9604         case CMD_SET_ASSEMBLY:
9605                 cmds = assembly_cmds_str;
9606                 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9607                 break;
9608         case CMD_SET_METHOD:
9609                 cmds = method_cmds_str;
9610                 cmds_len = G_N_ELEMENTS (method_cmds_str);
9611                 break;
9612         case CMD_SET_TYPE:
9613                 cmds = type_cmds_str;
9614                 cmds_len = G_N_ELEMENTS (type_cmds_str);
9615                 break;
9616         case CMD_SET_MODULE:
9617                 cmds = module_cmds_str;
9618                 cmds_len = G_N_ELEMENTS (module_cmds_str);
9619                 break;
9620         case CMD_SET_FIELD:
9621                 cmds = field_cmds_str;
9622                 cmds_len = G_N_ELEMENTS (field_cmds_str);
9623                 break;
9624         case CMD_SET_EVENT:
9625                 cmds = event_cmds_str;
9626                 cmds_len = G_N_ELEMENTS (event_cmds_str);
9627                 break;
9628         default:
9629                 return NULL;
9630         }
9631         if (command > 0 && command <= cmds_len)
9632                 return cmds [command - 1];
9633         else
9634                 return NULL;
9635 }
9636
9637 static gboolean
9638 wait_for_attach (void)
9639 {
9640 #ifndef DISABLE_SOCKET_TRANSPORT
9641         if (listen_fd == -1) {
9642                 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9643                 return FALSE;
9644         }
9645
9646         /* Block and wait for client connection */
9647         conn_fd = socket_transport_accept (listen_fd);
9648
9649         DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9650         if (conn_fd == -1) {
9651                 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9652                 return FALSE;
9653         }
9654 #else
9655         g_assert_not_reached ();
9656 #endif
9657
9658         /* Handshake */
9659         disconnected = !transport_handshake ();
9660         if (disconnected) {
9661                 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9662                 return FALSE;
9663         }
9664         
9665         return TRUE;
9666 }
9667
9668 /*
9669  * debugger_thread:
9670  *
9671  *   This thread handles communication with the debugger client using a JDWP
9672  * like protocol.
9673  */
9674 static guint32 WINAPI
9675 debugger_thread (void *arg)
9676 {
9677         int res, len, id, flags, command = 0;
9678         CommandSet command_set = (CommandSet)0;
9679         guint8 header [HEADER_LENGTH];
9680         guint8 *data, *p, *end;
9681         Buffer buf;
9682         ErrorCode err;
9683         gboolean no_reply;
9684         gboolean attach_failed = FALSE;
9685         gpointer attach_cookie, attach_dummy;
9686
9687         DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9688
9689         debugger_thread_id = mono_native_thread_id_get ();
9690
9691         attach_cookie = mono_jit_thread_attach (mono_get_root_domain (), &attach_dummy);
9692
9693         mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9694
9695         mono_set_is_debugger_attached (TRUE);
9696         
9697         if (agent_config.defer) {
9698                 if (!wait_for_attach ()) {
9699                         DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9700                         attach_failed = TRUE; // Don't abort process when we can't listen
9701                 } else {
9702                         /* Send start event to client */
9703                         process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9704                 }
9705         }
9706         
9707         while (!attach_failed) {
9708                 res = transport_recv (header, HEADER_LENGTH);
9709
9710                 /* This will break if the socket is closed during shutdown too */
9711                 if (res != HEADER_LENGTH) {
9712                         DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9713                         break;
9714                 }
9715
9716                 p = header;
9717                 end = header + HEADER_LENGTH;
9718
9719                 len = decode_int (p, &p, end);
9720                 id = decode_int (p, &p, end);
9721                 flags = decode_byte (p, &p, end);
9722                 command_set = (CommandSet)decode_byte (p, &p, end);
9723                 command = decode_byte (p, &p, end);
9724
9725                 g_assert (flags == 0);
9726
9727                 if (log_level) {
9728                         const char *cmd_str;
9729                         char cmd_num [256];
9730
9731                         cmd_str = cmd_to_string (command_set, command);
9732                         if (!cmd_str) {
9733                                 sprintf (cmd_num, "%d", command);
9734                                 cmd_str = cmd_num;
9735                         }
9736                         
9737                         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);
9738                 }
9739
9740                 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
9741                 if (len - HEADER_LENGTH > 0)
9742                 {
9743                         res = transport_recv (data, len - HEADER_LENGTH);
9744                         if (res != len - HEADER_LENGTH) {
9745                                 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9746                                 break;
9747                         }
9748                 }
9749
9750                 p = data;
9751                 end = data + (len - HEADER_LENGTH);
9752
9753                 buffer_init (&buf, 128);
9754
9755                 err = ERR_NONE;
9756                 no_reply = FALSE;
9757
9758                 /* Process the request */
9759                 switch (command_set) {
9760                 case CMD_SET_VM:
9761                         err = vm_commands (command, id, p, end, &buf);
9762                         if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
9763                                 /* Sent after the invoke is complete */
9764                                 no_reply = TRUE;
9765                         break;
9766                 case CMD_SET_EVENT_REQUEST:
9767                         err = event_commands (command, p, end, &buf);
9768                         break;
9769                 case CMD_SET_APPDOMAIN:
9770                         err = domain_commands (command, p, end, &buf);
9771                         break;
9772                 case CMD_SET_ASSEMBLY:
9773                         err = assembly_commands (command, p, end, &buf);
9774                         break;
9775                 case CMD_SET_MODULE:
9776                         err = module_commands (command, p, end, &buf);
9777                         break;
9778                 case CMD_SET_FIELD:
9779                         err = field_commands (command, p, end, &buf);
9780                         break;
9781                 case CMD_SET_TYPE:
9782                         err = type_commands (command, p, end, &buf);
9783                         break;
9784                 case CMD_SET_METHOD:
9785                         err = method_commands (command, p, end, &buf);
9786                         break;
9787                 case CMD_SET_THREAD:
9788                         err = thread_commands (command, p, end, &buf);
9789                         break;
9790                 case CMD_SET_STACK_FRAME:
9791                         err = frame_commands (command, p, end, &buf);
9792                         break;
9793                 case CMD_SET_ARRAY_REF:
9794                         err = array_commands (command, p, end, &buf);
9795                         break;
9796                 case CMD_SET_STRING_REF:
9797                         err = string_commands (command, p, end, &buf);
9798                         break;
9799                 case CMD_SET_OBJECT_REF:
9800                         err = object_commands (command, p, end, &buf);
9801                         break;
9802                 default:
9803                         err = ERR_NOT_IMPLEMENTED;
9804                 }               
9805
9806                 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9807                         buffer_replies = TRUE;
9808                 }
9809
9810                 if (!no_reply) {
9811                         if (buffer_replies) {
9812                                 buffer_reply_packet (id, err, &buf);
9813                         } else {
9814                                 send_reply_packet (id, err, &buf);
9815                                 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9816                         }
9817                 }
9818
9819                 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9820                         send_buffered_reply_packets ();
9821                         buffer_replies = FALSE;
9822                 }
9823
9824                 g_free (data);
9825                 buffer_free (&buf);
9826
9827                 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9828                         break;
9829         }
9830
9831         mono_set_is_debugger_attached (FALSE);
9832
9833         mono_coop_mutex_lock (&debugger_thread_exited_mutex);
9834         debugger_thread_exited = TRUE;
9835         mono_coop_cond_signal (&debugger_thread_exited_cond);
9836         mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
9837
9838         DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9839         
9840         if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9841                 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9842                 start_debugger_thread ();
9843         }
9844
9845         mono_jit_thread_detach (attach_cookie, &attach_dummy);
9846
9847         return 0;
9848 }
9849
9850 #else /* DISABLE_DEBUGGER_AGENT */
9851
9852 void
9853 mono_debugger_agent_parse_options (char *options)
9854 {
9855         g_error ("This runtime is configured with the debugger agent disabled.");
9856 }
9857
9858 void
9859 mono_debugger_agent_init (void)
9860 {
9861 }
9862
9863 void
9864 mono_debugger_agent_breakpoint_hit (void *sigctx)
9865 {
9866 }
9867
9868 void
9869 mono_debugger_agent_single_step_event (void *sigctx)
9870 {
9871 }
9872
9873 void
9874 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9875 {
9876 }
9877
9878 void
9879 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9880                                                                           MonoContext *catch_ctx)
9881 {
9882 }
9883
9884 void
9885 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9886 {
9887 }
9888
9889 void
9890 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9891 {
9892 }
9893
9894 void
9895 mono_debugger_agent_user_break (void)
9896 {
9897         G_BREAKPOINT ();
9898 }
9899
9900 void
9901 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9902 {
9903 }
9904
9905 gboolean
9906 mono_debugger_agent_debug_log_is_enabled (void)
9907 {
9908         return FALSE;
9909 }
9910
9911 void
9912 mono_debugger_agent_unhandled_exception (MonoException *exc)
9913 {
9914         g_assert_not_reached ();
9915 }
9916
9917 void
9918 debugger_agent_single_step_from_context (MonoContext *ctx)
9919 {
9920         g_assert_not_reached ();
9921 }
9922
9923 void
9924 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9925 {
9926         g_assert_not_reached ();
9927 }
9928
9929 #endif