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