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