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