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