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