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