MonoDroid needs a way to inform the debugger of possibly unhandled exceptions.
[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 #ifdef PLATFORM_ANDROID
5123 void
5124 mono_debugger_agent_unhandled_exception (MonoException *exc)
5125 {
5126         int suspend_policy;
5127         GSList *events;
5128         EventInfo ei;
5129
5130         if (!inited)
5131                 return;
5132
5133         memset (&ei, 0, sizeof (EventInfo));
5134         ei.exc = (MonoObject*)exc;
5135
5136         mono_loader_lock ();
5137         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5138         mono_loader_unlock ();
5139
5140         process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5141 }
5142 #endif
5143
5144 void
5145 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx, 
5146                                       MonoContext *catch_ctx)
5147 {
5148         int suspend_policy;
5149         GSList *events;
5150         MonoJitInfo *ji;
5151         EventInfo ei;
5152         DebuggerTlsData *tls = NULL;
5153
5154         if (thread_to_tls != NULL) {
5155                 MonoInternalThread *thread = mono_thread_internal_current ();
5156
5157                 mono_loader_lock ();
5158                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5159                 mono_loader_unlock ();
5160
5161                 if (tls && tls->abort_requested)
5162                         return;
5163                 if (tls && tls->disable_breakpoints)
5164                         return;
5165         }
5166
5167         memset (&ei, 0, sizeof (EventInfo));
5168
5169         /* Just-In-Time debugging */
5170         if (!catch_ctx) {
5171                 if (agent_config.onuncaught && !inited) {
5172                         finish_agent_init (FALSE);
5173
5174                         /*
5175                          * Send an unsolicited EXCEPTION event with a dummy request id.
5176                          */
5177                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5178                         ei.exc = (MonoObject*)exc;
5179                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5180                         return;
5181                 }
5182         } else if (agent_config.onthrow && !inited) {
5183                 GSList *l;
5184                 gboolean found = FALSE;
5185
5186                 for (l = agent_config.onthrow; l; l = l->next) {
5187                         char *ex_type = l->data;
5188                         char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5189
5190                         if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5191                                 found = TRUE;
5192
5193                         g_free (f);
5194                 }
5195
5196                 if (found) {
5197                         finish_agent_init (FALSE);
5198
5199                         /*
5200                          * Send an unsolicited EXCEPTION event with a dummy request id.
5201                          */
5202                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5203                         ei.exc = (MonoObject*)exc;
5204                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5205                         return;
5206                 }
5207         }
5208
5209         if (!inited)
5210                 return;
5211
5212         ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5213
5214         ei.exc = (MonoObject*)exc;
5215         ei.caught = catch_ctx != NULL;
5216
5217         mono_loader_lock ();
5218         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5219         mono_loader_unlock ();
5220
5221         if (tls && catch_ctx) {
5222                 tls->catch_ctx = *catch_ctx;
5223                 tls->has_catch_ctx = TRUE;
5224         }
5225
5226         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5227
5228         if (tls)
5229                 tls->has_catch_ctx = FALSE;
5230 }
5231
5232 void
5233 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5234 {
5235         DebuggerTlsData *tls;
5236
5237         if (!inited)
5238                 return;
5239
5240         tls = mono_native_tls_get_value (debugger_tls_id);
5241         if (!tls)
5242                 return;
5243
5244         /*
5245          * We're about to invoke an exception filter during the first pass of exception handling.
5246          *
5247          * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5248          * 'orig_ctx' is the context where the exception has been thrown.
5249          *
5250          *
5251          * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5252          *
5253          * If we're stopped in Filter(), normal stack unwinding would first unwind to
5254          * the call site (line 37) and then continue to Main(), but it would never
5255          * include the throw site (line 32).
5256          *
5257          * Since exception filters are invoked during the first pass of exception handling,
5258          * the stack frames of the throw site are still intact, so we should include them
5259          * in a stack trace.
5260          *
5261          * We do this here by saving the context of the throw site in 'tls->filter_state'.
5262          *
5263          * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5264          * but report the location of the 'throw' to the user.
5265          *
5266          */
5267
5268         g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5269 }
5270
5271 void
5272 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5273 {
5274         DebuggerTlsData *tls;
5275
5276         if (!inited)
5277                 return;
5278
5279         tls = mono_native_tls_get_value (debugger_tls_id);
5280         if (!tls)
5281                 return;
5282
5283         tls->filter_state.valid = FALSE;
5284 }
5285
5286 /*
5287  * buffer_add_value_full:
5288  *
5289  *   Add the encoding of the value at ADDR described by T to the buffer.
5290  * AS_VTYPE determines whenever to treat primitive types as primitive types or
5291  * vtypes.
5292  */
5293 static void
5294 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5295                                            gboolean as_vtype)
5296 {
5297         MonoObject *obj;
5298
5299         if (t->byref) {
5300                 g_assert (*(void**)addr);
5301                 addr = *(void**)addr;
5302         }
5303
5304         if (as_vtype) {
5305                 switch (t->type) {
5306                 case MONO_TYPE_BOOLEAN:
5307                 case MONO_TYPE_I1:
5308                 case MONO_TYPE_U1:
5309                 case MONO_TYPE_CHAR:
5310                 case MONO_TYPE_I2:
5311                 case MONO_TYPE_U2:
5312                 case MONO_TYPE_I4:
5313                 case MONO_TYPE_U4:
5314                 case MONO_TYPE_R4:
5315                 case MONO_TYPE_I8:
5316                 case MONO_TYPE_U8:
5317                 case MONO_TYPE_R8:
5318                 case MONO_TYPE_I:
5319                 case MONO_TYPE_U:
5320                 case MONO_TYPE_PTR:
5321                         goto handle_vtype;
5322                         break;
5323                 default:
5324                         break;
5325                 }
5326         }
5327
5328         switch (t->type) {
5329         case MONO_TYPE_VOID:
5330                 buffer_add_byte (buf, t->type);
5331                 break;
5332         case MONO_TYPE_BOOLEAN:
5333         case MONO_TYPE_I1:
5334         case MONO_TYPE_U1:
5335                 buffer_add_byte (buf, t->type);
5336                 buffer_add_int (buf, *(gint8*)addr);
5337                 break;
5338         case MONO_TYPE_CHAR:
5339         case MONO_TYPE_I2:
5340         case MONO_TYPE_U2:
5341                 buffer_add_byte (buf, t->type);
5342                 buffer_add_int (buf, *(gint16*)addr);
5343                 break;
5344         case MONO_TYPE_I4:
5345         case MONO_TYPE_U4:
5346         case MONO_TYPE_R4:
5347                 buffer_add_byte (buf, t->type);
5348                 buffer_add_int (buf, *(gint32*)addr);
5349                 break;
5350         case MONO_TYPE_I8:
5351         case MONO_TYPE_U8:
5352         case MONO_TYPE_R8:
5353                 buffer_add_byte (buf, t->type);
5354                 buffer_add_long (buf, *(gint64*)addr);
5355                 break;
5356         case MONO_TYPE_I:
5357         case MONO_TYPE_U:
5358                 /* Treat it as a vtype */
5359                 goto handle_vtype;
5360         case MONO_TYPE_PTR: {
5361                 gssize val = *(gssize*)addr;
5362                 
5363                 buffer_add_byte (buf, t->type);
5364                 buffer_add_long (buf, val);
5365                 break;
5366         }
5367         handle_ref:
5368         case MONO_TYPE_STRING:
5369         case MONO_TYPE_SZARRAY:
5370         case MONO_TYPE_OBJECT:
5371         case MONO_TYPE_CLASS:
5372         case MONO_TYPE_ARRAY:
5373                 obj = *(MonoObject**)addr;
5374
5375                 if (!obj) {
5376                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5377                 } else {
5378                         if (obj->vtable->klass->valuetype) {
5379                                 t = &obj->vtable->klass->byval_arg;
5380                                 addr = mono_object_unbox (obj);
5381                                 goto handle_vtype;
5382                         } else if (obj->vtable->klass->rank) {
5383                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5384                         } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5385                                 buffer_add_byte (buf, MONO_TYPE_CLASS);
5386                         } else {
5387                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5388                         }
5389                         buffer_add_objid (buf, obj);
5390                 }
5391                 break;
5392         handle_vtype:
5393         case MONO_TYPE_VALUETYPE: {
5394                 int nfields;
5395                 gpointer iter;
5396                 MonoClassField *f;
5397                 MonoClass *klass = mono_class_from_mono_type (t);
5398
5399                 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5400                 buffer_add_byte (buf, klass->enumtype);
5401                 buffer_add_typeid (buf, domain, klass);
5402
5403                 nfields = 0;
5404                 iter = NULL;
5405                 while ((f = mono_class_get_fields (klass, &iter))) {
5406                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5407                                 continue;
5408                         if (mono_field_is_deleted (f))
5409                                 continue;
5410                         nfields ++;
5411                 }
5412                 buffer_add_int (buf, nfields);
5413
5414                 iter = NULL;
5415                 while ((f = mono_class_get_fields (klass, &iter))) {
5416                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5417                                 continue;
5418                         if (mono_field_is_deleted (f))
5419                                 continue;
5420                         buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5421                 }
5422                 break;
5423         }
5424         case MONO_TYPE_GENERICINST:
5425                 if (mono_type_generic_inst_is_valuetype (t)) {
5426                         goto handle_vtype;
5427                 } else {
5428                         goto handle_ref;
5429                 }
5430                 break;
5431         default:
5432                 NOT_IMPLEMENTED;
5433         }
5434 }
5435
5436 static void
5437 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5438 {
5439         buffer_add_value_full (buf, t, addr, domain, FALSE);
5440 }
5441
5442 static gboolean
5443 obj_is_of_type (MonoObject *obj, MonoType *t)
5444 {
5445         MonoClass *klass = obj->vtable->klass;
5446         if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5447                 if (klass == mono_defaults.transparent_proxy_class) {
5448                         klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5449                         if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5450                                 return TRUE;
5451                         }
5452                 }
5453                 return FALSE;
5454         }
5455         return TRUE;
5456 }
5457
5458 static ErrorCode
5459 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5460
5461 static ErrorCode
5462 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5463 {
5464         int err;
5465
5466         if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5467                 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5468                 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5469                 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5470                 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5471                 char *name = mono_type_full_name (t);
5472                 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5473                 g_free (name);
5474                 return ERR_INVALID_ARGUMENT;
5475         }
5476
5477         switch (t->type) {
5478         case MONO_TYPE_BOOLEAN:
5479                 *(guint8*)addr = decode_int (buf, &buf, limit);
5480                 break;
5481         case MONO_TYPE_CHAR:
5482                 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5483                 break;
5484         case MONO_TYPE_I1:
5485                 *(gint8*)addr = decode_int (buf, &buf, limit);
5486                 break;
5487         case MONO_TYPE_U1:
5488                 *(guint8*)addr = decode_int (buf, &buf, limit);
5489                 break;
5490         case MONO_TYPE_I2:
5491                 *(gint16*)addr = decode_int (buf, &buf, limit);
5492                 break;
5493         case MONO_TYPE_U2:
5494                 *(guint16*)addr = decode_int (buf, &buf, limit);
5495                 break;
5496         case MONO_TYPE_I4:
5497                 *(gint32*)addr = decode_int (buf, &buf, limit);
5498                 break;
5499         case MONO_TYPE_U4:
5500                 *(guint32*)addr = decode_int (buf, &buf, limit);
5501                 break;
5502         case MONO_TYPE_I8:
5503                 *(gint64*)addr = decode_long (buf, &buf, limit);
5504                 break;
5505         case MONO_TYPE_U8:
5506                 *(guint64*)addr = decode_long (buf, &buf, limit);
5507                 break;
5508         case MONO_TYPE_R4:
5509                 *(guint32*)addr = decode_int (buf, &buf, limit);
5510                 break;
5511         case MONO_TYPE_R8:
5512                 *(guint64*)addr = decode_long (buf, &buf, limit);
5513                 break;
5514         case MONO_TYPE_PTR:
5515                 /* We send these as I8, so we get them back as such */
5516                 g_assert (type == MONO_TYPE_I8);
5517                 *(gssize*)addr = decode_long (buf, &buf, limit);
5518                 break;
5519         case MONO_TYPE_GENERICINST:
5520                 if (MONO_TYPE_ISSTRUCT (t)) {
5521                         /* The client sends these as a valuetype */
5522                         goto handle_vtype;
5523                 } else {
5524                         goto handle_ref;
5525                 }
5526                 break;
5527         case MONO_TYPE_I:
5528         case MONO_TYPE_U:
5529                 /* We send these as vtypes, so we get them back as such */
5530                 g_assert (type == MONO_TYPE_VALUETYPE);
5531                 /* Fall through */
5532                 handle_vtype:
5533         case MONO_TYPE_VALUETYPE: {
5534                 gboolean is_enum = decode_byte (buf, &buf, limit);
5535                 MonoClass *klass;
5536                 MonoClassField *f;
5537                 int nfields;
5538                 gpointer iter = NULL;
5539                 MonoDomain *d;
5540
5541                 /* Enums are sent as a normal vtype */
5542                 if (is_enum)
5543                         return ERR_NOT_IMPLEMENTED;
5544                 klass = decode_typeid (buf, &buf, limit, &d, &err);
5545                 if (err)
5546                         return err;
5547
5548                 if (klass != mono_class_from_mono_type (t))
5549                         return ERR_INVALID_ARGUMENT;
5550
5551                 nfields = decode_int (buf, &buf, limit);
5552                 while ((f = mono_class_get_fields (klass, &iter))) {
5553                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5554                                 continue;
5555                         if (mono_field_is_deleted (f))
5556                                 continue;
5557                         err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5558                         if (err)
5559                                 return err;
5560                         nfields --;
5561                 }
5562                 g_assert (nfields == 0);
5563                 break;
5564         }
5565         handle_ref:
5566         default:
5567                 if (MONO_TYPE_IS_REFERENCE (t)) {
5568                         if (type == MONO_TYPE_OBJECT) {
5569                                 int objid = decode_objid (buf, &buf, limit);
5570                                 int err;
5571                                 MonoObject *obj;
5572
5573                                 err = get_object (objid, (MonoObject**)&obj);
5574                                 if (err)
5575                                         return err;
5576
5577                                 if (obj) {
5578                                         if (!obj_is_of_type (obj, t)) {
5579                                                 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5580                                                 return ERR_INVALID_ARGUMENT;
5581                                         }
5582                                 }
5583                                 if (obj && obj->vtable->domain != domain)
5584                                         return ERR_INVALID_ARGUMENT;
5585
5586                                 mono_gc_wbarrier_generic_store (addr, obj);
5587                         } else if (type == VALUE_TYPE_ID_NULL) {
5588                                 *(MonoObject**)addr = NULL;
5589                         } else {
5590                                 return ERR_INVALID_ARGUMENT;
5591                         }
5592                 } else {
5593                         NOT_IMPLEMENTED;
5594                 }
5595                 break;
5596         }
5597
5598         *endbuf = buf;
5599
5600         return 0;
5601 }
5602
5603 static ErrorCode
5604 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5605 {
5606         int err;
5607         int type = decode_byte (buf, &buf, limit);
5608
5609         if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5610                 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5611                 guint8 *nullable_buf;
5612
5613                 /*
5614                  * First try decoding it as a Nullable`1
5615                  */
5616                 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5617                 if (!err)
5618                         return err;
5619
5620                 /*
5621                  * Then try decoding as a primitive value or null.
5622                  */
5623                 if (targ->type == type) {
5624                         nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5625                         err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5626                         if (err) {
5627                                 g_free (nullable_buf);
5628                                 return err;
5629                         }
5630                         mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5631                         g_free (nullable_buf);
5632                         *endbuf = buf;
5633                         return ERR_NONE;
5634                 } else if (type == VALUE_TYPE_ID_NULL) {
5635                         mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5636                         *endbuf = buf;
5637                         return ERR_NONE;
5638                 }
5639         }
5640
5641         return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5642 }
5643
5644 static void
5645 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5646 {
5647         guint32 flags;
5648         int reg;
5649         guint8 *addr;
5650         mgreg_t reg_val;
5651
5652         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5653         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5654
5655         switch (flags) {
5656         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5657                 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5658
5659                 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype);
5660                 break;
5661         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5662                 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5663                 addr += (gint32)var->offset;
5664
5665                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5666
5667                 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5668                 break;
5669         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5670                 NOT_IMPLEMENTED;
5671                 break;
5672         default:
5673                 g_assert_not_reached ();
5674         }
5675 }
5676
5677 static void
5678 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5679 {
5680         guint32 flags;
5681         int reg, size;
5682         guint8 *addr;
5683
5684         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5685         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5686
5687         if (MONO_TYPE_IS_REFERENCE (t))
5688                 size = sizeof (gpointer);
5689         else
5690                 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5691
5692         switch (flags) {
5693         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5694 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5695                 mgreg_t v;
5696                 gboolean is_signed = FALSE;
5697
5698                 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5699                         is_signed = TRUE;
5700
5701                 switch (size) {
5702                 case 1:
5703                         v = is_signed ? *(gint8*)val : *(guint8*)val;
5704                         break;
5705                 case 2:
5706                         v = is_signed ? *(gint16*)val : *(guint16*)val;
5707                         break;
5708                 case 4:
5709                         v = is_signed ? *(gint32*)val : *(guint32*)val;
5710                         break;
5711                 case 8:
5712                         v = is_signed ? *(gint64*)val : *(guint64*)val;
5713                         break;
5714                 default:
5715                         g_assert_not_reached ();
5716                 }
5717
5718                 if (t->byref)
5719                         NOT_IMPLEMENTED;
5720
5721                 /* Set value on the stack or in the return ctx */
5722                 if (reg_locations [reg]) {
5723                         /* Saved on the stack */
5724                         DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5725                         *(reg_locations [reg]) = v;
5726                 } else {
5727                         /* Not saved yet */
5728                         DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5729                         mono_arch_context_set_int_reg (restore_ctx, reg, v);
5730                 }                       
5731
5732                 // FIXME: Move these to mono-context.h/c.
5733                 mono_arch_context_set_int_reg (ctx, reg, v);
5734 #else
5735                 // FIXME: Can't set registers, so we disable linears
5736                 NOT_IMPLEMENTED;
5737 #endif
5738                 break;
5739         }
5740         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5741                 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5742                 addr += (gint32)var->offset;
5743
5744                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5745
5746                 if (t->byref) {
5747                         addr = *(guint8**)addr;
5748
5749                         if (!addr)
5750                                 break;
5751                 }
5752                         
5753                 // FIXME: Write barriers
5754                 mono_gc_memmove (addr, val, size);
5755                 break;
5756         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5757                 NOT_IMPLEMENTED;
5758                 break;
5759         default:
5760                 g_assert_not_reached ();
5761         }
5762 }
5763
5764 static void
5765 clear_event_request (int req_id, int etype)
5766 {
5767         int i;
5768
5769         mono_loader_lock ();
5770         for (i = 0; i < event_requests->len; ++i) {
5771                 EventRequest *req = g_ptr_array_index (event_requests, i);
5772
5773                 if (req->id == req_id && req->event_kind == etype) {
5774                         if (req->event_kind == EVENT_KIND_BREAKPOINT)
5775                                 clear_breakpoint (req->info);
5776                         if (req->event_kind == EVENT_KIND_STEP)
5777                                 ss_destroy (req->info);
5778                         if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5779                                 clear_breakpoint (req->info);
5780                         if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5781                                 clear_breakpoint (req->info);
5782                         g_ptr_array_remove_index_fast (event_requests, i);
5783                         g_free (req);
5784                         break;
5785                 }
5786         }
5787         mono_loader_unlock ();
5788 }
5789
5790 static gboolean
5791 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5792 {
5793         if (req->event_kind == EVENT_KIND_BREAKPOINT)
5794                 return breakpoint_matches_assembly (req->info, assembly);
5795         else {
5796                 int i, j;
5797
5798                 for (i = 0; i < req->nmodifiers; ++i) {
5799                         Modifier *m = &req->modifiers [i];
5800
5801                         if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5802                                 return TRUE;
5803                         if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5804                                 for (j = 0; m->data.assemblies [j]; ++j)
5805                                         if (m->data.assemblies [j] == assembly)
5806                                                 return TRUE;
5807                         }
5808                 }
5809         }
5810
5811         return FALSE;
5812 }
5813
5814 /*
5815  * clear_event_requests_for_assembly:
5816  *
5817  *   Clear all events requests which reference ASSEMBLY.
5818  */
5819 static void
5820 clear_event_requests_for_assembly (MonoAssembly *assembly)
5821 {
5822         int i;
5823         gboolean found;
5824
5825         mono_loader_lock ();
5826         found = TRUE;
5827         while (found) {
5828                 found = FALSE;
5829                 for (i = 0; i < event_requests->len; ++i) {
5830                         EventRequest *req = g_ptr_array_index (event_requests, i);
5831
5832                         if (event_req_matches_assembly (req, assembly)) {
5833                                 clear_event_request (req->id, req->event_kind);
5834                                 found = TRUE;
5835                                 break;
5836                         }
5837                 }
5838         }
5839         mono_loader_unlock ();
5840 }
5841
5842 /*
5843  * type_comes_from_assembly:
5844  *
5845  *   GHRFunc that returns TRUE if klass comes from assembly
5846  */
5847 static gboolean
5848 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5849 {
5850         return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5851 }
5852
5853 /*
5854  * clear_types_for_assembly:
5855  *
5856  *   Clears types from loaded_classes for a given assembly
5857  */
5858 static void
5859 clear_types_for_assembly (MonoAssembly *assembly)
5860 {
5861         MonoDomain *domain = mono_domain_get ();
5862         AgentDomainInfo *info = NULL;
5863
5864         mono_loader_lock ();
5865         info = get_agent_domain_info (domain);
5866         g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5867         mono_loader_unlock ();
5868 }
5869
5870 static void
5871 add_thread (gpointer key, gpointer value, gpointer user_data)
5872 {
5873         MonoInternalThread *thread = value;
5874         Buffer *buf = user_data;
5875
5876         buffer_add_objid (buf, (MonoObject*)thread);
5877 }
5878
5879 static ErrorCode
5880 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5881 {
5882         guint8 *end = invoke->endp;
5883         MonoMethod *m;
5884         int i, err, nargs;
5885         MonoMethodSignature *sig;
5886         guint8 **arg_buf;
5887         void **args;
5888         MonoObject *this, *res, *exc;
5889         MonoDomain *domain;
5890         guint8 *this_buf;
5891 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5892         MonoLMFExt ext;
5893 #endif
5894         MonoStopwatch watch;
5895
5896         if (invoke->method) {
5897                 /* 
5898                  * Invoke this method directly, currently only Environment.Exit () is supported.
5899                  */
5900                 this = NULL;
5901                 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>"));
5902                 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5903                 g_assert_not_reached ();
5904         }
5905
5906         m = decode_methodid (p, &p, end, &domain, &err);
5907         if (err)
5908                 return err;
5909         sig = mono_method_signature (m);
5910
5911         if (m->klass->valuetype)
5912                 this_buf = g_alloca (mono_class_instance_size (m->klass));
5913         else
5914                 this_buf = g_alloca (sizeof (MonoObject*));
5915         if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5916                 /* Should be null */
5917                 int type = decode_byte (p, &p, end);
5918                 if (type != VALUE_TYPE_ID_NULL)
5919                         return ERR_INVALID_ARGUMENT;
5920                 memset (this_buf, 0, mono_class_instance_size (m->klass));
5921         } else {
5922                 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5923                 if (err)
5924                         return err;
5925         }
5926
5927         if (!m->klass->valuetype)
5928                 this = *(MonoObject**)this_buf;
5929         else
5930                 this = NULL;
5931
5932         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>"));
5933
5934         if (this && this->vtable->domain != domain)
5935                 NOT_IMPLEMENTED;
5936
5937         if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5938                 if (!strcmp (m->name, ".ctor")) {
5939                         if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5940                                 return ERR_INVALID_ARGUMENT;
5941                         else
5942                                 this = mono_object_new (domain, m->klass);
5943                 } else {
5944                         return ERR_INVALID_ARGUMENT;
5945                 }
5946         }
5947
5948         if (this && !obj_is_of_type (this, &m->klass->byval_arg))
5949                 return ERR_INVALID_ARGUMENT;
5950
5951         nargs = decode_int (p, &p, end);
5952         if (nargs != sig->param_count)
5953                 return ERR_INVALID_ARGUMENT;
5954         /* Use alloca to get gc tracking */
5955         arg_buf = g_alloca (nargs * sizeof (gpointer));
5956         memset (arg_buf, 0, nargs * sizeof (gpointer));
5957         args = g_alloca (nargs * sizeof (gpointer));
5958         for (i = 0; i < nargs; ++i) {
5959                 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5960                         err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5961                         if (err)
5962                                 break;
5963
5964                         if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5965                                 NOT_IMPLEMENTED;
5966                 } else {
5967                         arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5968                         err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5969                         if (err)
5970                                 break;
5971                         args [i] = arg_buf [i];
5972                 }
5973         }
5974
5975         if (i < nargs)
5976                 return err;
5977
5978         if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5979                 tls->disable_breakpoints = TRUE;
5980         else
5981                 tls->disable_breakpoints = FALSE;
5982
5983         /* 
5984          * Add an LMF frame to link the stack frames on the invoke method with our caller.
5985          */
5986         /* FIXME: Move this to arch specific code */
5987 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5988         if (invoke->has_ctx) {
5989                 MonoLMF **lmf_addr;
5990
5991                 lmf_addr = mono_get_lmf_addr ();
5992
5993                 /* Setup our lmf */
5994                 memset (&ext, 0, sizeof (ext));
5995 #ifdef TARGET_AMD64
5996                 ext.lmf.previous_lmf = *(lmf_addr);
5997                 /* Mark that this is a MonoLMFExt */
5998                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5999                 ext.lmf.rsp = (gssize)&ext;
6000 #elif defined(TARGET_X86)
6001                 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6002                 /* Mark that this is a MonoLMFExt */
6003                 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6004                 ext.lmf.ebp = (gssize)&ext;
6005 #elif defined(TARGET_ARM)
6006                 ext.lmf.previous_lmf = *(lmf_addr);
6007                 /* Mark that this is a MonoLMFExt */
6008                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6009                 ext.lmf.sp = (gssize)&ext;
6010 #elif defined(TARGET_POWERPC)
6011                 ext.lmf.previous_lmf = *(lmf_addr);
6012                 /* Mark that this is a MonoLMFExt */
6013                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6014                 ext.lmf.ebp = (gssize)&ext;
6015 #elif defined(TARGET_S390X)
6016                 ext.lmf.previous_lmf = *(lmf_addr);
6017                 /* Mark that this is a MonoLMFExt */
6018                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6019                 ext.lmf.ebp = (gssize)&ext;
6020 #elif defined(TARGET_MIPS)
6021                 ext.lmf.previous_lmf = *(lmf_addr);
6022                 /* Mark that this is a MonoLMFExt */
6023                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6024                 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6025 #else
6026                 g_assert_not_reached ();
6027 #endif
6028
6029                 ext.debugger_invoke = TRUE;
6030                 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6031
6032                 mono_set_lmf ((MonoLMF*)&ext);
6033         }
6034 #endif
6035
6036         mono_stopwatch_start (&watch);
6037         if (m->klass->valuetype)
6038                 res = mono_runtime_invoke (m, this_buf, args, &exc);
6039         else
6040                 res = mono_runtime_invoke (m, this, args, &exc);
6041         mono_stopwatch_stop (&watch);
6042         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)));
6043         if (exc) {
6044                 buffer_add_byte (buf, 0);
6045                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6046         } else {
6047                 buffer_add_byte (buf, 1);
6048                 if (sig->ret->type == MONO_TYPE_VOID) {
6049                         if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6050                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6051                         }
6052                         else
6053                                 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6054                 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6055                         buffer_add_value (buf, sig->ret, &res, domain);
6056                 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6057                         if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6058                                 MonoClass *k = mono_class_from_mono_type (sig->ret);
6059                                 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6060
6061                                 g_assert (nullable_buf);
6062                                 mono_nullable_init (nullable_buf, res, k);
6063                                 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6064                         } else {
6065                                 g_assert (res);
6066                                 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6067                         }
6068                 } else {
6069                         NOT_IMPLEMENTED;
6070                 }
6071         }
6072
6073         tls->disable_breakpoints = FALSE;
6074
6075 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6076         if (invoke->has_ctx)
6077                 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6078 #endif
6079
6080         *endp = p;
6081         // FIXME: byref arguments
6082         // FIXME: varargs
6083         return ERR_NONE;
6084 }
6085
6086 /*
6087  * invoke_method:
6088  *
6089  *   Invoke the method given by tls->pending_invoke in the current thread.
6090  */
6091 static void
6092 invoke_method (void)
6093 {
6094         DebuggerTlsData *tls;
6095         InvokeData *invoke;
6096         int id;
6097         int i, err, mindex;
6098         Buffer buf;
6099         static void (*restore_context) (void *);
6100         MonoContext restore_ctx;
6101         guint8 *p;
6102
6103         if (!restore_context)
6104                 restore_context = mono_get_restore_context ();
6105
6106         tls = mono_native_tls_get_value (debugger_tls_id);
6107         g_assert (tls);
6108
6109         /*
6110          * Store the `InvokeData *' in `tls->invoke' until we're done with
6111          * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6112          */
6113
6114         mono_loader_lock ();
6115
6116         invoke = tls->pending_invoke;
6117         g_assert (invoke);
6118         tls->pending_invoke = NULL;
6119
6120         invoke->last_invoke = tls->invoke;
6121         tls->invoke = invoke;
6122
6123         mono_loader_unlock ();
6124
6125         tls->frames_up_to_date = FALSE;
6126
6127         id = invoke->id;
6128
6129         p = invoke->p;
6130         err = 0;
6131         for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6132                 buffer_init (&buf, 128);
6133
6134                 if (err) {
6135                         /* Fail the other invokes as well */
6136                 } else {
6137                         err = do_invoke_method (tls, &buf, invoke, p, &p);
6138                 }
6139
6140                 /* Start suspending before sending the reply */
6141                 if (mindex == invoke->nmethods - 1) {
6142                         if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6143                                 for (i = 0; i < invoke->suspend_count; ++i)
6144                                         suspend_vm ();
6145                         }
6146                 }
6147
6148                 send_reply_packet (id, err, &buf);
6149         
6150                 buffer_free (&buf);
6151         }
6152
6153         memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6154
6155         if (invoke->has_ctx)
6156                 save_thread_context (&restore_ctx);
6157
6158         if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6159                 g_assert (tls->resume_count);
6160                 tls->resume_count -= invoke->suspend_count;
6161         }
6162
6163         DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6164
6165         /*
6166          * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6167          *
6168          * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6169          * after the mono_runtime_invoke() already returned, but it doesn't matter
6170          * because we reset the abort here.
6171          */
6172
6173         mono_loader_lock ();
6174
6175         if (tls->abort_requested)
6176                 mono_thread_internal_reset_abort (tls->thread);
6177
6178         tls->invoke = tls->invoke->last_invoke;
6179         tls->abort_requested = FALSE;
6180
6181         mono_loader_unlock ();
6182
6183         g_free (invoke->p);
6184         g_free (invoke);
6185
6186         suspend_current ();
6187 }
6188
6189 static gboolean
6190 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6191 {
6192         MonoThread *thread = value;
6193         DebuggerTlsData *tls;
6194         gboolean res;
6195
6196         mono_loader_lock ();
6197         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6198         g_assert (tls);
6199         res = tls->really_suspended;
6200         mono_loader_unlock ();
6201
6202         return res;
6203 }
6204
6205 static GPtrArray*
6206 get_source_files_for_type (MonoClass *klass)
6207 {
6208         gpointer iter = NULL;
6209         MonoMethod *method;
6210         MonoDebugSourceInfo *sinfo;
6211         GPtrArray *files;
6212         int i, j;
6213
6214         files = g_ptr_array_new ();
6215
6216         while ((method = mono_class_get_methods (klass, &iter))) {
6217                 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6218                 GPtrArray *source_file_list;
6219
6220                 if (minfo) {
6221                         mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6222                         for (j = 0; j < source_file_list->len; ++j) {
6223                                 sinfo = g_ptr_array_index (source_file_list, j);
6224                                 for (i = 0; i < files->len; ++i)
6225                                         if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6226                                                 break;
6227                                 if (i == files->len)
6228                                         g_ptr_array_add (files, g_strdup (sinfo->source_file));
6229                         }
6230                         g_ptr_array_free (source_file_list, TRUE);
6231                 }
6232         }
6233
6234         return files;
6235 }
6236
6237 static ErrorCode
6238 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6239 {
6240         switch (command) {
6241         case CMD_VM_VERSION: {
6242                 char *build_info, *version;
6243
6244                 build_info = mono_get_runtime_build_info ();
6245                 version = g_strdup_printf ("mono %s", build_info);
6246
6247                 buffer_add_string (buf, version); /* vm version */
6248                 buffer_add_int (buf, MAJOR_VERSION);
6249                 buffer_add_int (buf, MINOR_VERSION);
6250                 g_free (build_info);
6251                 g_free (version);
6252                 break;
6253         }
6254         case CMD_VM_SET_PROTOCOL_VERSION: {
6255                 major_version = decode_int (p, &p, end);
6256                 minor_version = decode_int (p, &p, end);
6257                 protocol_version_set = TRUE;
6258                 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6259                 break;
6260         }
6261         case CMD_VM_ALL_THREADS: {
6262                 // FIXME: Domains
6263                 mono_loader_lock ();
6264                 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6265                 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6266                 mono_loader_unlock ();
6267                 break;
6268         }
6269         case CMD_VM_SUSPEND:
6270                 suspend_vm ();
6271                 wait_for_suspend ();
6272                 break;
6273         case CMD_VM_RESUME:
6274                 if (suspend_count == 0)
6275                         return ERR_NOT_SUSPENDED;
6276                 resume_vm ();
6277                 break;
6278         case CMD_VM_DISPOSE:
6279                 /* Clear all event requests */
6280                 mono_loader_lock ();
6281                 while (event_requests->len > 0) {
6282                         EventRequest *req = g_ptr_array_index (event_requests, 0);
6283
6284                         clear_event_request (req->id, req->event_kind);
6285                 }
6286                 mono_loader_unlock ();
6287
6288                 while (suspend_count > 0)
6289                         resume_vm ();
6290                 disconnected = TRUE;
6291                 vm_start_event_sent = FALSE;
6292                 break;
6293         case CMD_VM_EXIT: {
6294                 MonoInternalThread *thread;
6295                 DebuggerTlsData *tls;
6296                 MonoClass *env_class;
6297                 MonoMethod *exit_method = NULL;
6298                 gpointer *args;
6299                 int exit_code;
6300
6301                 exit_code = decode_int (p, &p, end);
6302
6303                 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6304
6305                 /* Have to send a reply before exiting */
6306                 send_reply_packet (id, 0, buf);
6307
6308                 /* Clear all event requests */
6309                 mono_loader_lock ();
6310                 while (event_requests->len > 0) {
6311                         EventRequest *req = g_ptr_array_index (event_requests, 0);
6312
6313                         clear_event_request (req->id, req->event_kind);
6314                 }
6315                 mono_loader_unlock ();
6316
6317                 /*
6318                  * The JDWP documentation says that the shutdown is not orderly. It doesn't
6319                  * specify whenever a VM_DEATH event is sent. We currently do an orderly
6320                  * shutdown by hijacking a thread to execute Environment.Exit (). This is
6321                  * better than doing the shutdown ourselves, since it avoids various races.
6322                  */
6323
6324                 suspend_vm ();
6325                 wait_for_suspend ();
6326
6327 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6328                 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6329                 if (env_class)
6330                         exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6331 #endif
6332
6333                 mono_loader_lock ();
6334                 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6335                 mono_loader_unlock ();
6336
6337                 if (thread && exit_method) {
6338                         mono_loader_lock ();
6339                         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6340                         mono_loader_unlock ();
6341
6342                         args = g_new0 (gpointer, 1);
6343                         args [0] = g_malloc (sizeof (int));
6344                         *(int*)(args [0]) = exit_code;
6345
6346                         tls->pending_invoke = g_new0 (InvokeData, 1);
6347                         tls->pending_invoke->method = exit_method;
6348                         tls->pending_invoke->args = args;
6349                         tls->pending_invoke->nmethods = 1;
6350
6351                         while (suspend_count > 0)
6352                                 resume_vm ();
6353                 } else {
6354                         /* 
6355                          * No thread found, do it ourselves.
6356                          * FIXME: This can race with normal shutdown etc.
6357                          */
6358                         while (suspend_count > 0)
6359                                 resume_vm ();
6360
6361                         mono_runtime_set_shutting_down ();
6362
6363                         mono_threads_set_shutting_down ();
6364
6365                         /* Suspend all managed threads since the runtime is going away */
6366                         DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6367                         mono_thread_suspend_all_other_threads ();
6368                         DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6369                         mono_runtime_quit ();
6370                         transport_close2 ();
6371                         DEBUG(1, fprintf (log_file, "Exiting...\n"));
6372
6373                         exit (exit_code);
6374                 }
6375                 break;
6376         }               
6377         case CMD_VM_INVOKE_METHOD:
6378         case CMD_VM_INVOKE_METHODS: {
6379                 int objid = decode_objid (p, &p, end);
6380                 MonoThread *thread;
6381                 DebuggerTlsData *tls;
6382                 int i, count, err, flags, nmethods;
6383
6384                 err = get_object (objid, (MonoObject**)&thread);
6385                 if (err)
6386                         return err;
6387
6388                 flags = decode_int (p, &p, end);
6389
6390                 if (command == CMD_VM_INVOKE_METHODS)
6391                         nmethods = decode_int (p, &p, end);
6392                 else
6393                         nmethods = 1;
6394
6395                 // Wait for suspending if it already started
6396                 if (suspend_count)
6397                         wait_for_suspend ();
6398                 if (!is_suspended ())
6399                         return ERR_NOT_SUSPENDED;
6400
6401                 mono_loader_lock ();
6402                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6403                 mono_loader_unlock ();
6404                 g_assert (tls);
6405
6406                 if (!tls->really_suspended)
6407                         /* The thread is still running native code, can't do invokes */
6408                         return ERR_NOT_SUSPENDED;
6409
6410                 /* 
6411                  * Store the invoke data into tls, the thread will execute it after it is
6412                  * resumed.
6413                  */
6414                 if (tls->pending_invoke)
6415                         return ERR_NOT_SUSPENDED;
6416                 tls->pending_invoke = g_new0 (InvokeData, 1);
6417                 tls->pending_invoke->id = id;
6418                 tls->pending_invoke->flags = flags;
6419                 tls->pending_invoke->p = g_malloc (end - p);
6420                 memcpy (tls->pending_invoke->p, p, end - p);
6421                 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6422                 tls->pending_invoke->suspend_count = suspend_count;
6423                 tls->pending_invoke->nmethods = nmethods;
6424
6425                 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6426                         resume_thread (THREAD_TO_INTERNAL (thread));
6427                 }
6428                 else {
6429                         count = suspend_count;
6430                         for (i = 0; i < count; ++i)
6431                                 resume_vm ();
6432                 }
6433                 break;
6434         }
6435         case CMD_VM_ABORT_INVOKE: {
6436                 int objid = decode_objid (p, &p, end);
6437                 MonoThread *thread;
6438                 DebuggerTlsData *tls;
6439                 int invoke_id, err;
6440
6441                 err = get_object (objid, (MonoObject**)&thread);
6442                 if (err)
6443                         return err;
6444
6445                 invoke_id = decode_int (p, &p, end);
6446
6447                 mono_loader_lock ();
6448                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6449                 g_assert (tls);
6450
6451                 if (tls->abort_requested) {
6452                         mono_loader_unlock ();
6453                         break;
6454                 }
6455
6456                 /*
6457                  * Check whether we're still inside the mono_runtime_invoke() and that it's
6458                  * actually the correct invocation.
6459                  *
6460                  * Careful, we do not stop the thread that's doing the invocation, so we can't
6461                  * inspect its stack.  However, invoke_method() also acquires the loader lock
6462                  * when it's done, so we're safe here.
6463                  *
6464                  */
6465
6466                 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6467                         mono_loader_unlock ();
6468                         return ERR_NO_INVOCATION;
6469                 }
6470
6471                 tls->abort_requested = TRUE;
6472
6473                 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6474                 mono_loader_unlock ();
6475                 break;
6476         }
6477
6478         case CMD_VM_SET_KEEPALIVE: {
6479                 int timeout = decode_int (p, &p, end);
6480                 agent_config.keepalive = timeout;
6481                 // FIXME:
6482 #ifndef DISABLE_SOCKET_TRANSPORT
6483                 set_keepalive ();
6484 #else
6485                 NOT_IMPLEMENTED;
6486 #endif
6487                 break;
6488         }
6489         case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6490                 GHashTableIter iter, kiter;
6491                 MonoDomain *domain;
6492                 MonoClass *klass;
6493                 GPtrArray *files;
6494                 int i;
6495                 char *fname, *basename;
6496                 gboolean ignore_case;
6497                 GSList *class_list, *l;
6498                 GPtrArray *res_classes, *res_domains;
6499
6500                 fname = decode_string (p, &p, end);
6501                 ignore_case = decode_byte (p, &p, end);
6502
6503                 basename = g_path_get_basename (fname);
6504
6505                 res_classes = g_ptr_array_new ();
6506                 res_domains = g_ptr_array_new ();
6507
6508                 mono_loader_lock ();
6509                 g_hash_table_iter_init (&iter, domains);
6510                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6511                         AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6512
6513                         /* Update 'source_file_to_class' cache */
6514                         g_hash_table_iter_init (&kiter, info->loaded_classes);
6515                         while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6516                                 if (!g_hash_table_lookup (info->source_files, klass)) {
6517                                         files = get_source_files_for_type (klass);
6518                                         g_hash_table_insert (info->source_files, klass, files);
6519
6520                                         for (i = 0; i < files->len; ++i) {
6521                                                 char *s = g_ptr_array_index (files, i);
6522                                                 char *s2 = g_path_get_basename (s);
6523                                                 char *s3;
6524
6525                                                 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6526                                                 if (!class_list) {
6527                                                         class_list = g_slist_prepend (class_list, klass);
6528                                                         g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6529                                                 } else {
6530                                                         class_list = g_slist_prepend (class_list, klass);
6531                                                         g_hash_table_insert (info->source_file_to_class, s2, class_list);
6532                                                 }
6533
6534                                                 /* The _ignorecase hash contains the lowercase path */
6535                                                 s3 = strdup_tolower (s2);
6536                                                 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6537                                                 if (!class_list) {
6538                                                         class_list = g_slist_prepend (class_list, klass);
6539                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6540                                                 } else {
6541                                                         class_list = g_slist_prepend (class_list, klass);
6542                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6543                                                 }
6544
6545                                                 g_free (s2);
6546                                                 g_free (s3);
6547                                         }
6548                                 }
6549                         }
6550
6551                         if (ignore_case) {
6552                                 char *s;
6553
6554                                 s = strdup_tolower (basename);
6555                                 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6556                                 g_free (s);
6557                         } else {
6558                                 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6559                         }
6560
6561                         for (l = class_list; l; l = l->next) {
6562                                 klass = l->data;
6563
6564                                 g_ptr_array_add (res_classes, klass);
6565                                 g_ptr_array_add (res_domains, domain);
6566                         }
6567                 }
6568                 mono_loader_unlock ();
6569
6570                 g_free (fname);
6571                 g_free (basename);
6572
6573                 buffer_add_int (buf, res_classes->len);
6574                 for (i = 0; i < res_classes->len; ++i)
6575                         buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6576                 g_ptr_array_free (res_classes, TRUE);
6577                 g_ptr_array_free (res_domains, TRUE);
6578                 break;
6579         }
6580         case CMD_VM_GET_TYPES: {
6581                 GHashTableIter iter;
6582                 MonoDomain *domain;
6583                 int i;
6584                 char *name;
6585                 gboolean ignore_case;
6586                 GPtrArray *res_classes, *res_domains;
6587                 MonoTypeNameParse info;
6588
6589                 name = decode_string (p, &p, end);
6590                 ignore_case = decode_byte (p, &p, end);
6591
6592                 if (!mono_reflection_parse_type (name, &info)) {
6593                         g_free (name);
6594                         mono_reflection_free_type_info (&info);
6595                         return ERR_INVALID_ARGUMENT;
6596                 }
6597
6598                 res_classes = g_ptr_array_new ();
6599                 res_domains = g_ptr_array_new ();
6600
6601                 mono_loader_lock ();
6602                 g_hash_table_iter_init (&iter, domains);
6603                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6604                         MonoAssembly *ass;
6605                         gboolean type_resolve;
6606                         MonoType *t;
6607                         GSList *tmp;
6608
6609                         mono_domain_assemblies_lock (domain);
6610                         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6611                                 ass = tmp->data;
6612
6613                                 if (ass->image) {
6614                                         type_resolve = TRUE;
6615                                         t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6616                                         if (t) {
6617                                                 g_ptr_array_add (res_classes, mono_type_get_class (t));
6618                                                 g_ptr_array_add (res_domains, domain);
6619                                         }
6620                                 }
6621                         }
6622                         mono_domain_assemblies_unlock (domain);
6623                 }
6624                 mono_loader_unlock ();
6625
6626                 g_free (name);
6627                 mono_reflection_free_type_info (&info);
6628
6629                 buffer_add_int (buf, res_classes->len);
6630                 for (i = 0; i < res_classes->len; ++i)
6631                         buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6632                 g_ptr_array_free (res_classes, TRUE);
6633                 g_ptr_array_free (res_domains, TRUE);
6634                 break;
6635         }
6636
6637         default:
6638                 return ERR_NOT_IMPLEMENTED;
6639         }
6640
6641         return ERR_NONE;
6642 }
6643
6644 static ErrorCode
6645 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6646 {
6647         int err;
6648         MonoError error;
6649
6650         switch (command) {
6651         case CMD_EVENT_REQUEST_SET: {
6652                 EventRequest *req;
6653                 int i, event_kind, suspend_policy, nmodifiers, mod;
6654                 MonoMethod *method;
6655                 long location = 0;
6656                 MonoThread *step_thread;
6657                 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6658                 MonoDomain *domain;
6659                 Modifier *modifier;
6660
6661                 event_kind = decode_byte (p, &p, end);
6662                 suspend_policy = decode_byte (p, &p, end);
6663                 nmodifiers = decode_byte (p, &p, end);
6664
6665                 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6666                 req->id = InterlockedIncrement (&event_request_id);
6667                 req->event_kind = event_kind;
6668                 req->suspend_policy = suspend_policy;
6669                 req->nmodifiers = nmodifiers;
6670
6671                 method = NULL;
6672                 for (i = 0; i < nmodifiers; ++i) {
6673                         mod = decode_byte (p, &p, end);
6674
6675                         req->modifiers [i].kind = mod;
6676                         if (mod == MOD_KIND_COUNT) {
6677                                 req->modifiers [i].data.count = decode_int (p, &p, end);
6678                         } else if (mod == MOD_KIND_LOCATION_ONLY) {
6679                                 method = decode_methodid (p, &p, end, &domain, &err);
6680                                 if (err)
6681                                         return err;
6682                                 location = decode_long (p, &p, end);
6683                         } else if (mod == MOD_KIND_STEP) {
6684                                 step_thread_id = decode_id (p, &p, end);
6685                                 size = decode_int (p, &p, end);
6686                                 depth = decode_int (p, &p, end);
6687                                 if (CHECK_PROTOCOL_VERSION (2, 16))
6688                                         filter = decode_int (p, &p, end);
6689                                 req->modifiers [i].data.filter = filter;
6690                         } else if (mod == MOD_KIND_THREAD_ONLY) {
6691                                 int id = decode_id (p, &p, end);
6692
6693                                 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6694                                 if (err) {
6695                                         g_free (req);
6696                                         return err;
6697                                 }
6698                         } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6699                                 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6700
6701                                 if (err)
6702                                         return err;
6703                                 req->modifiers [i].caught = decode_byte (p, &p, end);
6704                                 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6705                                 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" : ""));
6706                                 if (exc_class) {
6707                                         req->modifiers [i].data.exc_class = exc_class;
6708
6709                                         if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6710                                                 g_free (req);
6711                                                 return ERR_INVALID_ARGUMENT;
6712                                         }
6713                                 }
6714                         } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6715                                 int n = decode_int (p, &p, end);
6716                                 int j;
6717
6718                                 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6719                                 for (j = 0; j < n; ++j) {
6720                                         req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6721                                         if (err) {
6722                                                 g_free (req->modifiers [i].data.assemblies);
6723                                                 return err;
6724                                         }
6725                                 }
6726                         } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6727                                 int n = decode_int (p, &p, end);
6728                                 int j;
6729
6730                                 modifier = &req->modifiers [i];
6731                                 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6732                                 for (j = 0; j < n; ++j) {
6733                                         char *s = decode_string (p, &p, end);
6734                                         char *s2;
6735
6736                                         if (s) {
6737                                                 s2 = strdup_tolower (s);
6738                                                 g_hash_table_insert (modifier->data.source_files, s2, s2);
6739                                                 g_free (s);
6740                                         }
6741                                 }
6742                         } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6743                                 int n = decode_int (p, &p, end);
6744                                 int j;
6745
6746                                 modifier = &req->modifiers [i];
6747                                 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6748                                 for (j = 0; j < n; ++j) {
6749                                         char *s = decode_string (p, &p, end);
6750
6751                                         if (s)
6752                                                 g_hash_table_insert (modifier->data.type_names, s, s);
6753                                 }
6754                         } else {
6755                                 g_free (req);
6756                                 return ERR_NOT_IMPLEMENTED;
6757                         }
6758                 }
6759
6760                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6761                         g_assert (method);
6762
6763                         req->info = set_breakpoint (method, location, req, &error);
6764                         if (!mono_error_ok (&error)) {
6765                                 g_free (req);
6766                                 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6767                                 mono_error_cleanup (&error);
6768                                 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6769                         }
6770                 } else if (req->event_kind == EVENT_KIND_STEP) {
6771                         g_assert (step_thread_id);
6772
6773                         err = get_object (step_thread_id, (MonoObject**)&step_thread);
6774                         if (err) {
6775                                 g_free (req);
6776                                 return err;
6777                         }
6778
6779                         err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6780                         if (err) {
6781                                 g_free (req);
6782                                 return err;
6783                         }
6784                 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6785                         req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6786                 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6787                         req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6788                 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6789                 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6790                 } else {
6791                         if (req->nmodifiers) {
6792                                 g_free (req);
6793                                 return ERR_NOT_IMPLEMENTED;
6794                         }
6795                 }
6796
6797                 mono_loader_lock ();
6798                 g_ptr_array_add (event_requests, req);
6799                 
6800                 if (agent_config.defer) {
6801                         /* Transmit cached data to the client on receipt of the event request */
6802                         switch (req->event_kind) {
6803                         case EVENT_KIND_APPDOMAIN_CREATE:
6804                                 /* Emit load events for currently loaded domains */
6805                                 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6806                                 break;
6807                         case EVENT_KIND_ASSEMBLY_LOAD:
6808                                 /* Emit load events for currently loaded assemblies */
6809                                 mono_assembly_foreach (emit_assembly_load, NULL);
6810                                 break;
6811                         case EVENT_KIND_THREAD_START:
6812                                 /* Emit start events for currently started threads */
6813                                 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6814                                 break;
6815                         case EVENT_KIND_TYPE_LOAD:
6816                                 /* Emit type load events for currently loaded types */
6817                                 mono_domain_foreach (send_types_for_domain, NULL);
6818                                 break;
6819                         default:
6820                                 break;
6821                         }
6822                 }
6823                 mono_loader_unlock ();
6824
6825                 buffer_add_int (buf, req->id);
6826                 break;
6827         }
6828         case CMD_EVENT_REQUEST_CLEAR: {
6829                 int etype = decode_byte (p, &p, end);
6830                 int req_id = decode_int (p, &p, end);
6831
6832                 // FIXME: Make a faster mapping from req_id to request
6833                 mono_loader_lock ();
6834                 clear_event_request (req_id, etype);
6835                 mono_loader_unlock ();
6836                 break;
6837         }
6838         case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6839                 int i;
6840
6841                 mono_loader_lock ();
6842                 i = 0;
6843                 while (i < event_requests->len) {
6844                         EventRequest *req = g_ptr_array_index (event_requests, i);
6845
6846                         if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6847                                 clear_breakpoint (req->info);
6848
6849                                 g_ptr_array_remove_index_fast (event_requests, i);
6850                                 g_free (req);
6851                         } else {
6852                                 i ++;
6853                         }
6854                 }
6855                 mono_loader_unlock ();
6856                 break;
6857         }
6858         default:
6859                 return ERR_NOT_IMPLEMENTED;
6860         }
6861
6862         return ERR_NONE;
6863 }
6864
6865 static ErrorCode
6866 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6867 {
6868         int err;
6869         MonoDomain *domain;
6870
6871         switch (command) {
6872         case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6873                 buffer_add_domainid (buf, mono_get_root_domain ());
6874                 break;
6875         }
6876         case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6877                 domain = decode_domainid (p, &p, end, NULL, &err);
6878                 if (err)
6879                         return err;
6880                 buffer_add_string (buf, domain->friendly_name);
6881                 break;
6882         }
6883         case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6884                 GSList *tmp;
6885                 MonoAssembly *ass;
6886                 int count;
6887
6888                 domain = decode_domainid (p, &p, end, NULL, &err);
6889                 if (err)
6890                         return err;
6891                 mono_loader_lock ();
6892                 count = 0;
6893                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6894                         count ++;
6895                 }
6896                 buffer_add_int (buf, count);
6897                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6898                         ass = tmp->data;
6899                         buffer_add_assemblyid (buf, domain, ass);
6900                 }
6901                 mono_loader_unlock ();
6902                 break;
6903         }
6904         case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6905                 domain = decode_domainid (p, &p, end, NULL, &err);
6906                 if (err)
6907                         return err;
6908
6909                 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6910                 break;
6911         }
6912         case CMD_APPDOMAIN_GET_CORLIB: {
6913                 domain = decode_domainid (p, &p, end, NULL, &err);
6914                 if (err)
6915                         return err;
6916
6917                 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6918                 break;
6919         }
6920         case CMD_APPDOMAIN_CREATE_STRING: {
6921                 char *s;
6922                 MonoString *o;
6923
6924                 domain = decode_domainid (p, &p, end, NULL, &err);
6925                 if (err)
6926                         return err;
6927                 s = decode_string (p, &p, end);
6928
6929                 o = mono_string_new (domain, s);
6930                 buffer_add_objid (buf, (MonoObject*)o);
6931                 break;
6932         }
6933         case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6934                 MonoClass *klass;
6935                 MonoDomain *domain2;
6936                 MonoObject *o;
6937
6938                 domain = decode_domainid (p, &p, end, NULL, &err);
6939                 if (err)
6940                         return err;
6941                 klass = decode_typeid (p, &p, end, &domain2, &err);
6942                 if (err)
6943                         return err;
6944
6945                 // FIXME:
6946                 g_assert (domain == domain2);
6947
6948                 o = mono_object_new (domain, klass);
6949
6950                 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6951                 if (err)
6952                         return err;
6953
6954                 buffer_add_objid (buf, o);
6955                 break;
6956         }
6957         default:
6958                 return ERR_NOT_IMPLEMENTED;
6959         }
6960
6961         return ERR_NONE;
6962 }
6963
6964 static ErrorCode
6965 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6966 {
6967         int err;
6968         MonoAssembly *ass;
6969         MonoDomain *domain;
6970
6971         ass = decode_assemblyid (p, &p, end, &domain, &err);
6972         if (err)
6973                 return err;
6974
6975         switch (command) {
6976         case CMD_ASSEMBLY_GET_LOCATION: {
6977                 buffer_add_string (buf, mono_image_get_filename (ass->image));
6978                 break;                  
6979         }
6980         case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6981                 guint32 token;
6982                 MonoMethod *m;
6983
6984                 if (ass->image->dynamic) {
6985                         buffer_add_id (buf, 0);
6986                 } else {
6987                         token = mono_image_get_entry_point (ass->image);
6988                         if (token == 0) {
6989                                 buffer_add_id (buf, 0);
6990                         } else {
6991                                 m = mono_get_method (ass->image, token, NULL);
6992                                 buffer_add_methodid (buf, domain, m);
6993                         }
6994                 }
6995                 break;                  
6996         }
6997         case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6998                 buffer_add_moduleid (buf, domain, ass->image);
6999                 break;
7000         }
7001         case CMD_ASSEMBLY_GET_OBJECT: {
7002                 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7003                 buffer_add_objid (buf, o);
7004                 break;
7005         }
7006         case CMD_ASSEMBLY_GET_TYPE: {
7007                 char *s = decode_string (p, &p, end);
7008                 gboolean ignorecase = decode_byte (p, &p, end);
7009                 MonoTypeNameParse info;
7010                 MonoType *t;
7011                 gboolean type_resolve, res;
7012                 MonoDomain *d = mono_domain_get ();
7013
7014                 /* This is needed to be able to find referenced assemblies */
7015                 res = mono_domain_set (domain, FALSE);
7016                 g_assert (res);
7017
7018                 if (!mono_reflection_parse_type (s, &info)) {
7019                         t = NULL;
7020                 } else {
7021                         if (info.assembly.name)
7022                                 NOT_IMPLEMENTED;
7023                         t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7024                 }
7025                 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7026                 mono_reflection_free_type_info (&info);
7027                 g_free (s);
7028
7029                 mono_domain_set (d, TRUE);
7030
7031                 break;
7032         }
7033         case CMD_ASSEMBLY_GET_NAME: {
7034                 gchar *name;
7035                 MonoAssembly *mass = ass;
7036
7037                 name = g_strdup_printf (
7038                   "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7039                   mass->aname.name,
7040                   mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7041                   mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7042                   mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7043                   (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7044
7045                 buffer_add_string (buf, name);
7046                 g_free (name);
7047                 break;
7048         }
7049         default:
7050                 return ERR_NOT_IMPLEMENTED;
7051         }
7052
7053         return ERR_NONE;
7054 }
7055
7056 static ErrorCode
7057 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7058 {
7059         int err;
7060         MonoDomain *domain;
7061
7062         switch (command) {
7063         case CMD_MODULE_GET_INFO: {
7064                 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7065                 char *basename;
7066
7067                 basename = g_path_get_basename (image->name);
7068                 buffer_add_string (buf, basename); // name
7069                 buffer_add_string (buf, image->module_name); // scopename
7070                 buffer_add_string (buf, image->name); // fqname
7071                 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7072                 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7073                 g_free (basename);
7074                 break;                  
7075         }
7076         default:
7077                 return ERR_NOT_IMPLEMENTED;
7078         }
7079
7080         return ERR_NONE;
7081 }
7082
7083 static void
7084 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7085 {
7086         if (val && val->vtable->klass == mono_defaults.monotype_class) {
7087                 /* Special case these so the client doesn't have to handle Type objects */
7088                 
7089                 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7090                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7091         } else if (MONO_TYPE_IS_REFERENCE (t))
7092                 buffer_add_value (buf, t, &val, domain);
7093         else
7094                 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7095 }
7096
7097 static void
7098 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7099 {
7100         int i, j;
7101         int nattrs = 0;
7102
7103         if (!cinfo) {
7104                 buffer_add_int (buf, 0);
7105                 return;
7106         }
7107
7108         for (i = 0; i < cinfo->num_attrs; ++i) {
7109                 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7110                         nattrs ++;
7111         }
7112         buffer_add_int (buf, nattrs);
7113
7114         for (i = 0; i < cinfo->num_attrs; ++i) {
7115                 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7116                 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7117                         MonoArray *typed_args, *named_args;
7118                         MonoType *t;
7119                         CattrNamedArg *arginfo;
7120
7121                         mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7122
7123                         buffer_add_methodid (buf, domain, attr->ctor);
7124
7125                         /* Ctor args */
7126                         if (typed_args) {
7127                                 buffer_add_int (buf, mono_array_length (typed_args));
7128                                 for (j = 0; j < mono_array_length (typed_args); ++j) {
7129                                         MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7130
7131                                         t = mono_method_signature (attr->ctor)->params [j];
7132
7133                                         buffer_add_cattr_arg (buf, t, domain, val);
7134                                 }
7135                         } else {
7136                                 buffer_add_int (buf, 0);
7137                         }
7138
7139                         /* Named args */
7140                         if (named_args) {
7141                                 buffer_add_int (buf, mono_array_length (named_args));
7142
7143                                 for (j = 0; j < mono_array_length (named_args); ++j) {
7144                                         MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7145
7146                                         if (arginfo [j].prop) {
7147                                                 buffer_add_byte (buf, 0x54);
7148                                                 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7149                                         } else if (arginfo [j].field) {
7150                                                 buffer_add_byte (buf, 0x53);
7151                                                 buffer_add_fieldid (buf, domain, arginfo [j].field);
7152                                         } else {
7153                                                 g_assert_not_reached ();
7154                                         }
7155
7156                                         buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7157                                 }
7158                         } else {
7159                                 buffer_add_int (buf, 0);
7160                         }
7161                 }
7162         }
7163 }
7164
7165 /* FIXME: Code duplication with icall.c */
7166 static void
7167 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7168 {
7169         int i;
7170         MonoClass *ic;
7171
7172         mono_class_setup_interfaces (klass, error);
7173         if (!mono_error_ok (error))
7174                 return;
7175
7176         for (i = 0; i < klass->interface_count; i++) {
7177                 ic = klass->interfaces [i];
7178                 g_hash_table_insert (ifaces, ic, ic);
7179
7180                 collect_interfaces (ic, ifaces, error);
7181                 if (!mono_error_ok (error))
7182                         return;
7183         }
7184 }
7185
7186 static ErrorCode
7187 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7188 {
7189         MonoClass *nested;
7190         MonoType *type;
7191         gpointer iter;
7192         guint8 b;
7193         int err, nnested;
7194         char *name;
7195
7196         switch (command) {
7197         case CMD_TYPE_GET_INFO: {
7198                 buffer_add_string (buf, klass->name_space);
7199                 buffer_add_string (buf, klass->name);
7200                 // FIXME: byref
7201                 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7202                 buffer_add_string (buf, name);
7203                 g_free (name);
7204                 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7205                 buffer_add_moduleid (buf, domain, klass->image);
7206                 buffer_add_typeid (buf, domain, klass->parent);
7207                 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7208                         buffer_add_typeid (buf, domain, klass->element_class);
7209                 else
7210                         buffer_add_id (buf, 0);
7211                 buffer_add_int (buf, klass->type_token);
7212                 buffer_add_byte (buf, klass->rank);
7213                 buffer_add_int (buf, klass->flags);
7214                 b = 0;
7215                 type = &klass->byval_arg;
7216                 // FIXME: Can't decide whenever a class represents a byref type
7217                 if (FALSE)
7218                         b |= (1 << 0);
7219                 if (type->type == MONO_TYPE_PTR)
7220                         b |= (1 << 1);
7221                 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7222                         b |= (1 << 2);
7223                 if (type->type == MONO_TYPE_VALUETYPE)
7224                         b |= (1 << 3);
7225                 if (klass->enumtype)
7226                         b |= (1 << 4);
7227                 if (klass->generic_container)
7228                         b |= (1 << 5);
7229                 if (klass->generic_container || klass->generic_class)
7230                         b |= (1 << 6);
7231                 buffer_add_byte (buf, b);
7232                 nnested = 0;
7233                 iter = NULL;
7234                 while ((nested = mono_class_get_nested_types (klass, &iter)))
7235                         nnested ++;
7236                 buffer_add_int (buf, nnested);
7237                 iter = NULL;
7238                 while ((nested = mono_class_get_nested_types (klass, &iter)))
7239                         buffer_add_typeid (buf, domain, nested);
7240                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7241                         if (klass->generic_container)
7242                                 buffer_add_typeid (buf, domain, klass);
7243                         else if (klass->generic_class)
7244                                 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7245                         else
7246                                 buffer_add_id (buf, 0);
7247                 }
7248                 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7249                         int count, i;
7250
7251                         if (klass->generic_class) {
7252                                 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7253
7254                                 count = inst->type_argc;
7255                                 buffer_add_int (buf, count);
7256                                 for (i = 0; i < count; i++)
7257                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7258                         } else if (klass->generic_container) {
7259                                 MonoGenericContainer *container = klass->generic_container;
7260                                 MonoClass *pklass;
7261
7262                                 count = container->type_argc;
7263                                 buffer_add_int (buf, count);
7264                                 for (i = 0; i < count; i++) {
7265                                         pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7266                                         buffer_add_typeid (buf, domain, pklass);
7267                                 }
7268                         } else {
7269                                 buffer_add_int (buf, 0);
7270                         }
7271                 }
7272                 break;
7273         }
7274         case CMD_TYPE_GET_METHODS: {
7275                 int nmethods;
7276                 int i = 0;
7277                 gpointer iter = NULL;
7278                 MonoMethod *m;
7279
7280                 mono_class_setup_methods (klass);
7281
7282                 nmethods = mono_class_num_methods (klass);
7283
7284                 buffer_add_int (buf, nmethods);
7285
7286                 while ((m = mono_class_get_methods (klass, &iter))) {
7287                         buffer_add_methodid (buf, domain, m);
7288                         i ++;
7289                 }
7290                 g_assert (i == nmethods);
7291                 break;
7292         }
7293         case CMD_TYPE_GET_FIELDS: {
7294                 int nfields;
7295                 int i = 0;
7296                 gpointer iter = NULL;
7297                 MonoClassField *f;
7298
7299                 nfields = mono_class_num_fields (klass);
7300
7301                 buffer_add_int (buf, nfields);
7302
7303                 while ((f = mono_class_get_fields (klass, &iter))) {
7304                         buffer_add_fieldid (buf, domain, f);
7305                         buffer_add_string (buf, f->name);
7306                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7307                         buffer_add_int (buf, f->type->attrs);
7308                         i ++;
7309                 }
7310                 g_assert (i == nfields);
7311                 break;
7312         }
7313         case CMD_TYPE_GET_PROPERTIES: {
7314                 int nprops;
7315                 int i = 0;
7316                 gpointer iter = NULL;
7317                 MonoProperty *p;
7318
7319                 nprops = mono_class_num_properties (klass);
7320
7321                 buffer_add_int (buf, nprops);
7322
7323                 while ((p = mono_class_get_properties (klass, &iter))) {
7324                         buffer_add_propertyid (buf, domain, p);
7325                         buffer_add_string (buf, p->name);
7326                         buffer_add_methodid (buf, domain, p->get);
7327                         buffer_add_methodid (buf, domain, p->set);
7328                         buffer_add_int (buf, p->attrs);
7329                         i ++;
7330                 }
7331                 g_assert (i == nprops);
7332                 break;
7333         }
7334         case CMD_TYPE_GET_CATTRS: {
7335                 MonoClass *attr_klass;
7336                 MonoCustomAttrInfo *cinfo;
7337
7338                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7339                 /* attr_klass can be NULL */
7340                 if (err)
7341                         return err;
7342
7343                 cinfo = mono_custom_attrs_from_class (klass);
7344
7345                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7346                 break;
7347         }
7348         case CMD_TYPE_GET_FIELD_CATTRS: {
7349                 MonoClass *attr_klass;
7350                 MonoCustomAttrInfo *cinfo;
7351                 MonoClassField *field;
7352
7353                 field = decode_fieldid (p, &p, end, NULL, &err);
7354                 if (err)
7355                         return err;
7356                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7357                 if (err)
7358                         return err;
7359
7360                 cinfo = mono_custom_attrs_from_field (klass, field);
7361
7362                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7363                 break;
7364         }
7365         case CMD_TYPE_GET_PROPERTY_CATTRS: {
7366                 MonoClass *attr_klass;
7367                 MonoCustomAttrInfo *cinfo;
7368                 MonoProperty *prop;
7369
7370                 prop = decode_propertyid (p, &p, end, NULL, &err);
7371                 if (err)
7372                         return err;
7373                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7374                 if (err)
7375                         return err;
7376
7377                 cinfo = mono_custom_attrs_from_property (klass, prop);
7378
7379                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7380                 break;
7381         }
7382         case CMD_TYPE_GET_VALUES:
7383         case CMD_TYPE_GET_VALUES_2: {
7384                 guint8 *val;
7385                 MonoClassField *f;
7386                 MonoVTable *vtable;
7387                 MonoClass *k;
7388                 int len, i;
7389                 gboolean found;
7390                 MonoThread *thread_obj;
7391                 MonoInternalThread *thread = NULL;
7392                 guint32 special_static_type;
7393
7394                 if (command == CMD_TYPE_GET_VALUES_2) {
7395                         int objid = decode_objid (p, &p, end);
7396                         int err;
7397
7398                         err = get_object (objid, (MonoObject**)&thread_obj);
7399                         if (err)
7400                                 return err;
7401
7402                         thread = THREAD_TO_INTERNAL (thread_obj);
7403                 }
7404
7405                 len = decode_int (p, &p, end);
7406                 for (i = 0; i < len; ++i) {
7407                         f = decode_fieldid (p, &p, end, NULL, &err);
7408                         if (err)
7409                                 return err;
7410
7411                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7412                                 return ERR_INVALID_FIELDID;
7413                         special_static_type = mono_class_field_get_special_static_type (f);
7414                         if (special_static_type != SPECIAL_STATIC_NONE) {
7415                                 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7416                                         return ERR_INVALID_FIELDID;
7417                         }
7418
7419                         /* Check that the field belongs to the object */
7420                         found = FALSE;
7421                         for (k = klass; k; k = k->parent) {
7422                                 if (k == f->parent) {
7423                                         found = TRUE;
7424                                         break;
7425                                 }
7426                         }
7427                         if (!found)
7428                                 return ERR_INVALID_FIELDID;
7429
7430                         vtable = mono_class_vtable (domain, f->parent);
7431                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7432                         mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7433                         buffer_add_value (buf, f->type, val, domain);
7434                         g_free (val);
7435                 }
7436                 break;
7437         }
7438         case CMD_TYPE_SET_VALUES: {
7439                 guint8 *val;
7440                 MonoClassField *f;
7441                 MonoVTable *vtable;
7442                 MonoClass *k;
7443                 int len, i;
7444                 gboolean found;
7445
7446                 len = decode_int (p, &p, end);
7447                 for (i = 0; i < len; ++i) {
7448                         f = decode_fieldid (p, &p, end, NULL, &err);
7449                         if (err)
7450                                 return err;
7451
7452                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7453                                 return ERR_INVALID_FIELDID;
7454                         if (mono_class_field_is_special_static (f))
7455                                 return ERR_INVALID_FIELDID;
7456
7457                         /* Check that the field belongs to the object */
7458                         found = FALSE;
7459                         for (k = klass; k; k = k->parent) {
7460                                 if (k == f->parent) {
7461                                         found = TRUE;
7462                                         break;
7463                                 }
7464                         }
7465                         if (!found)
7466                                 return ERR_INVALID_FIELDID;
7467
7468                         // FIXME: Check for literal/const
7469
7470                         vtable = mono_class_vtable (domain, f->parent);
7471                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7472                         err = decode_value (f->type, domain, val, p, &p, end);
7473                         if (err) {
7474                                 g_free (val);
7475                                 return err;
7476                         }
7477                         if (MONO_TYPE_IS_REFERENCE (f->type))
7478                                 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7479                         else
7480                                 mono_field_static_set_value (vtable, f, val);
7481                         g_free (val);
7482                 }
7483                 break;
7484         }
7485         case CMD_TYPE_GET_OBJECT: {
7486                 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7487                 buffer_add_objid (buf, o);
7488                 break;
7489         }
7490         case CMD_TYPE_GET_SOURCE_FILES:
7491         case CMD_TYPE_GET_SOURCE_FILES_2: {
7492                 char *source_file, *base;
7493                 GPtrArray *files;
7494                 int i;
7495
7496                 files = get_source_files_for_type (klass);
7497
7498                 buffer_add_int (buf, files->len);
7499                 for (i = 0; i < files->len; ++i) {
7500                         source_file = g_ptr_array_index (files, i);
7501                         if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7502                                 buffer_add_string (buf, source_file);
7503                         } else {
7504                                 base = g_path_get_basename (source_file);
7505                                 buffer_add_string (buf, base);
7506                                 g_free (base);
7507                         }
7508                         g_free (source_file);
7509                 }
7510                 g_ptr_array_free (files, TRUE);
7511                 break;
7512         }
7513         case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7514                 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7515
7516                 if (err)
7517                         return err;
7518                 if (mono_class_is_assignable_from (klass, oklass))
7519                         buffer_add_byte (buf, 1);
7520                 else
7521                         buffer_add_byte (buf, 0);
7522                 break;
7523         }
7524         case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7525                 char *name = decode_string (p, &p, end);
7526                 int i, flags = decode_int (p, &p, end);
7527                 MonoException *ex = NULL;
7528                 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7529
7530                 if (!array)
7531                         return ERR_LOADER_ERROR;
7532                 buffer_add_int (buf, array->len);
7533                 for (i = 0; i < array->len; ++i) {
7534                         MonoMethod *method = g_ptr_array_index (array, i);
7535                         buffer_add_methodid (buf, domain, method);
7536                 }
7537
7538                 g_ptr_array_free (array, TRUE);
7539                 g_free (name);
7540                 break;
7541         }
7542         case CMD_TYPE_GET_INTERFACES: {
7543                 MonoClass *parent;
7544                 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7545                 MonoError error;
7546                 MonoClass *tclass, *iface;
7547                 GHashTableIter iter;
7548
7549                 tclass = klass;
7550
7551                 for (parent = tclass; parent; parent = parent->parent) {
7552                         mono_class_setup_interfaces (parent, &error);
7553                         if (!mono_error_ok (&error))
7554                                 return ERR_LOADER_ERROR;
7555                         collect_interfaces (parent, iface_hash, &error);
7556                         if (!mono_error_ok (&error))
7557                                 return ERR_LOADER_ERROR;
7558                 }
7559
7560                 buffer_add_int (buf, g_hash_table_size (iface_hash));
7561
7562                 g_hash_table_iter_init (&iter, iface_hash);
7563                 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7564                         buffer_add_typeid (buf, domain, iface);
7565                 g_hash_table_destroy (iface_hash);
7566                 break;
7567         }
7568         case CMD_TYPE_GET_INTERFACE_MAP: {
7569                 int tindex, ioffset;
7570                 gboolean variance_used;
7571                 MonoClass *iclass;
7572                 int len, nmethods, i;
7573                 gpointer iter;
7574                 MonoMethod *method;
7575
7576                 len = decode_int (p, &p, end);
7577                 mono_class_setup_vtable (klass);
7578
7579                 for (tindex = 0; tindex < len; ++tindex) {
7580                         iclass = decode_typeid (p, &p, end, NULL, &err);
7581                         if (err)
7582                                 return err;
7583
7584                         ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7585                         if (ioffset == -1)
7586                                 return ERR_INVALID_ARGUMENT;
7587
7588                         nmethods = mono_class_num_methods (iclass);
7589                         buffer_add_int (buf, nmethods);
7590
7591                         iter = NULL;
7592                         while ((method = mono_class_get_methods (iclass, &iter))) {
7593                                 buffer_add_methodid (buf, domain, method);
7594                         }
7595                         for (i = 0; i < nmethods; ++i)
7596                                 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7597                 }
7598                 break;
7599         }
7600         default:
7601                 return ERR_NOT_IMPLEMENTED;
7602         }
7603
7604         return ERR_NONE;
7605 }
7606
7607 static ErrorCode
7608 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7609 {
7610         MonoClass *klass;
7611         MonoDomain *old_domain;
7612         MonoDomain *domain;
7613         int err;
7614
7615         klass = decode_typeid (p, &p, end, &domain, &err);
7616         if (err)
7617                 return err;
7618
7619         old_domain = mono_domain_get ();
7620
7621         mono_domain_set (domain, TRUE);
7622
7623         err = type_commands_internal (command, klass, domain, p, end, buf);
7624
7625         mono_domain_set (old_domain, TRUE);
7626
7627         return err;
7628 }
7629
7630 static ErrorCode
7631 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7632 {
7633         MonoMethodHeader *header;
7634         int err;
7635
7636         switch (command) {
7637         case CMD_METHOD_GET_NAME: {
7638                 buffer_add_string (buf, method->name);
7639                 break;                  
7640         }
7641         case CMD_METHOD_GET_DECLARING_TYPE: {
7642                 buffer_add_typeid (buf, domain, method->klass);
7643                 break;
7644         }
7645         case CMD_METHOD_GET_DEBUG_INFO: {
7646                 MonoDebugMethodInfo *minfo;
7647                 char *source_file;
7648                 int i, j, n_il_offsets;
7649                 int *il_offsets;
7650                 int *line_numbers;
7651                 int *column_numbers;
7652                 int *source_files;
7653                 GPtrArray *source_file_list;
7654
7655                 header = mono_method_get_header (method);
7656                 if (!header) {
7657                         buffer_add_int (buf, 0);
7658                         buffer_add_string (buf, "");
7659                         buffer_add_int (buf, 0);
7660                         break;
7661                 }
7662
7663                 minfo = mono_debug_lookup_method (method);
7664                 if (!minfo) {
7665                         buffer_add_int (buf, header->code_size);
7666                         buffer_add_string (buf, "");
7667                         buffer_add_int (buf, 0);
7668                         mono_metadata_free_mh (header);
7669                         break;
7670                 }
7671
7672                 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7673                 buffer_add_int (buf, header->code_size);
7674                 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7675                         buffer_add_int (buf, source_file_list->len);
7676                         for (i = 0; i < source_file_list->len; ++i) {
7677                                 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7678                                 buffer_add_string (buf, sinfo->source_file);
7679                                 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7680                                         for (j = 0; j < 16; ++j)
7681                                                 buffer_add_byte (buf, sinfo->hash [j]);
7682                                 }
7683                         }
7684                 } else {
7685                         buffer_add_string (buf, source_file);
7686                 }
7687                 buffer_add_int (buf, n_il_offsets);
7688                 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method,  TRUE)));
7689                 for (i = 0; i < n_il_offsets; ++i) {
7690                         const char *srcfile = "";
7691
7692                         if (source_files [i] != -1) {
7693                                 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7694                                 srcfile = sinfo->source_file;
7695                         }
7696                         DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7697                         buffer_add_int (buf, il_offsets [i]);
7698                         buffer_add_int (buf, line_numbers [i]);
7699                         if (CHECK_PROTOCOL_VERSION (2, 13))
7700                                 buffer_add_int (buf, source_files [i]);
7701                         if (CHECK_PROTOCOL_VERSION (2, 19))
7702                                 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7703                 }
7704                 g_free (source_file);
7705                 g_free (il_offsets);
7706                 g_free (line_numbers);
7707                 g_free (source_files);
7708                 g_ptr_array_free (source_file_list, TRUE);
7709                 mono_metadata_free_mh (header);
7710                 break;
7711         }
7712         case CMD_METHOD_GET_PARAM_INFO: {
7713                 MonoMethodSignature *sig = mono_method_signature (method);
7714                 guint32 i;
7715                 char **names;
7716
7717                 /* FIXME: mono_class_from_mono_type () and byrefs */
7718
7719                 /* FIXME: Use a smaller encoding */
7720                 buffer_add_int (buf, sig->call_convention);
7721                 buffer_add_int (buf, sig->param_count);
7722                 buffer_add_int (buf, sig->generic_param_count);
7723                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7724                 for (i = 0; i < sig->param_count; ++i) {
7725                         /* FIXME: vararg */
7726                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7727                 }
7728
7729                 /* Emit parameter names */
7730                 names = g_new (char *, sig->param_count);
7731                 mono_method_get_param_names (method, (const char **) names);
7732                 for (i = 0; i < sig->param_count; ++i)
7733                         buffer_add_string (buf, names [i]);
7734                 g_free (names);
7735
7736                 break;
7737         }
7738         case CMD_METHOD_GET_LOCALS_INFO: {
7739                 int i, j, num_locals;
7740                 MonoDebugLocalsInfo *locals;
7741
7742                 header = mono_method_get_header (method);
7743                 if (!header)
7744                         return ERR_INVALID_ARGUMENT;
7745
7746                 buffer_add_int (buf, header->num_locals);
7747
7748                 /* Types */
7749                 for (i = 0; i < header->num_locals; ++i)
7750                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7751
7752                 /* Names */
7753                 locals = mono_debug_lookup_locals (method);
7754                 if (locals)
7755                         num_locals = locals->num_locals;
7756                 else
7757                         num_locals = 0;
7758                 for (i = 0; i < header->num_locals; ++i) {
7759                         for (j = 0; j < num_locals; ++j)
7760                                 if (locals->locals [j].index == i)
7761                                         break;
7762                         if (j < num_locals)
7763                                 buffer_add_string (buf, locals->locals [j].name);
7764                         else
7765                                 buffer_add_string (buf, "");
7766                 }
7767
7768                 /* Scopes */
7769                 for (i = 0; i < header->num_locals; ++i) {
7770                         for (j = 0; j < num_locals; ++j)
7771                                 if (locals->locals [j].index == i)
7772                                         break;
7773                         if (j < num_locals && locals->locals [j].block) {
7774                                 buffer_add_int (buf, locals->locals [j].block->start_offset);
7775                                 buffer_add_int (buf, locals->locals [j].block->end_offset);
7776                         } else {
7777                                 buffer_add_int (buf, 0);
7778                                 buffer_add_int (buf, header->code_size);
7779                         }
7780                 }
7781                 mono_metadata_free_mh (header);
7782
7783                 if (locals)
7784                         mono_debug_symfile_free_locals (locals);
7785
7786                 break;
7787         }
7788         case CMD_METHOD_GET_INFO:
7789                 buffer_add_int (buf, method->flags);
7790                 buffer_add_int (buf, method->iflags);
7791                 buffer_add_int (buf, method->token);
7792                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7793                         guint8 attrs = 0;
7794                         if (method->is_generic)
7795                                 attrs |= (1 << 0);
7796                         if (mono_method_signature (method)->generic_param_count)
7797                                 attrs |= (1 << 1);
7798                         buffer_add_byte (buf, attrs);
7799                         if (method->is_generic || method->is_inflated) {
7800                                 MonoMethod *result;
7801
7802                                 if (method->is_generic) {
7803                                         result = method;
7804                                 } else {
7805                                         MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7806                                         
7807                                         result = imethod->declaring;
7808                                         if (imethod->context.class_inst) {
7809                                                 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7810                                                 /*Generic methods gets the context of the GTD.*/
7811                                                 if (mono_class_get_context (klass))
7812                                                         result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7813                                         }
7814                                 }
7815
7816                                 buffer_add_methodid (buf, domain, result);
7817                         } else {
7818                                 buffer_add_id (buf, 0);
7819                         }
7820                         if (CHECK_PROTOCOL_VERSION (2, 15)) {
7821                                 if (mono_method_signature (method)->generic_param_count) {
7822                                         int count, i;
7823
7824                                         if (method->is_inflated) {
7825                                                 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7826                                                 if (inst) {
7827                                                         count = inst->type_argc;
7828                                                         buffer_add_int (buf, count);
7829
7830                                                         for (i = 0; i < count; i++)
7831                                                                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7832                                                 } else {
7833                                                         buffer_add_int (buf, 0);
7834                                                 }
7835                                         } else if (method->is_generic) {
7836                                                 MonoGenericContainer *container = mono_method_get_generic_container (method);
7837
7838                                                 count = mono_method_signature (method)->generic_param_count;
7839                                                 buffer_add_int (buf, count);
7840                                                 for (i = 0; i < count; i++) {
7841                                                         MonoGenericParam *param = mono_generic_container_get_param (container, i);
7842                                                         MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7843                                                         buffer_add_typeid (buf, domain, pklass);
7844                                                 }
7845                                         } else {
7846                                                 buffer_add_int (buf, 0);
7847                                         }
7848                                 } else {
7849                                         buffer_add_int (buf, 0);
7850                                 }
7851                         }
7852                 }
7853                 break;
7854         case CMD_METHOD_GET_BODY: {
7855                 int i;
7856
7857                 header = mono_method_get_header (method);
7858                 if (!header) {
7859                         buffer_add_int (buf, 0);
7860
7861                         if (CHECK_PROTOCOL_VERSION (2, 18))
7862                                 buffer_add_int (buf, 0);
7863                 } else {
7864                         buffer_add_int (buf, header->code_size);
7865                         for (i = 0; i < header->code_size; ++i)
7866                                 buffer_add_byte (buf, header->code [i]);
7867
7868                         if (CHECK_PROTOCOL_VERSION (2, 18)) {
7869                                 buffer_add_int (buf, header->num_clauses);
7870                                 for (i = 0; i < header->num_clauses; ++i) {
7871                                         MonoExceptionClause *clause = &header->clauses [i];
7872
7873                                         buffer_add_int (buf, clause->flags);
7874                                         buffer_add_int (buf, clause->try_offset);
7875                                         buffer_add_int (buf, clause->try_len);
7876                                         buffer_add_int (buf, clause->handler_offset);
7877                                         buffer_add_int (buf, clause->handler_len);
7878                                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7879                                                 buffer_add_typeid (buf, domain, clause->data.catch_class);
7880                                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7881                                                 buffer_add_int (buf, clause->data.filter_offset);
7882                                 }
7883                         }
7884
7885                         mono_metadata_free_mh (header);
7886                 }
7887
7888                 break;
7889         }
7890         case CMD_METHOD_RESOLVE_TOKEN: {
7891                 guint32 token = decode_int (p, &p, end);
7892
7893                 // FIXME: Generics
7894                 switch (mono_metadata_token_code (token)) {
7895                 case MONO_TOKEN_STRING: {
7896                         MonoString *s;
7897                         char *s2;
7898
7899                         s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7900                         g_assert (s);
7901
7902                         s2 = mono_string_to_utf8 (s);
7903
7904                         buffer_add_byte (buf, TOKEN_TYPE_STRING);
7905                         buffer_add_string (buf, s2);
7906                         g_free (s2);
7907                         break;
7908                 }
7909                 default: {
7910                         gpointer val;
7911                         MonoClass *handle_class;
7912
7913                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7914                                 val = mono_method_get_wrapper_data (method, token);
7915                                 handle_class = mono_method_get_wrapper_data (method, token + 1);
7916
7917                                 if (handle_class == NULL) {
7918                                         // Can't figure out the token type
7919                                         buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7920                                         break;
7921                                 }
7922                         } else {
7923                                 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7924                                 g_assert (val);
7925                         }
7926
7927                         if (handle_class == mono_defaults.typehandle_class) {
7928                                 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7929                                 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7930                                         buffer_add_typeid (buf, domain, (MonoClass *) val);
7931                                 else
7932                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7933                         } else if (handle_class == mono_defaults.fieldhandle_class) {
7934                                 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7935                                 buffer_add_fieldid (buf, domain, val);
7936                         } else if (handle_class == mono_defaults.methodhandle_class) {
7937                                 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7938                                 buffer_add_methodid (buf, domain, val);
7939                         } else if (handle_class == mono_defaults.string_class) {
7940                                 char *s;
7941
7942                                 s = mono_string_to_utf8 (val);
7943                                 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7944                                 buffer_add_string (buf, s);
7945                                 g_free (s);
7946                         } else {
7947                                 g_assert_not_reached ();
7948                         }
7949                         break;
7950                 }
7951                 }
7952                 break;
7953         }
7954         case CMD_METHOD_GET_CATTRS: {
7955                 MonoClass *attr_klass;
7956                 MonoCustomAttrInfo *cinfo;
7957
7958                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7959                 /* attr_klass can be NULL */
7960                 if (err)
7961                         return err;
7962
7963                 cinfo = mono_custom_attrs_from_method (method);
7964
7965                 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
7966                 break;
7967         }
7968         default:
7969                 return ERR_NOT_IMPLEMENTED;
7970         }
7971
7972         return ERR_NONE;
7973 }
7974
7975 static ErrorCode
7976 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7977 {
7978         int err;
7979         MonoDomain *old_domain;
7980         MonoDomain *domain;
7981         MonoMethod *method;
7982
7983         method = decode_methodid (p, &p, end, &domain, &err);
7984         if (err)
7985                 return err;
7986
7987         old_domain = mono_domain_get ();
7988
7989         mono_domain_set (domain, TRUE);
7990
7991         err = method_commands_internal (command, method, domain, p, end, buf);
7992
7993         mono_domain_set (old_domain, TRUE);
7994
7995         return err;
7996 }
7997
7998 static ErrorCode
7999 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8000 {
8001         int objid = decode_objid (p, &p, end);
8002         int err;
8003         MonoThread *thread_obj;
8004         MonoInternalThread *thread;
8005
8006         err = get_object (objid, (MonoObject**)&thread_obj);
8007         if (err)
8008                 return err;
8009
8010         thread = THREAD_TO_INTERNAL (thread_obj);
8011            
8012         switch (command) {
8013         case CMD_THREAD_GET_NAME: {
8014                 guint32 name_len;
8015                 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8016
8017                 if (!s) {
8018                         buffer_add_int (buf, 0);
8019                 } else {
8020                         char *name;
8021                         glong len;
8022
8023                         name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8024                         g_assert (name);
8025                         buffer_add_int (buf, len);
8026                         buffer_add_data (buf, (guint8*)name, len);
8027                         g_free (s);
8028                 }
8029                 break;
8030         }
8031         case CMD_THREAD_GET_FRAME_INFO: {
8032                 DebuggerTlsData *tls;
8033                 int i, start_frame, length;
8034
8035                 // Wait for suspending if it already started
8036                 // FIXME: Races with suspend_count
8037                 while (!is_suspended ()) {
8038                         if (suspend_count)
8039                                 wait_for_suspend ();
8040                 }
8041                 /*
8042                 if (suspend_count)
8043                         wait_for_suspend ();
8044                 if (!is_suspended ())
8045                         return ERR_NOT_SUSPENDED;
8046                 */
8047
8048                 start_frame = decode_int (p, &p, end);
8049                 length = decode_int (p, &p, end);
8050
8051                 if (start_frame != 0 || length != -1)
8052                         return ERR_NOT_IMPLEMENTED;
8053
8054                 mono_loader_lock ();
8055                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8056                 mono_loader_unlock ();
8057                 g_assert (tls);
8058
8059                 compute_frame_info (thread, tls);
8060
8061                 buffer_add_int (buf, tls->frame_count);
8062                 for (i = 0; i < tls->frame_count; ++i) {
8063                         buffer_add_int (buf, tls->frames [i]->id);
8064                         buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8065                         buffer_add_int (buf, tls->frames [i]->il_offset);
8066                         /*
8067                          * Instead of passing the frame type directly to the client, we associate
8068                          * it with the previous frame using a set of flags. This avoids lots of
8069                          * conditional code in the client, since a frame whose type isn't 
8070                          * FRAME_TYPE_MANAGED has no method, location, etc.
8071                          */
8072                         buffer_add_byte (buf, tls->frames [i]->flags);
8073                 }
8074
8075                 break;
8076         }
8077         case CMD_THREAD_GET_STATE:
8078                 buffer_add_int (buf, thread->state);
8079                 break;
8080         case CMD_THREAD_GET_INFO:
8081                 buffer_add_byte (buf, thread->threadpool_thread);
8082                 break;
8083         case CMD_THREAD_GET_ID:
8084                 buffer_add_long (buf, (guint64)(gsize)thread);
8085                 break;
8086         case CMD_THREAD_GET_TID:
8087                 buffer_add_long (buf, (guint64)thread->tid);
8088                 break;
8089         default:
8090                 return ERR_NOT_IMPLEMENTED;
8091         }
8092
8093         return ERR_NONE;
8094 }
8095
8096 static ErrorCode
8097 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8098 {
8099         int objid;
8100         int err;
8101         MonoThread *thread_obj;
8102         MonoInternalThread *thread;
8103         int pos, i, len, frame_idx;
8104         DebuggerTlsData *tls;
8105         StackFrame *frame;
8106         MonoDebugMethodJitInfo *jit;
8107         MonoDebugVarInfo *var;
8108         MonoMethodSignature *sig;
8109         gssize id;
8110         MonoMethodHeader *header;
8111
8112         objid = decode_objid (p, &p, end);
8113         err = get_object (objid, (MonoObject**)&thread_obj);
8114         if (err)
8115                 return err;
8116
8117         thread = THREAD_TO_INTERNAL (thread_obj);
8118
8119         id = decode_id (p, &p, end);
8120
8121         mono_loader_lock ();
8122         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8123         mono_loader_unlock ();
8124         g_assert (tls);
8125
8126         for (i = 0; i < tls->frame_count; ++i) {
8127                 if (tls->frames [i]->id == id)
8128                         break;
8129         }
8130         if (i == tls->frame_count)
8131                 return ERR_INVALID_FRAMEID;
8132
8133         frame_idx = i;
8134         frame = tls->frames [frame_idx];
8135
8136         if (!frame->has_ctx)
8137                 // FIXME:
8138                 return ERR_INVALID_FRAMEID;
8139
8140         if (!frame->jit) {
8141                 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8142                 if (!frame->jit && frame->api_method->is_inflated)
8143                         frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8144                 if (!frame->jit) {
8145                         char *s;
8146
8147                         /* This could happen for aot images with no jit debug info */
8148                         s = mono_method_full_name (frame->api_method, TRUE);
8149                         DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8150                         g_free (s);
8151                         return ERR_ABSENT_INFORMATION;
8152                 }
8153         }
8154         jit = frame->jit;
8155
8156         sig = mono_method_signature (frame->actual_method);
8157
8158         if (!get_seq_points (frame->domain, frame->actual_method))
8159                 /*
8160                  * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8161                  */
8162                 return ERR_ABSENT_INFORMATION;
8163
8164         switch (command) {
8165         case CMD_STACK_FRAME_GET_VALUES: {
8166                 len = decode_int (p, &p, end);
8167                 header = mono_method_get_header (frame->actual_method);
8168
8169                 for (i = 0; i < len; ++i) {
8170                         pos = decode_int (p, &p, end);
8171
8172                         if (pos < 0) {
8173                                 pos = - pos - 1;
8174
8175                                 g_assert (pos >= 0 && pos < jit->num_params);
8176
8177                                 var = &jit->params [pos];
8178
8179                                 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8180                         } else {
8181                                 g_assert (pos >= 0 && pos < jit->num_locals);
8182
8183                                 var = &jit->locals [pos];
8184                                 
8185                                 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8186                         }
8187                 }
8188                 mono_metadata_free_mh (header);
8189                 break;
8190         }
8191         case CMD_STACK_FRAME_GET_THIS: {
8192                 if (frame->api_method->klass->valuetype) {
8193                         if (!sig->hasthis) {
8194                                 MonoObject *p = NULL;
8195                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8196                         } else {
8197                                 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8198                         }
8199                 } else {
8200                         if (!sig->hasthis) {
8201                                 MonoObject *p = NULL;
8202                                 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8203                         } else {
8204                                 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8205                         }
8206                 }
8207                 break;
8208         }
8209         case CMD_STACK_FRAME_SET_VALUES: {
8210                 guint8 *val_buf;
8211                 MonoType *t;
8212                 MonoDebugVarInfo *var;
8213
8214                 len = decode_int (p, &p, end);
8215                 header = mono_method_get_header (frame->actual_method);
8216
8217                 for (i = 0; i < len; ++i) {
8218                         pos = decode_int (p, &p, end);
8219
8220                         if (pos < 0) {
8221                                 pos = - pos - 1;
8222
8223                                 g_assert (pos >= 0 && pos < jit->num_params);
8224
8225                                 t = sig->params [pos];
8226                                 var = &jit->params [pos];
8227                         } else {
8228                                 g_assert (pos >= 0 && pos < jit->num_locals);
8229
8230                                 t = header->locals [pos];
8231                                 var = &jit->locals [pos];
8232                         }
8233
8234                         if (MONO_TYPE_IS_REFERENCE (t))
8235                                 val_buf = g_alloca (sizeof (MonoObject*));
8236                         else
8237                                 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8238                         err = decode_value (t, frame->domain, val_buf, p, &p, end);
8239                         if (err)
8240                                 return err;
8241
8242                         set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8243                 }
8244                 mono_metadata_free_mh (header);
8245                 break;
8246         }
8247         default:
8248                 return ERR_NOT_IMPLEMENTED;
8249         }
8250
8251         return ERR_NONE;
8252 }
8253
8254 static ErrorCode
8255 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8256 {
8257         MonoArray *arr;
8258         int objid, err, index, len, i, esize;
8259         gpointer elem;
8260
8261         objid = decode_objid (p, &p, end);
8262         err = get_object (objid, (MonoObject**)&arr);
8263         if (err)
8264                 return err;
8265
8266         switch (command) {
8267         case CMD_ARRAY_REF_GET_LENGTH:
8268                 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8269                 if (!arr->bounds) {
8270                         buffer_add_int (buf, arr->max_length);
8271                         buffer_add_int (buf, 0);
8272                 } else {
8273                         for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8274                                 buffer_add_int (buf, arr->bounds [i].length);
8275                                 buffer_add_int (buf, arr->bounds [i].lower_bound);
8276                         }
8277                 }
8278                 break;
8279         case CMD_ARRAY_REF_GET_VALUES:
8280                 index = decode_int (p, &p, end);
8281                 len = decode_int (p, &p, end);
8282
8283                 g_assert (index >= 0 && len >= 0);
8284                 // Reordered to avoid integer overflow
8285                 g_assert (!(index > arr->max_length - len));
8286
8287                 esize = mono_array_element_size (arr->obj.vtable->klass);
8288                 for (i = index; i < index + len; ++i) {
8289                         elem = (gpointer*)((char*)arr->vector + (i * esize));
8290                         buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8291                 }
8292                 break;
8293         case CMD_ARRAY_REF_SET_VALUES:
8294                 index = decode_int (p, &p, end);
8295                 len = decode_int (p, &p, end);
8296
8297                 g_assert (index >= 0 && len >= 0);
8298                 // Reordered to avoid integer overflow
8299                 g_assert (!(index > arr->max_length - len));
8300
8301                 esize = mono_array_element_size (arr->obj.vtable->klass);
8302                 for (i = index; i < index + len; ++i) {
8303                         elem = (gpointer*)((char*)arr->vector + (i * esize));
8304
8305                         decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8306                 }
8307                 break;
8308         default:
8309                 return ERR_NOT_IMPLEMENTED;
8310         }
8311
8312         return ERR_NONE;
8313 }
8314
8315 static ErrorCode
8316 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8317 {
8318         int objid, err;
8319         MonoString *str;
8320         char *s;
8321         int i, index, length;
8322         gunichar2 *c;
8323
8324         objid = decode_objid (p, &p, end);
8325         err = get_object (objid, (MonoObject**)&str);
8326         if (err)
8327                 return err;
8328
8329         switch (command) {
8330         case CMD_STRING_REF_GET_VALUE:
8331                 s = mono_string_to_utf8 (str);
8332                 buffer_add_string (buf, s);
8333                 g_free (s);
8334                 break;
8335         case CMD_STRING_REF_GET_LENGTH:
8336                 buffer_add_long (buf, mono_string_length (str));
8337                 break;
8338         case CMD_STRING_REF_GET_CHARS:
8339                 index = decode_long (p, &p, end);
8340                 length = decode_long (p, &p, end);
8341                 if (index > mono_string_length (str) - length)
8342                         return ERR_INVALID_ARGUMENT;
8343                 c = mono_string_chars (str) + index;
8344                 for (i = 0; i < length; ++i)
8345                         buffer_add_short (buf, c [i]);
8346                 break;
8347         default:
8348                 return ERR_NOT_IMPLEMENTED;
8349         }
8350
8351         return ERR_NONE;
8352 }
8353
8354 static ErrorCode
8355 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8356 {
8357         int objid, err;
8358         MonoObject *obj;
8359         int len, i;
8360         MonoClassField *f;
8361         MonoClass *k;
8362         gboolean found;
8363
8364         if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8365                 objid = decode_objid (p, &p, end);
8366                 err = get_object (objid, &obj);
8367                 if (err)
8368                         buffer_add_int (buf, 1);
8369                 else
8370                         buffer_add_int (buf, 0);
8371                 return 0;
8372         }
8373
8374         objid = decode_objid (p, &p, end);
8375         err = get_object (objid, &obj);
8376         if (err)
8377                 return err;
8378
8379         switch (command) {
8380         case CMD_OBJECT_REF_GET_TYPE:
8381                 /* This handles transparent proxies too */
8382                 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8383                 break;
8384         case CMD_OBJECT_REF_GET_VALUES:
8385                 len = decode_int (p, &p, end);
8386
8387                 for (i = 0; i < len; ++i) {
8388                         MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8389                         if (err)
8390                                 return err;
8391
8392                         /* Check that the field belongs to the object */
8393                         found = FALSE;
8394                         for (k = obj->vtable->klass; k; k = k->parent) {
8395                                 if (k == f->parent) {
8396                                         found = TRUE;
8397                                         break;
8398                                 }
8399                         }
8400                         if (!found)
8401                                 return ERR_INVALID_FIELDID;
8402
8403                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8404                                 guint8 *val;
8405                                 MonoVTable *vtable;
8406
8407                                 if (mono_class_field_is_special_static (f))
8408                                         return ERR_INVALID_FIELDID;
8409
8410                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8411                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8412                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8413                                 mono_field_static_get_value (vtable, f, val);
8414                                 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8415                                 g_free (val);
8416                         } else {
8417                                 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8418                         }
8419                 }
8420                 break;
8421         case CMD_OBJECT_REF_SET_VALUES:
8422                 len = decode_int (p, &p, end);
8423
8424                 for (i = 0; i < len; ++i) {
8425                         f = decode_fieldid (p, &p, end, NULL, &err);
8426                         if (err)
8427                                 return err;
8428
8429                         /* Check that the field belongs to the object */
8430                         found = FALSE;
8431                         for (k = obj->vtable->klass; k; k = k->parent) {
8432                                 if (k == f->parent) {
8433                                         found = TRUE;
8434                                         break;
8435                                 }
8436                         }
8437                         if (!found)
8438                                 return ERR_INVALID_FIELDID;
8439
8440                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8441                                 guint8 *val;
8442                                 MonoVTable *vtable;
8443
8444                                 if (mono_class_field_is_special_static (f))
8445                                         return ERR_INVALID_FIELDID;
8446
8447                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8448                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8449
8450                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8451                                 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8452                                 if (err) {
8453                                         g_free (val);
8454                                         return err;
8455                                 }
8456                                 mono_field_static_set_value (vtable, f, val);
8457                                 g_free (val);
8458                         } else {
8459                                 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8460                                 if (err)
8461                                         return err;
8462                         }
8463                 }
8464                 break;
8465         case CMD_OBJECT_REF_GET_ADDRESS:
8466                 buffer_add_long (buf, (gssize)obj);
8467                 break;
8468         case CMD_OBJECT_REF_GET_DOMAIN:
8469                 buffer_add_domainid (buf, obj->vtable->domain);
8470                 break;
8471         case CMD_OBJECT_REF_GET_INFO:
8472                 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8473                 buffer_add_domainid (buf, obj->vtable->domain);
8474                 break;
8475         default:
8476                 return ERR_NOT_IMPLEMENTED;
8477         }
8478
8479         return ERR_NONE;
8480 }
8481
8482 static const char*
8483 command_set_to_string (CommandSet command_set)
8484 {
8485         switch (command_set) {
8486         case CMD_SET_VM:
8487                 return "VM";
8488         case CMD_SET_OBJECT_REF:
8489                 return "OBJECT_REF";
8490         case CMD_SET_STRING_REF:
8491                 return "STRING_REF"; 
8492         case CMD_SET_THREAD:
8493                 return "THREAD"; 
8494         case CMD_SET_ARRAY_REF:
8495                 return "ARRAY_REF"; 
8496         case CMD_SET_EVENT_REQUEST:
8497                 return "EVENT_REQUEST"; 
8498         case CMD_SET_STACK_FRAME:
8499                 return "STACK_FRAME"; 
8500         case CMD_SET_APPDOMAIN:
8501                 return "APPDOMAIN"; 
8502         case CMD_SET_ASSEMBLY:
8503                 return "ASSEMBLY"; 
8504         case CMD_SET_METHOD:
8505                 return "METHOD"; 
8506         case CMD_SET_TYPE:
8507                 return "TYPE"; 
8508         case CMD_SET_MODULE:
8509                 return "MODULE"; 
8510         case CMD_SET_EVENT:
8511                 return "EVENT"; 
8512         default:
8513                 return "";
8514         }
8515 }
8516
8517 static const char*
8518 cmd_to_string (CommandSet set, int command)
8519 {
8520         switch (set) {
8521         case CMD_SET_VM: {
8522                 switch (command) {
8523                 case CMD_VM_VERSION:
8524                         return "VERSION";
8525                 case CMD_VM_ALL_THREADS:
8526                         return "ALL_THREADS";
8527                 case CMD_VM_SUSPEND:
8528                         return "SUSPEND";
8529                 case CMD_VM_RESUME:
8530                         return "RESUME";
8531                 case CMD_VM_EXIT:
8532                         return "EXIT";
8533                 case CMD_VM_DISPOSE:
8534                         return "DISPOSE";
8535                 case CMD_VM_INVOKE_METHOD:
8536                         return "INVOKE_METHOD";
8537                 case CMD_VM_SET_PROTOCOL_VERSION:
8538                         return "SET_PROTOCOL_VERSION";
8539                 case CMD_VM_ABORT_INVOKE:
8540                         return "ABORT_INVOKE";
8541                 case CMD_VM_SET_KEEPALIVE:
8542                         return "SET_KEEPALIVE";
8543                 default:
8544                         break;
8545                 }
8546                 break;
8547         }
8548         default:
8549                 break;
8550         }
8551         return NULL;
8552 }
8553
8554 static gboolean
8555 wait_for_attach (void)
8556 {
8557 #ifndef DISABLE_SOCKET_TRANSPORT
8558         if (listen_fd == -1) {
8559                 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8560                 return FALSE;
8561         }
8562
8563         /* Block and wait for client connection */
8564         conn_fd = socket_transport_accept (listen_fd);
8565         DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8566         if (conn_fd == -1) {
8567                 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8568                 return FALSE;
8569         }
8570 #else
8571         g_assert_not_reached ();
8572 #endif
8573
8574         /* Handshake */
8575         disconnected = !transport_handshake ();
8576         if (disconnected) {
8577                 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8578                 return FALSE;
8579         }
8580         
8581         return TRUE;
8582 }
8583
8584 /*
8585  * debugger_thread:
8586  *
8587  *   This thread handles communication with the debugger client using a JDWP
8588  * like protocol.
8589  */
8590 static guint32 WINAPI
8591 debugger_thread (void *arg)
8592 {
8593         int res, len, id, flags, command_set = 0, command = 0;
8594         guint8 header [HEADER_LENGTH];
8595         guint8 *data, *p, *end;
8596         Buffer buf;
8597         ErrorCode err;
8598         gboolean no_reply;
8599         gboolean attach_failed = FALSE;
8600
8601         DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8602
8603         debugger_thread_id = GetCurrentThreadId ();
8604
8605         mono_jit_thread_attach (mono_get_root_domain ());
8606
8607         mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8608
8609         mono_set_is_debugger_attached (TRUE);
8610         
8611         if (agent_config.defer) {
8612                 if (!wait_for_attach ()) {
8613                         DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8614                         attach_failed = TRUE; // Don't abort process when we can't listen
8615                 } else {
8616                         /* Send start event to client */
8617                         process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8618                 }
8619         }
8620         
8621         while (!attach_failed) {
8622                 res = transport_recv (header, HEADER_LENGTH);
8623
8624                 /* This will break if the socket is closed during shutdown too */
8625                 if (res != HEADER_LENGTH)
8626                         break;
8627
8628                 p = header;
8629                 end = header + HEADER_LENGTH;
8630
8631                 len = decode_int (p, &p, end);
8632                 id = decode_int (p, &p, end);
8633                 flags = decode_byte (p, &p, end);
8634                 command_set = decode_byte (p, &p, end);
8635                 command = decode_byte (p, &p, end);
8636
8637                 g_assert (flags == 0);
8638
8639                 if (log_level) {
8640                         const char *cmd_str;
8641                         char cmd_num [256];
8642
8643                         cmd_str = cmd_to_string (command_set, command);
8644                         if (!cmd_str) {
8645                                 sprintf (cmd_num, "%d", command);
8646                                 cmd_str = cmd_num;
8647                         }
8648                         
8649                         DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8650                 }
8651
8652                 data = g_malloc (len - HEADER_LENGTH);
8653                 if (len - HEADER_LENGTH > 0)
8654                 {
8655                         res = transport_recv (data, len - HEADER_LENGTH);
8656                         if (res != len - HEADER_LENGTH)
8657                                 break;
8658                 }
8659
8660                 p = data;
8661                 end = data + (len - HEADER_LENGTH);
8662
8663                 buffer_init (&buf, 128);
8664
8665                 err = ERR_NONE;
8666                 no_reply = FALSE;
8667
8668                 /* Process the request */
8669                 switch (command_set) {
8670                 case CMD_SET_VM:
8671                         err = vm_commands (command, id, p, end, &buf);
8672                         if (!err && command == CMD_VM_INVOKE_METHOD)
8673                                 /* Sent after the invoke is complete */
8674                                 no_reply = TRUE;
8675                         break;
8676                 case CMD_SET_EVENT_REQUEST:
8677                         err = event_commands (command, p, end, &buf);
8678                         break;
8679                 case CMD_SET_APPDOMAIN:
8680                         err = domain_commands (command, p, end, &buf);
8681                         break;
8682                 case CMD_SET_ASSEMBLY:
8683                         err = assembly_commands (command, p, end, &buf);
8684                         break;
8685                 case CMD_SET_MODULE:
8686                         err = module_commands (command, p, end, &buf);
8687                         break;
8688                 case CMD_SET_TYPE:
8689                         err = type_commands (command, p, end, &buf);
8690                         break;
8691                 case CMD_SET_METHOD:
8692                         err = method_commands (command, p, end, &buf);
8693                         break;
8694                 case CMD_SET_THREAD:
8695                         err = thread_commands (command, p, end, &buf);
8696                         break;
8697                 case CMD_SET_STACK_FRAME:
8698                         err = frame_commands (command, p, end, &buf);
8699                         break;
8700                 case CMD_SET_ARRAY_REF:
8701                         err = array_commands (command, p, end, &buf);
8702                         break;
8703                 case CMD_SET_STRING_REF:
8704                         err = string_commands (command, p, end, &buf);
8705                         break;
8706                 case CMD_SET_OBJECT_REF:
8707                         err = object_commands (command, p, end, &buf);
8708                         break;
8709                 default:
8710                         err = ERR_NOT_IMPLEMENTED;
8711                 }               
8712
8713                 if (!no_reply)
8714                         send_reply_packet (id, err, &buf);
8715
8716                 g_free (data);
8717                 buffer_free (&buf);
8718
8719                 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8720                         break;
8721         }
8722
8723         mono_set_is_debugger_attached (FALSE);
8724         
8725         mono_mutex_lock (&debugger_thread_exited_mutex);
8726         debugger_thread_exited = TRUE;
8727         mono_cond_signal (&debugger_thread_exited_cond);
8728         mono_mutex_unlock (&debugger_thread_exited_mutex);
8729
8730         DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8731         
8732         if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8733                 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8734                 start_debugger_thread ();
8735         }
8736         
8737         return 0;
8738 }
8739
8740 #else /* DISABLE_DEBUGGER_AGENT */
8741
8742 void
8743 mono_debugger_agent_parse_options (char *options)
8744 {
8745         g_error ("This runtime is configured with the debugger agent disabled.");
8746 }
8747
8748 void
8749 mono_debugger_agent_init (void)
8750 {
8751 }
8752
8753 void
8754 mono_debugger_agent_breakpoint_hit (void *sigctx)
8755 {
8756 }
8757
8758 void
8759 mono_debugger_agent_single_step_event (void *sigctx)
8760 {
8761 }
8762
8763 void
8764 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8765 {
8766 }
8767
8768 gboolean
8769 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8770 {
8771         return FALSE;
8772 }
8773
8774 void
8775 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8776                                                                           MonoContext *catch_ctx)
8777 {
8778 }
8779
8780 void
8781 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8782 {
8783 }
8784
8785 void
8786 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8787 {
8788 }
8789
8790 void
8791 mono_debugger_agent_user_break (void)
8792 {
8793         G_BREAKPOINT ();
8794 }
8795
8796 void
8797 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8798 {
8799 }
8800
8801 gboolean
8802 mono_debugger_agent_debug_log_is_enabled (void)
8803 {
8804         return FALSE;
8805 }
8806
8807 #endif
8808