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