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