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