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