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