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