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