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