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