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