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