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