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