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