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