[xbuild] Actually delete common files (CopyLocal) during Clean.
[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 (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4077                 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4078         } else if (count == 0) {
4079 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4080                 mono_arch_set_breakpoint (ji, inst->ip);
4081 #else
4082                 NOT_IMPLEMENTED;
4083 #endif
4084         }
4085
4086         DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));  
4087 }
4088
4089 static void
4090 remove_breakpoint (BreakpointInstance *inst)
4091 {
4092 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4093         int count;
4094         MonoJitInfo *ji = inst->ji;
4095         guint8 *ip = inst->ip;
4096
4097         mono_loader_lock ();
4098         count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4099         g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4100         mono_loader_unlock ();
4101
4102         g_assert (count > 0);
4103
4104         if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4105                 mono_arch_clear_breakpoint (ji, ip);
4106         }
4107 #else
4108         NOT_IMPLEMENTED;
4109 #endif
4110 }       
4111
4112 static inline gboolean
4113 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4114 {
4115         int i;
4116
4117         if (!bp->method)
4118                 return TRUE;
4119         if (method == bp->method)
4120                 return TRUE;
4121         if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4122                 return TRUE;
4123
4124         if (bp->method->is_inflated && method->is_inflated) {
4125                 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4126                 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4127
4128                 /* Open generic methods should match closed generic methods of the same class */
4129                 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4130                         for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4131                                 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4132
4133                                 /* FIXME: Handle !mvar */
4134                                 if (t1->type != MONO_TYPE_MVAR)
4135                                         return FALSE;
4136                         }
4137                         return TRUE;
4138                 }
4139         }
4140
4141         return FALSE;
4142 }
4143
4144 /*
4145  * add_pending_breakpoints:
4146  *
4147  *   Insert pending breakpoints into the newly JITted method METHOD.
4148  */
4149 static void
4150 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4151 {
4152         int i, j;
4153         MonoSeqPointInfo *seq_points;
4154         MonoDomain *domain;
4155
4156         if (!breakpoints)
4157                 return;
4158
4159         domain = mono_domain_get ();
4160
4161         mono_loader_lock ();
4162
4163         for (i = 0; i < breakpoints->len; ++i) {
4164                 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4165                 gboolean found = FALSE;
4166
4167                 if (!bp_matches_method (bp, method))
4168                         continue;
4169
4170                 for (j = 0; j < bp->children->len; ++j) {
4171                         BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4172
4173                         if (inst->ji == ji)
4174                                 found = TRUE;
4175                 }
4176
4177                 if (!found) {
4178                         mono_domain_lock (domain);
4179                         seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4180                         if (!seq_points && ji->method->is_inflated)
4181                                 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4182                         mono_domain_unlock (domain);
4183                         if (!seq_points)
4184                                 /* Could be AOT code */
4185                                 continue;
4186                         g_assert (seq_points);
4187
4188                         insert_breakpoint (seq_points, domain, ji, bp, NULL);
4189                 }
4190         }
4191
4192         mono_loader_unlock ();
4193 }
4194
4195 static void
4196 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4197 {
4198         gpointer code;
4199         MonoJitInfo *ji;
4200
4201         if (error)
4202                 mono_error_init (error);
4203
4204         code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4205         if (!code) {
4206                 /* Might be AOTed code */
4207                 code = mono_aot_get_method (domain, method);
4208                 g_assert (code);
4209                 ji = mono_jit_info_table_find (domain, code);
4210                 g_assert (ji);
4211         }
4212         g_assert (code);
4213
4214         insert_breakpoint (seq_points, domain, ji, bp, error);
4215 }
4216
4217 static void
4218 clear_breakpoint (MonoBreakpoint *bp);
4219
4220 /*
4221  * set_breakpoint:
4222  *
4223  *   Set a breakpoint at IL_OFFSET in METHOD.
4224  * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4225  * METHOD can also be a generic method definition, in which case a breakpoint
4226  * is placed in all instances of the method.
4227  * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4228  * inserted.
4229  */
4230 static MonoBreakpoint*
4231 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4232 {
4233         MonoBreakpoint *bp;
4234         GHashTableIter iter, iter2;
4235         MonoDomain *domain;
4236         MonoMethod *m;
4237         MonoSeqPointInfo *seq_points;
4238
4239         if (error)
4240                 mono_error_init (error);
4241
4242         // FIXME:
4243         // - suspend/resume the vm to prevent code patching problems
4244         // - multiple breakpoints on the same location
4245         // - dynamic methods
4246         // - races
4247
4248         bp = g_new0 (MonoBreakpoint, 1);
4249         bp->method = method;
4250         bp->il_offset = il_offset;
4251         bp->req = req;
4252         bp->children = g_ptr_array_new ();
4253
4254         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));
4255
4256         mono_loader_lock ();
4257
4258         g_hash_table_iter_init (&iter, domains);
4259         while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4260                 mono_domain_lock (domain);
4261
4262                 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4263                 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4264                         if (bp_matches_method (bp, m))
4265                                 set_bp_in_method (domain, m, seq_points, bp, error);
4266                 }
4267
4268                 mono_domain_unlock (domain);
4269         }
4270
4271         mono_loader_unlock ();
4272
4273         mono_loader_lock ();
4274         g_ptr_array_add (breakpoints, bp);
4275         mono_loader_unlock ();
4276
4277         if (error && !mono_error_ok (error)) {
4278                 clear_breakpoint (bp);
4279                 return NULL;
4280         }
4281
4282         return bp;
4283 }
4284
4285 static void
4286 clear_breakpoint (MonoBreakpoint *bp)
4287 {
4288         int i;
4289
4290         // FIXME: locking, races
4291         for (i = 0; i < bp->children->len; ++i) {
4292                 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4293
4294                 remove_breakpoint (inst);
4295
4296                 g_free (inst);
4297         }
4298
4299         mono_loader_lock ();
4300         g_ptr_array_remove (breakpoints, bp);
4301         mono_loader_unlock ();
4302
4303         g_ptr_array_free (bp->children, TRUE);
4304         g_free (bp);
4305 }
4306
4307 static void
4308 breakpoints_cleanup (void)
4309 {
4310         int i;
4311
4312         mono_loader_lock ();
4313         i = 0;
4314         while (i < event_requests->len) {
4315                 EventRequest *req = g_ptr_array_index (event_requests, i);
4316
4317                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4318                         clear_breakpoint (req->info);
4319                         g_ptr_array_remove_index_fast (event_requests, i);
4320                         g_free (req);
4321                 } else {
4322                         i ++;
4323                 }
4324         }
4325
4326         for (i = 0; i < breakpoints->len; ++i)
4327                 g_free (g_ptr_array_index (breakpoints, i));
4328
4329         g_ptr_array_free (breakpoints, TRUE);
4330         g_hash_table_destroy (bp_locs);
4331
4332         breakpoints = NULL;
4333         bp_locs = NULL;
4334
4335         mono_loader_unlock ();
4336 }
4337
4338 /*
4339  * clear_breakpoints_for_domain:
4340  *
4341  *   Clear breakpoint instances which reference DOMAIN.
4342  */
4343 static void
4344 clear_breakpoints_for_domain (MonoDomain *domain)
4345 {
4346         int i, j;
4347
4348         /* This could be called after shutdown */
4349         if (!breakpoints)
4350                 return;
4351
4352         mono_loader_lock ();
4353         for (i = 0; i < breakpoints->len; ++i) {
4354                 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4355
4356                 j = 0;
4357                 while (j < bp->children->len) {
4358                         BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4359
4360                         if (inst->domain == domain) {
4361                                 remove_breakpoint (inst);
4362
4363                                 g_free (inst);
4364
4365                                 g_ptr_array_remove_index_fast (bp->children, j);
4366                         } else {
4367                                 j ++;
4368                         }
4369                 }
4370         }
4371         mono_loader_unlock ();
4372 }
4373
4374 static gboolean
4375 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4376 {
4377         return bp->method && bp->method->klass->image->assembly == assembly;
4378 }
4379
4380 static void
4381 process_breakpoint_inner (DebuggerTlsData *tls)
4382 {
4383         MonoJitInfo *ji;
4384         guint8 *ip;
4385         int i, j, suspend_policy;
4386         guint32 native_offset;
4387         MonoBreakpoint *bp;
4388         BreakpointInstance *inst;
4389         GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4390         GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4391         EventKind kind = EVENT_KIND_BREAKPOINT;
4392         MonoContext *ctx = &tls->restore_ctx;
4393         MonoSeqPointInfo *info;
4394         SeqPoint *sp;
4395
4396         // FIXME: Speed this up
4397
4398         ip = MONO_CONTEXT_GET_IP (ctx);
4399         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4400         g_assert (ji);
4401         g_assert (ji->method);
4402
4403         /* Compute the native offset of the breakpoint from the ip */
4404         native_offset = ip - (guint8*)ji->code_start;   
4405
4406         /* 
4407          * Skip the instruction causing the breakpoint signal.
4408          */
4409         mono_arch_skip_breakpoint (ctx, ji);
4410
4411         if (ji->method->wrapper_type || tls->disable_breakpoints)
4412                 return;
4413
4414         bp_reqs = g_ptr_array_new ();
4415         ss_reqs = g_ptr_array_new ();
4416         ss_reqs_orig = g_ptr_array_new ();
4417
4418         mono_loader_lock ();
4419
4420         /*
4421          * The ip points to the instruction causing the breakpoint event, which is after
4422          * the offset recorded in the seq point map, so find the prev seq point before ip.
4423          */
4424         sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4425         if (!sp)
4426                 no_seq_points_found (ji->method);
4427         g_assert (sp);
4428
4429         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));
4430
4431         bp = NULL;
4432         for (i = 0; i < breakpoints->len; ++i) {
4433                 bp = g_ptr_array_index (breakpoints, i);
4434
4435                 if (!bp->method)
4436                         continue;
4437
4438                 for (j = 0; j < bp->children->len; ++j) {
4439                         inst = g_ptr_array_index (bp->children, j);
4440                         if (inst->ji == ji && inst->sp == sp) {
4441                                 if (bp->req->event_kind == EVENT_KIND_STEP) {
4442                                         g_ptr_array_add (ss_reqs_orig, bp->req);
4443                                 } else {
4444                                         g_ptr_array_add (bp_reqs, bp->req);
4445                                 }
4446                         }
4447                 }
4448         }
4449         if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4450                 /* Maybe a method entry/exit event */
4451                 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4452                         kind = EVENT_KIND_METHOD_ENTRY;
4453                 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4454                         kind = EVENT_KIND_METHOD_EXIT;
4455         }
4456
4457         /* Process single step requests */
4458         for (i = 0; i < ss_reqs_orig->len; ++i) {
4459                 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4460                 SingleStepReq *ss_req = req->info;
4461                 gboolean hit = TRUE;
4462
4463                 if (ss_req->size == STEP_SIZE_LINE) {
4464                         /* Have to check whenever a different source line was reached */
4465                         MonoDebugMethodInfo *minfo;
4466                         MonoDebugSourceLocation *loc = NULL;
4467
4468                         minfo = mono_debug_lookup_method (ji->method);
4469
4470                         if (minfo)
4471                                 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4472
4473                         if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4474                                 /* Have to continue single stepping */
4475                                 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4476                                 hit = FALSE;
4477                         }
4478                                 
4479                         if (loc) {
4480                                 ss_req->last_method = ji->method;
4481                                 ss_req->last_line = loc->row;
4482                                 mono_debug_free_source_location (loc);
4483                         }
4484                 }
4485
4486                 if (hit)
4487                         g_ptr_array_add (ss_reqs, req);
4488
4489                 /* Start single stepping again from the current sequence point */
4490                 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4491         }
4492         
4493         if (ss_reqs->len > 0)
4494                 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4495         if (bp_reqs->len > 0)
4496                 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4497         if (kind != EVENT_KIND_BREAKPOINT)
4498                 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4499
4500         mono_loader_unlock ();
4501
4502         g_ptr_array_free (bp_reqs, TRUE);
4503         g_ptr_array_free (ss_reqs, TRUE);
4504
4505         /* 
4506          * FIXME: The first event will suspend, so the second will only be sent after the
4507          * resume.
4508          */
4509         if (ss_events)
4510                 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4511         if (bp_events)
4512                 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4513         if (enter_leave_events)
4514                 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4515 }
4516
4517 /* Process a breakpoint/single step event after resuming from a signal handler */
4518 static void
4519 process_signal_event (void (*func) (DebuggerTlsData*))
4520 {
4521         DebuggerTlsData *tls;
4522         MonoContext orig_restore_ctx, ctx;
4523         static void (*restore_context) (void *);
4524
4525         if (!restore_context)
4526                 restore_context = mono_get_restore_context ();
4527
4528         tls = mono_native_tls_get_value (debugger_tls_id);
4529         /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4530         memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4531         memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4532
4533         func (tls);
4534
4535         /* This is called when resuming from a signal handler, so it shouldn't return */
4536         memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4537         memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4538         restore_context (&ctx);
4539         g_assert_not_reached ();
4540 }
4541
4542 static void
4543 process_breakpoint (void)
4544 {
4545         process_signal_event (process_breakpoint_inner);
4546 }
4547
4548 static void
4549 resume_from_signal_handler (void *sigctx, void *func)
4550 {
4551         DebuggerTlsData *tls;
4552         MonoContext ctx;
4553
4554         /* Save the original context in TLS */
4555         // FIXME: This might not work on an altstack ?
4556         tls = mono_native_tls_get_value (debugger_tls_id);
4557         if (!tls)
4558                 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4559         g_assert (tls);
4560
4561         // FIXME: MonoContext usually doesn't include the fp registers, so these are 
4562         // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4563         // clob:c could be added to op_seq_point.
4564
4565         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4566         memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4567 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4568         mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4569 #else
4570         MONO_CONTEXT_SET_IP (&ctx, func);
4571 #endif
4572         mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4573
4574 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4575         mono_ppc_set_func_into_sigctx (sigctx, func);
4576 #endif
4577 }
4578
4579 void
4580 mono_debugger_agent_breakpoint_hit (void *sigctx)
4581 {
4582         /*
4583          * We are called from a signal handler, and running code there causes all kinds of
4584          * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4585          * So set up the signal context to return to the real breakpoint handler function.
4586          */
4587         resume_from_signal_handler (sigctx, process_breakpoint);
4588 }
4589
4590 static gboolean
4591 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4592 {
4593         if (frame->managed) {
4594                 *(MonoContext*)data = *ctx;
4595
4596                 return TRUE;
4597         } else {
4598                 return FALSE;
4599         }
4600 }
4601
4602 /*
4603  * Called by System.Diagnostics.Debugger:Break ().
4604  */
4605 void
4606 mono_debugger_agent_user_break (void)
4607 {
4608         if (agent_config.enabled) {
4609                 MonoContext ctx;
4610                 int suspend_policy;
4611                 GSList *events;
4612
4613                 /* Obtain a context */
4614                 MONO_CONTEXT_SET_IP (&ctx, NULL);
4615                 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4616                 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4617
4618                 mono_loader_lock ();
4619                 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4620                 mono_loader_unlock ();
4621
4622                 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4623         } else {
4624                 G_BREAKPOINT ();
4625         }
4626 }
4627
4628 static const char*
4629 ss_depth_to_string (StepDepth depth)
4630 {
4631         switch (depth) {
4632         case STEP_DEPTH_OVER:
4633                 return "over";
4634         case STEP_DEPTH_OUT:
4635                 return "out";
4636         case STEP_DEPTH_INTO:
4637                 return "into";
4638         default:
4639                 g_assert_not_reached ();
4640                 return NULL;
4641         }
4642 }
4643
4644 static void
4645 process_single_step_inner (DebuggerTlsData *tls)
4646 {
4647         MonoJitInfo *ji;
4648         guint8 *ip;
4649         GPtrArray *reqs;
4650         int il_offset, suspend_policy;
4651         MonoDomain *domain;
4652         GSList *events;
4653         MonoContext *ctx = &tls->restore_ctx;
4654         SeqPoint *sp;
4655         MonoSeqPointInfo *info;
4656
4657         ip = MONO_CONTEXT_GET_IP (ctx);
4658
4659         /* Skip the instruction causing the single step */
4660         mono_arch_skip_single_step (ctx);
4661
4662         if (suspend_count > 0) {
4663                 process_suspend (tls, ctx);
4664                 return;
4665         }
4666
4667         if (!ss_req)
4668                 // FIXME: A suspend race
4669                 return;
4670
4671         if (mono_thread_internal_current () != ss_req->thread)
4672                 return;
4673
4674         if (log_level > 0) {
4675                 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4676
4677                 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));
4678         }
4679
4680         ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4681         g_assert (ji);
4682         g_assert (ji->method);
4683
4684         if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4685                 return;
4686
4687         /* 
4688          * FIXME: 
4689          * Stopping in memset makes half-initialized vtypes visible.
4690          * Stopping in memcpy makes half-copied vtypes visible.
4691          */
4692         if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4693                 return;
4694
4695         /*
4696          * The ip points to the instruction causing the single step event, which is before
4697          * the offset recorded in the seq point map, so find the next seq point after ip.
4698          */
4699         sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4700         if (!sp)
4701                 return;
4702         il_offset = sp->il_offset;
4703
4704         // FIXME: No tests fail if this is disabled
4705 #if 0
4706         if (ss_req->size == STEP_SIZE_LINE) {
4707                 // FIXME:
4708                 NOT_IMPLEMENTED;
4709
4710                 /* Step until a different source line is reached */
4711                 MonoDebugMethodInfo *minfo;
4712
4713                 minfo = mono_debug_lookup_method (ji->method);
4714
4715                 if (minfo) {
4716                         MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4717
4718                         if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4719                                 mono_debug_free_source_location (loc);
4720                                 return;
4721                         }
4722                         if (!loc)
4723                                 /*
4724                                  * Step until we reach a location with line number info, 
4725                                  * otherwise the client can't show a location.
4726                                  * This can happen for example with statics initialized inline
4727                                  * outside of a cctor.
4728                                  */
4729                                 return;
4730
4731                         if (loc) {
4732                                 ss_req->last_method = ji->method;
4733                                 ss_req->last_line = loc->row;
4734                                 mono_debug_free_source_location (loc);
4735                         }
4736                 }
4737         }
4738 #endif
4739
4740         /* Start single stepping again from the current sequence point */
4741         ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4742
4743         if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4744                 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4745                 !strcmp (ji->method->name, ".cctor"))
4746                 return;
4747
4748         // FIXME: Has to lock earlier
4749
4750         reqs = g_ptr_array_new ();
4751
4752         mono_loader_lock ();
4753
4754         g_ptr_array_add (reqs, ss_req->req);
4755
4756         events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4757
4758         g_ptr_array_free (reqs, TRUE);
4759
4760         mono_loader_unlock ();
4761
4762         process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4763 }
4764
4765 static void
4766 process_single_step (void)
4767 {
4768         process_signal_event (process_single_step_inner);
4769 }
4770
4771 /*
4772  * mono_debugger_agent_single_step_event:
4773  *
4774  *   Called from a signal handler to handle a single step event.
4775  */
4776 void
4777 mono_debugger_agent_single_step_event (void *sigctx)
4778 {
4779         /* Resume to process_single_step through the signal context */
4780
4781         // FIXME: Since step out/over is implemented using step in, the step in case should
4782         // be as fast as possible. Move the relevant code from process_single_step_inner ()
4783         // here
4784
4785         if (GetCurrentThreadId () == debugger_thread_id) {
4786                 /* 
4787                  * This could happen despite our best effors when the runtime calls 
4788                  * assembly/type resolve hooks.
4789                  * FIXME: Breakpoints too.
4790                  */
4791                 MonoContext ctx;
4792
4793                 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4794                 mono_arch_skip_single_step (&ctx);
4795                 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4796                 return;
4797         }
4798
4799         resume_from_signal_handler (sigctx, process_single_step);
4800 }
4801
4802 void
4803 debugger_agent_single_step_from_context (MonoContext *ctx)
4804 {
4805         DebuggerTlsData *tls;
4806         MonoContext orig_restore_ctx;
4807
4808         tls = mono_native_tls_get_value (debugger_tls_id);
4809         g_assert (tls);
4810
4811         /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4812         memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4813         memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4814
4815         process_single_step_inner (tls);
4816
4817         memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4818         memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4819 }
4820
4821 void
4822 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4823 {
4824         DebuggerTlsData *tls;
4825         MonoContext orig_restore_ctx;
4826
4827         tls = mono_native_tls_get_value (debugger_tls_id);
4828         g_assert (tls);
4829         memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4830         memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4831
4832         process_breakpoint_inner (tls);
4833
4834         memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4835         memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4836 }
4837
4838 /*
4839  * start_single_stepping:
4840  *
4841  *   Turn on single stepping. Can be called multiple times, for example,
4842  * by a single step event request + a suspend.
4843  */
4844 static void
4845 start_single_stepping (void)
4846 {
4847 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4848         int val = InterlockedIncrement (&ss_count);
4849
4850         if (val == 1)
4851                 mono_arch_start_single_stepping ();
4852
4853         if (ss_req != NULL && ss_invoke_addr == NULL) {
4854                 DebuggerTlsData *tls;
4855         
4856                 mono_loader_lock ();
4857         
4858                 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4859                 ss_invoke_addr = tls->invoke_addr;
4860                 
4861                 mono_loader_unlock ();
4862         }
4863 #else
4864         g_assert_not_reached ();
4865 #endif
4866 }
4867
4868 static void
4869 stop_single_stepping (void)
4870 {
4871 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4872         int val = InterlockedDecrement (&ss_count);
4873
4874         if (val == 0)
4875                 mono_arch_stop_single_stepping ();
4876 #else
4877         g_assert_not_reached ();
4878 #endif
4879 }
4880
4881 /*
4882  * ss_stop:
4883  *
4884  *   Stop the single stepping operation given by SS_REQ.
4885  */
4886 static void
4887 ss_stop (SingleStepReq *ss_req)
4888 {
4889         if (ss_req->bps) {
4890                 GSList *l;
4891
4892                 for (l = ss_req->bps; l; l = l->next) {
4893                         clear_breakpoint (l->data);
4894                 }
4895                 g_slist_free (ss_req->bps);
4896                 ss_req->bps = NULL;
4897         }
4898
4899         if (ss_req->global) {
4900                 stop_single_stepping ();
4901                 ss_req->global = FALSE;
4902         }
4903 }
4904
4905 /*
4906  * ss_start:
4907  *
4908  *   Start the single stepping operation given by SS_REQ from the sequence point SP.
4909  * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4910  * belong to the same thread as CTX.
4911  */
4912 static void
4913 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4914 {
4915         int i, j, frame_index;
4916         SeqPoint *next_sp;
4917         MonoBreakpoint *bp;
4918         gboolean enable_global = FALSE;
4919
4920         /* Stop the previous operation */
4921         ss_stop (ss_req);
4922
4923         /*
4924          * Implement single stepping using breakpoints if possible.
4925          */
4926         if (step_to_catch) {
4927                 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4928                 ss_req->bps = g_slist_append (ss_req->bps, bp);
4929         } else {
4930                 frame_index = 1;
4931
4932                 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4933                         /* Need parent frames */
4934                         if (!tls->context.valid)
4935                                 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4936                         compute_frame_info (tls->thread, tls);
4937                 }
4938
4939                 /*
4940                  * Find the first sequence point in the current or in a previous frame which
4941                  * is not the last in its method.
4942                  */
4943                 if (ss_req->depth == STEP_DEPTH_OUT) {
4944                         /* Ignore seq points in current method */
4945                         while (frame_index < tls->frame_count) {
4946                                 StackFrame *frame = tls->frames [frame_index];
4947
4948                                 method = frame->method;
4949                                 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4950                                 frame_index ++;
4951                                 if (sp && sp->next_len != 0)
4952                                         break;
4953                         }
4954                         // There could be method calls before the next seq point in the caller when using nested calls
4955                         //enable_global = TRUE;
4956                 } else {
4957                         if (sp && sp->next_len == 0) {
4958                                 sp = NULL;
4959                                 while (frame_index < tls->frame_count) {
4960                                         StackFrame *frame = tls->frames [frame_index];
4961
4962                                         method = frame->method;
4963                                         sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4964                                         if (sp && sp->next_len != 0)
4965                                                 break;
4966                                         sp = NULL;
4967                                         frame_index ++;
4968                                 }
4969                         }
4970                 }
4971
4972                 if (sp && sp->next_len > 0) {
4973                         for (i = 0; i < sp->next_len; ++i) {
4974                                 next_sp = &info->seq_points [sp->next [i]];
4975
4976                                 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4977                                 ss_req->bps = g_slist_append (ss_req->bps, bp);
4978                         }
4979                 }
4980
4981                 if (ss_req->depth == STEP_DEPTH_OVER) {
4982                         /* Need to stop in catch clauses as well */
4983                         for (i = 0; i < tls->frame_count; ++i) {
4984                                 StackFrame *frame = tls->frames [i];
4985
4986                                 if (frame->ji) {
4987                                         MonoJitInfo *jinfo = frame->ji;
4988                                         for (j = 0; j < jinfo->num_clauses; ++j) {
4989                                                 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4990
4991                                                 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4992                                                 if (sp) {
4993                                                         bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4994                                                         ss_req->bps = g_slist_append (ss_req->bps, bp);
4995                                                 }
4996                                         }
4997                                 }
4998                         }
4999                 }
5000
5001
5002                 if (ss_req->depth == STEP_DEPTH_INTO) {
5003                         /* Enable global stepping so we stop at method entry too */
5004                         enable_global = TRUE;
5005                 }
5006
5007                 /*
5008                  * The ctx/frame info computed above will become invalid when we continue.
5009                  */
5010                 tls->context.valid = FALSE;
5011                 tls->async_state.valid = FALSE;
5012                 invalidate_frames (tls);
5013         }
5014
5015         if (enable_global) {
5016                 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5017                 ss_req->global = TRUE;
5018                 start_single_stepping ();
5019         } else if (!ss_req->bps) {
5020                 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5021                 ss_req->global = TRUE;
5022                 start_single_stepping ();
5023         } else {
5024                 ss_req->global = FALSE;
5025         }
5026 }
5027
5028 /*
5029  * Start single stepping of thread THREAD
5030  */
5031 static ErrorCode
5032 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5033 {
5034         DebuggerTlsData *tls;
5035         MonoSeqPointInfo *info = NULL;
5036         SeqPoint *sp = NULL;
5037         MonoMethod *method = NULL;
5038         MonoDebugMethodInfo *minfo;
5039         gboolean step_to_catch = FALSE;
5040
5041         if (suspend_count == 0)
5042                 return ERR_NOT_SUSPENDED;
5043
5044         wait_for_suspend ();
5045
5046         // FIXME: Multiple requests
5047         if (ss_req) {
5048                 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5049                 return ERR_NOT_IMPLEMENTED;
5050         }
5051
5052         DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5053
5054         ss_req = g_new0 (SingleStepReq, 1);
5055         ss_req->req = req;
5056         ss_req->thread = thread;
5057         ss_req->size = size;
5058         ss_req->depth = depth;
5059         req->info = ss_req;
5060
5061         mono_loader_lock ();
5062         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5063         mono_loader_unlock ();
5064         g_assert (tls);
5065         g_assert (tls->context.valid);
5066         ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5067
5068         if (tls->catch_state.valid) {
5069                 gboolean res;
5070                 StackFrameInfo frame;
5071                 MonoContext new_ctx;
5072                 MonoLMF *lmf = NULL;
5073
5074                 /*
5075                  * We are stopped at a throw site. Stepping should go to the catch site.
5076                  */
5077
5078                 /* Find the the jit info for the catch context */
5079                 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);
5080                 g_assert (res);
5081                 g_assert (frame.type == FRAME_TYPE_MANAGED);
5082
5083                 /*
5084                  * Find the seq point corresponding to the landing site ip, which is the first seq
5085                  * point after ip.
5086                  */
5087                 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5088                 if (!sp)
5089                         no_seq_points_found (frame.method);
5090                 g_assert (sp);
5091
5092                 method = frame.method;
5093
5094                 step_to_catch = TRUE;
5095                 /* This make sure the seq point is not skipped by process_single_step () */
5096                 ss_req->last_sp = NULL;
5097         }
5098
5099         if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5100                 StackFrame *frame;
5101
5102                 /* Compute the initial line info */
5103                 compute_frame_info (thread, tls);
5104
5105                 if (tls->frame_count) {
5106                         frame = tls->frames [0];
5107
5108                         ss_req->last_method = frame->method;
5109                         ss_req->last_line = -1;
5110
5111                         minfo = mono_debug_lookup_method (frame->method);
5112                         if (minfo && frame->il_offset != -1) {
5113                                 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5114
5115                                 if (loc) {
5116                                         ss_req->last_line = loc->row;
5117                                         g_free (loc);
5118                                 }
5119                         }
5120                 }
5121         }
5122
5123         if (!step_to_catch) {
5124                 StackFrame *frame;
5125
5126                 compute_frame_info (thread, tls);
5127
5128                 if (tls->frame_count) {
5129                         frame = tls->frames [0];
5130
5131                         if (!method && frame->il_offset != -1) {
5132                                 /* FIXME: Sort the table and use a binary search */
5133                                 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5134                                 if (!sp)
5135                                         no_seq_points_found (frame->method);
5136                                 g_assert (sp);
5137                                 method = frame->method;
5138                         }
5139                 }
5140         }
5141
5142         ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5143
5144         return 0;
5145 }
5146
5147 static void
5148 ss_destroy (SingleStepReq *req)
5149 {
5150         // FIXME: Locking
5151         g_assert (ss_req == req);
5152
5153         ss_stop (ss_req);
5154
5155         g_free (ss_req);
5156         ss_req = NULL;
5157 }
5158
5159 /*
5160  * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5161  */
5162 void
5163 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5164 {
5165         int suspend_policy;
5166         GSList *events;
5167         EventInfo ei;
5168
5169         if (!agent_config.enabled)
5170                 return;
5171
5172         mono_loader_lock ();
5173         events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5174         mono_loader_unlock ();
5175
5176         ei.level = level;
5177         ei.category = category ? mono_string_to_utf8 (category) : NULL;
5178         ei.message = message ? mono_string_to_utf8 (message) : NULL;
5179
5180         process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5181
5182         g_free (ei.category);
5183         g_free (ei.message);
5184 }
5185
5186 gboolean
5187 mono_debugger_agent_debug_log_is_enabled (void)
5188 {
5189         /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5190         return agent_config.enabled;
5191 }
5192
5193 #ifdef PLATFORM_ANDROID
5194 void
5195 mono_debugger_agent_unhandled_exception (MonoException *exc)
5196 {
5197         int suspend_policy;
5198         GSList *events;
5199         EventInfo ei;
5200
5201         if (!inited)
5202                 return;
5203
5204         memset (&ei, 0, sizeof (EventInfo));
5205         ei.exc = (MonoObject*)exc;
5206
5207         mono_loader_lock ();
5208         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5209         mono_loader_unlock ();
5210
5211         process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5212 }
5213 #endif
5214
5215 void
5216 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx, 
5217                                       MonoContext *catch_ctx)
5218 {
5219         int i, j, suspend_policy;
5220         GSList *events;
5221         MonoJitInfo *ji, *catch_ji;
5222         EventInfo ei;
5223         DebuggerTlsData *tls = NULL;
5224
5225         if (thread_to_tls != NULL) {
5226                 MonoInternalThread *thread = mono_thread_internal_current ();
5227
5228                 mono_loader_lock ();
5229                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5230                 mono_loader_unlock ();
5231
5232                 if (tls && tls->abort_requested)
5233                         return;
5234                 if (tls && tls->disable_breakpoints)
5235                         return;
5236         }
5237
5238         memset (&ei, 0, sizeof (EventInfo));
5239
5240         /* Just-In-Time debugging */
5241         if (!catch_ctx) {
5242                 if (agent_config.onuncaught && !inited) {
5243                         finish_agent_init (FALSE);
5244
5245                         /*
5246                          * Send an unsolicited EXCEPTION event with a dummy request id.
5247                          */
5248                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5249                         ei.exc = (MonoObject*)exc;
5250                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5251                         return;
5252                 }
5253         } else if (agent_config.onthrow && !inited) {
5254                 GSList *l;
5255                 gboolean found = FALSE;
5256
5257                 for (l = agent_config.onthrow; l; l = l->next) {
5258                         char *ex_type = l->data;
5259                         char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5260
5261                         if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5262                                 found = TRUE;
5263
5264                         g_free (f);
5265                 }
5266
5267                 if (found) {
5268                         finish_agent_init (FALSE);
5269
5270                         /*
5271                          * Send an unsolicited EXCEPTION event with a dummy request id.
5272                          */
5273                         events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5274                         ei.exc = (MonoObject*)exc;
5275                         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5276                         return;
5277                 }
5278         }
5279
5280         if (!inited)
5281                 return;
5282
5283         ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5284         if (catch_ctx)
5285                 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5286         else
5287                 catch_ji = NULL;
5288
5289         ei.exc = (MonoObject*)exc;
5290         ei.caught = catch_ctx != NULL;
5291
5292         mono_loader_lock ();
5293
5294         /* Treat exceptions which are caught in non-user code as unhandled */
5295         for (i = 0; i < event_requests->len; ++i) {
5296                 EventRequest *req = g_ptr_array_index (event_requests, i);
5297                 if (req->event_kind != EVENT_KIND_EXCEPTION)
5298                         continue;
5299
5300                 for (j = 0; j < req->nmodifiers; ++j) {
5301                         Modifier *mod = &req->modifiers [j];
5302
5303                         if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5304                                 int k;
5305                                 gboolean found = FALSE;
5306                                 MonoAssembly **assemblies = mod->data.assemblies;
5307
5308                                 if (assemblies) {
5309                                         for (k = 0; assemblies [k]; ++k)
5310                                                 if (assemblies [k] == catch_ji->method->klass->image->assembly)
5311                                                         found = TRUE;
5312                                 }
5313                                 if (!found)
5314                                         ei.caught = FALSE;
5315                         }
5316                 }
5317         }
5318
5319         events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5320         mono_loader_unlock ();
5321
5322         if (tls && ei.caught && catch_ctx) {
5323                 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5324                 tls->catch_state.ctx = *catch_ctx;
5325                 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5326                 tls->catch_state.valid = TRUE;
5327         }
5328
5329         process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5330
5331         if (tls)
5332                 tls->catch_state.valid = FALSE;
5333 }
5334
5335 void
5336 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5337 {
5338         DebuggerTlsData *tls;
5339
5340         if (!inited)
5341                 return;
5342
5343         tls = mono_native_tls_get_value (debugger_tls_id);
5344         if (!tls)
5345                 return;
5346
5347         /*
5348          * We're about to invoke an exception filter during the first pass of exception handling.
5349          *
5350          * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5351          * 'orig_ctx' is the context where the exception has been thrown.
5352          *
5353          *
5354          * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5355          *
5356          * If we're stopped in Filter(), normal stack unwinding would first unwind to
5357          * the call site (line 37) and then continue to Main(), but it would never
5358          * include the throw site (line 32).
5359          *
5360          * Since exception filters are invoked during the first pass of exception handling,
5361          * the stack frames of the throw site are still intact, so we should include them
5362          * in a stack trace.
5363          *
5364          * We do this here by saving the context of the throw site in 'tls->filter_state'.
5365          *
5366          * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5367          * but report the location of the 'throw' to the user.
5368          *
5369          */
5370
5371         g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5372 }
5373
5374 void
5375 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5376 {
5377         DebuggerTlsData *tls;
5378
5379         if (!inited)
5380                 return;
5381
5382         tls = mono_native_tls_get_value (debugger_tls_id);
5383         if (!tls)
5384                 return;
5385
5386         tls->filter_state.valid = FALSE;
5387 }
5388
5389 /*
5390  * buffer_add_value_full:
5391  *
5392  *   Add the encoding of the value at ADDR described by T to the buffer.
5393  * AS_VTYPE determines whenever to treat primitive types as primitive types or
5394  * vtypes.
5395  */
5396 static void
5397 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5398                                            gboolean as_vtype)
5399 {
5400         MonoObject *obj;
5401
5402         if (t->byref) {
5403                 if (!(*(void**)addr)) {
5404                         /* This can happen with compiler generated locals */
5405                         //printf ("%s\n", mono_type_full_name (t));
5406                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5407                         return;
5408                 }
5409                 g_assert (*(void**)addr);
5410                 addr = *(void**)addr;
5411         }
5412
5413         if (as_vtype) {
5414                 switch (t->type) {
5415                 case MONO_TYPE_BOOLEAN:
5416                 case MONO_TYPE_I1:
5417                 case MONO_TYPE_U1:
5418                 case MONO_TYPE_CHAR:
5419                 case MONO_TYPE_I2:
5420                 case MONO_TYPE_U2:
5421                 case MONO_TYPE_I4:
5422                 case MONO_TYPE_U4:
5423                 case MONO_TYPE_R4:
5424                 case MONO_TYPE_I8:
5425                 case MONO_TYPE_U8:
5426                 case MONO_TYPE_R8:
5427                 case MONO_TYPE_I:
5428                 case MONO_TYPE_U:
5429                 case MONO_TYPE_PTR:
5430                         goto handle_vtype;
5431                         break;
5432                 default:
5433                         break;
5434                 }
5435         }
5436
5437         switch (t->type) {
5438         case MONO_TYPE_VOID:
5439                 buffer_add_byte (buf, t->type);
5440                 break;
5441         case MONO_TYPE_BOOLEAN:
5442         case MONO_TYPE_I1:
5443         case MONO_TYPE_U1:
5444                 buffer_add_byte (buf, t->type);
5445                 buffer_add_int (buf, *(gint8*)addr);
5446                 break;
5447         case MONO_TYPE_CHAR:
5448         case MONO_TYPE_I2:
5449         case MONO_TYPE_U2:
5450                 buffer_add_byte (buf, t->type);
5451                 buffer_add_int (buf, *(gint16*)addr);
5452                 break;
5453         case MONO_TYPE_I4:
5454         case MONO_TYPE_U4:
5455         case MONO_TYPE_R4:
5456                 buffer_add_byte (buf, t->type);
5457                 buffer_add_int (buf, *(gint32*)addr);
5458                 break;
5459         case MONO_TYPE_I8:
5460         case MONO_TYPE_U8:
5461         case MONO_TYPE_R8:
5462                 buffer_add_byte (buf, t->type);
5463                 buffer_add_long (buf, *(gint64*)addr);
5464                 break;
5465         case MONO_TYPE_I:
5466         case MONO_TYPE_U:
5467                 /* Treat it as a vtype */
5468                 goto handle_vtype;
5469         case MONO_TYPE_PTR: {
5470                 gssize val = *(gssize*)addr;
5471                 
5472                 buffer_add_byte (buf, t->type);
5473                 buffer_add_long (buf, val);
5474                 break;
5475         }
5476         handle_ref:
5477         case MONO_TYPE_STRING:
5478         case MONO_TYPE_SZARRAY:
5479         case MONO_TYPE_OBJECT:
5480         case MONO_TYPE_CLASS:
5481         case MONO_TYPE_ARRAY:
5482                 obj = *(MonoObject**)addr;
5483
5484                 if (!obj) {
5485                         buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5486                 } else {
5487                         if (obj->vtable->klass->valuetype) {
5488                                 t = &obj->vtable->klass->byval_arg;
5489                                 addr = mono_object_unbox (obj);
5490                                 goto handle_vtype;
5491                         } else if (obj->vtable->klass->rank) {
5492                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5493                         } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5494                                 buffer_add_byte (buf, MONO_TYPE_CLASS);
5495                         } else {
5496                                 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5497                         }
5498                         buffer_add_objid (buf, obj);
5499                 }
5500                 break;
5501         handle_vtype:
5502         case MONO_TYPE_VALUETYPE: {
5503                 int nfields;
5504                 gpointer iter;
5505                 MonoClassField *f;
5506                 MonoClass *klass = mono_class_from_mono_type (t);
5507
5508                 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5509                 buffer_add_byte (buf, klass->enumtype);
5510                 buffer_add_typeid (buf, domain, klass);
5511
5512                 nfields = 0;
5513                 iter = NULL;
5514                 while ((f = mono_class_get_fields (klass, &iter))) {
5515                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5516                                 continue;
5517                         if (mono_field_is_deleted (f))
5518                                 continue;
5519                         nfields ++;
5520                 }
5521                 buffer_add_int (buf, nfields);
5522
5523                 iter = NULL;
5524                 while ((f = mono_class_get_fields (klass, &iter))) {
5525                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5526                                 continue;
5527                         if (mono_field_is_deleted (f))
5528                                 continue;
5529                         buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5530                 }
5531                 break;
5532         }
5533         case MONO_TYPE_GENERICINST:
5534                 if (mono_type_generic_inst_is_valuetype (t)) {
5535                         goto handle_vtype;
5536                 } else {
5537                         goto handle_ref;
5538                 }
5539                 break;
5540         default:
5541                 NOT_IMPLEMENTED;
5542         }
5543 }
5544
5545 static void
5546 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5547 {
5548         buffer_add_value_full (buf, t, addr, domain, FALSE);
5549 }
5550
5551 static gboolean
5552 obj_is_of_type (MonoObject *obj, MonoType *t)
5553 {
5554         MonoClass *klass = obj->vtable->klass;
5555         if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5556                 if (mono_class_is_transparent_proxy (klass)) {
5557                         klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5558                         if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5559                                 return TRUE;
5560                         }
5561                 }
5562                 return FALSE;
5563         }
5564         return TRUE;
5565 }
5566
5567 static ErrorCode
5568 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5569
5570 static ErrorCode
5571 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5572 {
5573         int err;
5574
5575         if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5576                 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5577                 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5578                 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5579                 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5580                 char *name = mono_type_full_name (t);
5581                 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5582                 g_free (name);
5583                 return ERR_INVALID_ARGUMENT;
5584         }
5585
5586         switch (t->type) {
5587         case MONO_TYPE_BOOLEAN:
5588                 *(guint8*)addr = decode_int (buf, &buf, limit);
5589                 break;
5590         case MONO_TYPE_CHAR:
5591                 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5592                 break;
5593         case MONO_TYPE_I1:
5594                 *(gint8*)addr = decode_int (buf, &buf, limit);
5595                 break;
5596         case MONO_TYPE_U1:
5597                 *(guint8*)addr = decode_int (buf, &buf, limit);
5598                 break;
5599         case MONO_TYPE_I2:
5600                 *(gint16*)addr = decode_int (buf, &buf, limit);
5601                 break;
5602         case MONO_TYPE_U2:
5603                 *(guint16*)addr = decode_int (buf, &buf, limit);
5604                 break;
5605         case MONO_TYPE_I4:
5606                 *(gint32*)addr = decode_int (buf, &buf, limit);
5607                 break;
5608         case MONO_TYPE_U4:
5609                 *(guint32*)addr = decode_int (buf, &buf, limit);
5610                 break;
5611         case MONO_TYPE_I8:
5612                 *(gint64*)addr = decode_long (buf, &buf, limit);
5613                 break;
5614         case MONO_TYPE_U8:
5615                 *(guint64*)addr = decode_long (buf, &buf, limit);
5616                 break;
5617         case MONO_TYPE_R4:
5618                 *(guint32*)addr = decode_int (buf, &buf, limit);
5619                 break;
5620         case MONO_TYPE_R8:
5621                 *(guint64*)addr = decode_long (buf, &buf, limit);
5622                 break;
5623         case MONO_TYPE_PTR:
5624                 /* We send these as I8, so we get them back as such */
5625                 g_assert (type == MONO_TYPE_I8);
5626                 *(gssize*)addr = decode_long (buf, &buf, limit);
5627                 break;
5628         case MONO_TYPE_GENERICINST:
5629                 if (MONO_TYPE_ISSTRUCT (t)) {
5630                         /* The client sends these as a valuetype */
5631                         goto handle_vtype;
5632                 } else {
5633                         goto handle_ref;
5634                 }
5635                 break;
5636         case MONO_TYPE_I:
5637         case MONO_TYPE_U:
5638                 /* We send these as vtypes, so we get them back as such */
5639                 g_assert (type == MONO_TYPE_VALUETYPE);
5640                 /* Fall through */
5641                 handle_vtype:
5642         case MONO_TYPE_VALUETYPE: {
5643                 gboolean is_enum = decode_byte (buf, &buf, limit);
5644                 MonoClass *klass;
5645                 MonoClassField *f;
5646                 int nfields;
5647                 gpointer iter = NULL;
5648                 MonoDomain *d;
5649
5650                 /* Enums are sent as a normal vtype */
5651                 if (is_enum)
5652                         return ERR_NOT_IMPLEMENTED;
5653                 klass = decode_typeid (buf, &buf, limit, &d, &err);
5654                 if (err)
5655                         return err;
5656
5657                 if (klass != mono_class_from_mono_type (t))
5658                         return ERR_INVALID_ARGUMENT;
5659
5660                 nfields = decode_int (buf, &buf, limit);
5661                 while ((f = mono_class_get_fields (klass, &iter))) {
5662                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5663                                 continue;
5664                         if (mono_field_is_deleted (f))
5665                                 continue;
5666                         err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5667                         if (err)
5668                                 return err;
5669                         nfields --;
5670                 }
5671                 g_assert (nfields == 0);
5672                 break;
5673         }
5674         handle_ref:
5675         default:
5676                 if (MONO_TYPE_IS_REFERENCE (t)) {
5677                         if (type == MONO_TYPE_OBJECT) {
5678                                 int objid = decode_objid (buf, &buf, limit);
5679                                 int err;
5680                                 MonoObject *obj;
5681
5682                                 err = get_object (objid, (MonoObject**)&obj);
5683                                 if (err)
5684                                         return err;
5685
5686                                 if (obj) {
5687                                         if (!obj_is_of_type (obj, t)) {
5688                                                 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5689                                                 return ERR_INVALID_ARGUMENT;
5690                                         }
5691                                 }
5692                                 if (obj && obj->vtable->domain != domain)
5693                                         return ERR_INVALID_ARGUMENT;
5694
5695                                 mono_gc_wbarrier_generic_store (addr, obj);
5696                         } else if (type == VALUE_TYPE_ID_NULL) {
5697                                 *(MonoObject**)addr = NULL;
5698                         } else {
5699                                 return ERR_INVALID_ARGUMENT;
5700                         }
5701                 } else {
5702                         NOT_IMPLEMENTED;
5703                 }
5704                 break;
5705         }
5706
5707         *endbuf = buf;
5708
5709         return 0;
5710 }
5711
5712 static ErrorCode
5713 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5714 {
5715         int err;
5716         int type = decode_byte (buf, &buf, limit);
5717
5718         if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5719                 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5720                 guint8 *nullable_buf;
5721
5722                 /*
5723                  * First try decoding it as a Nullable`1
5724                  */
5725                 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5726                 if (!err)
5727                         return err;
5728
5729                 /*
5730                  * Then try decoding as a primitive value or null.
5731                  */
5732                 if (targ->type == type) {
5733                         nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5734                         err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5735                         if (err) {
5736                                 g_free (nullable_buf);
5737                                 return err;
5738                         }
5739                         mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5740                         g_free (nullable_buf);
5741                         *endbuf = buf;
5742                         return ERR_NONE;
5743                 } else if (type == VALUE_TYPE_ID_NULL) {
5744                         mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5745                         *endbuf = buf;
5746                         return ERR_NONE;
5747                 }
5748         }
5749
5750         return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5751 }
5752
5753 static void
5754 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5755 {
5756         guint32 flags;
5757         int reg;
5758         guint8 *addr;
5759         mgreg_t reg_val;
5760
5761         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5762         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5763
5764         switch (flags) {
5765         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5766                 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5767
5768                 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype);
5769                 break;
5770         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5771                 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5772                 addr += (gint32)var->offset;
5773
5774                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5775
5776                 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5777                 break;
5778         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5779                 NOT_IMPLEMENTED;
5780                 break;
5781         default:
5782                 g_assert_not_reached ();
5783         }
5784 }
5785
5786 static void
5787 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5788 {
5789         guint32 flags;
5790         int reg, size;
5791         guint8 *addr;
5792
5793         flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5794         reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5795
5796         if (MONO_TYPE_IS_REFERENCE (t))
5797                 size = sizeof (gpointer);
5798         else
5799                 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5800
5801         switch (flags) {
5802         case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5803 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5804                 mgreg_t v;
5805                 gboolean is_signed = FALSE;
5806
5807                 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5808                         is_signed = TRUE;
5809
5810                 switch (size) {
5811                 case 1:
5812                         v = is_signed ? *(gint8*)val : *(guint8*)val;
5813                         break;
5814                 case 2:
5815                         v = is_signed ? *(gint16*)val : *(guint16*)val;
5816                         break;
5817                 case 4:
5818                         v = is_signed ? *(gint32*)val : *(guint32*)val;
5819                         break;
5820                 case 8:
5821                         v = is_signed ? *(gint64*)val : *(guint64*)val;
5822                         break;
5823                 default:
5824                         g_assert_not_reached ();
5825                 }
5826
5827                 if (t->byref)
5828                         NOT_IMPLEMENTED;
5829
5830                 /* Set value on the stack or in the return ctx */
5831                 if (reg_locations [reg]) {
5832                         /* Saved on the stack */
5833                         DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5834                         *(reg_locations [reg]) = v;
5835                 } else {
5836                         /* Not saved yet */
5837                         DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5838                         mono_arch_context_set_int_reg (restore_ctx, reg, v);
5839                 }                       
5840
5841                 // FIXME: Move these to mono-context.h/c.
5842                 mono_arch_context_set_int_reg (ctx, reg, v);
5843 #else
5844                 // FIXME: Can't set registers, so we disable linears
5845                 NOT_IMPLEMENTED;
5846 #endif
5847                 break;
5848         }
5849         case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5850                 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5851                 addr += (gint32)var->offset;
5852
5853                 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5854
5855                 if (t->byref) {
5856                         addr = *(guint8**)addr;
5857
5858                         if (!addr)
5859                                 break;
5860                 }
5861                         
5862                 // FIXME: Write barriers
5863                 mono_gc_memmove (addr, val, size);
5864                 break;
5865         case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5866                 NOT_IMPLEMENTED;
5867                 break;
5868         default:
5869                 g_assert_not_reached ();
5870         }
5871 }
5872
5873 static void
5874 clear_event_request (int req_id, int etype)
5875 {
5876         int i;
5877
5878         mono_loader_lock ();
5879         for (i = 0; i < event_requests->len; ++i) {
5880                 EventRequest *req = g_ptr_array_index (event_requests, i);
5881
5882                 if (req->id == req_id && req->event_kind == etype) {
5883                         if (req->event_kind == EVENT_KIND_BREAKPOINT)
5884                                 clear_breakpoint (req->info);
5885                         if (req->event_kind == EVENT_KIND_STEP)
5886                                 ss_destroy (req->info);
5887                         if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5888                                 clear_breakpoint (req->info);
5889                         if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5890                                 clear_breakpoint (req->info);
5891                         g_ptr_array_remove_index_fast (event_requests, i);
5892                         g_free (req);
5893                         break;
5894                 }
5895         }
5896         mono_loader_unlock ();
5897 }
5898
5899 static gboolean
5900 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5901 {
5902         if (req->event_kind == EVENT_KIND_BREAKPOINT)
5903                 return breakpoint_matches_assembly (req->info, assembly);
5904         else {
5905                 int i, j;
5906
5907                 for (i = 0; i < req->nmodifiers; ++i) {
5908                         Modifier *m = &req->modifiers [i];
5909
5910                         if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5911                                 return TRUE;
5912                         if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5913                                 for (j = 0; m->data.assemblies [j]; ++j)
5914                                         if (m->data.assemblies [j] == assembly)
5915                                                 return TRUE;
5916                         }
5917                 }
5918         }
5919
5920         return FALSE;
5921 }
5922
5923 /*
5924  * clear_event_requests_for_assembly:
5925  *
5926  *   Clear all events requests which reference ASSEMBLY.
5927  */
5928 static void
5929 clear_event_requests_for_assembly (MonoAssembly *assembly)
5930 {
5931         int i;
5932         gboolean found;
5933
5934         mono_loader_lock ();
5935         found = TRUE;
5936         while (found) {
5937                 found = FALSE;
5938                 for (i = 0; i < event_requests->len; ++i) {
5939                         EventRequest *req = g_ptr_array_index (event_requests, i);
5940
5941                         if (event_req_matches_assembly (req, assembly)) {
5942                                 clear_event_request (req->id, req->event_kind);
5943                                 found = TRUE;
5944                                 break;
5945                         }
5946                 }
5947         }
5948         mono_loader_unlock ();
5949 }
5950
5951 /*
5952  * type_comes_from_assembly:
5953  *
5954  *   GHRFunc that returns TRUE if klass comes from assembly
5955  */
5956 static gboolean
5957 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5958 {
5959         return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5960 }
5961
5962 /*
5963  * clear_types_for_assembly:
5964  *
5965  *   Clears types from loaded_classes for a given assembly
5966  */
5967 static void
5968 clear_types_for_assembly (MonoAssembly *assembly)
5969 {
5970         MonoDomain *domain = mono_domain_get ();
5971         AgentDomainInfo *info = NULL;
5972
5973         mono_loader_lock ();
5974         info = get_agent_domain_info (domain);
5975         g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5976         mono_loader_unlock ();
5977 }
5978
5979 static void
5980 add_thread (gpointer key, gpointer value, gpointer user_data)
5981 {
5982         MonoInternalThread *thread = value;
5983         Buffer *buf = user_data;
5984
5985         buffer_add_objid (buf, (MonoObject*)thread);
5986 }
5987
5988 static ErrorCode
5989 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5990 {
5991         guint8 *end = invoke->endp;
5992         MonoMethod *m;
5993         int i, err, nargs;
5994         MonoMethodSignature *sig;
5995         guint8 **arg_buf;
5996         void **args;
5997         MonoObject *this, *res, *exc;
5998         MonoDomain *domain;
5999         guint8 *this_buf;
6000 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6001         MonoLMFExt ext;
6002 #endif
6003         MonoStopwatch watch;
6004
6005         if (invoke->method) {
6006                 /* 
6007                  * Invoke this method directly, currently only Environment.Exit () is supported.
6008                  */
6009                 this = NULL;
6010                 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>"));
6011                 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6012                 g_assert_not_reached ();
6013         }
6014
6015         m = decode_methodid (p, &p, end, &domain, &err);
6016         if (err)
6017                 return err;
6018         sig = mono_method_signature (m);
6019
6020         if (m->klass->valuetype)
6021                 this_buf = g_alloca (mono_class_instance_size (m->klass));
6022         else
6023                 this_buf = g_alloca (sizeof (MonoObject*));
6024         if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6025                 /* Should be null */
6026                 int type = decode_byte (p, &p, end);
6027                 if (type != VALUE_TYPE_ID_NULL)
6028                         return ERR_INVALID_ARGUMENT;
6029                 memset (this_buf, 0, mono_class_instance_size (m->klass));
6030         } else {
6031                 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6032                 if (err)
6033                         return err;
6034         }
6035
6036         if (!m->klass->valuetype)
6037                 this = *(MonoObject**)this_buf;
6038         else
6039                 this = NULL;
6040
6041         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>"));
6042
6043         if (this && this->vtable->domain != domain)
6044                 NOT_IMPLEMENTED;
6045
6046         if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6047                 if (!strcmp (m->name, ".ctor")) {
6048                         if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6049                                 return ERR_INVALID_ARGUMENT;
6050                         else
6051                                 this = mono_object_new (domain, m->klass);
6052                 } else {
6053                         return ERR_INVALID_ARGUMENT;
6054                 }
6055         }
6056
6057         if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6058                 return ERR_INVALID_ARGUMENT;
6059
6060         nargs = decode_int (p, &p, end);
6061         if (nargs != sig->param_count)
6062                 return ERR_INVALID_ARGUMENT;
6063         /* Use alloca to get gc tracking */
6064         arg_buf = g_alloca (nargs * sizeof (gpointer));
6065         memset (arg_buf, 0, nargs * sizeof (gpointer));
6066         args = g_alloca (nargs * sizeof (gpointer));
6067         for (i = 0; i < nargs; ++i) {
6068                 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6069                         err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6070                         if (err)
6071                                 break;
6072
6073                         if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6074                                 NOT_IMPLEMENTED;
6075                 } else {
6076                         arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6077                         err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6078                         if (err)
6079                                 break;
6080                         args [i] = arg_buf [i];
6081                 }
6082         }
6083
6084         if (i < nargs)
6085                 return err;
6086
6087         if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6088                 tls->disable_breakpoints = TRUE;
6089         else
6090                 tls->disable_breakpoints = FALSE;
6091
6092         /* 
6093          * Add an LMF frame to link the stack frames on the invoke method with our caller.
6094          */
6095         /* FIXME: Move this to arch specific code */
6096 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6097         if (invoke->has_ctx) {
6098                 MonoLMF **lmf_addr;
6099
6100                 lmf_addr = mono_get_lmf_addr ();
6101
6102                 /* Setup our lmf */
6103                 memset (&ext, 0, sizeof (ext));
6104 #ifdef TARGET_AMD64
6105                 ext.lmf.previous_lmf = *(lmf_addr);
6106                 /* Mark that this is a MonoLMFExt */
6107                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6108                 ext.lmf.rsp = (gssize)&ext;
6109 #elif defined(TARGET_X86)
6110                 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6111                 /* Mark that this is a MonoLMFExt */
6112                 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6113                 ext.lmf.ebp = (gssize)&ext;
6114 #elif defined(TARGET_ARM)
6115                 ext.lmf.previous_lmf = *(lmf_addr);
6116                 /* Mark that this is a MonoLMFExt */
6117                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6118                 ext.lmf.sp = (gssize)&ext;
6119 #elif defined(TARGET_POWERPC)
6120                 ext.lmf.previous_lmf = *(lmf_addr);
6121                 /* Mark that this is a MonoLMFExt */
6122                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6123                 ext.lmf.ebp = (gssize)&ext;
6124 #elif defined(TARGET_S390X)
6125                 ext.lmf.previous_lmf = *(lmf_addr);
6126                 /* Mark that this is a MonoLMFExt */
6127                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6128                 ext.lmf.ebp = (gssize)&ext;
6129 #elif defined(TARGET_MIPS)
6130                 ext.lmf.previous_lmf = *(lmf_addr);
6131                 /* Mark that this is a MonoLMFExt */
6132                 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6133                 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6134 #else
6135                 g_assert_not_reached ();
6136 #endif
6137
6138                 ext.debugger_invoke = TRUE;
6139                 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6140
6141                 mono_set_lmf ((MonoLMF*)&ext);
6142         }
6143 #endif
6144
6145         mono_stopwatch_start (&watch);
6146         if (m->klass->valuetype)
6147                 res = mono_runtime_invoke (m, this_buf, args, &exc);
6148         else
6149                 res = mono_runtime_invoke (m, this, args, &exc);
6150         mono_stopwatch_stop (&watch);
6151         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)));
6152         if (exc) {
6153                 buffer_add_byte (buf, 0);
6154                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6155         } else {
6156                 buffer_add_byte (buf, 1);
6157                 if (sig->ret->type == MONO_TYPE_VOID) {
6158                         if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6159                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6160                         }
6161                         else
6162                                 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6163                 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6164                         buffer_add_value (buf, sig->ret, &res, domain);
6165                 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6166                         if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6167                                 MonoClass *k = mono_class_from_mono_type (sig->ret);
6168                                 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6169
6170                                 g_assert (nullable_buf);
6171                                 mono_nullable_init (nullable_buf, res, k);
6172                                 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6173                         } else {
6174                                 g_assert (res);
6175                                 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6176                         }
6177                 } else {
6178                         NOT_IMPLEMENTED;
6179                 }
6180         }
6181
6182         tls->disable_breakpoints = FALSE;
6183
6184 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6185         if (invoke->has_ctx)
6186                 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6187 #endif
6188
6189         *endp = p;
6190         // FIXME: byref arguments
6191         // FIXME: varargs
6192         return ERR_NONE;
6193 }
6194
6195 /*
6196  * invoke_method:
6197  *
6198  *   Invoke the method given by tls->pending_invoke in the current thread.
6199  */
6200 static void
6201 invoke_method (void)
6202 {
6203         DebuggerTlsData *tls;
6204         InvokeData *invoke;
6205         int id;
6206         int i, err, mindex;
6207         Buffer buf;
6208         static void (*restore_context) (void *);
6209         MonoContext restore_ctx;
6210         guint8 *p;
6211
6212         if (!restore_context)
6213                 restore_context = mono_get_restore_context ();
6214
6215         tls = mono_native_tls_get_value (debugger_tls_id);
6216         g_assert (tls);
6217
6218         /*
6219          * Store the `InvokeData *' in `tls->invoke' until we're done with
6220          * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6221          */
6222
6223         mono_loader_lock ();
6224
6225         invoke = tls->pending_invoke;
6226         g_assert (invoke);
6227         tls->pending_invoke = NULL;
6228
6229         invoke->last_invoke = tls->invoke;
6230         tls->invoke = invoke;
6231
6232         mono_loader_unlock ();
6233
6234         tls->frames_up_to_date = FALSE;
6235
6236         id = invoke->id;
6237
6238         p = invoke->p;
6239         err = 0;
6240         for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6241                 buffer_init (&buf, 128);
6242
6243                 if (err) {
6244                         /* Fail the other invokes as well */
6245                 } else {
6246                         err = do_invoke_method (tls, &buf, invoke, p, &p);
6247                 }
6248
6249                 /* Start suspending before sending the reply */
6250                 if (mindex == invoke->nmethods - 1) {
6251                         if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6252                                 for (i = 0; i < invoke->suspend_count; ++i)
6253                                         suspend_vm ();
6254                         }
6255                 }
6256
6257                 send_reply_packet (id, err, &buf);
6258         
6259                 buffer_free (&buf);
6260         }
6261
6262         memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6263
6264         if (invoke->has_ctx)
6265                 save_thread_context (&restore_ctx);
6266
6267         if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6268                 g_assert (tls->resume_count);
6269                 tls->resume_count -= invoke->suspend_count;
6270         }
6271
6272         DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6273
6274         /*
6275          * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6276          *
6277          * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6278          * after the mono_runtime_invoke() already returned, but it doesn't matter
6279          * because we reset the abort here.
6280          */
6281
6282         mono_loader_lock ();
6283
6284         if (tls->abort_requested)
6285                 mono_thread_internal_reset_abort (tls->thread);
6286
6287         tls->invoke = tls->invoke->last_invoke;
6288         tls->abort_requested = FALSE;
6289
6290         mono_loader_unlock ();
6291
6292         g_free (invoke->p);
6293         g_free (invoke);
6294
6295         suspend_current ();
6296 }
6297
6298 static gboolean
6299 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6300 {
6301         MonoThread *thread = value;
6302         DebuggerTlsData *tls;
6303         gboolean res;
6304
6305         mono_loader_lock ();
6306         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6307         g_assert (tls);
6308         res = tls->really_suspended;
6309         mono_loader_unlock ();
6310
6311         return res;
6312 }
6313
6314 static GPtrArray*
6315 get_source_files_for_type (MonoClass *klass)
6316 {
6317         gpointer iter = NULL;
6318         MonoMethod *method;
6319         MonoDebugSourceInfo *sinfo;
6320         GPtrArray *files;
6321         int i, j;
6322
6323         files = g_ptr_array_new ();
6324
6325         while ((method = mono_class_get_methods (klass, &iter))) {
6326                 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6327                 GPtrArray *source_file_list;
6328
6329                 if (minfo) {
6330                         mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6331                         for (j = 0; j < source_file_list->len; ++j) {
6332                                 sinfo = g_ptr_array_index (source_file_list, j);
6333                                 for (i = 0; i < files->len; ++i)
6334                                         if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6335                                                 break;
6336                                 if (i == files->len)
6337                                         g_ptr_array_add (files, g_strdup (sinfo->source_file));
6338                         }
6339                         g_ptr_array_free (source_file_list, TRUE);
6340                 }
6341         }
6342
6343         return files;
6344 }
6345
6346 static ErrorCode
6347 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6348 {
6349         switch (command) {
6350         case CMD_VM_VERSION: {
6351                 char *build_info, *version;
6352
6353                 build_info = mono_get_runtime_build_info ();
6354                 version = g_strdup_printf ("mono %s", build_info);
6355
6356                 buffer_add_string (buf, version); /* vm version */
6357                 buffer_add_int (buf, MAJOR_VERSION);
6358                 buffer_add_int (buf, MINOR_VERSION);
6359                 g_free (build_info);
6360                 g_free (version);
6361                 break;
6362         }
6363         case CMD_VM_SET_PROTOCOL_VERSION: {
6364                 major_version = decode_int (p, &p, end);
6365                 minor_version = decode_int (p, &p, end);
6366                 protocol_version_set = TRUE;
6367                 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6368                 break;
6369         }
6370         case CMD_VM_ALL_THREADS: {
6371                 // FIXME: Domains
6372                 mono_loader_lock ();
6373                 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6374                 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6375                 mono_loader_unlock ();
6376                 break;
6377         }
6378         case CMD_VM_SUSPEND:
6379                 suspend_vm ();
6380                 wait_for_suspend ();
6381                 break;
6382         case CMD_VM_RESUME:
6383                 if (suspend_count == 0)
6384                         return ERR_NOT_SUSPENDED;
6385                 resume_vm ();
6386                 clear_suspended_objs ();
6387                 break;
6388         case CMD_VM_DISPOSE:
6389                 /* Clear all event requests */
6390                 mono_loader_lock ();
6391                 while (event_requests->len > 0) {
6392                         EventRequest *req = g_ptr_array_index (event_requests, 0);
6393
6394                         clear_event_request (req->id, req->event_kind);
6395                 }
6396                 mono_loader_unlock ();
6397
6398                 while (suspend_count > 0)
6399                         resume_vm ();
6400                 disconnected = TRUE;
6401                 vm_start_event_sent = FALSE;
6402                 break;
6403         case CMD_VM_EXIT: {
6404                 MonoInternalThread *thread;
6405                 DebuggerTlsData *tls;
6406 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6407                 MonoClass *env_class;
6408 #endif
6409                 MonoMethod *exit_method = NULL;
6410                 gpointer *args;
6411                 int exit_code;
6412
6413                 exit_code = decode_int (p, &p, end);
6414
6415                 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6416
6417                 /* Have to send a reply before exiting */
6418                 send_reply_packet (id, 0, buf);
6419
6420                 /* Clear all event requests */
6421                 mono_loader_lock ();
6422                 while (event_requests->len > 0) {
6423                         EventRequest *req = g_ptr_array_index (event_requests, 0);
6424
6425                         clear_event_request (req->id, req->event_kind);
6426                 }
6427                 mono_loader_unlock ();
6428
6429                 /*
6430                  * The JDWP documentation says that the shutdown is not orderly. It doesn't
6431                  * specify whenever a VM_DEATH event is sent. We currently do an orderly
6432                  * shutdown by hijacking a thread to execute Environment.Exit (). This is
6433                  * better than doing the shutdown ourselves, since it avoids various races.
6434                  */
6435
6436                 suspend_vm ();
6437                 wait_for_suspend ();
6438
6439 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6440                 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6441                 if (env_class)
6442                         exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6443 #endif
6444
6445                 mono_loader_lock ();
6446                 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6447                 mono_loader_unlock ();
6448
6449                 if (thread && exit_method) {
6450                         mono_loader_lock ();
6451                         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6452                         mono_loader_unlock ();
6453
6454                         args = g_new0 (gpointer, 1);
6455                         args [0] = g_malloc (sizeof (int));
6456                         *(int*)(args [0]) = exit_code;
6457
6458                         tls->pending_invoke = g_new0 (InvokeData, 1);
6459                         tls->pending_invoke->method = exit_method;
6460                         tls->pending_invoke->args = args;
6461                         tls->pending_invoke->nmethods = 1;
6462
6463                         while (suspend_count > 0)
6464                                 resume_vm ();
6465                 } else {
6466                         /* 
6467                          * No thread found, do it ourselves.
6468                          * FIXME: This can race with normal shutdown etc.
6469                          */
6470                         while (suspend_count > 0)
6471                                 resume_vm ();
6472
6473                         mono_runtime_shutdown ();
6474
6475                         /* Suspend all managed threads since the runtime is going away */
6476                         DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6477                         mono_thread_suspend_all_other_threads ();
6478                         DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6479                         mono_runtime_quit ();
6480                         transport_close2 ();
6481                         DEBUG(1, fprintf (log_file, "Exiting...\n"));
6482
6483                         exit (exit_code);
6484                 }
6485                 break;
6486         }               
6487         case CMD_VM_INVOKE_METHOD:
6488         case CMD_VM_INVOKE_METHODS: {
6489                 int objid = decode_objid (p, &p, end);
6490                 MonoThread *thread;
6491                 DebuggerTlsData *tls;
6492                 int i, count, err, flags, nmethods;
6493
6494                 err = get_object (objid, (MonoObject**)&thread);
6495                 if (err)
6496                         return err;
6497
6498                 flags = decode_int (p, &p, end);
6499
6500                 if (command == CMD_VM_INVOKE_METHODS)
6501                         nmethods = decode_int (p, &p, end);
6502                 else
6503                         nmethods = 1;
6504
6505                 // Wait for suspending if it already started
6506                 if (suspend_count)
6507                         wait_for_suspend ();
6508                 if (!is_suspended ())
6509                         return ERR_NOT_SUSPENDED;
6510
6511                 mono_loader_lock ();
6512                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6513                 mono_loader_unlock ();
6514                 g_assert (tls);
6515
6516                 if (!tls->really_suspended)
6517                         /* The thread is still running native code, can't do invokes */
6518                         return ERR_NOT_SUSPENDED;
6519
6520                 /* 
6521                  * Store the invoke data into tls, the thread will execute it after it is
6522                  * resumed.
6523                  */
6524                 if (tls->pending_invoke)
6525                         return ERR_NOT_SUSPENDED;
6526                 tls->pending_invoke = g_new0 (InvokeData, 1);
6527                 tls->pending_invoke->id = id;
6528                 tls->pending_invoke->flags = flags;
6529                 tls->pending_invoke->p = g_malloc (end - p);
6530                 memcpy (tls->pending_invoke->p, p, end - p);
6531                 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6532                 tls->pending_invoke->suspend_count = suspend_count;
6533                 tls->pending_invoke->nmethods = nmethods;
6534
6535                 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6536                         resume_thread (THREAD_TO_INTERNAL (thread));
6537                 }
6538                 else {
6539                         count = suspend_count;
6540                         for (i = 0; i < count; ++i)
6541                                 resume_vm ();
6542                 }
6543                 break;
6544         }
6545         case CMD_VM_ABORT_INVOKE: {
6546                 int objid = decode_objid (p, &p, end);
6547                 MonoThread *thread;
6548                 DebuggerTlsData *tls;
6549                 int invoke_id, err;
6550
6551                 err = get_object (objid, (MonoObject**)&thread);
6552                 if (err)
6553                         return err;
6554
6555                 invoke_id = decode_int (p, &p, end);
6556
6557                 mono_loader_lock ();
6558                 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6559                 g_assert (tls);
6560
6561                 if (tls->abort_requested) {
6562                         mono_loader_unlock ();
6563                         break;
6564                 }
6565
6566                 /*
6567                  * Check whether we're still inside the mono_runtime_invoke() and that it's
6568                  * actually the correct invocation.
6569                  *
6570                  * Careful, we do not stop the thread that's doing the invocation, so we can't
6571                  * inspect its stack.  However, invoke_method() also acquires the loader lock
6572                  * when it's done, so we're safe here.
6573                  *
6574                  */
6575
6576                 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6577                         mono_loader_unlock ();
6578                         return ERR_NO_INVOCATION;
6579                 }
6580
6581                 tls->abort_requested = TRUE;
6582
6583                 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6584                 mono_loader_unlock ();
6585                 break;
6586         }
6587
6588         case CMD_VM_SET_KEEPALIVE: {
6589                 int timeout = decode_int (p, &p, end);
6590                 agent_config.keepalive = timeout;
6591                 // FIXME:
6592 #ifndef DISABLE_SOCKET_TRANSPORT
6593                 set_keepalive ();
6594 #else
6595                 NOT_IMPLEMENTED;
6596 #endif
6597                 break;
6598         }
6599         case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6600                 GHashTableIter iter, kiter;
6601                 MonoDomain *domain;
6602                 MonoClass *klass;
6603                 GPtrArray *files;
6604                 int i;
6605                 char *fname, *basename;
6606                 gboolean ignore_case;
6607                 GSList *class_list, *l;
6608                 GPtrArray *res_classes, *res_domains;
6609
6610                 fname = decode_string (p, &p, end);
6611                 ignore_case = decode_byte (p, &p, end);
6612
6613                 basename = g_path_get_basename (fname);
6614
6615                 res_classes = g_ptr_array_new ();
6616                 res_domains = g_ptr_array_new ();
6617
6618                 mono_loader_lock ();
6619                 g_hash_table_iter_init (&iter, domains);
6620                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6621                         AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6622
6623                         /* Update 'source_file_to_class' cache */
6624                         g_hash_table_iter_init (&kiter, info->loaded_classes);
6625                         while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6626                                 if (!g_hash_table_lookup (info->source_files, klass)) {
6627                                         files = get_source_files_for_type (klass);
6628                                         g_hash_table_insert (info->source_files, klass, files);
6629
6630                                         for (i = 0; i < files->len; ++i) {
6631                                                 char *s = g_ptr_array_index (files, i);
6632                                                 char *s2 = g_path_get_basename (s);
6633                                                 char *s3;
6634
6635                                                 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6636                                                 if (!class_list) {
6637                                                         class_list = g_slist_prepend (class_list, klass);
6638                                                         g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6639                                                 } else {
6640                                                         class_list = g_slist_prepend (class_list, klass);
6641                                                         g_hash_table_insert (info->source_file_to_class, s2, class_list);
6642                                                 }
6643
6644                                                 /* The _ignorecase hash contains the lowercase path */
6645                                                 s3 = strdup_tolower (s2);
6646                                                 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6647                                                 if (!class_list) {
6648                                                         class_list = g_slist_prepend (class_list, klass);
6649                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6650                                                 } else {
6651                                                         class_list = g_slist_prepend (class_list, klass);
6652                                                         g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6653                                                 }
6654
6655                                                 g_free (s2);
6656                                                 g_free (s3);
6657                                         }
6658                                 }
6659                         }
6660
6661                         if (ignore_case) {
6662                                 char *s;
6663
6664                                 s = strdup_tolower (basename);
6665                                 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6666                                 g_free (s);
6667                         } else {
6668                                 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6669                         }
6670
6671                         for (l = class_list; l; l = l->next) {
6672                                 klass = l->data;
6673
6674                                 g_ptr_array_add (res_classes, klass);
6675                                 g_ptr_array_add (res_domains, domain);
6676                         }
6677                 }
6678                 mono_loader_unlock ();
6679
6680                 g_free (fname);
6681                 g_free (basename);
6682
6683                 buffer_add_int (buf, res_classes->len);
6684                 for (i = 0; i < res_classes->len; ++i)
6685                         buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6686                 g_ptr_array_free (res_classes, TRUE);
6687                 g_ptr_array_free (res_domains, TRUE);
6688                 break;
6689         }
6690         case CMD_VM_GET_TYPES: {
6691                 GHashTableIter iter;
6692                 MonoDomain *domain;
6693                 int i;
6694                 char *name;
6695                 gboolean ignore_case;
6696                 GPtrArray *res_classes, *res_domains;
6697                 MonoTypeNameParse info;
6698
6699                 name = decode_string (p, &p, end);
6700                 ignore_case = decode_byte (p, &p, end);
6701
6702                 if (!mono_reflection_parse_type (name, &info)) {
6703                         g_free (name);
6704                         mono_reflection_free_type_info (&info);
6705                         return ERR_INVALID_ARGUMENT;
6706                 }
6707
6708                 res_classes = g_ptr_array_new ();
6709                 res_domains = g_ptr_array_new ();
6710
6711                 mono_loader_lock ();
6712                 g_hash_table_iter_init (&iter, domains);
6713                 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6714                         MonoAssembly *ass;
6715                         gboolean type_resolve;
6716                         MonoType *t;
6717                         GSList *tmp;
6718
6719                         mono_domain_assemblies_lock (domain);
6720                         for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6721                                 ass = tmp->data;
6722
6723                                 if (ass->image) {
6724                                         type_resolve = TRUE;
6725                                         t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6726                                         if (t) {
6727                                                 g_ptr_array_add (res_classes, mono_type_get_class (t));
6728                                                 g_ptr_array_add (res_domains, domain);
6729                                         }
6730                                 }
6731                         }
6732                         mono_domain_assemblies_unlock (domain);
6733                 }
6734                 mono_loader_unlock ();
6735
6736                 g_free (name);
6737                 mono_reflection_free_type_info (&info);
6738
6739                 buffer_add_int (buf, res_classes->len);
6740                 for (i = 0; i < res_classes->len; ++i)
6741                         buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6742                 g_ptr_array_free (res_classes, TRUE);
6743                 g_ptr_array_free (res_domains, TRUE);
6744                 break;
6745         }
6746
6747         default:
6748                 return ERR_NOT_IMPLEMENTED;
6749         }
6750
6751         return ERR_NONE;
6752 }
6753
6754 static ErrorCode
6755 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6756 {
6757         int err;
6758         MonoError error;
6759
6760         switch (command) {
6761         case CMD_EVENT_REQUEST_SET: {
6762                 EventRequest *req;
6763                 int i, event_kind, suspend_policy, nmodifiers, mod;
6764                 MonoMethod *method;
6765                 long location = 0;
6766                 MonoThread *step_thread;
6767                 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6768                 MonoDomain *domain;
6769                 Modifier *modifier;
6770
6771                 event_kind = decode_byte (p, &p, end);
6772                 suspend_policy = decode_byte (p, &p, end);
6773                 nmodifiers = decode_byte (p, &p, end);
6774
6775                 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6776                 req->id = InterlockedIncrement (&event_request_id);
6777                 req->event_kind = event_kind;
6778                 req->suspend_policy = suspend_policy;
6779                 req->nmodifiers = nmodifiers;
6780
6781                 method = NULL;
6782                 for (i = 0; i < nmodifiers; ++i) {
6783                         mod = decode_byte (p, &p, end);
6784
6785                         req->modifiers [i].kind = mod;
6786                         if (mod == MOD_KIND_COUNT) {
6787                                 req->modifiers [i].data.count = decode_int (p, &p, end);
6788                         } else if (mod == MOD_KIND_LOCATION_ONLY) {
6789                                 method = decode_methodid (p, &p, end, &domain, &err);
6790                                 if (err)
6791                                         return err;
6792                                 location = decode_long (p, &p, end);
6793                         } else if (mod == MOD_KIND_STEP) {
6794                                 step_thread_id = decode_id (p, &p, end);
6795                                 size = decode_int (p, &p, end);
6796                                 depth = decode_int (p, &p, end);
6797                                 if (CHECK_PROTOCOL_VERSION (2, 16))
6798                                         filter = decode_int (p, &p, end);
6799                                 req->modifiers [i].data.filter = filter;
6800                         } else if (mod == MOD_KIND_THREAD_ONLY) {
6801                                 int id = decode_id (p, &p, end);
6802
6803                                 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6804                                 if (err) {
6805                                         g_free (req);
6806                                         return err;
6807                                 }
6808                         } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6809                                 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6810
6811                                 if (err)
6812                                         return err;
6813                                 req->modifiers [i].caught = decode_byte (p, &p, end);
6814                                 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6815                                 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" : ""));
6816                                 if (exc_class) {
6817                                         req->modifiers [i].data.exc_class = exc_class;
6818
6819                                         if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6820                                                 g_free (req);
6821                                                 return ERR_INVALID_ARGUMENT;
6822                                         }
6823                                 }
6824                         } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6825                                 int n = decode_int (p, &p, end);
6826                                 int j;
6827
6828                                 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6829                                 for (j = 0; j < n; ++j) {
6830                                         req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6831                                         if (err) {
6832                                                 g_free (req->modifiers [i].data.assemblies);
6833                                                 return err;
6834                                         }
6835                                 }
6836                         } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6837                                 int n = decode_int (p, &p, end);
6838                                 int j;
6839
6840                                 modifier = &req->modifiers [i];
6841                                 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6842                                 for (j = 0; j < n; ++j) {
6843                                         char *s = decode_string (p, &p, end);
6844                                         char *s2;
6845
6846                                         if (s) {
6847                                                 s2 = strdup_tolower (s);
6848                                                 g_hash_table_insert (modifier->data.source_files, s2, s2);
6849                                                 g_free (s);
6850                                         }
6851                                 }
6852                         } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6853                                 int n = decode_int (p, &p, end);
6854                                 int j;
6855
6856                                 modifier = &req->modifiers [i];
6857                                 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6858                                 for (j = 0; j < n; ++j) {
6859                                         char *s = decode_string (p, &p, end);
6860
6861                                         if (s)
6862                                                 g_hash_table_insert (modifier->data.type_names, s, s);
6863                                 }
6864                         } else {
6865                                 g_free (req);
6866                                 return ERR_NOT_IMPLEMENTED;
6867                         }
6868                 }
6869
6870                 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6871                         g_assert (method);
6872
6873                         req->info = set_breakpoint (method, location, req, &error);
6874                         if (!mono_error_ok (&error)) {
6875                                 g_free (req);
6876                                 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6877                                 mono_error_cleanup (&error);
6878                                 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6879                         }
6880                 } else if (req->event_kind == EVENT_KIND_STEP) {
6881                         g_assert (step_thread_id);
6882
6883                         err = get_object (step_thread_id, (MonoObject**)&step_thread);
6884                         if (err) {
6885                                 g_free (req);
6886                                 return err;
6887                         }
6888
6889                         err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6890                         if (err) {
6891                                 g_free (req);
6892                                 return err;
6893                         }
6894                 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6895                         req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6896                 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6897                         req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6898                 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6899                 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6900                 } else {
6901                         if (req->nmodifiers) {
6902                                 g_free (req);
6903                                 return ERR_NOT_IMPLEMENTED;
6904                         }
6905                 }
6906
6907                 mono_loader_lock ();
6908                 g_ptr_array_add (event_requests, req);
6909                 
6910                 if (agent_config.defer) {
6911                         /* Transmit cached data to the client on receipt of the event request */
6912                         switch (req->event_kind) {
6913                         case EVENT_KIND_APPDOMAIN_CREATE:
6914                                 /* Emit load events for currently loaded domains */
6915                                 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6916                                 break;
6917                         case EVENT_KIND_ASSEMBLY_LOAD:
6918                                 /* Emit load events for currently loaded assemblies */
6919                                 mono_assembly_foreach (emit_assembly_load, NULL);
6920                                 break;
6921                         case EVENT_KIND_THREAD_START:
6922                                 /* Emit start events for currently started threads */
6923                                 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6924                                 break;
6925                         case EVENT_KIND_TYPE_LOAD:
6926                                 /* Emit type load events for currently loaded types */
6927                                 mono_domain_foreach (send_types_for_domain, NULL);
6928                                 break;
6929                         default:
6930                                 break;
6931                         }
6932                 }
6933                 mono_loader_unlock ();
6934
6935                 buffer_add_int (buf, req->id);
6936                 break;
6937         }
6938         case CMD_EVENT_REQUEST_CLEAR: {
6939                 int etype = decode_byte (p, &p, end);
6940                 int req_id = decode_int (p, &p, end);
6941
6942                 // FIXME: Make a faster mapping from req_id to request
6943                 mono_loader_lock ();
6944                 clear_event_request (req_id, etype);
6945                 mono_loader_unlock ();
6946                 break;
6947         }
6948         case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6949                 int i;
6950
6951                 mono_loader_lock ();
6952                 i = 0;
6953                 while (i < event_requests->len) {
6954                         EventRequest *req = g_ptr_array_index (event_requests, i);
6955
6956                         if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6957                                 clear_breakpoint (req->info);
6958
6959                                 g_ptr_array_remove_index_fast (event_requests, i);
6960                                 g_free (req);
6961                         } else {
6962                                 i ++;
6963                         }
6964                 }
6965                 mono_loader_unlock ();
6966                 break;
6967         }
6968         default:
6969                 return ERR_NOT_IMPLEMENTED;
6970         }
6971
6972         return ERR_NONE;
6973 }
6974
6975 static ErrorCode
6976 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6977 {
6978         int err;
6979         MonoDomain *domain;
6980
6981         switch (command) {
6982         case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6983                 buffer_add_domainid (buf, mono_get_root_domain ());
6984                 break;
6985         }
6986         case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6987                 domain = decode_domainid (p, &p, end, NULL, &err);
6988                 if (err)
6989                         return err;
6990                 buffer_add_string (buf, domain->friendly_name);
6991                 break;
6992         }
6993         case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6994                 GSList *tmp;
6995                 MonoAssembly *ass;
6996                 int count;
6997
6998                 domain = decode_domainid (p, &p, end, NULL, &err);
6999                 if (err)
7000                         return err;
7001                 mono_loader_lock ();
7002                 count = 0;
7003                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7004                         count ++;
7005                 }
7006                 buffer_add_int (buf, count);
7007                 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7008                         ass = tmp->data;
7009                         buffer_add_assemblyid (buf, domain, ass);
7010                 }
7011                 mono_loader_unlock ();
7012                 break;
7013         }
7014         case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7015                 domain = decode_domainid (p, &p, end, NULL, &err);
7016                 if (err)
7017                         return err;
7018
7019                 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7020                 break;
7021         }
7022         case CMD_APPDOMAIN_GET_CORLIB: {
7023                 domain = decode_domainid (p, &p, end, NULL, &err);
7024                 if (err)
7025                         return err;
7026
7027                 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7028                 break;
7029         }
7030         case CMD_APPDOMAIN_CREATE_STRING: {
7031                 char *s;
7032                 MonoString *o;
7033
7034                 domain = decode_domainid (p, &p, end, NULL, &err);
7035                 if (err)
7036                         return err;
7037                 s = decode_string (p, &p, end);
7038
7039                 o = mono_string_new (domain, s);
7040                 buffer_add_objid (buf, (MonoObject*)o);
7041                 break;
7042         }
7043         case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7044                 MonoClass *klass;
7045                 MonoDomain *domain2;
7046                 MonoObject *o;
7047
7048                 domain = decode_domainid (p, &p, end, NULL, &err);
7049                 if (err)
7050                         return err;
7051                 klass = decode_typeid (p, &p, end, &domain2, &err);
7052                 if (err)
7053                         return err;
7054
7055                 // FIXME:
7056                 g_assert (domain == domain2);
7057
7058                 o = mono_object_new (domain, klass);
7059
7060                 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7061                 if (err)
7062                         return err;
7063
7064                 buffer_add_objid (buf, o);
7065                 break;
7066         }
7067         default:
7068                 return ERR_NOT_IMPLEMENTED;
7069         }
7070
7071         return ERR_NONE;
7072 }
7073
7074 static ErrorCode
7075 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7076 {
7077         int err;
7078         MonoAssembly *ass;
7079         MonoDomain *domain;
7080
7081         ass = decode_assemblyid (p, &p, end, &domain, &err);
7082         if (err)
7083                 return err;
7084
7085         switch (command) {
7086         case CMD_ASSEMBLY_GET_LOCATION: {
7087                 buffer_add_string (buf, mono_image_get_filename (ass->image));
7088                 break;                  
7089         }
7090         case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7091                 guint32 token;
7092                 MonoMethod *m;
7093
7094                 if (ass->image->dynamic) {
7095                         buffer_add_id (buf, 0);
7096                 } else {
7097                         token = mono_image_get_entry_point (ass->image);
7098                         if (token == 0) {
7099                                 buffer_add_id (buf, 0);
7100                         } else {
7101                                 m = mono_get_method (ass->image, token, NULL);
7102                                 buffer_add_methodid (buf, domain, m);
7103                         }
7104                 }
7105                 break;                  
7106         }
7107         case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7108                 buffer_add_moduleid (buf, domain, ass->image);
7109                 break;
7110         }
7111         case CMD_ASSEMBLY_GET_OBJECT: {
7112                 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7113                 buffer_add_objid (buf, o);
7114                 break;
7115         }
7116         case CMD_ASSEMBLY_GET_TYPE: {
7117                 char *s = decode_string (p, &p, end);
7118                 gboolean ignorecase = decode_byte (p, &p, end);
7119                 MonoTypeNameParse info;
7120                 MonoType *t;
7121                 gboolean type_resolve, res;
7122                 MonoDomain *d = mono_domain_get ();
7123
7124                 /* This is needed to be able to find referenced assemblies */
7125                 res = mono_domain_set (domain, FALSE);
7126                 g_assert (res);
7127
7128                 if (!mono_reflection_parse_type (s, &info)) {
7129                         t = NULL;
7130                 } else {
7131                         if (info.assembly.name)
7132                                 NOT_IMPLEMENTED;
7133                         t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7134                 }
7135                 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7136                 mono_reflection_free_type_info (&info);
7137                 g_free (s);
7138
7139                 mono_domain_set (d, TRUE);
7140
7141                 break;
7142         }
7143         case CMD_ASSEMBLY_GET_NAME: {
7144                 gchar *name;
7145                 MonoAssembly *mass = ass;
7146
7147                 name = g_strdup_printf (
7148                   "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7149                   mass->aname.name,
7150                   mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7151                   mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7152                   mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7153                   (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7154
7155                 buffer_add_string (buf, name);
7156                 g_free (name);
7157                 break;
7158         }
7159         default:
7160                 return ERR_NOT_IMPLEMENTED;
7161         }
7162
7163         return ERR_NONE;
7164 }
7165
7166 static ErrorCode
7167 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7168 {
7169         int err;
7170         MonoDomain *domain;
7171
7172         switch (command) {
7173         case CMD_MODULE_GET_INFO: {
7174                 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7175                 char *basename;
7176
7177                 basename = g_path_get_basename (image->name);
7178                 buffer_add_string (buf, basename); // name
7179                 buffer_add_string (buf, image->module_name); // scopename
7180                 buffer_add_string (buf, image->name); // fqname
7181                 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7182                 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7183                 g_free (basename);
7184                 break;                  
7185         }
7186         default:
7187                 return ERR_NOT_IMPLEMENTED;
7188         }
7189
7190         return ERR_NONE;
7191 }
7192
7193 static void
7194 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7195 {
7196         if (val && val->vtable->klass == mono_defaults.monotype_class) {
7197                 /* Special case these so the client doesn't have to handle Type objects */
7198                 
7199                 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7200                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7201         } else if (MONO_TYPE_IS_REFERENCE (t))
7202                 buffer_add_value (buf, t, &val, domain);
7203         else
7204                 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7205 }
7206
7207 static void
7208 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7209 {
7210         int i, j;
7211         int nattrs = 0;
7212
7213         if (!cinfo) {
7214                 buffer_add_int (buf, 0);
7215                 return;
7216         }
7217
7218         for (i = 0; i < cinfo->num_attrs; ++i) {
7219                 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7220                         nattrs ++;
7221         }
7222         buffer_add_int (buf, nattrs);
7223
7224         for (i = 0; i < cinfo->num_attrs; ++i) {
7225                 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7226                 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7227                         MonoArray *typed_args, *named_args;
7228                         MonoType *t;
7229                         CattrNamedArg *arginfo;
7230
7231                         mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7232
7233                         buffer_add_methodid (buf, domain, attr->ctor);
7234
7235                         /* Ctor args */
7236                         if (typed_args) {
7237                                 buffer_add_int (buf, mono_array_length (typed_args));
7238                                 for (j = 0; j < mono_array_length (typed_args); ++j) {
7239                                         MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7240
7241                                         t = mono_method_signature (attr->ctor)->params [j];
7242
7243                                         buffer_add_cattr_arg (buf, t, domain, val);
7244                                 }
7245                         } else {
7246                                 buffer_add_int (buf, 0);
7247                         }
7248
7249                         /* Named args */
7250                         if (named_args) {
7251                                 buffer_add_int (buf, mono_array_length (named_args));
7252
7253                                 for (j = 0; j < mono_array_length (named_args); ++j) {
7254                                         MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7255
7256                                         if (arginfo [j].prop) {
7257                                                 buffer_add_byte (buf, 0x54);
7258                                                 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7259                                         } else if (arginfo [j].field) {
7260                                                 buffer_add_byte (buf, 0x53);
7261                                                 buffer_add_fieldid (buf, domain, arginfo [j].field);
7262                                         } else {
7263                                                 g_assert_not_reached ();
7264                                         }
7265
7266                                         buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7267                                 }
7268                         } else {
7269                                 buffer_add_int (buf, 0);
7270                         }
7271                 }
7272         }
7273 }
7274
7275 /* FIXME: Code duplication with icall.c */
7276 static void
7277 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7278 {
7279         int i;
7280         MonoClass *ic;
7281
7282         mono_class_setup_interfaces (klass, error);
7283         if (!mono_error_ok (error))
7284                 return;
7285
7286         for (i = 0; i < klass->interface_count; i++) {
7287                 ic = klass->interfaces [i];
7288                 g_hash_table_insert (ifaces, ic, ic);
7289
7290                 collect_interfaces (ic, ifaces, error);
7291                 if (!mono_error_ok (error))
7292                         return;
7293         }
7294 }
7295
7296 static ErrorCode
7297 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7298 {
7299         MonoClass *nested;
7300         MonoType *type;
7301         gpointer iter;
7302         guint8 b;
7303         int err, nnested;
7304         char *name;
7305
7306         switch (command) {
7307         case CMD_TYPE_GET_INFO: {
7308                 buffer_add_string (buf, klass->name_space);
7309                 buffer_add_string (buf, klass->name);
7310                 // FIXME: byref
7311                 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7312                 buffer_add_string (buf, name);
7313                 g_free (name);
7314                 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7315                 buffer_add_moduleid (buf, domain, klass->image);
7316                 buffer_add_typeid (buf, domain, klass->parent);
7317                 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7318                         buffer_add_typeid (buf, domain, klass->element_class);
7319                 else
7320                         buffer_add_id (buf, 0);
7321                 buffer_add_int (buf, klass->type_token);
7322                 buffer_add_byte (buf, klass->rank);
7323                 buffer_add_int (buf, klass->flags);
7324                 b = 0;
7325                 type = &klass->byval_arg;
7326                 // FIXME: Can't decide whenever a class represents a byref type
7327                 if (FALSE)
7328                         b |= (1 << 0);
7329                 if (type->type == MONO_TYPE_PTR)
7330                         b |= (1 << 1);
7331                 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7332                         b |= (1 << 2);
7333                 if (type->type == MONO_TYPE_VALUETYPE)
7334                         b |= (1 << 3);
7335                 if (klass->enumtype)
7336                         b |= (1 << 4);
7337                 if (klass->generic_container)
7338                         b |= (1 << 5);
7339                 if (klass->generic_container || klass->generic_class)
7340                         b |= (1 << 6);
7341                 buffer_add_byte (buf, b);
7342                 nnested = 0;
7343                 iter = NULL;
7344                 while ((nested = mono_class_get_nested_types (klass, &iter)))
7345                         nnested ++;
7346                 buffer_add_int (buf, nnested);
7347                 iter = NULL;
7348                 while ((nested = mono_class_get_nested_types (klass, &iter)))
7349                         buffer_add_typeid (buf, domain, nested);
7350                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7351                         if (klass->generic_container)
7352                                 buffer_add_typeid (buf, domain, klass);
7353                         else if (klass->generic_class)
7354                                 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7355                         else
7356                                 buffer_add_id (buf, 0);
7357                 }
7358                 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7359                         int count, i;
7360
7361                         if (klass->generic_class) {
7362                                 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7363
7364                                 count = inst->type_argc;
7365                                 buffer_add_int (buf, count);
7366                                 for (i = 0; i < count; i++)
7367                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7368                         } else if (klass->generic_container) {
7369                                 MonoGenericContainer *container = klass->generic_container;
7370                                 MonoClass *pklass;
7371
7372                                 count = container->type_argc;
7373                                 buffer_add_int (buf, count);
7374                                 for (i = 0; i < count; i++) {
7375                                         pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7376                                         buffer_add_typeid (buf, domain, pklass);
7377                                 }
7378                         } else {
7379                                 buffer_add_int (buf, 0);
7380                         }
7381                 }
7382                 break;
7383         }
7384         case CMD_TYPE_GET_METHODS: {
7385                 int nmethods;
7386                 int i = 0;
7387                 gpointer iter = NULL;
7388                 MonoMethod *m;
7389
7390                 mono_class_setup_methods (klass);
7391
7392                 nmethods = mono_class_num_methods (klass);
7393
7394                 buffer_add_int (buf, nmethods);
7395
7396                 while ((m = mono_class_get_methods (klass, &iter))) {
7397                         buffer_add_methodid (buf, domain, m);
7398                         i ++;
7399                 }
7400                 g_assert (i == nmethods);
7401                 break;
7402         }
7403         case CMD_TYPE_GET_FIELDS: {
7404                 int nfields;
7405                 int i = 0;
7406                 gpointer iter = NULL;
7407                 MonoClassField *f;
7408
7409                 nfields = mono_class_num_fields (klass);
7410
7411                 buffer_add_int (buf, nfields);
7412
7413                 while ((f = mono_class_get_fields (klass, &iter))) {
7414                         buffer_add_fieldid (buf, domain, f);
7415                         buffer_add_string (buf, f->name);
7416                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7417                         buffer_add_int (buf, f->type->attrs);
7418                         i ++;
7419                 }
7420                 g_assert (i == nfields);
7421                 break;
7422         }
7423         case CMD_TYPE_GET_PROPERTIES: {
7424                 int nprops;
7425                 int i = 0;
7426                 gpointer iter = NULL;
7427                 MonoProperty *p;
7428
7429                 nprops = mono_class_num_properties (klass);
7430
7431                 buffer_add_int (buf, nprops);
7432
7433                 while ((p = mono_class_get_properties (klass, &iter))) {
7434                         buffer_add_propertyid (buf, domain, p);
7435                         buffer_add_string (buf, p->name);
7436                         buffer_add_methodid (buf, domain, p->get);
7437                         buffer_add_methodid (buf, domain, p->set);
7438                         buffer_add_int (buf, p->attrs);
7439                         i ++;
7440                 }
7441                 g_assert (i == nprops);
7442                 break;
7443         }
7444         case CMD_TYPE_GET_CATTRS: {
7445                 MonoClass *attr_klass;
7446                 MonoCustomAttrInfo *cinfo;
7447
7448                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7449                 /* attr_klass can be NULL */
7450                 if (err)
7451                         return err;
7452
7453                 cinfo = mono_custom_attrs_from_class (klass);
7454
7455                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7456                 break;
7457         }
7458         case CMD_TYPE_GET_FIELD_CATTRS: {
7459                 MonoClass *attr_klass;
7460                 MonoCustomAttrInfo *cinfo;
7461                 MonoClassField *field;
7462
7463                 field = decode_fieldid (p, &p, end, NULL, &err);
7464                 if (err)
7465                         return err;
7466                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7467                 if (err)
7468                         return err;
7469
7470                 cinfo = mono_custom_attrs_from_field (klass, field);
7471
7472                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7473                 break;
7474         }
7475         case CMD_TYPE_GET_PROPERTY_CATTRS: {
7476                 MonoClass *attr_klass;
7477                 MonoCustomAttrInfo *cinfo;
7478                 MonoProperty *prop;
7479
7480                 prop = decode_propertyid (p, &p, end, NULL, &err);
7481                 if (err)
7482                         return err;
7483                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7484                 if (err)
7485                         return err;
7486
7487                 cinfo = mono_custom_attrs_from_property (klass, prop);
7488
7489                 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7490                 break;
7491         }
7492         case CMD_TYPE_GET_VALUES:
7493         case CMD_TYPE_GET_VALUES_2: {
7494                 guint8 *val;
7495                 MonoClassField *f;
7496                 MonoVTable *vtable;
7497                 MonoClass *k;
7498                 int len, i;
7499                 gboolean found;
7500                 MonoThread *thread_obj;
7501                 MonoInternalThread *thread = NULL;
7502                 guint32 special_static_type;
7503
7504                 if (command == CMD_TYPE_GET_VALUES_2) {
7505                         int objid = decode_objid (p, &p, end);
7506                         int err;
7507
7508                         err = get_object (objid, (MonoObject**)&thread_obj);
7509                         if (err)
7510                                 return err;
7511
7512                         thread = THREAD_TO_INTERNAL (thread_obj);
7513                 }
7514
7515                 len = decode_int (p, &p, end);
7516                 for (i = 0; i < len; ++i) {
7517                         f = decode_fieldid (p, &p, end, NULL, &err);
7518                         if (err)
7519                                 return err;
7520
7521                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7522                                 return ERR_INVALID_FIELDID;
7523                         special_static_type = mono_class_field_get_special_static_type (f);
7524                         if (special_static_type != SPECIAL_STATIC_NONE) {
7525                                 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7526                                         return ERR_INVALID_FIELDID;
7527                         }
7528
7529                         /* Check that the field belongs to the object */
7530                         found = FALSE;
7531                         for (k = klass; k; k = k->parent) {
7532                                 if (k == f->parent) {
7533                                         found = TRUE;
7534                                         break;
7535                                 }
7536                         }
7537                         if (!found)
7538                                 return ERR_INVALID_FIELDID;
7539
7540                         vtable = mono_class_vtable (domain, f->parent);
7541                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7542                         mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7543                         buffer_add_value (buf, f->type, val, domain);
7544                         g_free (val);
7545                 }
7546                 break;
7547         }
7548         case CMD_TYPE_SET_VALUES: {
7549                 guint8 *val;
7550                 MonoClassField *f;
7551                 MonoVTable *vtable;
7552                 MonoClass *k;
7553                 int len, i;
7554                 gboolean found;
7555
7556                 len = decode_int (p, &p, end);
7557                 for (i = 0; i < len; ++i) {
7558                         f = decode_fieldid (p, &p, end, NULL, &err);
7559                         if (err)
7560                                 return err;
7561
7562                         if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7563                                 return ERR_INVALID_FIELDID;
7564                         if (mono_class_field_is_special_static (f))
7565                                 return ERR_INVALID_FIELDID;
7566
7567                         /* Check that the field belongs to the object */
7568                         found = FALSE;
7569                         for (k = klass; k; k = k->parent) {
7570                                 if (k == f->parent) {
7571                                         found = TRUE;
7572                                         break;
7573                                 }
7574                         }
7575                         if (!found)
7576                                 return ERR_INVALID_FIELDID;
7577
7578                         // FIXME: Check for literal/const
7579
7580                         vtable = mono_class_vtable (domain, f->parent);
7581                         val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7582                         err = decode_value (f->type, domain, val, p, &p, end);
7583                         if (err) {
7584                                 g_free (val);
7585                                 return err;
7586                         }
7587                         if (MONO_TYPE_IS_REFERENCE (f->type))
7588                                 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7589                         else
7590                                 mono_field_static_set_value (vtable, f, val);
7591                         g_free (val);
7592                 }
7593                 break;
7594         }
7595         case CMD_TYPE_GET_OBJECT: {
7596                 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7597                 buffer_add_objid (buf, o);
7598                 break;
7599         }
7600         case CMD_TYPE_GET_SOURCE_FILES:
7601         case CMD_TYPE_GET_SOURCE_FILES_2: {
7602                 char *source_file, *base;
7603                 GPtrArray *files;
7604                 int i;
7605
7606                 files = get_source_files_for_type (klass);
7607
7608                 buffer_add_int (buf, files->len);
7609                 for (i = 0; i < files->len; ++i) {
7610                         source_file = g_ptr_array_index (files, i);
7611                         if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7612                                 buffer_add_string (buf, source_file);
7613                         } else {
7614                                 base = g_path_get_basename (source_file);
7615                                 buffer_add_string (buf, base);
7616                                 g_free (base);
7617                         }
7618                         g_free (source_file);
7619                 }
7620                 g_ptr_array_free (files, TRUE);
7621                 break;
7622         }
7623         case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7624                 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7625
7626                 if (err)
7627                         return err;
7628                 if (mono_class_is_assignable_from (klass, oklass))
7629                         buffer_add_byte (buf, 1);
7630                 else
7631                         buffer_add_byte (buf, 0);
7632                 break;
7633         }
7634         case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7635                 char *name = decode_string (p, &p, end);
7636                 int i, flags = decode_int (p, &p, end);
7637                 MonoException *ex = NULL;
7638                 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7639
7640                 if (!array)
7641                         return ERR_LOADER_ERROR;
7642                 buffer_add_int (buf, array->len);
7643                 for (i = 0; i < array->len; ++i) {
7644                         MonoMethod *method = g_ptr_array_index (array, i);
7645                         buffer_add_methodid (buf, domain, method);
7646                 }
7647
7648                 g_ptr_array_free (array, TRUE);
7649                 g_free (name);
7650                 break;
7651         }
7652         case CMD_TYPE_GET_INTERFACES: {
7653                 MonoClass *parent;
7654                 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7655                 MonoError error;
7656                 MonoClass *tclass, *iface;
7657                 GHashTableIter iter;
7658
7659                 tclass = klass;
7660
7661                 for (parent = tclass; parent; parent = parent->parent) {
7662                         mono_class_setup_interfaces (parent, &error);
7663                         if (!mono_error_ok (&error))
7664                                 return ERR_LOADER_ERROR;
7665                         collect_interfaces (parent, iface_hash, &error);
7666                         if (!mono_error_ok (&error))
7667                                 return ERR_LOADER_ERROR;
7668                 }
7669
7670                 buffer_add_int (buf, g_hash_table_size (iface_hash));
7671
7672                 g_hash_table_iter_init (&iter, iface_hash);
7673                 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7674                         buffer_add_typeid (buf, domain, iface);
7675                 g_hash_table_destroy (iface_hash);
7676                 break;
7677         }
7678         case CMD_TYPE_GET_INTERFACE_MAP: {
7679                 int tindex, ioffset;
7680                 gboolean variance_used;
7681                 MonoClass *iclass;
7682                 int len, nmethods, i;
7683                 gpointer iter;
7684                 MonoMethod *method;
7685
7686                 len = decode_int (p, &p, end);
7687                 mono_class_setup_vtable (klass);
7688
7689                 for (tindex = 0; tindex < len; ++tindex) {
7690                         iclass = decode_typeid (p, &p, end, NULL, &err);
7691                         if (err)
7692                                 return err;
7693
7694                         ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7695                         if (ioffset == -1)
7696                                 return ERR_INVALID_ARGUMENT;
7697
7698                         nmethods = mono_class_num_methods (iclass);
7699                         buffer_add_int (buf, nmethods);
7700
7701                         iter = NULL;
7702                         while ((method = mono_class_get_methods (iclass, &iter))) {
7703                                 buffer_add_methodid (buf, domain, method);
7704                         }
7705                         for (i = 0; i < nmethods; ++i)
7706                                 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7707                 }
7708                 break;
7709         }
7710         case CMD_TYPE_IS_INITIALIZED: {
7711                 MonoVTable *vtable = mono_class_vtable (domain, klass);
7712
7713                 if (vtable)
7714                         buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7715                 else
7716                         buffer_add_int (buf, 0);
7717                 break;
7718         }
7719         default:
7720                 return ERR_NOT_IMPLEMENTED;
7721         }
7722
7723         return ERR_NONE;
7724 }
7725
7726 static ErrorCode
7727 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7728 {
7729         MonoClass *klass;
7730         MonoDomain *old_domain;
7731         MonoDomain *domain;
7732         int err;
7733
7734         klass = decode_typeid (p, &p, end, &domain, &err);
7735         if (err)
7736                 return err;
7737
7738         old_domain = mono_domain_get ();
7739
7740         mono_domain_set (domain, TRUE);
7741
7742         err = type_commands_internal (command, klass, domain, p, end, buf);
7743
7744         mono_domain_set (old_domain, TRUE);
7745
7746         return err;
7747 }
7748
7749 static ErrorCode
7750 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7751 {
7752         MonoMethodHeader *header;
7753         int err;
7754
7755         switch (command) {
7756         case CMD_METHOD_GET_NAME: {
7757                 buffer_add_string (buf, method->name);
7758                 break;                  
7759         }
7760         case CMD_METHOD_GET_DECLARING_TYPE: {
7761                 buffer_add_typeid (buf, domain, method->klass);
7762                 break;
7763         }
7764         case CMD_METHOD_GET_DEBUG_INFO: {
7765                 MonoDebugMethodInfo *minfo;
7766                 char *source_file;
7767                 int i, j, n_il_offsets;
7768                 int *il_offsets;
7769                 int *line_numbers;
7770                 int *column_numbers;
7771                 int *source_files;
7772                 GPtrArray *source_file_list;
7773
7774                 header = mono_method_get_header (method);
7775                 if (!header) {
7776                         buffer_add_int (buf, 0);
7777                         buffer_add_string (buf, "");
7778                         buffer_add_int (buf, 0);
7779                         break;
7780                 }
7781
7782                 minfo = mono_debug_lookup_method (method);
7783                 if (!minfo) {
7784                         buffer_add_int (buf, header->code_size);
7785                         buffer_add_string (buf, "");
7786                         buffer_add_int (buf, 0);
7787                         mono_metadata_free_mh (header);
7788                         break;
7789                 }
7790
7791                 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7792                 buffer_add_int (buf, header->code_size);
7793                 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7794                         buffer_add_int (buf, source_file_list->len);
7795                         for (i = 0; i < source_file_list->len; ++i) {
7796                                 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7797                                 buffer_add_string (buf, sinfo->source_file);
7798                                 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7799                                         for (j = 0; j < 16; ++j)
7800                                                 buffer_add_byte (buf, sinfo->hash [j]);
7801                                 }
7802                         }
7803                 } else {
7804                         buffer_add_string (buf, source_file);
7805                 }
7806                 buffer_add_int (buf, n_il_offsets);
7807                 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method,  TRUE)));
7808                 for (i = 0; i < n_il_offsets; ++i) {
7809                         const char *srcfile = "";
7810
7811                         if (source_files [i] != -1) {
7812                                 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7813                                 srcfile = sinfo->source_file;
7814                         }
7815                         DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7816                         buffer_add_int (buf, il_offsets [i]);
7817                         buffer_add_int (buf, line_numbers [i]);
7818                         if (CHECK_PROTOCOL_VERSION (2, 13))
7819                                 buffer_add_int (buf, source_files [i]);
7820                         if (CHECK_PROTOCOL_VERSION (2, 19))
7821                                 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7822                 }
7823                 g_free (source_file);
7824                 g_free (il_offsets);
7825                 g_free (line_numbers);
7826                 g_free (source_files);
7827                 g_ptr_array_free (source_file_list, TRUE);
7828                 mono_metadata_free_mh (header);
7829                 break;
7830         }
7831         case CMD_METHOD_GET_PARAM_INFO: {
7832                 MonoMethodSignature *sig = mono_method_signature (method);
7833                 guint32 i;
7834                 char **names;
7835
7836                 /* FIXME: mono_class_from_mono_type () and byrefs */
7837
7838                 /* FIXME: Use a smaller encoding */
7839                 buffer_add_int (buf, sig->call_convention);
7840                 buffer_add_int (buf, sig->param_count);
7841                 buffer_add_int (buf, sig->generic_param_count);
7842                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7843                 for (i = 0; i < sig->param_count; ++i) {
7844                         /* FIXME: vararg */
7845                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7846                 }
7847
7848                 /* Emit parameter names */
7849                 names = g_new (char *, sig->param_count);
7850                 mono_method_get_param_names (method, (const char **) names);
7851                 for (i = 0; i < sig->param_count; ++i)
7852                         buffer_add_string (buf, names [i]);
7853                 g_free (names);
7854
7855                 break;
7856         }
7857         case CMD_METHOD_GET_LOCALS_INFO: {
7858                 int i, j, num_locals;
7859                 MonoDebugLocalsInfo *locals;
7860
7861                 header = mono_method_get_header (method);
7862                 if (!header)
7863                         return ERR_INVALID_ARGUMENT;
7864
7865                 buffer_add_int (buf, header->num_locals);
7866
7867                 /* Types */
7868                 for (i = 0; i < header->num_locals; ++i)
7869                         buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7870
7871                 /* Names */
7872                 locals = mono_debug_lookup_locals (method);
7873                 if (locals)
7874                         num_locals = locals->num_locals;
7875                 else
7876                         num_locals = 0;
7877                 for (i = 0; i < header->num_locals; ++i) {
7878                         for (j = 0; j < num_locals; ++j)
7879                                 if (locals->locals [j].index == i)
7880                                         break;
7881                         if (j < num_locals)
7882                                 buffer_add_string (buf, locals->locals [j].name);
7883                         else
7884                                 buffer_add_string (buf, "");
7885                 }
7886
7887                 /* Scopes */
7888                 for (i = 0; i < header->num_locals; ++i) {
7889                         for (j = 0; j < num_locals; ++j)
7890                                 if (locals->locals [j].index == i)
7891                                         break;
7892                         if (j < num_locals && locals->locals [j].block) {
7893                                 buffer_add_int (buf, locals->locals [j].block->start_offset);
7894                                 buffer_add_int (buf, locals->locals [j].block->end_offset);
7895                         } else {
7896                                 buffer_add_int (buf, 0);
7897                                 buffer_add_int (buf, header->code_size);
7898                         }
7899                 }
7900                 mono_metadata_free_mh (header);
7901
7902                 if (locals)
7903                         mono_debug_symfile_free_locals (locals);
7904
7905                 break;
7906         }
7907         case CMD_METHOD_GET_INFO:
7908                 buffer_add_int (buf, method->flags);
7909                 buffer_add_int (buf, method->iflags);
7910                 buffer_add_int (buf, method->token);
7911                 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7912                         guint8 attrs = 0;
7913                         if (method->is_generic)
7914                                 attrs |= (1 << 0);
7915                         if (mono_method_signature (method)->generic_param_count)
7916                                 attrs |= (1 << 1);
7917                         buffer_add_byte (buf, attrs);
7918                         if (method->is_generic || method->is_inflated) {
7919                                 MonoMethod *result;
7920
7921                                 if (method->is_generic) {
7922                                         result = method;
7923                                 } else {
7924                                         MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7925                                         
7926                                         result = imethod->declaring;
7927                                         if (imethod->context.class_inst) {
7928                                                 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7929                                                 /*Generic methods gets the context of the GTD.*/
7930                                                 if (mono_class_get_context (klass))
7931                                                         result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7932                                         }
7933                                 }
7934
7935                                 buffer_add_methodid (buf, domain, result);
7936                         } else {
7937                                 buffer_add_id (buf, 0);
7938                         }
7939                         if (CHECK_PROTOCOL_VERSION (2, 15)) {
7940                                 if (mono_method_signature (method)->generic_param_count) {
7941                                         int count, i;
7942
7943                                         if (method->is_inflated) {
7944                                                 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7945                                                 if (inst) {
7946                                                         count = inst->type_argc;
7947                                                         buffer_add_int (buf, count);
7948
7949                                                         for (i = 0; i < count; i++)
7950                                                                 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7951                                                 } else {
7952                                                         buffer_add_int (buf, 0);
7953                                                 }
7954                                         } else if (method->is_generic) {
7955                                                 MonoGenericContainer *container = mono_method_get_generic_container (method);
7956
7957                                                 count = mono_method_signature (method)->generic_param_count;
7958                                                 buffer_add_int (buf, count);
7959                                                 for (i = 0; i < count; i++) {
7960                                                         MonoGenericParam *param = mono_generic_container_get_param (container, i);
7961                                                         MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7962                                                         buffer_add_typeid (buf, domain, pklass);
7963                                                 }
7964                                         } else {
7965                                                 buffer_add_int (buf, 0);
7966                                         }
7967                                 } else {
7968                                         buffer_add_int (buf, 0);
7969                                 }
7970                         }
7971                 }
7972                 break;
7973         case CMD_METHOD_GET_BODY: {
7974                 int i;
7975
7976                 header = mono_method_get_header (method);
7977                 if (!header) {
7978                         buffer_add_int (buf, 0);
7979
7980                         if (CHECK_PROTOCOL_VERSION (2, 18))
7981                                 buffer_add_int (buf, 0);
7982                 } else {
7983                         buffer_add_int (buf, header->code_size);
7984                         for (i = 0; i < header->code_size; ++i)
7985                                 buffer_add_byte (buf, header->code [i]);
7986
7987                         if (CHECK_PROTOCOL_VERSION (2, 18)) {
7988                                 buffer_add_int (buf, header->num_clauses);
7989                                 for (i = 0; i < header->num_clauses; ++i) {
7990                                         MonoExceptionClause *clause = &header->clauses [i];
7991
7992                                         buffer_add_int (buf, clause->flags);
7993                                         buffer_add_int (buf, clause->try_offset);
7994                                         buffer_add_int (buf, clause->try_len);
7995                                         buffer_add_int (buf, clause->handler_offset);
7996                                         buffer_add_int (buf, clause->handler_len);
7997                                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7998                                                 buffer_add_typeid (buf, domain, clause->data.catch_class);
7999                                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8000                                                 buffer_add_int (buf, clause->data.filter_offset);
8001                                 }
8002                         }
8003
8004                         mono_metadata_free_mh (header);
8005                 }
8006
8007                 break;
8008         }
8009         case CMD_METHOD_RESOLVE_TOKEN: {
8010                 guint32 token = decode_int (p, &p, end);
8011
8012                 // FIXME: Generics
8013                 switch (mono_metadata_token_code (token)) {
8014                 case MONO_TOKEN_STRING: {
8015                         MonoString *s;
8016                         char *s2;
8017
8018                         s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8019                         g_assert (s);
8020
8021                         s2 = mono_string_to_utf8 (s);
8022
8023                         buffer_add_byte (buf, TOKEN_TYPE_STRING);
8024                         buffer_add_string (buf, s2);
8025                         g_free (s2);
8026                         break;
8027                 }
8028                 default: {
8029                         gpointer val;
8030                         MonoClass *handle_class;
8031
8032                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8033                                 val = mono_method_get_wrapper_data (method, token);
8034                                 handle_class = mono_method_get_wrapper_data (method, token + 1);
8035
8036                                 if (handle_class == NULL) {
8037                                         // Can't figure out the token type
8038                                         buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8039                                         break;
8040                                 }
8041                         } else {
8042                                 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8043                                 g_assert (val);
8044                         }
8045
8046                         if (handle_class == mono_defaults.typehandle_class) {
8047                                 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8048                                 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8049                                         buffer_add_typeid (buf, domain, (MonoClass *) val);
8050                                 else
8051                                         buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8052                         } else if (handle_class == mono_defaults.fieldhandle_class) {
8053                                 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8054                                 buffer_add_fieldid (buf, domain, val);
8055                         } else if (handle_class == mono_defaults.methodhandle_class) {
8056                                 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8057                                 buffer_add_methodid (buf, domain, val);
8058                         } else if (handle_class == mono_defaults.string_class) {
8059                                 char *s;
8060
8061                                 s = mono_string_to_utf8 (val);
8062                                 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8063                                 buffer_add_string (buf, s);
8064                                 g_free (s);
8065                         } else {
8066                                 g_assert_not_reached ();
8067                         }
8068                         break;
8069                 }
8070                 }
8071                 break;
8072         }
8073         case CMD_METHOD_GET_CATTRS: {
8074                 MonoClass *attr_klass;
8075                 MonoCustomAttrInfo *cinfo;
8076
8077                 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8078                 /* attr_klass can be NULL */
8079                 if (err)
8080                         return err;
8081
8082                 cinfo = mono_custom_attrs_from_method (method);
8083
8084                 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8085                 break;
8086         }
8087         default:
8088                 return ERR_NOT_IMPLEMENTED;
8089         }
8090
8091         return ERR_NONE;
8092 }
8093
8094 static ErrorCode
8095 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8096 {
8097         int err;
8098         MonoDomain *old_domain;
8099         MonoDomain *domain;
8100         MonoMethod *method;
8101
8102         method = decode_methodid (p, &p, end, &domain, &err);
8103         if (err)
8104                 return err;
8105
8106         old_domain = mono_domain_get ();
8107
8108         mono_domain_set (domain, TRUE);
8109
8110         err = method_commands_internal (command, method, domain, p, end, buf);
8111
8112         mono_domain_set (old_domain, TRUE);
8113
8114         return err;
8115 }
8116
8117 static ErrorCode
8118 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8119 {
8120         int objid = decode_objid (p, &p, end);
8121         int err;
8122         MonoThread *thread_obj;
8123         MonoInternalThread *thread;
8124
8125         err = get_object (objid, (MonoObject**)&thread_obj);
8126         if (err)
8127                 return err;
8128
8129         thread = THREAD_TO_INTERNAL (thread_obj);
8130            
8131         switch (command) {
8132         case CMD_THREAD_GET_NAME: {
8133                 guint32 name_len;
8134                 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8135
8136                 if (!s) {
8137                         buffer_add_int (buf, 0);
8138                 } else {
8139                         char *name;
8140                         glong len;
8141
8142                         name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8143                         g_assert (name);
8144                         buffer_add_int (buf, len);
8145                         buffer_add_data (buf, (guint8*)name, len);
8146                         g_free (s);
8147                 }
8148                 break;
8149         }
8150         case CMD_THREAD_GET_FRAME_INFO: {
8151                 DebuggerTlsData *tls;
8152                 int i, start_frame, length;
8153
8154                 // Wait for suspending if it already started
8155                 // FIXME: Races with suspend_count
8156                 while (!is_suspended ()) {
8157                         if (suspend_count)
8158                                 wait_for_suspend ();
8159                 }
8160                 /*
8161                 if (suspend_count)
8162                         wait_for_suspend ();
8163                 if (!is_suspended ())
8164                         return ERR_NOT_SUSPENDED;
8165                 */
8166
8167                 start_frame = decode_int (p, &p, end);
8168                 length = decode_int (p, &p, end);
8169
8170                 if (start_frame != 0 || length != -1)
8171                         return ERR_NOT_IMPLEMENTED;
8172
8173                 mono_loader_lock ();
8174                 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8175                 mono_loader_unlock ();
8176                 g_assert (tls);
8177
8178                 compute_frame_info (thread, tls);
8179
8180                 buffer_add_int (buf, tls->frame_count);
8181                 for (i = 0; i < tls->frame_count; ++i) {
8182                         buffer_add_int (buf, tls->frames [i]->id);
8183                         buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8184                         buffer_add_int (buf, tls->frames [i]->il_offset);
8185                         /*
8186                          * Instead of passing the frame type directly to the client, we associate
8187                          * it with the previous frame using a set of flags. This avoids lots of
8188                          * conditional code in the client, since a frame whose type isn't 
8189                          * FRAME_TYPE_MANAGED has no method, location, etc.
8190                          */
8191                         buffer_add_byte (buf, tls->frames [i]->flags);
8192                 }
8193
8194                 break;
8195         }
8196         case CMD_THREAD_GET_STATE:
8197                 buffer_add_int (buf, thread->state);
8198                 break;
8199         case CMD_THREAD_GET_INFO:
8200                 buffer_add_byte (buf, thread->threadpool_thread);
8201                 break;
8202         case CMD_THREAD_GET_ID:
8203                 buffer_add_long (buf, (guint64)(gsize)thread);
8204                 break;
8205         case CMD_THREAD_GET_TID:
8206                 buffer_add_long (buf, (guint64)thread->tid);
8207                 break;
8208         default:
8209                 return ERR_NOT_IMPLEMENTED;
8210         }
8211
8212         return ERR_NONE;
8213 }
8214
8215 static ErrorCode
8216 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8217 {
8218         int objid;
8219         int err;
8220         MonoThread *thread_obj;
8221         MonoInternalThread *thread;
8222         int pos, i, len, frame_idx;
8223         DebuggerTlsData *tls;
8224         StackFrame *frame;
8225         MonoDebugMethodJitInfo *jit;
8226         MonoDebugVarInfo *var;
8227         MonoMethodSignature *sig;
8228         gssize id;
8229         MonoMethodHeader *header;
8230
8231         objid = decode_objid (p, &p, end);
8232         err = get_object (objid, (MonoObject**)&thread_obj);
8233         if (err)
8234                 return err;
8235
8236         thread = THREAD_TO_INTERNAL (thread_obj);
8237
8238         id = decode_id (p, &p, end);
8239
8240         mono_loader_lock ();
8241         tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8242         mono_loader_unlock ();
8243         g_assert (tls);
8244
8245         for (i = 0; i < tls->frame_count; ++i) {
8246                 if (tls->frames [i]->id == id)
8247                         break;
8248         }
8249         if (i == tls->frame_count)
8250                 return ERR_INVALID_FRAMEID;
8251
8252         frame_idx = i;
8253         frame = tls->frames [frame_idx];
8254
8255         if (!frame->has_ctx)
8256                 // FIXME:
8257                 return ERR_INVALID_FRAMEID;
8258
8259         if (!frame->jit) {
8260                 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8261                 if (!frame->jit && frame->api_method->is_inflated)
8262                         frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8263                 if (!frame->jit) {
8264                         char *s;
8265
8266                         /* This could happen for aot images with no jit debug info */
8267                         s = mono_method_full_name (frame->api_method, TRUE);
8268                         DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8269                         g_free (s);
8270                         return ERR_ABSENT_INFORMATION;
8271                 }
8272         }
8273         jit = frame->jit;
8274
8275         sig = mono_method_signature (frame->actual_method);
8276
8277         if (!get_seq_points (frame->domain, frame->actual_method))
8278                 /*
8279                  * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8280                  */
8281                 return ERR_ABSENT_INFORMATION;
8282
8283         switch (command) {
8284         case CMD_STACK_FRAME_GET_VALUES: {
8285                 len = decode_int (p, &p, end);
8286                 header = mono_method_get_header (frame->actual_method);
8287
8288                 for (i = 0; i < len; ++i) {
8289                         pos = decode_int (p, &p, end);
8290
8291                         if (pos < 0) {
8292                                 pos = - pos - 1;
8293
8294                                 g_assert (pos >= 0 && pos < jit->num_params);
8295
8296                                 var = &jit->params [pos];
8297
8298                                 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8299                         } else {
8300                                 g_assert (pos >= 0 && pos < jit->num_locals);
8301
8302                                 var = &jit->locals [pos];
8303                                 
8304                                 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8305                         }
8306                 }
8307                 mono_metadata_free_mh (header);
8308                 break;
8309         }
8310         case CMD_STACK_FRAME_GET_THIS: {
8311                 if (frame->api_method->klass->valuetype) {
8312                         if (!sig->hasthis) {
8313                                 MonoObject *p = NULL;
8314                                 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8315                         } else {
8316                                 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8317                         }
8318                 } else {
8319                         if (!sig->hasthis) {
8320                                 MonoObject *p = NULL;
8321                                 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8322                         } else {
8323                                 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8324                         }
8325                 }
8326                 break;
8327         }
8328         case CMD_STACK_FRAME_SET_VALUES: {
8329                 guint8 *val_buf;
8330                 MonoType *t;
8331                 MonoDebugVarInfo *var;
8332
8333                 len = decode_int (p, &p, end);
8334                 header = mono_method_get_header (frame->actual_method);
8335
8336                 for (i = 0; i < len; ++i) {
8337                         pos = decode_int (p, &p, end);
8338
8339                         if (pos < 0) {
8340                                 pos = - pos - 1;
8341
8342                                 g_assert (pos >= 0 && pos < jit->num_params);
8343
8344                                 t = sig->params [pos];
8345                                 var = &jit->params [pos];
8346                         } else {
8347                                 g_assert (pos >= 0 && pos < jit->num_locals);
8348
8349                                 t = header->locals [pos];
8350                                 var = &jit->locals [pos];
8351                         }
8352
8353                         if (MONO_TYPE_IS_REFERENCE (t))
8354                                 val_buf = g_alloca (sizeof (MonoObject*));
8355                         else
8356                                 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8357                         err = decode_value (t, frame->domain, val_buf, p, &p, end);
8358                         if (err)
8359                                 return err;
8360
8361                         set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8362                 }
8363                 mono_metadata_free_mh (header);
8364                 break;
8365         }
8366         default:
8367                 return ERR_NOT_IMPLEMENTED;
8368         }
8369
8370         return ERR_NONE;
8371 }
8372
8373 static ErrorCode
8374 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8375 {
8376         MonoArray *arr;
8377         int objid, err, index, len, i, esize;
8378         gpointer elem;
8379
8380         objid = decode_objid (p, &p, end);
8381         err = get_object (objid, (MonoObject**)&arr);
8382         if (err)
8383                 return err;
8384
8385         switch (command) {
8386         case CMD_ARRAY_REF_GET_LENGTH:
8387                 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8388                 if (!arr->bounds) {
8389                         buffer_add_int (buf, arr->max_length);
8390                         buffer_add_int (buf, 0);
8391                 } else {
8392                         for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8393                                 buffer_add_int (buf, arr->bounds [i].length);
8394                                 buffer_add_int (buf, arr->bounds [i].lower_bound);
8395                         }
8396                 }
8397                 break;
8398         case CMD_ARRAY_REF_GET_VALUES:
8399                 index = decode_int (p, &p, end);
8400                 len = decode_int (p, &p, end);
8401
8402                 g_assert (index >= 0 && len >= 0);
8403                 // Reordered to avoid integer overflow
8404                 g_assert (!(index > arr->max_length - len));
8405
8406                 esize = mono_array_element_size (arr->obj.vtable->klass);
8407                 for (i = index; i < index + len; ++i) {
8408                         elem = (gpointer*)((char*)arr->vector + (i * esize));
8409                         buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8410                 }
8411                 break;
8412         case CMD_ARRAY_REF_SET_VALUES:
8413                 index = decode_int (p, &p, end);
8414                 len = decode_int (p, &p, end);
8415
8416                 g_assert (index >= 0 && len >= 0);
8417                 // Reordered to avoid integer overflow
8418                 g_assert (!(index > arr->max_length - len));
8419
8420                 esize = mono_array_element_size (arr->obj.vtable->klass);
8421                 for (i = index; i < index + len; ++i) {
8422                         elem = (gpointer*)((char*)arr->vector + (i * esize));
8423
8424                         decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8425                 }
8426                 break;
8427         default:
8428                 return ERR_NOT_IMPLEMENTED;
8429         }
8430
8431         return ERR_NONE;
8432 }
8433
8434 static ErrorCode
8435 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8436 {
8437         int objid, err;
8438         MonoString *str;
8439         char *s;
8440         int i, index, length;
8441         gunichar2 *c;
8442
8443         objid = decode_objid (p, &p, end);
8444         err = get_object (objid, (MonoObject**)&str);
8445         if (err)
8446                 return err;
8447
8448         switch (command) {
8449         case CMD_STRING_REF_GET_VALUE:
8450                 s = mono_string_to_utf8 (str);
8451                 buffer_add_string (buf, s);
8452                 g_free (s);
8453                 break;
8454         case CMD_STRING_REF_GET_LENGTH:
8455                 buffer_add_long (buf, mono_string_length (str));
8456                 break;
8457         case CMD_STRING_REF_GET_CHARS:
8458                 index = decode_long (p, &p, end);
8459                 length = decode_long (p, &p, end);
8460                 if (index > mono_string_length (str) - length)
8461                         return ERR_INVALID_ARGUMENT;
8462                 c = mono_string_chars (str) + index;
8463                 for (i = 0; i < length; ++i)
8464                         buffer_add_short (buf, c [i]);
8465                 break;
8466         default:
8467                 return ERR_NOT_IMPLEMENTED;
8468         }
8469
8470         return ERR_NONE;
8471 }
8472
8473 static ErrorCode
8474 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8475 {
8476         int objid, err;
8477         MonoObject *obj;
8478         int len, i;
8479         MonoClassField *f;
8480         MonoClass *k;
8481         gboolean found;
8482
8483         if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8484                 objid = decode_objid (p, &p, end);
8485                 err = get_object (objid, &obj);
8486                 if (err)
8487                         buffer_add_int (buf, 1);
8488                 else
8489                         buffer_add_int (buf, 0);
8490                 return 0;
8491         }
8492
8493         objid = decode_objid (p, &p, end);
8494         err = get_object (objid, &obj);
8495         if (err)
8496                 return err;
8497
8498         switch (command) {
8499         case CMD_OBJECT_REF_GET_TYPE:
8500                 /* This handles transparent proxies too */
8501                 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8502                 break;
8503         case CMD_OBJECT_REF_GET_VALUES:
8504                 len = decode_int (p, &p, end);
8505
8506                 for (i = 0; i < len; ++i) {
8507                         MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8508                         if (err)
8509                                 return err;
8510
8511                         /* Check that the field belongs to the object */
8512                         found = FALSE;
8513                         for (k = obj->vtable->klass; k; k = k->parent) {
8514                                 if (k == f->parent) {
8515                                         found = TRUE;
8516                                         break;
8517                                 }
8518                         }
8519                         if (!found)
8520                                 return ERR_INVALID_FIELDID;
8521
8522                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8523                                 guint8 *val;
8524                                 MonoVTable *vtable;
8525
8526                                 if (mono_class_field_is_special_static (f))
8527                                         return ERR_INVALID_FIELDID;
8528
8529                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8530                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8531                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8532                                 mono_field_static_get_value (vtable, f, val);
8533                                 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8534                                 g_free (val);
8535                         } else {
8536                                 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8537                         }
8538                 }
8539                 break;
8540         case CMD_OBJECT_REF_SET_VALUES:
8541                 len = decode_int (p, &p, end);
8542
8543                 for (i = 0; i < len; ++i) {
8544                         f = decode_fieldid (p, &p, end, NULL, &err);
8545                         if (err)
8546                                 return err;
8547
8548                         /* Check that the field belongs to the object */
8549                         found = FALSE;
8550                         for (k = obj->vtable->klass; k; k = k->parent) {
8551                                 if (k == f->parent) {
8552                                         found = TRUE;
8553                                         break;
8554                                 }
8555                         }
8556                         if (!found)
8557                                 return ERR_INVALID_FIELDID;
8558
8559                         if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8560                                 guint8 *val;
8561                                 MonoVTable *vtable;
8562
8563                                 if (mono_class_field_is_special_static (f))
8564                                         return ERR_INVALID_FIELDID;
8565
8566                                 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8567                                 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8568
8569                                 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8570                                 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8571                                 if (err) {
8572                                         g_free (val);
8573                                         return err;
8574                                 }
8575                                 mono_field_static_set_value (vtable, f, val);
8576                                 g_free (val);
8577                         } else {
8578                                 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8579                                 if (err)
8580                                         return err;
8581                         }
8582                 }
8583                 break;
8584         case CMD_OBJECT_REF_GET_ADDRESS:
8585                 buffer_add_long (buf, (gssize)obj);
8586                 break;
8587         case CMD_OBJECT_REF_GET_DOMAIN:
8588                 buffer_add_domainid (buf, obj->vtable->domain);
8589                 break;
8590         case CMD_OBJECT_REF_GET_INFO:
8591                 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8592                 buffer_add_domainid (buf, obj->vtable->domain);
8593                 break;
8594         default:
8595                 return ERR_NOT_IMPLEMENTED;
8596         }
8597
8598         return ERR_NONE;
8599 }
8600
8601 static const char*
8602 command_set_to_string (CommandSet command_set)
8603 {
8604         switch (command_set) {
8605         case CMD_SET_VM:
8606                 return "VM";
8607         case CMD_SET_OBJECT_REF:
8608                 return "OBJECT_REF";
8609         case CMD_SET_STRING_REF:
8610                 return "STRING_REF"; 
8611         case CMD_SET_THREAD:
8612                 return "THREAD"; 
8613         case CMD_SET_ARRAY_REF:
8614                 return "ARRAY_REF"; 
8615         case CMD_SET_EVENT_REQUEST:
8616                 return "EVENT_REQUEST"; 
8617         case CMD_SET_STACK_FRAME:
8618                 return "STACK_FRAME"; 
8619         case CMD_SET_APPDOMAIN:
8620                 return "APPDOMAIN"; 
8621         case CMD_SET_ASSEMBLY:
8622                 return "ASSEMBLY"; 
8623         case CMD_SET_METHOD:
8624                 return "METHOD"; 
8625         case CMD_SET_TYPE:
8626                 return "TYPE"; 
8627         case CMD_SET_MODULE:
8628                 return "MODULE"; 
8629         case CMD_SET_EVENT:
8630                 return "EVENT"; 
8631         default:
8632                 return "";
8633         }
8634 }
8635
8636 static const char*
8637 cmd_to_string (CommandSet set, int command)
8638 {
8639         switch (set) {
8640         case CMD_SET_VM: {
8641                 switch (command) {
8642                 case CMD_VM_VERSION:
8643                         return "VERSION";
8644                 case CMD_VM_ALL_THREADS:
8645                         return "ALL_THREADS";
8646                 case CMD_VM_SUSPEND:
8647                         return "SUSPEND";
8648                 case CMD_VM_RESUME:
8649                         return "RESUME";
8650                 case CMD_VM_EXIT:
8651                         return "EXIT";
8652                 case CMD_VM_DISPOSE:
8653                         return "DISPOSE";
8654                 case CMD_VM_INVOKE_METHOD:
8655                         return "INVOKE_METHOD";
8656                 case CMD_VM_SET_PROTOCOL_VERSION:
8657                         return "SET_PROTOCOL_VERSION";
8658                 case CMD_VM_ABORT_INVOKE:
8659                         return "ABORT_INVOKE";
8660                 case CMD_VM_SET_KEEPALIVE:
8661                         return "SET_KEEPALIVE";
8662                 default:
8663                         break;
8664                 }
8665                 break;
8666         }
8667         default:
8668                 break;
8669         }
8670         return NULL;
8671 }
8672
8673 static gboolean
8674 wait_for_attach (void)
8675 {
8676 #ifndef DISABLE_SOCKET_TRANSPORT
8677         if (listen_fd == -1) {
8678                 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8679                 return FALSE;
8680         }
8681
8682         /* Block and wait for client connection */
8683         conn_fd = socket_transport_accept (listen_fd);
8684         DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8685         if (conn_fd == -1) {
8686                 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8687                 return FALSE;
8688         }
8689 #else
8690         g_assert_not_reached ();
8691 #endif
8692
8693         /* Handshake */
8694         disconnected = !transport_handshake ();
8695         if (disconnected) {
8696                 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8697                 return FALSE;
8698         }
8699         
8700         return TRUE;
8701 }
8702
8703 /*
8704  * debugger_thread:
8705  *
8706  *   This thread handles communication with the debugger client using a JDWP
8707  * like protocol.
8708  */
8709 static guint32 WINAPI
8710 debugger_thread (void *arg)
8711 {
8712         int res, len, id, flags, command_set = 0, command = 0;
8713         guint8 header [HEADER_LENGTH];
8714         guint8 *data, *p, *end;
8715         Buffer buf;
8716         ErrorCode err;
8717         gboolean no_reply;
8718         gboolean attach_failed = FALSE;
8719
8720         DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8721
8722         debugger_thread_id = GetCurrentThreadId ();
8723
8724         mono_jit_thread_attach (mono_get_root_domain ());
8725
8726         mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8727
8728         mono_set_is_debugger_attached (TRUE);
8729         
8730         if (agent_config.defer) {
8731                 if (!wait_for_attach ()) {
8732                         DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8733                         attach_failed = TRUE; // Don't abort process when we can't listen
8734                 } else {
8735                         /* Send start event to client */
8736                         process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8737                 }
8738         }
8739         
8740         while (!attach_failed) {
8741                 res = transport_recv (header, HEADER_LENGTH);
8742
8743                 /* This will break if the socket is closed during shutdown too */
8744                 if (res != HEADER_LENGTH) {
8745                         DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
8746                         break;
8747                 }
8748
8749                 p = header;
8750                 end = header + HEADER_LENGTH;
8751
8752                 len = decode_int (p, &p, end);
8753                 id = decode_int (p, &p, end);
8754                 flags = decode_byte (p, &p, end);
8755                 command_set = decode_byte (p, &p, end);
8756                 command = decode_byte (p, &p, end);
8757
8758                 g_assert (flags == 0);
8759
8760                 if (log_level) {
8761                         const char *cmd_str;
8762                         char cmd_num [256];
8763
8764                         cmd_str = cmd_to_string (command_set, command);
8765                         if (!cmd_str) {
8766                                 sprintf (cmd_num, "%d", command);
8767                                 cmd_str = cmd_num;
8768                         }
8769                         
8770                         DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8771                 }
8772
8773                 data = g_malloc (len - HEADER_LENGTH);
8774                 if (len - HEADER_LENGTH > 0)
8775                 {
8776                         res = transport_recv (data, len - HEADER_LENGTH);
8777                         if (res != len - HEADER_LENGTH) {
8778                                 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
8779                                 break;
8780                         }
8781                 }
8782
8783                 p = data;
8784                 end = data + (len - HEADER_LENGTH);
8785
8786                 buffer_init (&buf, 128);
8787
8788                 err = ERR_NONE;
8789                 no_reply = FALSE;
8790
8791                 /* Process the request */
8792                 switch (command_set) {
8793                 case CMD_SET_VM:
8794                         err = vm_commands (command, id, p, end, &buf);
8795                         if (!err && command == CMD_VM_INVOKE_METHOD)
8796                                 /* Sent after the invoke is complete */
8797                                 no_reply = TRUE;
8798                         break;
8799                 case CMD_SET_EVENT_REQUEST:
8800                         err = event_commands (command, p, end, &buf);
8801                         break;
8802                 case CMD_SET_APPDOMAIN:
8803                         err = domain_commands (command, p, end, &buf);
8804                         break;
8805                 case CMD_SET_ASSEMBLY:
8806                         err = assembly_commands (command, p, end, &buf);
8807                         break;
8808                 case CMD_SET_MODULE:
8809                         err = module_commands (command, p, end, &buf);
8810                         break;
8811                 case CMD_SET_TYPE:
8812                         err = type_commands (command, p, end, &buf);
8813                         break;
8814                 case CMD_SET_METHOD:
8815                         err = method_commands (command, p, end, &buf);
8816                         break;
8817                 case CMD_SET_THREAD:
8818                         err = thread_commands (command, p, end, &buf);
8819                         break;
8820                 case CMD_SET_STACK_FRAME:
8821                         err = frame_commands (command, p, end, &buf);
8822                         break;
8823                 case CMD_SET_ARRAY_REF:
8824                         err = array_commands (command, p, end, &buf);
8825                         break;
8826                 case CMD_SET_STRING_REF:
8827                         err = string_commands (command, p, end, &buf);
8828                         break;
8829                 case CMD_SET_OBJECT_REF:
8830                         err = object_commands (command, p, end, &buf);
8831                         break;
8832                 default:
8833                         err = ERR_NOT_IMPLEMENTED;
8834                 }               
8835
8836                 if (!no_reply)
8837                         send_reply_packet (id, err, &buf);
8838
8839                 g_free (data);
8840                 buffer_free (&buf);
8841
8842                 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8843                         break;
8844         }
8845
8846         mono_set_is_debugger_attached (FALSE);
8847         
8848         mono_mutex_lock (&debugger_thread_exited_mutex);
8849         debugger_thread_exited = TRUE;
8850         mono_cond_signal (&debugger_thread_exited_cond);
8851         mono_mutex_unlock (&debugger_thread_exited_mutex);
8852
8853         DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8854         
8855         if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8856                 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8857                 start_debugger_thread ();
8858         }
8859         
8860         return 0;
8861 }
8862
8863 #else /* DISABLE_DEBUGGER_AGENT */
8864
8865 void
8866 mono_debugger_agent_parse_options (char *options)
8867 {
8868         g_error ("This runtime is configured with the debugger agent disabled.");
8869 }
8870
8871 void
8872 mono_debugger_agent_init (void)
8873 {
8874 }
8875
8876 void
8877 mono_debugger_agent_breakpoint_hit (void *sigctx)
8878 {
8879 }
8880
8881 void
8882 mono_debugger_agent_single_step_event (void *sigctx)
8883 {
8884 }
8885
8886 void
8887 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8888 {
8889 }
8890
8891 gboolean
8892 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8893 {
8894         return FALSE;
8895 }
8896
8897 void
8898 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8899                                                                           MonoContext *catch_ctx)
8900 {
8901 }
8902
8903 void
8904 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8905 {
8906 }
8907
8908 void
8909 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8910 {
8911 }
8912
8913 void
8914 mono_debugger_agent_user_break (void)
8915 {
8916         G_BREAKPOINT ();
8917 }
8918
8919 void
8920 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8921 {
8922 }
8923
8924 gboolean
8925 mono_debugger_agent_debug_log_is_enabled (void)
8926 {
8927         return FALSE;
8928 }
8929
8930 #endif
8931