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