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