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