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