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