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