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