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