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