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