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