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