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