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