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