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