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