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