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