Fix mono_arch_setup_async_callback and add mono_arch_setup_resume_sighandler_ctx...
[mono-project.git] / mono / mini / debugger-agent.c
blob0113fbcde38925c3657d74caaf23ab46fe0090aa
1 /**
2 * \file
3 * Soft Debugger back-end module
5 * Author:
6 * Zoltan Varga (vargaz@gmail.com)
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.
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>
38 #ifdef HAVE_PTHREAD_H
39 #include <pthread.h>
40 #endif
42 #ifdef HOST_WIN32
43 #ifdef _MSC_VER
44 #include <winsock2.h>
45 #include <process.h>
46 #endif
47 #include <ws2tcpip.h>
48 #endif
50 #ifdef HOST_ANDROID
51 #include <linux/in.h>
52 #include <linux/tcp.h>
53 #include <sys/endian.h>
54 #endif
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"
84 * On iOS we can't use System.Environment.Exit () as it will do the wrong
85 * shutdown sequence.
87 #if !defined (TARGET_IOS)
88 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
89 #endif
92 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
93 #define DISABLE_DEBUGGER_AGENT 1
94 #endif
96 #ifdef DISABLE_SOFT_DEBUG
97 #define DISABLE_DEBUGGER_AGENT 1
98 #endif
100 #ifndef DISABLE_DEBUGGER_AGENT
102 #include <mono/utils/mono-os-mutex.h>
104 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
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;
124 typedef struct
126 int id;
127 guint32 il_offset, native_offset;
128 MonoDomain *domain;
129 MonoMethod *method;
131 * If method is gshared, this is the actual instance, otherwise this is equal to
132 * method.
134 MonoMethod *actual_method;
136 * This is the method which is visible to debugger clients. Same as method,
137 * except for native-to-managed wrappers.
139 MonoMethod *api_method;
140 MonoContext ctx;
141 MonoDebugMethodJitInfo *jit;
142 MonoJitInfo *ji;
143 MonoInterpFrameHandle interp_frame;
144 gpointer frame_addr;
145 int flags;
146 mgreg_t *reg_locations [MONO_MAX_IREGS];
148 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
149 * the frame can become invalid.
151 gboolean has_ctx;
152 } StackFrame;
154 typedef struct _InvokeData InvokeData;
156 struct _InvokeData
158 int id;
159 int flags;
160 guint8 *p;
161 guint8 *endp;
162 /* This is the context which needs to be restored after the invoke */
163 MonoContext ctx;
164 gboolean has_ctx;
166 * If this is set, invoke this method with the arguments given by ARGS.
168 MonoMethod *method;
169 gpointer *args;
170 guint32 suspend_count;
171 int nmethods;
173 InvokeData *last_invoke;
176 typedef struct {
177 MonoThreadUnwindState context;
179 /* This is computed on demand when it is requested using the wire protocol */
180 /* It is freed up when the thread is resumed */
181 int frame_count;
182 StackFrame **frames;
184 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
185 * re-compute it.
187 gboolean frames_up_to_date;
189 * Points to data about a pending invoke which needs to be executed after the thread
190 * resumes.
192 InvokeData *pending_invoke;
194 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
195 * native code.
197 gboolean suspended;
199 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
200 * within a finite amount of time.
202 gboolean suspending;
204 * Set to TRUE if this thread is suspended in suspend_current ().
206 gboolean really_suspended;
207 /* Used to pass the context to the breakpoint/single step handler */
208 MonoContext handler_ctx;
209 /* Whenever thread_stop () was called for this thread */
210 gboolean terminated;
212 /* Whenever to disable breakpoints (used during invokes) */
213 gboolean disable_breakpoints;
216 * Number of times this thread has been resumed using resume_thread ().
218 guint32 resume_count;
220 MonoInternalThread *thread;
223 * Information about the frame which transitioned to native code for running
224 * threads.
226 StackFrameInfo async_last_frame;
229 * The context where the stack walk can be started for running threads.
231 MonoThreadUnwindState async_state;
234 * The context used for filter clauses
236 MonoThreadUnwindState filter_state;
238 gboolean abort_requested;
241 * The current mono_runtime_invoke_checked invocation.
243 InvokeData *invoke;
245 StackFrameInfo catch_frame;
246 gboolean has_catch_frame;
249 * The context which needs to be restored after handling a single step/breakpoint
250 * event. This is the same as the ctx at step/breakpoint site, but includes changes
251 * to caller saved registers done by set_var ().
253 MonoThreadUnwindState restore_state;
254 /* Frames computed from restore_state */
255 int restore_frame_count;
256 StackFrame **restore_frames;
258 /* The currently unloading appdomain */
259 MonoDomain *domain_unloading;
260 } DebuggerTlsData;
262 typedef struct {
263 const char *name;
264 void (*connect) (const char *address);
265 void (*close1) (void);
266 void (*close2) (void);
267 gboolean (*send) (void *buf, int len);
268 int (*recv) (void *buf, int len);
269 } DebuggerTransport;
272 * Wire Protocol definitions
275 #define HEADER_LENGTH 11
277 #define MAJOR_VERSION 2
278 #define MINOR_VERSION 45
280 typedef enum {
281 CMD_SET_VM = 1,
282 CMD_SET_OBJECT_REF = 9,
283 CMD_SET_STRING_REF = 10,
284 CMD_SET_THREAD = 11,
285 CMD_SET_ARRAY_REF = 13,
286 CMD_SET_EVENT_REQUEST = 15,
287 CMD_SET_STACK_FRAME = 16,
288 CMD_SET_APPDOMAIN = 20,
289 CMD_SET_ASSEMBLY = 21,
290 CMD_SET_METHOD = 22,
291 CMD_SET_TYPE = 23,
292 CMD_SET_MODULE = 24,
293 CMD_SET_FIELD = 25,
294 CMD_SET_EVENT = 64
295 } CommandSet;
297 typedef enum {
298 EVENT_KIND_VM_START = 0,
299 EVENT_KIND_VM_DEATH = 1,
300 EVENT_KIND_THREAD_START = 2,
301 EVENT_KIND_THREAD_DEATH = 3,
302 EVENT_KIND_APPDOMAIN_CREATE = 4,
303 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
304 EVENT_KIND_METHOD_ENTRY = 6,
305 EVENT_KIND_METHOD_EXIT = 7,
306 EVENT_KIND_ASSEMBLY_LOAD = 8,
307 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
308 EVENT_KIND_BREAKPOINT = 10,
309 EVENT_KIND_STEP = 11,
310 EVENT_KIND_TYPE_LOAD = 12,
311 EVENT_KIND_EXCEPTION = 13,
312 EVENT_KIND_KEEPALIVE = 14,
313 EVENT_KIND_USER_BREAK = 15,
314 EVENT_KIND_USER_LOG = 16
315 } EventKind;
317 typedef enum {
318 SUSPEND_POLICY_NONE = 0,
319 SUSPEND_POLICY_EVENT_THREAD = 1,
320 SUSPEND_POLICY_ALL = 2
321 } SuspendPolicy;
323 typedef enum {
324 ERR_NONE = 0,
325 ERR_INVALID_OBJECT = 20,
326 ERR_INVALID_FIELDID = 25,
327 ERR_INVALID_FRAMEID = 30,
328 ERR_NOT_IMPLEMENTED = 100,
329 ERR_NOT_SUSPENDED = 101,
330 ERR_INVALID_ARGUMENT = 102,
331 ERR_UNLOADED = 103,
332 ERR_NO_INVOCATION = 104,
333 ERR_ABSENT_INFORMATION = 105,
334 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
335 ERR_INVOKE_ABORTED = 107,
336 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
337 } ErrorCode;
339 typedef enum {
340 MOD_KIND_COUNT = 1,
341 MOD_KIND_THREAD_ONLY = 3,
342 MOD_KIND_LOCATION_ONLY = 7,
343 MOD_KIND_EXCEPTION_ONLY = 8,
344 MOD_KIND_STEP = 10,
345 MOD_KIND_ASSEMBLY_ONLY = 11,
346 MOD_KIND_SOURCE_FILE_ONLY = 12,
347 MOD_KIND_TYPE_NAME_ONLY = 13,
348 MOD_KIND_NONE = 14
349 } ModifierKind;
351 typedef enum {
352 STEP_DEPTH_INTO = 0,
353 STEP_DEPTH_OVER = 1,
354 STEP_DEPTH_OUT = 2
355 } StepDepth;
357 typedef enum {
358 STEP_SIZE_MIN = 0,
359 STEP_SIZE_LINE = 1
360 } StepSize;
362 typedef enum {
363 STEP_FILTER_NONE = 0,
364 STEP_FILTER_STATIC_CTOR = 1,
365 STEP_FILTER_DEBUGGER_HIDDEN = 2,
366 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
367 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
368 } StepFilter;
370 typedef enum {
371 TOKEN_TYPE_STRING = 0,
372 TOKEN_TYPE_TYPE = 1,
373 TOKEN_TYPE_FIELD = 2,
374 TOKEN_TYPE_METHOD = 3,
375 TOKEN_TYPE_UNKNOWN = 4
376 } DebuggerTokenType;
378 typedef enum {
379 VALUE_TYPE_ID_NULL = 0xf0,
380 VALUE_TYPE_ID_TYPE = 0xf1,
381 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
382 } ValueTypeId;
384 typedef enum {
385 FRAME_FLAG_DEBUGGER_INVOKE = 1,
386 FRAME_FLAG_NATIVE_TRANSITION = 2
387 } StackFrameFlags;
389 typedef enum {
390 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
391 INVOKE_FLAG_SINGLE_THREADED = 2,
392 INVOKE_FLAG_RETURN_OUT_THIS = 4,
393 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
394 INVOKE_FLAG_VIRTUAL = 16
395 } InvokeFlags;
397 typedef enum {
398 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
399 } BindingFlagsExtensions;
401 typedef enum {
402 CMD_VM_VERSION = 1,
403 CMD_VM_ALL_THREADS = 2,
404 CMD_VM_SUSPEND = 3,
405 CMD_VM_RESUME = 4,
406 CMD_VM_EXIT = 5,
407 CMD_VM_DISPOSE = 6,
408 CMD_VM_INVOKE_METHOD = 7,
409 CMD_VM_SET_PROTOCOL_VERSION = 8,
410 CMD_VM_ABORT_INVOKE = 9,
411 CMD_VM_SET_KEEPALIVE = 10,
412 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
413 CMD_VM_GET_TYPES = 12,
414 CMD_VM_INVOKE_METHODS = 13,
415 CMD_VM_START_BUFFERING = 14,
416 CMD_VM_STOP_BUFFERING = 15
417 } CmdVM;
419 typedef enum {
420 CMD_THREAD_GET_FRAME_INFO = 1,
421 CMD_THREAD_GET_NAME = 2,
422 CMD_THREAD_GET_STATE = 3,
423 CMD_THREAD_GET_INFO = 4,
424 CMD_THREAD_GET_ID = 5,
425 CMD_THREAD_GET_TID = 6,
426 CMD_THREAD_SET_IP = 7
427 } CmdThread;
429 typedef enum {
430 CMD_EVENT_REQUEST_SET = 1,
431 CMD_EVENT_REQUEST_CLEAR = 2,
432 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
433 } CmdEvent;
435 typedef enum {
436 CMD_COMPOSITE = 100
437 } CmdComposite;
439 typedef enum {
440 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
441 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
442 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
443 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
444 CMD_APPDOMAIN_CREATE_STRING = 5,
445 CMD_APPDOMAIN_GET_CORLIB = 6,
446 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
447 } CmdAppDomain;
449 typedef enum {
450 CMD_ASSEMBLY_GET_LOCATION = 1,
451 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
452 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
453 CMD_ASSEMBLY_GET_OBJECT = 4,
454 CMD_ASSEMBLY_GET_TYPE = 5,
455 CMD_ASSEMBLY_GET_NAME = 6,
456 CMD_ASSEMBLY_GET_DOMAIN = 7
457 } CmdAssembly;
459 typedef enum {
460 CMD_MODULE_GET_INFO = 1,
461 } CmdModule;
463 typedef enum {
464 CMD_FIELD_GET_INFO = 1,
465 } CmdField;
467 typedef enum {
468 CMD_METHOD_GET_NAME = 1,
469 CMD_METHOD_GET_DECLARING_TYPE = 2,
470 CMD_METHOD_GET_DEBUG_INFO = 3,
471 CMD_METHOD_GET_PARAM_INFO = 4,
472 CMD_METHOD_GET_LOCALS_INFO = 5,
473 CMD_METHOD_GET_INFO = 6,
474 CMD_METHOD_GET_BODY = 7,
475 CMD_METHOD_RESOLVE_TOKEN = 8,
476 CMD_METHOD_GET_CATTRS = 9,
477 CMD_METHOD_MAKE_GENERIC_METHOD = 10
478 } CmdMethod;
480 typedef enum {
481 CMD_TYPE_GET_INFO = 1,
482 CMD_TYPE_GET_METHODS = 2,
483 CMD_TYPE_GET_FIELDS = 3,
484 CMD_TYPE_GET_VALUES = 4,
485 CMD_TYPE_GET_OBJECT = 5,
486 CMD_TYPE_GET_SOURCE_FILES = 6,
487 CMD_TYPE_SET_VALUES = 7,
488 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
489 CMD_TYPE_GET_PROPERTIES = 9,
490 CMD_TYPE_GET_CATTRS = 10,
491 CMD_TYPE_GET_FIELD_CATTRS = 11,
492 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
493 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
494 CMD_TYPE_GET_VALUES_2 = 14,
495 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
496 CMD_TYPE_GET_INTERFACES = 16,
497 CMD_TYPE_GET_INTERFACE_MAP = 17,
498 CMD_TYPE_IS_INITIALIZED = 18,
499 CMD_TYPE_CREATE_INSTANCE = 19
500 } CmdType;
502 typedef enum {
503 CMD_STACK_FRAME_GET_VALUES = 1,
504 CMD_STACK_FRAME_GET_THIS = 2,
505 CMD_STACK_FRAME_SET_VALUES = 3,
506 CMD_STACK_FRAME_GET_DOMAIN = 4,
507 CMD_STACK_FRAME_SET_THIS = 5,
508 } CmdStackFrame;
510 typedef enum {
511 CMD_ARRAY_REF_GET_LENGTH = 1,
512 CMD_ARRAY_REF_GET_VALUES = 2,
513 CMD_ARRAY_REF_SET_VALUES = 3,
514 } CmdArray;
516 typedef enum {
517 CMD_STRING_REF_GET_VALUE = 1,
518 CMD_STRING_REF_GET_LENGTH = 2,
519 CMD_STRING_REF_GET_CHARS = 3
520 } CmdString;
522 typedef enum {
523 CMD_OBJECT_REF_GET_TYPE = 1,
524 CMD_OBJECT_REF_GET_VALUES = 2,
525 CMD_OBJECT_REF_IS_COLLECTED = 3,
526 CMD_OBJECT_REF_GET_ADDRESS = 4,
527 CMD_OBJECT_REF_GET_DOMAIN = 5,
528 CMD_OBJECT_REF_SET_VALUES = 6,
529 CMD_OBJECT_REF_GET_INFO = 7,
530 } CmdObject;
532 typedef struct {
533 ModifierKind kind;
534 union {
535 int count; /* For kind == MOD_KIND_COUNT */
536 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
537 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
538 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
539 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
540 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
541 StepFilter filter; /* For kind == MOD_KIND_STEP */
542 } data;
543 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
544 } Modifier;
546 typedef struct{
547 int id;
548 int event_kind;
549 int suspend_policy;
550 int nmodifiers;
551 gpointer info;
552 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
553 } EventRequest;
556 * Describes a single step request.
558 typedef struct {
559 EventRequest *req;
560 MonoInternalThread *thread;
561 StepDepth depth;
562 StepSize size;
563 StepFilter filter;
564 gpointer last_sp;
565 gpointer start_sp;
566 MonoMethod *start_method;
567 MonoMethod *last_method;
568 int last_line;
569 /* Whenever single stepping is performed using start/stop_single_stepping () */
570 gboolean global;
571 /* The list of breakpoints used to implement step-over */
572 GSList *bps;
573 /* The number of frames at the start of a step-over */
574 int nframes;
575 /* If set, don't stop in methods that are not part of user assemblies */
576 MonoAssembly** user_assemblies;
577 /* Used to distinguish stepping breakpoint hits in parallel tasks executions */
578 int async_id;
579 /* Used to know if we are in process of async step-out and distishing from exception breakpoints */
580 MonoMethod* async_stepout_method;
581 } SingleStepReq;
584 * Contains additional information for an event
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;
598 typedef struct {
599 guint8 *buf, *p, *end;
600 } Buffer;
602 typedef struct ReplyPacket {
603 int id;
604 int error;
605 Buffer *data;
606 } ReplyPacket;
608 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
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
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
626 #define CHECK_PROTOCOL_VERSION(major,minor) \
627 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
630 * Globals
633 static AgentConfig agent_config;
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.
642 static gint32 inited;
644 #ifndef DISABLE_SOCKET_TRANSPORT
645 static int conn_fd;
646 static int listen_fd;
647 #endif
649 static int packet_id = 0;
651 static int objref_id = 0;
653 static int event_request_id = 0;
655 static int frame_id = 0;
657 static GPtrArray *event_requests;
659 static MonoNativeTlsKey debugger_tls_id;
661 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
663 /* Maps MonoInternalThread -> DebuggerTlsData */
664 /* Protected by the loader lock */
665 static MonoGHashTable *thread_to_tls;
667 /* Maps tid -> MonoInternalThread */
668 /* Protected by the loader lock */
669 static MonoGHashTable *tid_to_thread;
671 /* Maps tid -> MonoThread (not MonoInternalThread) */
672 /* Protected by the loader lock */
673 static MonoGHashTable *tid_to_thread_obj;
675 static MonoNativeThreadId debugger_thread_id;
677 static MonoThreadHandle *debugger_thread_handle;
679 static int log_level;
681 static gboolean embedding;
683 static FILE *log_file;
685 /* Assemblies whose assembly load event has no been sent yet */
686 /* Protected by the dbg lock */
687 static GPtrArray *pending_assembly_loads;
689 /* Whenever the debugger thread has exited */
690 static gboolean debugger_thread_exited;
692 /* Cond variable used to wait for debugger_thread_exited becoming true */
693 static MonoCoopCond debugger_thread_exited_cond;
695 /* Mutex for the cond var above */
696 static MonoCoopMutex debugger_thread_exited_mutex;
698 /* The single step request instance */
699 static SingleStepReq *ss_req;
701 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
702 /* Number of single stepping operations in progress */
703 static int ss_count;
704 #endif
706 /* The protocol version of the client */
707 static int major_version, minor_version;
709 /* Whenever the variables above are set by the client */
710 static gboolean protocol_version_set;
712 /* A hash table containing all active domains */
713 /* Protected by the loader lock */
714 static GHashTable *domains;
716 /* The number of times the runtime is suspended */
717 static gint32 suspend_count;
719 /* Whenever to buffer reply messages and send them together */
720 static gboolean buffer_replies;
722 /* Buffered reply packets */
723 static ReplyPacket reply_packets [128];
724 int nreply_packets;
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;
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);
735 static gsize WINAPI debugger_thread (void *arg);
737 static void runtime_initialized (MonoProfiler *prof);
739 static void runtime_shutdown (MonoProfiler *prof);
741 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
743 static void thread_end (MonoProfiler *prof, uintptr_t tid);
745 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain);
747 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
749 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
751 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
753 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
755 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
757 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly);
759 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
761 static void emit_assembly_load (gpointer assembly, gpointer user_data);
763 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
765 static void jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
767 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
769 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
771 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
773 static void start_single_stepping (void);
775 static void stop_single_stepping (void);
777 static void suspend_current (void);
779 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
781 static void clear_types_for_assembly (MonoAssembly *assembly);
783 static void clear_breakpoints_for_domain (MonoDomain *domain);
785 static void process_profiler_event (EventKind event, gpointer arg);
787 /* Submodule init/cleanup */
788 static void breakpoints_init (void);
789 static void breakpoints_cleanup (void);
791 static void objrefs_init (void);
792 static void objrefs_cleanup (void);
794 static void ids_init (void);
795 static void ids_cleanup (void);
797 static void suspend_init (void);
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);
804 static void start_debugger_thread (void);
805 static void stop_debugger_thread (void);
807 static void finish_agent_init (gboolean on_startup);
809 static void process_profiler_event (EventKind event, gpointer arg);
811 static void invalidate_frames (DebuggerTlsData *tls);
813 #ifndef DISABLE_SOCKET_TRANSPORT
814 static void
815 register_socket_transport (void);
816 #endif
818 static inline gboolean
819 is_debugger_thread (void)
821 MonoInternalThread *internal;
823 internal = mono_thread_internal_current ();
824 if (!internal)
825 return FALSE;
827 return internal->debugger_thread;
830 static int
831 parse_address (char *address, char **host, int *port)
833 char *pos = strchr (address, ':');
835 if (pos == NULL || pos == address)
836 return 1;
838 size_t len = pos - address;
839 *host = (char *)g_malloc (len + 1);
840 memcpy (*host, address, len);
841 (*host) [len] = '\0';
843 *port = atoi (pos + 1);
845 return 0;
848 static void
849 print_usage (void)
851 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
852 fprintf (stderr, "Available options:\n");
853 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
854 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
855 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
856 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
857 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
858 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
859 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
860 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
861 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
862 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
865 static gboolean
866 parse_flag (const char *option, char *flag)
868 if (!strcmp (flag, "y"))
869 return TRUE;
870 else if (!strcmp (flag, "n"))
871 return FALSE;
872 else {
873 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
874 exit (1);
875 return FALSE;
879 void
880 mono_debugger_agent_parse_options (char *options)
882 char **args, **ptr;
883 char *host;
884 int port;
885 char *extra;
887 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
888 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
889 exit (1);
890 #endif
892 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
893 if (extra) {
894 options = g_strdup_printf ("%s,%s", options, extra);
895 g_free (extra);
898 agent_config.enabled = TRUE;
899 agent_config.suspend = TRUE;
900 agent_config.server = FALSE;
901 agent_config.defer = FALSE;
902 agent_config.address = NULL;
904 //agent_config.log_level = 10;
906 args = g_strsplit (options, ",", -1);
907 for (ptr = args; ptr && *ptr; ptr ++) {
908 char *arg = *ptr;
910 if (strncmp (arg, "transport=", 10) == 0) {
911 agent_config.transport = g_strdup (arg + 10);
912 } else if (strncmp (arg, "address=", 8) == 0) {
913 agent_config.address = g_strdup (arg + 8);
914 } else if (strncmp (arg, "loglevel=", 9) == 0) {
915 agent_config.log_level = atoi (arg + 9);
916 } else if (strncmp (arg, "logfile=", 8) == 0) {
917 agent_config.log_file = g_strdup (arg + 8);
918 } else if (strncmp (arg, "suspend=", 8) == 0) {
919 agent_config.suspend = parse_flag ("suspend", arg + 8);
920 } else if (strncmp (arg, "server=", 7) == 0) {
921 agent_config.server = parse_flag ("server", arg + 7);
922 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
923 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
924 } else if (strncmp (arg, "onthrow=", 8) == 0) {
925 /* We support multiple onthrow= options */
926 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
927 } else if (strncmp (arg, "onthrow", 7) == 0) {
928 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
929 } else if (strncmp (arg, "help", 4) == 0) {
930 print_usage ();
931 exit (0);
932 } else if (strncmp (arg, "timeout=", 8) == 0) {
933 agent_config.timeout = atoi (arg + 8);
934 } else if (strncmp (arg, "launch=", 7) == 0) {
935 agent_config.launch = g_strdup (arg + 7);
936 } else if (strncmp (arg, "embedding=", 10) == 0) {
937 agent_config.embedding = atoi (arg + 10) == 1;
938 } else if (strncmp (arg, "keepalive=", 10) == 0) {
939 agent_config.keepalive = atoi (arg + 10);
940 } else if (strncmp (arg, "setpgid=", 8) == 0) {
941 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
942 } else {
943 print_usage ();
944 exit (1);
948 if (agent_config.server && !agent_config.suspend) {
949 /* Waiting for deferred attachment */
950 agent_config.defer = TRUE;
951 if (agent_config.address == NULL) {
952 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
956 //agent_config.log_level = 0;
958 if (agent_config.transport == NULL) {
959 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
960 exit (1);
963 if (agent_config.address == NULL && !agent_config.server) {
964 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
965 exit (1);
968 // FIXME:
969 if (!strcmp (agent_config.transport, "dt_socket")) {
970 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
971 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
972 exit (1);
977 void
978 mono_debugger_agent_init (void)
980 mono_coop_mutex_init_recursive (&debug_mutex);
982 if (!agent_config.enabled)
983 return;
985 transport_init ();
987 /* Need to know whenever a thread has acquired the loader mutex */
988 mono_loader_lock_track_ownership (TRUE);
990 event_requests = g_ptr_array_new ();
992 mono_coop_mutex_init (&debugger_thread_exited_mutex);
993 mono_coop_cond_init (&debugger_thread_exited_cond);
995 MonoProfilerHandle prof = mono_profiler_create (NULL);
996 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
997 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
998 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
999 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
1000 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
1001 mono_profiler_set_thread_started_callback (prof, thread_startup);
1002 mono_profiler_set_thread_stopped_callback (prof, thread_end);
1003 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
1004 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
1005 mono_profiler_set_jit_done_callback (prof, jit_done);
1006 mono_profiler_set_jit_failed_callback (prof, jit_failed);
1008 mono_native_tls_alloc (&debugger_tls_id, NULL);
1010 /* Needed by the hash_table_new_type () call below */
1011 mono_gc_base_init ();
1013 thread_to_tls = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger TLS Table");
1015 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Table");
1017 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Object Table");
1019 pending_assembly_loads = g_ptr_array_new ();
1020 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1022 log_level = agent_config.log_level;
1024 embedding = agent_config.embedding;
1025 disconnected = TRUE;
1027 if (agent_config.log_file) {
1028 log_file = fopen (agent_config.log_file, "w+");
1029 if (!log_file) {
1030 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1031 exit (1);
1033 } else {
1034 log_file = stdout;
1037 ids_init ();
1038 objrefs_init ();
1039 breakpoints_init ();
1040 suspend_init ();
1042 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1044 * This is needed because currently we don't handle liveness info.
1046 mini_get_debug_options ()->mdb_optimizations = TRUE;
1048 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1049 /* This is needed because we can't set local variables in registers yet */
1050 mono_disable_optimizations (MONO_OPT_LINEARS);
1051 #endif
1054 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1055 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1056 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1057 * workaround.
1059 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1061 #ifdef HAVE_SETPGID
1062 if (agent_config.setpgid)
1063 setpgid (0, 0);
1064 #endif
1066 if (!agent_config.onuncaught && !agent_config.onthrow)
1067 finish_agent_init (TRUE);
1071 * finish_agent_init:
1073 * Finish the initialization of the agent. This involves connecting the transport
1074 * and starting the agent thread. This is either done at startup, or
1075 * in response to some event like an unhandled exception.
1077 static void
1078 finish_agent_init (gboolean on_startup)
1080 int res;
1082 if (mono_atomic_cas_i32 (&inited, 1, 0) == 1)
1083 return;
1085 if (agent_config.launch) {
1086 char *argv [16];
1088 // FIXME: Generated address
1089 // FIXME: Races with transport_connect ()
1091 argv [0] = agent_config.launch;
1092 argv [1] = agent_config.transport;
1093 argv [2] = agent_config.address;
1094 argv [3] = NULL;
1096 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1097 if (!res) {
1098 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1099 exit (1);
1103 transport_connect (agent_config.address);
1105 if (!on_startup) {
1106 /* Do some which is usually done after sending the VMStart () event */
1107 vm_start_event_sent = TRUE;
1108 start_debugger_thread ();
1112 static void
1113 mono_debugger_agent_cleanup (void)
1115 if (!inited)
1116 return;
1118 stop_debugger_thread ();
1120 breakpoints_cleanup ();
1121 objrefs_cleanup ();
1122 ids_cleanup ();
1126 * SOCKET TRANSPORT
1129 #ifndef DISABLE_SOCKET_TRANSPORT
1132 * recv_length:
1134 * recv() + handle incomplete reads and EINTR
1136 static int
1137 socket_transport_recv (void *buf, int len)
1139 int res;
1140 int total = 0;
1141 int fd = conn_fd;
1142 int flags = 0;
1143 static gint64 last_keepalive;
1144 gint64 msecs;
1146 MONO_ENTER_GC_SAFE;
1148 do {
1149 again:
1150 res = recv (fd, (char *) buf + total, len - total, flags);
1151 if (res > 0)
1152 total += res;
1153 if (agent_config.keepalive) {
1154 gboolean need_keepalive = FALSE;
1155 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1156 need_keepalive = TRUE;
1157 } else if (res == -1) {
1158 /* This could happen if recv () is interrupted repeatedly */
1159 msecs = mono_msec_ticks ();
1160 if (msecs - last_keepalive >= agent_config.keepalive) {
1161 need_keepalive = TRUE;
1162 last_keepalive = msecs;
1165 if (need_keepalive) {
1166 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1167 goto again;
1170 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1172 MONO_EXIT_GC_SAFE;
1174 return total;
1177 static void
1178 set_keepalive (void)
1180 struct timeval tv;
1181 int result;
1183 if (!agent_config.keepalive || !conn_fd)
1184 return;
1186 tv.tv_sec = agent_config.keepalive / 1000;
1187 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1189 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1190 g_assert (result >= 0);
1193 static int
1194 socket_transport_accept (int socket_fd)
1196 MONO_ENTER_GC_SAFE;
1197 conn_fd = accept (socket_fd, NULL, NULL);
1198 MONO_EXIT_GC_SAFE;
1200 if (conn_fd == -1) {
1201 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1202 } else {
1203 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1206 return conn_fd;
1209 static gboolean
1210 socket_transport_send (void *data, int len)
1212 int res;
1214 MONO_ENTER_GC_SAFE;
1216 do {
1217 res = send (conn_fd, data, len, 0);
1218 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1220 MONO_EXIT_GC_SAFE;
1222 if (res != len)
1223 return FALSE;
1224 else
1225 return TRUE;
1229 * socket_transport_connect:
1231 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1233 static void
1234 socket_transport_connect (const char *address)
1236 MonoAddressInfo *result;
1237 MonoAddressEntry *rp;
1238 int sfd = -1, s, res;
1239 char *host;
1240 int port;
1242 if (agent_config.address) {
1243 res = parse_address (agent_config.address, &host, &port);
1244 g_assert (res == 0);
1245 } else {
1246 host = NULL;
1247 port = 0;
1250 conn_fd = -1;
1251 listen_fd = -1;
1253 if (host) {
1255 mono_network_init ();
1257 /* Obtain address(es) matching host/port */
1258 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1259 if (s != 0) {
1260 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1261 exit (1);
1265 if (agent_config.server) {
1266 /* Wait for a connection */
1267 if (!host) {
1268 struct sockaddr_in addr;
1269 socklen_t addrlen;
1271 /* No address, generate one */
1272 sfd = socket (AF_INET, SOCK_STREAM, 0);
1273 g_assert (sfd);
1275 /* This will bind the socket to a random port */
1276 res = listen (sfd, 16);
1277 if (res == -1) {
1278 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1279 exit (1);
1281 listen_fd = sfd;
1283 addrlen = sizeof (addr);
1284 memset (&addr, 0, sizeof (addr));
1285 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1286 g_assert (res == 0);
1288 host = (char*)"127.0.0.1";
1289 port = ntohs (addr.sin_port);
1291 /* Emit the address to stdout */
1292 /* FIXME: Should print another interface, not localhost */
1293 printf ("%s:%d\n", host, port);
1294 } else {
1295 /* Listen on the provided address */
1296 for (rp = result->entries; rp != NULL; rp = rp->next) {
1297 MonoSocketAddress sockaddr;
1298 socklen_t sock_len;
1299 int n = 1;
1301 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1303 sfd = socket (rp->family, rp->socktype,
1304 rp->protocol);
1305 if (sfd == -1)
1306 continue;
1308 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1309 continue;
1311 res = bind (sfd, &sockaddr.addr, sock_len);
1312 if (res == -1)
1313 continue;
1315 res = listen (sfd, 16);
1316 if (res == -1)
1317 continue;
1318 listen_fd = sfd;
1319 break;
1322 mono_free_address_info (result);
1325 if (agent_config.defer)
1326 return;
1328 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1330 if (agent_config.timeout) {
1331 fd_set readfds;
1332 struct timeval tv;
1334 tv.tv_sec = 0;
1335 tv.tv_usec = agent_config.timeout * 1000;
1336 FD_ZERO (&readfds);
1337 FD_SET (sfd, &readfds);
1339 MONO_ENTER_GC_SAFE;
1340 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1341 MONO_EXIT_GC_SAFE;
1343 if (res == 0) {
1344 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1345 exit (1);
1349 conn_fd = socket_transport_accept (sfd);
1350 if (conn_fd == -1)
1351 exit (1);
1353 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1354 } else {
1355 /* Connect to the specified address */
1356 /* FIXME: Respect the timeout */
1357 for (rp = result->entries; rp != NULL; rp = rp->next) {
1358 MonoSocketAddress sockaddr;
1359 socklen_t sock_len;
1361 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1363 sfd = socket (rp->family, rp->socktype,
1364 rp->protocol);
1365 if (sfd == -1)
1366 continue;
1368 MONO_ENTER_GC_SAFE;
1369 res = connect (sfd, &sockaddr.addr, sock_len);
1370 MONO_EXIT_GC_SAFE;
1372 if (res != -1)
1373 break; /* Success */
1375 MONO_ENTER_GC_SAFE;
1376 close (sfd);
1377 MONO_EXIT_GC_SAFE;
1380 if (rp == 0) {
1381 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1382 exit (1);
1385 conn_fd = sfd;
1387 mono_free_address_info (result);
1390 if (!transport_handshake ())
1391 exit (1);
1394 static void
1395 socket_transport_close1 (void)
1397 /* This will interrupt the agent thread */
1398 /* Close the read part only so it can still send back replies */
1399 /* Also shut down the connection listener so that we can exit normally */
1400 #ifdef HOST_WIN32
1401 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1402 shutdown (conn_fd, SD_BOTH);
1403 shutdown (listen_fd, SD_BOTH);
1404 closesocket (listen_fd);
1405 #else
1406 shutdown (conn_fd, SHUT_RD);
1407 shutdown (listen_fd, SHUT_RDWR);
1408 MONO_ENTER_GC_SAFE;
1409 close (listen_fd);
1410 MONO_EXIT_GC_SAFE;
1411 #endif
1414 static void
1415 socket_transport_close2 (void)
1417 #ifdef HOST_WIN32
1418 shutdown (conn_fd, SD_BOTH);
1419 #else
1420 shutdown (conn_fd, SHUT_RDWR);
1421 #endif
1424 static void
1425 register_socket_transport (void)
1427 DebuggerTransport trans;
1429 trans.name = "dt_socket";
1430 trans.connect = socket_transport_connect;
1431 trans.close1 = socket_transport_close1;
1432 trans.close2 = socket_transport_close2;
1433 trans.send = socket_transport_send;
1434 trans.recv = socket_transport_recv;
1436 register_transport (&trans);
1440 * socket_fd_transport_connect:
1443 static void
1444 socket_fd_transport_connect (const char *address)
1446 int res;
1448 res = sscanf (address, "%d", &conn_fd);
1449 if (res != 1) {
1450 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1451 exit (1);
1454 if (!transport_handshake ())
1455 exit (1);
1458 static void
1459 register_socket_fd_transport (void)
1461 DebuggerTransport trans;
1463 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1464 trans.name = "socket-fd";
1465 trans.connect = socket_fd_transport_connect;
1466 trans.close1 = socket_transport_close1;
1467 trans.close2 = socket_transport_close2;
1468 trans.send = socket_transport_send;
1469 trans.recv = socket_transport_recv;
1471 register_transport (&trans);
1474 #endif /* DISABLE_SOCKET_TRANSPORT */
1477 * TRANSPORT CODE
1480 #define MAX_TRANSPORTS 16
1482 static DebuggerTransport *transport;
1484 static DebuggerTransport transports [MAX_TRANSPORTS];
1485 static int ntransports;
1487 MONO_API void
1488 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1490 void
1491 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1493 register_transport (trans);
1496 static void
1497 register_transport (DebuggerTransport *trans)
1499 g_assert (ntransports < MAX_TRANSPORTS);
1501 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1502 ntransports ++;
1505 static void
1506 transport_init (void)
1508 int i;
1510 #ifndef DISABLE_SOCKET_TRANSPORT
1511 register_socket_transport ();
1512 register_socket_fd_transport ();
1513 #endif
1515 for (i = 0; i < ntransports; ++i) {
1516 if (!strcmp (agent_config.transport, transports [i].name))
1517 break;
1519 if (i == ntransports) {
1520 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1521 for (i = 0; i < ntransports; ++i)
1522 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1523 fprintf (stderr, "\n");
1524 exit (1);
1526 transport = &transports [i];
1529 void
1530 transport_connect (const char *address)
1532 transport->connect (address);
1535 static void
1536 transport_close1 (void)
1538 transport->close1 ();
1541 static void
1542 transport_close2 (void)
1544 transport->close2 ();
1547 static int
1548 transport_send (void *buf, int len)
1550 return transport->send (buf, len);
1553 static int
1554 transport_recv (void *buf, int len)
1556 return transport->recv (buf, len);
1559 gboolean
1560 mono_debugger_agent_transport_handshake (void)
1562 return transport_handshake ();
1565 static gboolean
1566 transport_handshake (void)
1568 char handshake_msg [128];
1569 guint8 buf [128];
1570 int res;
1572 disconnected = TRUE;
1574 /* Write handshake message */
1575 sprintf (handshake_msg, "DWP-Handshake");
1577 do {
1578 res = transport_send (handshake_msg, strlen (handshake_msg));
1579 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1581 g_assert (res != -1);
1583 /* Read answer */
1584 res = transport_recv (buf, strlen (handshake_msg));
1585 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1586 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1587 return FALSE;
1591 * To support older clients, the client sends its protocol version after connecting
1592 * using a command. Until that is received, default to our protocol version.
1594 major_version = MAJOR_VERSION;
1595 minor_version = MINOR_VERSION;
1596 protocol_version_set = FALSE;
1598 #ifndef DISABLE_SOCKET_TRANSPORT
1599 // FIXME: Move this somewhere else
1601 * Set TCP_NODELAY on the socket so the client receives events/command
1602 * results immediately.
1604 if (conn_fd) {
1605 int flag = 1;
1606 int result = setsockopt (conn_fd,
1607 IPPROTO_TCP,
1608 TCP_NODELAY,
1609 (char *) &flag,
1610 sizeof(int));
1611 g_assert (result >= 0);
1614 set_keepalive ();
1615 #endif
1617 disconnected = FALSE;
1618 return TRUE;
1621 static void
1622 stop_debugger_thread (void)
1624 if (!inited)
1625 return;
1627 transport_close1 ();
1630 * Wait for the thread to exit.
1632 * If we continue with the shutdown without waiting for it, then the client might
1633 * not receive an answer to its last command like a resume.
1635 if (!is_debugger_thread ()) {
1636 do {
1637 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1638 if (!debugger_thread_exited)
1639 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1640 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1641 } while (!debugger_thread_exited);
1643 if (debugger_thread_handle)
1644 mono_thread_info_wait_one_handle (debugger_thread_handle, MONO_INFINITE_WAIT, TRUE);
1647 transport_close2 ();
1650 static void
1651 start_debugger_thread (void)
1653 ERROR_DECL (error);
1654 MonoInternalThread *thread;
1656 thread = mono_thread_create_internal (mono_get_root_domain (), debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, error);
1657 mono_error_assert_ok (error);
1659 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1660 g_assert (debugger_thread_handle);
1664 * Functions to decode protocol data
1667 static inline int
1668 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1670 *endbuf = buf + 1;
1671 g_assert (*endbuf <= limit);
1672 return buf [0];
1675 static inline int
1676 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1678 *endbuf = buf + 4;
1679 g_assert (*endbuf <= limit);
1681 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1684 static inline gint64
1685 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1687 guint32 high = decode_int (buf, &buf, limit);
1688 guint32 low = decode_int (buf, &buf, limit);
1690 *endbuf = buf;
1692 return ((((guint64)high) << 32) | ((guint64)low));
1695 static inline int
1696 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1698 return decode_int (buf, endbuf, limit);
1701 static inline char*
1702 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1704 int len = decode_int (buf, &buf, limit);
1705 char *s;
1707 if (len < 0) {
1708 *endbuf = buf;
1709 return NULL;
1712 s = (char *)g_malloc (len + 1);
1713 g_assert (s);
1715 memcpy (s, buf, len);
1716 s [len] = '\0';
1717 buf += len;
1718 *endbuf = buf;
1720 return s;
1724 * Functions to encode protocol data
1727 static inline void
1728 buffer_init (Buffer *buf, int size)
1730 buf->buf = (guint8 *)g_malloc (size);
1731 buf->p = buf->buf;
1732 buf->end = buf->buf + size;
1735 static inline int
1736 buffer_len (Buffer *buf)
1738 return buf->p - buf->buf;
1741 static inline void
1742 buffer_make_room (Buffer *buf, int size)
1744 if (buf->end - buf->p < size) {
1745 int new_size = buf->end - buf->buf + size + 32;
1746 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1747 size = buf->p - buf->buf;
1748 buf->buf = p;
1749 buf->p = p + size;
1750 buf->end = buf->buf + new_size;
1754 static inline void
1755 buffer_add_byte (Buffer *buf, guint8 val)
1757 buffer_make_room (buf, 1);
1758 buf->p [0] = val;
1759 buf->p++;
1762 static inline void
1763 buffer_add_short (Buffer *buf, guint32 val)
1765 buffer_make_room (buf, 2);
1766 buf->p [0] = (val >> 8) & 0xff;
1767 buf->p [1] = (val >> 0) & 0xff;
1768 buf->p += 2;
1771 static inline void
1772 buffer_add_int (Buffer *buf, guint32 val)
1774 buffer_make_room (buf, 4);
1775 buf->p [0] = (val >> 24) & 0xff;
1776 buf->p [1] = (val >> 16) & 0xff;
1777 buf->p [2] = (val >> 8) & 0xff;
1778 buf->p [3] = (val >> 0) & 0xff;
1779 buf->p += 4;
1782 static inline void
1783 buffer_add_long (Buffer *buf, guint64 l)
1785 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1786 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1789 static inline void
1790 buffer_add_id (Buffer *buf, int id)
1792 buffer_add_int (buf, (guint64)id);
1795 static inline void
1796 buffer_add_data (Buffer *buf, guint8 *data, int len)
1798 buffer_make_room (buf, len);
1799 memcpy (buf->p, data, len);
1800 buf->p += len;
1803 static inline void
1804 buffer_add_string (Buffer *buf, const char *str)
1806 int len;
1808 if (str == NULL) {
1809 buffer_add_int (buf, 0);
1810 } else {
1811 len = strlen (str);
1812 buffer_add_int (buf, len);
1813 buffer_add_data (buf, (guint8*)str, len);
1817 static inline void
1818 buffer_add_buffer (Buffer *buf, Buffer *data)
1820 buffer_add_data (buf, data->buf, buffer_len (data));
1823 static inline void
1824 buffer_free (Buffer *buf)
1826 g_free (buf->buf);
1829 static gboolean
1830 send_packet (int command_set, int command, Buffer *data)
1832 Buffer buf;
1833 int len, id;
1834 gboolean res;
1836 id = mono_atomic_inc_i32 (&packet_id);
1838 len = data->p - data->buf + 11;
1839 buffer_init (&buf, len);
1840 buffer_add_int (&buf, len);
1841 buffer_add_int (&buf, id);
1842 buffer_add_byte (&buf, 0); /* flags */
1843 buffer_add_byte (&buf, command_set);
1844 buffer_add_byte (&buf, command);
1845 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1847 res = transport_send (buf.buf, len);
1849 buffer_free (&buf);
1851 return res;
1854 static gboolean
1855 send_reply_packets (int npackets, ReplyPacket *packets)
1857 Buffer buf;
1858 int i, len;
1859 gboolean res;
1861 len = 0;
1862 for (i = 0; i < npackets; ++i)
1863 len += buffer_len (packets [i].data) + 11;
1864 buffer_init (&buf, len);
1865 for (i = 0; i < npackets; ++i) {
1866 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1867 buffer_add_int (&buf, packets [i].id);
1868 buffer_add_byte (&buf, 0x80); /* flags */
1869 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1870 buffer_add_byte (&buf, packets [i].error);
1871 buffer_add_buffer (&buf, packets [i].data);
1874 res = transport_send (buf.buf, len);
1876 buffer_free (&buf);
1878 return res;
1881 static gboolean
1882 send_reply_packet (int id, int error, Buffer *data)
1884 ReplyPacket packet;
1886 memset (&packet, 0, sizeof (ReplyPacket));
1887 packet.id = id;
1888 packet.error = error;
1889 packet.data = data;
1891 return send_reply_packets (1, &packet);
1894 static void
1895 send_buffered_reply_packets (void)
1897 int i;
1899 send_reply_packets (nreply_packets, reply_packets);
1900 for (i = 0; i < nreply_packets; ++i)
1901 buffer_free (reply_packets [i].data);
1902 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1903 nreply_packets = 0;
1906 static void
1907 buffer_reply_packet (int id, int error, Buffer *data)
1909 ReplyPacket *p;
1911 if (nreply_packets == 128)
1912 send_buffered_reply_packets ();
1914 p = &reply_packets [nreply_packets];
1915 p->id = id;
1916 p->error = error;
1917 p->data = g_new0 (Buffer, 1);
1918 buffer_init (p->data, buffer_len (data));
1919 buffer_add_buffer (p->data, data);
1920 nreply_packets ++;
1924 * OBJECT IDS
1928 * Represents an object accessible by the debugger client.
1930 typedef struct {
1931 /* Unique id used in the wire protocol to refer to objects */
1932 int id;
1934 * A weakref gc handle pointing to the object. The gc handle is used to
1935 * detect if the object was garbage collected.
1937 guint32 handle;
1938 } ObjRef;
1940 /* Maps objid -> ObjRef */
1941 /* Protected by the loader lock */
1942 static GHashTable *objrefs;
1943 /* Protected by the loader lock */
1944 static GHashTable *obj_to_objref;
1945 /* Protected by the dbg lock */
1946 static MonoGHashTable *suspended_objs;
1948 static void
1949 free_objref (gpointer value)
1951 ObjRef *o = (ObjRef *)value;
1953 mono_gchandle_free (o->handle);
1955 g_free (o);
1958 static void
1959 objrefs_init (void)
1961 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1962 obj_to_objref = g_hash_table_new (NULL, NULL);
1963 suspended_objs = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Suspended Object Table");
1966 static void
1967 objrefs_cleanup (void)
1969 g_hash_table_destroy (objrefs);
1970 objrefs = NULL;
1974 * Return an ObjRef for OBJ.
1976 static ObjRef*
1977 get_objref (MonoObject *obj)
1979 ObjRef *ref;
1980 GSList *reflist = NULL, *l;
1981 int hash = 0;
1983 if (obj == NULL)
1984 return NULL;
1986 if (suspend_count) {
1988 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1990 dbg_lock ();
1991 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1992 dbg_unlock ();
1995 mono_loader_lock ();
1997 /* FIXME: The tables can grow indefinitely */
1999 if (mono_gc_is_moving ()) {
2001 * Objects can move, so use a hash table mapping hash codes to lists of
2002 * ObjRef structures.
2004 hash = mono_object_hash (obj);
2006 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2007 for (l = reflist; l; l = l->next) {
2008 ref = (ObjRef *)l->data;
2009 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2010 mono_loader_unlock ();
2011 return ref;
2014 } else {
2015 /* Use a hash table with masked pointers to internalize object references */
2016 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2017 /* ref might refer to a different object with the same addr which was GCd */
2018 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2019 mono_loader_unlock ();
2020 return ref;
2024 ref = g_new0 (ObjRef, 1);
2025 ref->id = mono_atomic_inc_i32 (&objref_id);
2026 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2028 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2030 if (mono_gc_is_moving ()) {
2031 reflist = g_slist_append (reflist, ref);
2032 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2033 } else {
2034 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2037 mono_loader_unlock ();
2039 return ref;
2042 static gboolean
2043 true_pred (gpointer key, gpointer value, gpointer user_data)
2045 return TRUE;
2048 static void
2049 clear_suspended_objs (void)
2051 dbg_lock ();
2052 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2053 dbg_unlock ();
2056 static inline int
2057 get_objid (MonoObject *obj)
2059 if (!obj)
2060 return 0;
2061 else
2062 return get_objref (obj)->id;
2066 * Set OBJ to the object identified by OBJID.
2067 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2068 * collected.
2070 static ErrorCode
2071 get_object_allow_null (int objid, MonoObject **obj)
2073 ObjRef *ref;
2075 if (objid == 0) {
2076 *obj = NULL;
2077 return ERR_NONE;
2080 if (!objrefs)
2081 return ERR_INVALID_OBJECT;
2083 mono_loader_lock ();
2085 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2087 if (ref) {
2088 *obj = mono_gchandle_get_target (ref->handle);
2089 mono_loader_unlock ();
2090 if (!(*obj))
2091 return ERR_INVALID_OBJECT;
2092 return ERR_NONE;
2093 } else {
2094 mono_loader_unlock ();
2095 return ERR_INVALID_OBJECT;
2099 static ErrorCode
2100 get_object (int objid, MonoObject **obj)
2102 ErrorCode err = get_object_allow_null (objid, obj);
2104 if (err != ERR_NONE)
2105 return err;
2106 if (!(*obj))
2107 return ERR_INVALID_OBJECT;
2108 return ERR_NONE;
2111 static inline int
2112 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2114 return decode_id (buf, endbuf, limit);
2117 static inline void
2118 buffer_add_objid (Buffer *buf, MonoObject *o)
2120 buffer_add_id (buf, get_objid (o));
2124 * IDS
2127 typedef enum {
2128 ID_ASSEMBLY = 0,
2129 ID_MODULE = 1,
2130 ID_TYPE = 2,
2131 ID_METHOD = 3,
2132 ID_FIELD = 4,
2133 ID_DOMAIN = 5,
2134 ID_PROPERTY = 6,
2135 ID_NUM
2136 } IdType;
2139 * Represents a runtime structure accessible to the debugger client
2141 typedef struct {
2142 /* Unique id used in the wire protocol */
2143 int id;
2144 /* Domain of the runtime structure, NULL if the domain was unloaded */
2145 MonoDomain *domain;
2146 union {
2147 gpointer val;
2148 MonoClass *klass;
2149 MonoMethod *method;
2150 MonoImage *image;
2151 MonoAssembly *assembly;
2152 MonoClassField *field;
2153 MonoDomain *domain;
2154 MonoProperty *property;
2155 } data;
2156 } Id;
2158 typedef struct {
2159 /* Maps runtime structure -> Id */
2160 /* Protected by the dbg lock */
2161 GHashTable *val_to_id [ID_NUM];
2162 /* Classes whose class load event has been sent */
2163 /* Protected by the loader lock */
2164 GHashTable *loaded_classes;
2165 /* Maps MonoClass->GPtrArray of file names */
2166 GHashTable *source_files;
2167 /* Maps source file basename -> GSList of classes */
2168 GHashTable *source_file_to_class;
2169 /* Same with ignore-case */
2170 GHashTable *source_file_to_class_ignorecase;
2171 } AgentDomainInfo;
2173 /* Maps id -> Id */
2174 /* Protected by the dbg lock */
2175 static GPtrArray *ids [ID_NUM];
2177 static void
2178 ids_init (void)
2180 int i;
2182 for (i = 0; i < ID_NUM; ++i)
2183 ids [i] = g_ptr_array_new ();
2186 static void
2187 ids_cleanup (void)
2189 int i, j;
2191 for (i = 0; i < ID_NUM; ++i) {
2192 if (ids [i]) {
2193 for (j = 0; j < ids [i]->len; ++j)
2194 g_free (g_ptr_array_index (ids [i], j));
2195 g_ptr_array_free (ids [i], TRUE);
2197 ids [i] = NULL;
2201 void
2202 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2204 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2205 int i, j;
2206 GHashTableIter iter;
2207 GPtrArray *file_names;
2208 char *basename;
2209 GSList *l;
2211 if (info) {
2212 for (i = 0; i < ID_NUM; ++i)
2213 if (info->val_to_id [i])
2214 g_hash_table_destroy (info->val_to_id [i]);
2215 g_hash_table_destroy (info->loaded_classes);
2217 g_hash_table_iter_init (&iter, info->source_files);
2218 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2219 for (i = 0; i < file_names->len; ++i)
2220 g_free (g_ptr_array_index (file_names, i));
2221 g_ptr_array_free (file_names, TRUE);
2224 g_hash_table_iter_init (&iter, info->source_file_to_class);
2225 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2226 g_free (basename);
2227 g_slist_free (l);
2230 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2231 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2232 g_free (basename);
2233 g_slist_free (l);
2236 g_free (info);
2239 domain_jit_info (domain)->agent_info = NULL;
2241 /* Clear ids referencing structures in the domain */
2242 dbg_lock ();
2243 for (i = 0; i < ID_NUM; ++i) {
2244 if (ids [i]) {
2245 for (j = 0; j < ids [i]->len; ++j) {
2246 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2247 if (id->domain == domain)
2248 id->domain = NULL;
2252 dbg_unlock ();
2254 mono_loader_lock ();
2255 g_hash_table_remove (domains, domain);
2256 mono_loader_unlock ();
2259 static AgentDomainInfo*
2260 get_agent_domain_info (MonoDomain *domain)
2262 AgentDomainInfo *info = NULL;
2264 mono_domain_lock (domain);
2266 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2267 if (!info) {
2268 info = g_new0 (AgentDomainInfo, 1);
2269 domain_jit_info (domain)->agent_info = info;
2270 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2271 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2272 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2273 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2276 mono_domain_unlock (domain);
2278 return info;
2281 static int
2282 get_id (MonoDomain *domain, IdType type, gpointer val)
2284 Id *id;
2285 AgentDomainInfo *info;
2287 if (val == NULL)
2288 return 0;
2290 info = get_agent_domain_info (domain);
2292 dbg_lock ();
2294 if (info->val_to_id [type] == NULL)
2295 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2297 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2298 if (id) {
2299 dbg_unlock ();
2300 return id->id;
2303 id = g_new0 (Id, 1);
2304 /* Reserve id 0 */
2305 id->id = ids [type]->len + 1;
2306 id->domain = domain;
2307 id->data.val = val;
2309 g_hash_table_insert (info->val_to_id [type], val, id);
2310 g_ptr_array_add (ids [type], id);
2312 dbg_unlock ();
2314 return id->id;
2317 static inline gpointer
2318 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2320 Id *res;
2322 int id = decode_id (buf, endbuf, limit);
2324 *err = ERR_NONE;
2325 if (domain)
2326 *domain = NULL;
2328 if (id == 0)
2329 return NULL;
2331 // FIXME: error handling
2332 dbg_lock ();
2333 g_assert (id > 0 && id <= ids [type]->len);
2335 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2336 dbg_unlock ();
2338 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2339 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2340 *err = ERR_UNLOADED;
2341 return NULL;
2344 if (domain)
2345 *domain = res->domain;
2347 return res->data.val;
2350 static inline int
2351 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2353 int id = get_id (domain, type, val);
2355 buffer_add_id (buf, id);
2356 return id;
2359 static inline MonoClass*
2360 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2362 MonoClass *klass;
2364 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2365 if (G_UNLIKELY (log_level >= 2) && klass) {
2366 char *s;
2368 s = mono_type_full_name (&klass->byval_arg);
2369 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2370 g_free (s);
2372 return klass;
2375 static inline MonoAssembly*
2376 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2378 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2381 static inline MonoImage*
2382 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2384 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2387 static inline MonoMethod*
2388 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2390 MonoMethod *m;
2392 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2393 if (G_UNLIKELY (log_level >= 2) && m) {
2394 char *s;
2396 s = mono_method_full_name (m, TRUE);
2397 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2398 g_free (s);
2400 return m;
2403 static inline MonoClassField*
2404 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2406 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2409 static inline MonoDomain*
2410 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2412 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2415 static inline MonoProperty*
2416 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2418 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2421 static inline void
2422 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2424 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2425 if (G_UNLIKELY (log_level >= 2) && klass) {
2426 char *s;
2428 s = mono_type_full_name (&klass->byval_arg);
2429 if (is_debugger_thread ())
2430 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2431 else
2432 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2433 g_free (s);
2437 static inline void
2438 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2440 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2441 if (G_UNLIKELY (log_level >= 2) && method) {
2442 char *s;
2444 s = mono_method_full_name (method, 1);
2445 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2446 g_free (s);
2450 static inline void
2451 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2453 int id;
2455 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2456 if (G_UNLIKELY (log_level >= 2) && assembly)
2457 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2460 static inline void
2461 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2463 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2466 static inline void
2467 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2469 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2472 static inline void
2473 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2475 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2478 static inline void
2479 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2481 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2484 static void invoke_method (void);
2487 * SUSPEND/RESUME
2490 static MonoJitInfo*
2491 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2493 MonoJitInfo *ji;
2495 if (out_ip)
2496 *out_ip = ip;
2498 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2499 if (!ji) {
2500 /* Could be an interpreter method */
2502 MonoLMF *lmf = mono_get_lmf ();
2503 MonoInterpFrameHandle *frame;
2505 g_assert (((guint64)lmf->previous_lmf) & 2);
2506 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2508 g_assert (ext->interp_exit);
2509 frame = ext->interp_exit_data;
2510 ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame);
2511 if (domain)
2512 *domain = mono_domain_get ();
2513 if (out_ip)
2514 *out_ip = mini_get_interp_callbacks ()->frame_get_ip (frame);
2516 return ji;
2520 * save_thread_context:
2522 * Set CTX as the current threads context which is used for computing stack traces.
2523 * This function is signal-safe.
2525 static void
2526 save_thread_context (MonoContext *ctx)
2528 DebuggerTlsData *tls;
2530 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2531 g_assert (tls);
2533 if (ctx)
2534 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2535 else
2536 mono_thread_state_init_from_current (&tls->context);
2539 /* Number of threads suspended */
2541 * If this is equal to the size of thread_to_tls, the runtime is considered
2542 * suspended.
2544 static gint32 threads_suspend_count;
2546 static MonoCoopMutex suspend_mutex;
2548 /* Cond variable used to wait for suspend_count becoming 0 */
2549 static MonoCoopCond suspend_cond;
2551 /* Semaphore used to wait for a thread becoming suspended */
2552 static MonoCoopSem suspend_sem;
2554 static void
2555 suspend_init (void)
2557 mono_coop_mutex_init (&suspend_mutex);
2558 mono_coop_cond_init (&suspend_cond);
2559 mono_coop_sem_init (&suspend_sem, 0);
2562 typedef struct
2564 StackFrameInfo last_frame;
2565 gboolean last_frame_set;
2566 MonoContext ctx;
2567 gpointer lmf;
2568 MonoDomain *domain;
2569 } GetLastFrameUserData;
2571 static gboolean
2572 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2574 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2576 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2577 return FALSE;
2579 if (!data->last_frame_set) {
2580 /* Store the last frame */
2581 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2582 data->last_frame_set = TRUE;
2583 return FALSE;
2584 } else {
2585 /* Store the context/lmf for the frame above the last frame */
2586 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2587 data->lmf = info->lmf;
2588 data->domain = info->domain;
2589 return TRUE;
2593 static void
2594 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2596 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2598 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2599 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2600 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2601 to->valid = TRUE;
2605 * thread_interrupt:
2607 * Process interruption of a thread. This should be signal safe.
2609 * This always runs in the debugger thread.
2611 static void
2612 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2614 gpointer ip;
2615 MonoNativeThreadId tid;
2617 g_assert (info);
2619 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2620 tid = mono_thread_info_get_tid (info);
2622 // FIXME: Races when the thread leaves managed code before hitting a single step
2623 // event.
2625 if (ji && !ji->is_trampoline) {
2626 /* Running managed code, will be suspended by the single step code */
2627 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2628 } else {
2630 * Running native code, will be suspended when it returns to/enters
2631 * managed code. Treat it as already suspended.
2632 * This might interrupt the code in process_single_step_inner (), we use the
2633 * tls->suspending flag to avoid races when that happens.
2635 if (!tls->suspended && !tls->suspending) {
2636 GetLastFrameUserData data;
2638 // FIXME: printf is not signal safe, but this is only used during
2639 // debugger debugging
2640 if (ip)
2641 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2642 //save_thread_context (&ctx);
2644 if (!tls->thread)
2645 /* Already terminated */
2646 return;
2649 * We are in a difficult position: we want to be able to provide stack
2650 * traces for this thread, but we can't use the current ctx+lmf, since
2651 * the thread is still running, so it might return to managed code,
2652 * making these invalid.
2653 * So we start a stack walk and save the first frame, along with the
2654 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2655 * suspended when it returns to managed code, so the parent's ctx should
2656 * remain valid.
2658 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2660 data.last_frame_set = FALSE;
2661 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2662 if (data.last_frame_set) {
2663 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2665 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2667 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED) {
2669 * Store the current lmf instead of the parent one, since that
2670 * contains the interp exit data.
2672 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2675 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2676 /* Don't set tls->context, it could race with the thread processing a breakpoint etc. */
2677 } else {
2678 tls->async_state.valid = FALSE;
2681 mono_memory_barrier ();
2683 tls->suspended = TRUE;
2684 mono_coop_sem_post (&suspend_sem);
2690 * reset_native_thread_suspend_state:
2692 * Reset the suspended flag and state on native threads
2694 static void
2695 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2697 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2699 if (!tls->really_suspended && tls->suspended) {
2700 tls->suspended = FALSE;
2702 * The thread might still be running if it was executing native code, so the state won't be invalided by
2703 * suspend_current ().
2705 tls->context.valid = FALSE;
2706 tls->async_state.valid = FALSE;
2707 invalidate_frames (tls);
2711 typedef struct {
2712 DebuggerTlsData *tls;
2713 gboolean valid_info;
2714 } InterruptData;
2716 static SuspendThreadResult
2717 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2719 InterruptData *data = (InterruptData *)user_data;
2720 MonoJitInfo *ji;
2722 data->valid_info = TRUE;
2723 ji = mono_jit_info_table_find_internal (
2724 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2725 MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2726 TRUE,
2727 TRUE);
2729 /* This is signal safe */
2730 thread_interrupt (data->tls, info, ji);
2731 return MonoResumeThread;
2735 * notify_thread:
2737 * Notify a thread that it needs to suspend.
2739 static void
2740 notify_thread (gpointer key, gpointer value, gpointer user_data)
2742 MonoInternalThread *thread = (MonoInternalThread *)key;
2743 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2744 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2746 if (mono_thread_internal_is_current (thread) || tls->terminated)
2747 return;
2749 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2751 /* This is _not_ equivalent to mono_thread_internal_abort () */
2752 InterruptData interrupt_data = { 0 };
2753 interrupt_data.tls = tls;
2755 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2756 if (!interrupt_data.valid_info) {
2757 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2759 * Attached thread which died without detaching.
2761 tls->terminated = TRUE;
2765 static void
2766 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2768 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2769 MonoJitInfo *ji;
2770 MonoMethod *method;
2772 if (mono_loader_lock_is_owned_by_self ()) {
2774 * Shortcut for the check in suspend_current (). This speeds up processing
2775 * when executing long running code inside the loader lock, i.e. assembly load
2776 * hooks.
2778 return;
2781 if (is_debugger_thread ())
2782 return;
2784 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2785 if (suspend_count - tls->resume_count > 0)
2786 tls->suspending = TRUE;
2788 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2790 if (suspend_count - tls->resume_count == 0) {
2792 * We are executing a single threaded invoke but the single step for
2793 * suspending is still active.
2794 * FIXME: This slows down single threaded invokes.
2796 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2797 return;
2800 ji = get_top_method_ji (ip, NULL, NULL);
2801 g_assert (ji);
2802 /* Can't suspend in these methods */
2803 method = jinfo_get_method (ji);
2804 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2805 return;
2807 save_thread_context (ctx);
2809 suspend_current ();
2813 * suspend_vm:
2815 * Increase the suspend count of the VM. While the suspend count is greater
2816 * than 0, runtime threads are suspended at certain points during execution.
2818 static void
2819 suspend_vm (void)
2821 mono_loader_lock ();
2823 mono_coop_mutex_lock (&suspend_mutex);
2825 suspend_count ++;
2827 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2829 if (suspend_count == 1) {
2830 // FIXME: Is it safe to call this inside the lock ?
2831 start_single_stepping ();
2832 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2835 mono_coop_mutex_unlock (&suspend_mutex);
2837 if (suspend_count == 1)
2839 * Suspend creation of new threadpool threads, since they cannot run
2841 mono_threadpool_suspend ();
2843 mono_loader_unlock ();
2847 * resume_vm:
2849 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2850 * are resumed.
2852 static void
2853 resume_vm (void)
2855 g_assert (is_debugger_thread ());
2857 mono_loader_lock ();
2859 mono_coop_mutex_lock (&suspend_mutex);
2861 g_assert (suspend_count > 0);
2862 suspend_count --;
2864 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2866 if (suspend_count == 0) {
2867 // FIXME: Is it safe to call this inside the lock ?
2868 stop_single_stepping ();
2869 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2872 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2873 mono_coop_cond_broadcast (&suspend_cond);
2875 mono_coop_mutex_unlock (&suspend_mutex);
2876 //g_assert (err == 0);
2878 if (suspend_count == 0)
2879 mono_threadpool_resume ();
2881 mono_loader_unlock ();
2885 * resume_thread:
2887 * Resume just one thread.
2889 static void
2890 resume_thread (MonoInternalThread *thread)
2892 DebuggerTlsData *tls;
2894 g_assert (is_debugger_thread ());
2896 mono_loader_lock ();
2898 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2899 g_assert (tls);
2901 mono_coop_mutex_lock (&suspend_mutex);
2903 g_assert (suspend_count > 0);
2905 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2907 tls->resume_count += suspend_count;
2910 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2911 * but only the one whose resume_count field is > 0 will be resumed.
2913 mono_coop_cond_broadcast (&suspend_cond);
2915 mono_coop_mutex_unlock (&suspend_mutex);
2916 //g_assert (err == 0);
2918 mono_loader_unlock ();
2921 static void
2922 free_frames (StackFrame **frames, int nframes)
2924 int i;
2926 for (i = 0; i < nframes; ++i) {
2927 if (frames [i]->jit)
2928 mono_debug_free_method_jit_info (frames [i]->jit);
2929 g_free (frames [i]);
2931 g_free (frames);
2934 static void
2935 invalidate_frames (DebuggerTlsData *tls)
2937 if (!tls)
2938 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2939 g_assert (tls);
2941 free_frames (tls->frames, tls->frame_count);
2942 tls->frame_count = 0;
2943 tls->frames = NULL;
2945 free_frames (tls->restore_frames, tls->restore_frame_count);
2946 tls->restore_frame_count = 0;
2947 tls->restore_frames = NULL;
2951 * suspend_current:
2953 * Suspend the current thread until the runtime is resumed. If the thread has a
2954 * pending invoke, then the invoke is executed before this function returns.
2956 static void
2957 suspend_current (void)
2959 DebuggerTlsData *tls;
2961 g_assert (!is_debugger_thread ());
2963 if (mono_loader_lock_is_owned_by_self ()) {
2965 * If we own the loader mutex, can't suspend until we release it, since the
2966 * whole runtime can deadlock otherwise.
2968 return;
2971 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2972 g_assert (tls);
2974 mono_coop_mutex_lock (&suspend_mutex);
2976 tls->suspending = FALSE;
2977 tls->really_suspended = TRUE;
2979 if (!tls->suspended) {
2980 tls->suspended = TRUE;
2981 mono_coop_sem_post (&suspend_sem);
2984 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2986 while (suspend_count - tls->resume_count > 0) {
2987 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2990 tls->suspended = FALSE;
2991 tls->really_suspended = FALSE;
2993 threads_suspend_count --;
2995 mono_coop_mutex_unlock (&suspend_mutex);
2997 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2999 if (tls->pending_invoke) {
3000 /* Save the original context */
3001 tls->pending_invoke->has_ctx = TRUE;
3002 tls->pending_invoke->ctx = tls->context.ctx;
3004 invoke_method ();
3007 /* The frame info becomes invalid after a resume */
3008 tls->context.valid = FALSE;
3009 tls->async_state.valid = FALSE;
3010 invalidate_frames (tls);
3013 static void
3014 count_thread (gpointer key, gpointer value, gpointer user_data)
3016 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3018 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3019 *(int*)user_data = *(int*)user_data + 1;
3022 static int
3023 count_threads_to_wait_for (void)
3025 int count = 0;
3027 mono_loader_lock ();
3028 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3029 mono_loader_unlock ();
3031 return count;
3035 * wait_for_suspend:
3037 * Wait until the runtime is completely suspended.
3039 static void
3040 wait_for_suspend (void)
3042 int nthreads, nwait, err;
3043 gboolean waited = FALSE;
3045 // FIXME: Threads starting/stopping ?
3046 mono_loader_lock ();
3047 nthreads = mono_g_hash_table_size (thread_to_tls);
3048 mono_loader_unlock ();
3050 while (TRUE) {
3051 nwait = count_threads_to_wait_for ();
3052 if (nwait) {
3053 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3054 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3055 g_assert (err == 0);
3056 waited = TRUE;
3057 } else {
3058 break;
3062 if (waited)
3063 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3067 * is_suspended:
3069 * Return whenever the runtime is suspended.
3071 static gboolean
3072 is_suspended (void)
3074 return count_threads_to_wait_for () == 0;
3077 static void
3078 no_seq_points_found (MonoMethod *method, int offset)
3081 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3083 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3086 typedef struct {
3087 DebuggerTlsData *tls;
3088 GSList *frames;
3089 } ComputeFramesUserData;
3091 static gboolean
3092 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3094 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3095 StackFrame *frame;
3096 MonoMethod *method, *actual_method, *api_method;
3097 SeqPoint sp;
3098 int flags = 0;
3100 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP) {
3101 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3102 /* Mark the last frame as an invoke frame */
3103 if (ud->frames)
3104 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3106 return FALSE;
3109 if (info->ji)
3110 method = jinfo_get_method (info->ji);
3111 else
3112 method = info->method;
3113 actual_method = info->actual_method;
3114 api_method = method;
3116 if (!method)
3117 return FALSE;
3119 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3120 return FALSE;
3122 if (info->il_offset == -1) {
3123 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3124 if (ud->frames == NULL) {
3125 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3126 info->il_offset = sp.il_offset;
3128 if (info->il_offset == -1)
3129 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3132 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);
3134 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3135 if (!CHECK_PROTOCOL_VERSION (2, 17))
3136 /* Older clients can't handle this flag */
3137 return FALSE;
3138 api_method = mono_marshal_method_from_wrapper (method);
3139 if (!api_method)
3140 return FALSE;
3141 actual_method = api_method;
3142 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3145 frame = g_new0 (StackFrame, 1);
3146 frame->method = method;
3147 frame->actual_method = actual_method;
3148 frame->api_method = api_method;
3149 frame->il_offset = info->il_offset;
3150 frame->native_offset = info->native_offset;
3151 frame->flags = flags;
3152 frame->ji = info->ji;
3153 frame->interp_frame = info->interp_frame;
3154 frame->frame_addr = info->frame_addr;
3155 if (info->reg_locations)
3156 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3157 if (ctx) {
3158 frame->ctx = *ctx;
3159 frame->has_ctx = TRUE;
3161 frame->domain = info->domain;
3163 ud->frames = g_slist_append (ud->frames, frame);
3165 return FALSE;
3168 static gboolean
3169 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3171 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3174 * 'tls->filter_ctx' is the location of the throw site.
3176 * mono_walk_stack() will never actually hit the throw site, but unwind
3177 * directly from the filter to the call site; we abort stack unwinding here
3178 * once this happens and resume from the throw site.
3180 if (info->frame_addr >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3181 return TRUE;
3183 return process_frame (info, ctx, user_data);
3187 * Return a malloc-ed list of StackFrame structures.
3189 static StackFrame**
3190 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3192 ComputeFramesUserData user_data;
3193 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3194 StackFrame **res;
3195 int i, nframes;
3196 GSList *l;
3198 user_data.tls = tls;
3199 user_data.frames = NULL;
3201 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3203 nframes = g_slist_length (user_data.frames);
3204 res = g_new0 (StackFrame*, nframes);
3205 l = user_data.frames;
3206 for (i = 0; i < nframes; ++i) {
3207 res [i] = (StackFrame *)l->data;
3208 l = l->next;
3210 *out_nframes = nframes;
3212 return res;
3215 static void
3216 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3218 ComputeFramesUserData user_data;
3219 GSList *tmp;
3220 int i, findex, new_frame_count;
3221 StackFrame **new_frames, *f;
3222 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3224 // FIXME: Locking on tls
3225 if (tls->frames && tls->frames_up_to_date)
3226 return;
3228 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3230 user_data.tls = tls;
3231 user_data.frames = NULL;
3232 if (tls->terminated) {
3233 tls->frame_count = 0;
3234 return;
3235 } if (!tls->really_suspended && tls->async_state.valid) {
3236 /* Have to use the state saved by the signal handler */
3237 process_frame (&tls->async_last_frame, NULL, &user_data);
3238 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3239 } else if (tls->filter_state.valid) {
3241 * We are inside an exception filter.
3243 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3245 if (tls->context.valid) {
3246 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3247 DEBUG_PRINTF (1, "\tFrame: <call filter>\n");
3250 * After that, we resume unwinding from the location where the exception has been thrown.
3252 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3253 } else if (tls->context.valid) {
3254 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3255 } else {
3256 // FIXME:
3257 tls->frame_count = 0;
3258 return;
3261 new_frame_count = g_slist_length (user_data.frames);
3262 new_frames = g_new0 (StackFrame*, new_frame_count);
3263 findex = 0;
3264 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3265 f = (StackFrame *)tmp->data;
3268 * Reuse the id for already existing stack frames, so invokes don't invalidate
3269 * the still valid stack frames.
3271 for (i = 0; i < tls->frame_count; ++i) {
3272 if (tls->frames [i]->frame_addr == f->frame_addr) {
3273 f->id = tls->frames [i]->id;
3274 break;
3278 if (i >= tls->frame_count)
3279 f->id = mono_atomic_inc_i32 (&frame_id);
3281 new_frames [findex ++] = f;
3284 g_slist_free (user_data.frames);
3286 invalidate_frames (tls);
3288 tls->frames = new_frames;
3289 tls->frame_count = new_frame_count;
3290 tls->frames_up_to_date = TRUE;
3294 * GHFunc to emit an appdomain creation event
3295 * @param key Don't care
3296 * @param value A loaded appdomain
3297 * @param user_data Don't care
3299 static void
3300 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3302 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3303 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3307 * GHFunc to emit a thread start event
3308 * @param key A thread id
3309 * @param value A thread object
3310 * @param user_data Don't care
3312 static void
3313 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3315 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3316 process_profiler_event (EVENT_KIND_THREAD_START, value);
3320 * GFunc to emit an assembly load event
3321 * @param value A loaded assembly
3322 * @param user_data Don't care
3324 static void
3325 emit_assembly_load (gpointer value, gpointer user_data)
3327 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3331 * GFunc to emit a type load event
3332 * @param value A loaded type
3333 * @param user_data Don't care
3335 static void
3336 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3338 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3341 static char*
3342 strdup_tolower (char *s)
3344 char *s2, *p;
3346 s2 = g_strdup (s);
3347 for (p = s2; *p; ++p)
3348 *p = tolower (*p);
3349 return s2;
3353 * Same as g_path_get_basename () but handles windows paths as well,
3354 * which can occur in .mdb files created by pdb2mdb.
3356 static char*
3357 dbg_path_get_basename (const char *filename)
3359 char *r;
3361 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3362 return g_path_get_basename (filename);
3364 /* From gpath.c */
3366 /* No separator -> filename */
3367 r = strrchr (filename, '\\');
3368 if (r == NULL)
3369 return g_strdup (filename);
3371 /* Trailing slash, remove component */
3372 if (r [1] == 0){
3373 char *copy = g_strdup (filename);
3374 copy [r-filename] = 0;
3375 r = strrchr (copy, '\\');
3377 if (r == NULL){
3378 g_free (copy);
3379 return g_strdup ("/");
3381 r = g_strdup (&r[1]);
3382 g_free (copy);
3383 return r;
3386 return g_strdup (&r[1]);
3389 static void
3390 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3392 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3393 ERROR_DECL (error);
3394 MonoCustomAttrInfo *ainfo;
3396 if (ji->dbg_attrs_inited)
3397 return;
3399 if (!hidden_klass)
3400 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3402 if (!step_through_klass)
3403 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3405 if (!non_user_klass)
3406 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3408 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), error);
3409 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3410 if (ainfo) {
3411 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3412 ji->dbg_hidden = TRUE;
3413 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3414 ji->dbg_step_through = TRUE;
3415 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3416 ji->dbg_non_user_code = TRUE;
3417 mono_custom_attrs_free (ainfo);
3420 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, error);
3421 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3422 if (ainfo) {
3423 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3424 ji->dbg_step_through = TRUE;
3425 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3426 ji->dbg_non_user_code = TRUE;
3427 mono_custom_attrs_free (ainfo);
3430 mono_memory_barrier ();
3431 ji->dbg_attrs_inited = TRUE;
3435 * EVENT HANDLING
3439 * create_event_list:
3441 * Return a list of event request ids matching EVENT, starting from REQS, which
3442 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3443 * policy.
3444 * We return request ids, instead of requests, to simplify threading, since
3445 * requests could be deleted anytime when the loader lock is not held.
3446 * LOCKING: Assumes the loader lock is held.
3448 static GSList*
3449 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3451 int i, j;
3452 GSList *events = NULL;
3454 *suspend_policy = SUSPEND_POLICY_NONE;
3456 if (!reqs)
3457 reqs = event_requests;
3459 if (!reqs)
3460 return NULL;
3462 for (i = 0; i < reqs->len; ++i) {
3463 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3464 if (req->event_kind == event) {
3465 gboolean filtered = FALSE;
3467 /* Apply filters */
3468 for (j = 0; j < req->nmodifiers; ++j) {
3469 Modifier *mod = &req->modifiers [j];
3471 if (mod->kind == MOD_KIND_COUNT) {
3472 filtered = TRUE;
3473 if (mod->data.count > 0) {
3474 if (mod->data.count > 0) {
3475 mod->data.count --;
3476 if (mod->data.count == 0)
3477 filtered = FALSE;
3480 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3481 if (mod->data.thread != mono_thread_internal_current ())
3482 filtered = TRUE;
3483 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3484 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3485 filtered = TRUE;
3486 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3487 filtered = TRUE;
3488 if (ei->caught && !mod->caught)
3489 filtered = TRUE;
3490 if (!ei->caught && !mod->uncaught)
3491 filtered = TRUE;
3492 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3493 int k;
3494 gboolean found = FALSE;
3495 MonoAssembly **assemblies = mod->data.assemblies;
3497 if (assemblies) {
3498 for (k = 0; assemblies [k]; ++k)
3499 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3500 found = TRUE;
3502 if (!found)
3503 filtered = TRUE;
3504 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3505 gpointer iter = NULL;
3506 MonoMethod *method;
3507 MonoDebugSourceInfo *sinfo;
3508 char *source_file, *s;
3509 gboolean found = FALSE;
3510 int i;
3511 GPtrArray *source_file_list;
3513 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3514 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3516 if (minfo) {
3517 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3518 for (i = 0; i < source_file_list->len; ++i) {
3519 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3521 * Do a case-insesitive match by converting the file name to
3522 * lowercase.
3524 s = strdup_tolower (sinfo->source_file);
3525 if (g_hash_table_lookup (mod->data.source_files, s))
3526 found = TRUE;
3527 else {
3528 char *s2 = dbg_path_get_basename (sinfo->source_file);
3529 char *s3 = strdup_tolower (s2);
3531 if (g_hash_table_lookup (mod->data.source_files, s3))
3532 found = TRUE;
3533 g_free (s2);
3534 g_free (s3);
3536 g_free (s);
3538 g_ptr_array_free (source_file_list, TRUE);
3541 if (!found)
3542 filtered = TRUE;
3543 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3544 char *s;
3546 s = mono_type_full_name (&ei->klass->byval_arg);
3547 if (!g_hash_table_lookup (mod->data.type_names, s))
3548 filtered = TRUE;
3549 g_free (s);
3550 } else if (mod->kind == MOD_KIND_STEP) {
3551 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3552 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3553 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3554 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3555 filtered = TRUE;
3556 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3557 init_jit_info_dbg_attrs (ji);
3558 if (ji->dbg_hidden)
3559 filtered = TRUE;
3561 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3562 init_jit_info_dbg_attrs (ji);
3563 if (ji->dbg_step_through)
3564 filtered = TRUE;
3566 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3567 init_jit_info_dbg_attrs (ji);
3568 if (ji->dbg_non_user_code)
3569 filtered = TRUE;
3574 if (!filtered) {
3575 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3576 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3581 /* Send a VM START/DEATH event by default */
3582 if (event == EVENT_KIND_VM_START)
3583 events = g_slist_append (events, GINT_TO_POINTER (0));
3584 if (event == EVENT_KIND_VM_DEATH)
3585 events = g_slist_append (events, GINT_TO_POINTER (0));
3587 return events;
3590 static G_GNUC_UNUSED const char*
3591 event_to_string (EventKind event)
3593 switch (event) {
3594 case EVENT_KIND_VM_START: return "VM_START";
3595 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3596 case EVENT_KIND_THREAD_START: return "THREAD_START";
3597 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3598 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3599 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3600 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3601 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3602 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3603 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3604 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3605 case EVENT_KIND_STEP: return "STEP";
3606 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3607 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3608 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3609 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3610 case EVENT_KIND_USER_LOG: return "USER_LOG";
3611 default:
3612 g_assert_not_reached ();
3613 return "";
3618 * process_event:
3620 * Send an event to the client, suspending the vm if needed.
3621 * LOCKING: Since this can suspend the calling thread, no locks should be held
3622 * by the caller.
3623 * The EVENTS list is freed by this function.
3625 static void
3626 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3628 Buffer buf;
3629 GSList *l;
3630 MonoDomain *domain = mono_domain_get ();
3631 MonoThread *thread = NULL;
3632 MonoObject *keepalive_obj = NULL;
3633 gboolean send_success = FALSE;
3634 static int ecount;
3635 int nevents;
3637 if (!inited) {
3638 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3639 return;
3642 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3643 // FIXME: We miss those events
3644 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3645 return;
3648 if (vm_death_event_sent) {
3649 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3650 return;
3653 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3654 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3655 return;
3658 if (disconnected) {
3659 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3660 return;
3663 if (event == EVENT_KIND_KEEPALIVE)
3664 suspend_policy = SUSPEND_POLICY_NONE;
3665 else {
3666 if (events == NULL)
3667 return;
3669 if (agent_config.defer) {
3670 if (is_debugger_thread ()) {
3671 /* Don't suspend on events from the debugger thread */
3672 suspend_policy = SUSPEND_POLICY_NONE;
3674 } else {
3675 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3676 // FIXME: Send these with a NULL thread, don't suspend the current thread
3677 return;
3681 nevents = g_slist_length (events);
3682 buffer_init (&buf, 128);
3683 buffer_add_byte (&buf, suspend_policy);
3684 buffer_add_int (&buf, nevents);
3686 for (l = events; l; l = l->next) {
3687 buffer_add_byte (&buf, event); // event kind
3688 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3690 ecount ++;
3692 if (event == EVENT_KIND_VM_DEATH) {
3693 thread = NULL;
3694 } else {
3695 if (!thread)
3696 thread = is_debugger_thread () ? mono_thread_get_main () : mono_thread_current ();
3698 if (event == EVENT_KIND_VM_START && arg != NULL)
3699 thread = (MonoThread *)arg;
3702 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3704 switch (event) {
3705 case EVENT_KIND_THREAD_START:
3706 case EVENT_KIND_THREAD_DEATH:
3707 break;
3708 case EVENT_KIND_APPDOMAIN_CREATE:
3709 case EVENT_KIND_APPDOMAIN_UNLOAD:
3710 buffer_add_domainid (&buf, (MonoDomain *)arg);
3711 break;
3712 case EVENT_KIND_METHOD_ENTRY:
3713 case EVENT_KIND_METHOD_EXIT:
3714 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3715 break;
3716 case EVENT_KIND_ASSEMBLY_LOAD:
3717 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3718 break;
3719 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3720 DebuggerTlsData *tls;
3722 /* The domain the assembly belonged to is not equal to the current domain */
3723 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3724 g_assert (tls);
3725 g_assert (tls->domain_unloading);
3727 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3728 break;
3730 case EVENT_KIND_TYPE_LOAD:
3731 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3732 break;
3733 case EVENT_KIND_BREAKPOINT:
3734 case EVENT_KIND_STEP: {
3735 MonoMethod *method = (MonoMethod *)arg;
3737 buffer_add_methodid (&buf, domain, method);
3738 buffer_add_long (&buf, il_offset);
3739 break;
3741 case EVENT_KIND_VM_START:
3742 buffer_add_domainid (&buf, mono_get_root_domain ());
3743 break;
3744 case EVENT_KIND_VM_DEATH:
3745 if (CHECK_PROTOCOL_VERSION (2, 27))
3746 buffer_add_int (&buf, mono_environment_exitcode_get ());
3747 break;
3748 case EVENT_KIND_EXCEPTION: {
3749 EventInfo *ei = (EventInfo *)arg;
3750 buffer_add_objid (&buf, ei->exc);
3752 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3753 * later after the suspension. (#12494).
3755 keepalive_obj = ei->exc;
3756 break;
3758 case EVENT_KIND_USER_BREAK:
3759 break;
3760 case EVENT_KIND_USER_LOG: {
3761 EventInfo *ei = (EventInfo *)arg;
3762 buffer_add_int (&buf, ei->level);
3763 buffer_add_string (&buf, ei->category ? ei->category : "");
3764 buffer_add_string (&buf, ei->message ? ei->message : "");
3765 break;
3767 case EVENT_KIND_KEEPALIVE:
3768 suspend_policy = SUSPEND_POLICY_NONE;
3769 break;
3770 default:
3771 g_assert_not_reached ();
3775 if (event == EVENT_KIND_VM_START) {
3776 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3777 if (!agent_config.defer)
3778 start_debugger_thread ();
3781 if (event == EVENT_KIND_VM_DEATH) {
3782 vm_death_event_sent = TRUE;
3783 suspend_policy = SUSPEND_POLICY_NONE;
3786 if (mono_runtime_is_shutting_down ())
3787 suspend_policy = SUSPEND_POLICY_NONE;
3789 if (suspend_policy != SUSPEND_POLICY_NONE) {
3791 * Save the thread context and start suspending before sending the packet,
3792 * since we could be receiving the resume request before send_packet ()
3793 * returns.
3795 save_thread_context (ctx);
3796 suspend_vm ();
3798 if (keepalive_obj)
3799 /* This will keep this object alive */
3800 get_objref (keepalive_obj);
3803 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3805 buffer_free (&buf);
3807 g_slist_free (events);
3808 events = NULL;
3810 if (!send_success) {
3811 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3812 return;
3815 if (event == EVENT_KIND_VM_START) {
3816 vm_start_event_sent = TRUE;
3819 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);
3821 switch (suspend_policy) {
3822 case SUSPEND_POLICY_NONE:
3823 break;
3824 case SUSPEND_POLICY_ALL:
3825 suspend_current ();
3826 break;
3827 case SUSPEND_POLICY_EVENT_THREAD:
3828 NOT_IMPLEMENTED;
3829 break;
3830 default:
3831 g_assert_not_reached ();
3835 static void
3836 process_profiler_event (EventKind event, gpointer arg)
3838 int suspend_policy;
3839 GSList *events;
3840 EventInfo ei, *ei_arg = NULL;
3842 if (event == EVENT_KIND_TYPE_LOAD) {
3843 ei.klass = (MonoClass *)arg;
3844 ei_arg = &ei;
3847 mono_loader_lock ();
3848 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3849 mono_loader_unlock ();
3851 process_event (event, arg, 0, NULL, events, suspend_policy);
3854 static void
3855 runtime_initialized (MonoProfiler *prof)
3857 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3858 if (agent_config.defer)
3859 start_debugger_thread ();
3862 static void
3863 runtime_shutdown (MonoProfiler *prof)
3865 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3867 mono_debugger_agent_cleanup ();
3870 static void
3871 thread_startup (MonoProfiler *prof, uintptr_t tid)
3873 MonoInternalThread *thread = mono_thread_internal_current ();
3874 MonoInternalThread *old_thread;
3875 DebuggerTlsData *tls;
3877 if (is_debugger_thread ())
3878 return;
3880 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3882 mono_loader_lock ();
3883 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3884 mono_loader_unlock ();
3885 if (old_thread) {
3886 if (thread == old_thread) {
3888 * For some reason, thread_startup () might be called for the same thread
3889 * multiple times (attach ?).
3891 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3892 return;
3893 } else {
3895 * thread_end () might not be called for some threads, and the tid could
3896 * get reused.
3898 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3899 mono_loader_lock ();
3900 mono_g_hash_table_remove (thread_to_tls, old_thread);
3901 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3902 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3903 mono_loader_unlock ();
3907 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3908 g_assert (!tls);
3909 // FIXME: Free this somewhere
3910 tls = g_new0 (DebuggerTlsData, 1);
3911 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Reference");
3912 tls->thread = thread;
3913 mono_native_tls_set_value (debugger_tls_id, tls);
3915 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3917 mono_loader_lock ();
3918 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3919 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3920 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3921 mono_loader_unlock ();
3923 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3926 * suspend_vm () could have missed this thread, so wait for a resume.
3928 suspend_current ();
3931 static void
3932 thread_end (MonoProfiler *prof, uintptr_t tid)
3934 MonoInternalThread *thread;
3935 DebuggerTlsData *tls = NULL;
3937 mono_loader_lock ();
3938 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3939 if (thread) {
3940 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3941 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3942 if (tls) {
3943 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3944 tls->terminated = TRUE;
3945 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3946 MONO_GC_UNREGISTER_ROOT (tls->thread);
3947 tls->thread = NULL;
3950 mono_loader_unlock ();
3952 /* We might be called for threads started before we registered the start callback */
3953 if (thread) {
3954 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3956 if (mono_thread_internal_is_current (thread) && !mono_native_tls_get_value (debugger_tls_id)
3959 * This can happen on darwin since we deregister threads using pthread dtors.
3960 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3962 return;
3965 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3969 static void
3970 appdomain_load (MonoProfiler *prof, MonoDomain *domain)
3972 mono_loader_lock ();
3973 g_hash_table_insert (domains, domain, domain);
3974 mono_loader_unlock ();
3976 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3979 static void
3980 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3982 DebuggerTlsData *tls;
3984 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3985 if (is_debugger_thread ())
3986 return;
3989 * Remember the currently unloading appdomain as it is needed to generate
3990 * proper ids for unloading assemblies.
3992 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3993 g_assert (tls);
3994 tls->domain_unloading = domain;
3997 static void
3998 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4000 DebuggerTlsData *tls;
4002 if (is_debugger_thread ())
4003 return;
4005 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4006 g_assert (tls);
4007 tls->domain_unloading = NULL;
4009 clear_breakpoints_for_domain (domain);
4011 mono_loader_lock ();
4012 /* Invalidate each thread's frame stack */
4013 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4014 mono_loader_unlock ();
4016 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4020 * invalidate_each_thread:
4022 * A GHFunc to invalidate frames.
4023 * value must be a DebuggerTlsData*
4025 static void
4026 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4028 invalidate_frames ((DebuggerTlsData *)value);
4031 static void
4032 assembly_load (MonoProfiler *prof, MonoAssembly *assembly)
4034 /* Sent later in jit_end () */
4035 dbg_lock ();
4036 g_ptr_array_add (pending_assembly_loads, assembly);
4037 dbg_unlock ();
4040 static void
4041 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4043 if (is_debugger_thread ())
4044 return;
4046 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4048 clear_event_requests_for_assembly (assembly);
4049 clear_types_for_assembly (assembly);
4052 static void
4053 send_type_load (MonoClass *klass)
4055 gboolean type_load = FALSE;
4056 MonoDomain *domain = mono_domain_get ();
4057 AgentDomainInfo *info = NULL;
4059 info = get_agent_domain_info (domain);
4061 mono_loader_lock ();
4063 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4064 type_load = TRUE;
4065 g_hash_table_insert (info->loaded_classes, klass, klass);
4068 mono_loader_unlock ();
4070 if (type_load)
4071 emit_type_load (klass, klass, NULL);
4075 * Emit load events for all types currently loaded in the domain.
4076 * Takes the loader and domain locks.
4077 * user_data is unused.
4079 static void
4080 send_types_for_domain (MonoDomain *domain, void *user_data)
4082 MonoDomain* old_domain;
4083 AgentDomainInfo *info = NULL;
4085 info = get_agent_domain_info (domain);
4086 g_assert (info);
4088 old_domain = mono_domain_get ();
4090 mono_domain_set (domain, TRUE);
4092 mono_loader_lock ();
4093 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4094 mono_loader_unlock ();
4096 mono_domain_set (old_domain, TRUE);
4099 static void
4100 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4102 GSList *tmp;
4103 MonoDomain* old_domain;
4105 old_domain = mono_domain_get ();
4107 mono_domain_set (domain, TRUE);
4109 mono_domain_assemblies_lock (domain);
4110 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4111 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4112 emit_assembly_load (ass, NULL);
4114 mono_domain_assemblies_unlock (domain);
4116 mono_domain_set (old_domain, TRUE);
4119 static void
4120 jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4122 jit_end (prof, method, jinfo);
4125 static void
4126 jit_failed (MonoProfiler *prof, MonoMethod *method)
4128 jit_end (prof, method, NULL);
4131 static void
4132 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4135 * We emit type load events when the first method of the type is JITted,
4136 * since the class load profiler callbacks might be called with the
4137 * loader lock held. They could also occur in the debugger thread.
4138 * Same for assembly load events.
4140 while (TRUE) {
4141 MonoAssembly *assembly = NULL;
4143 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4144 dbg_lock ();
4145 if (pending_assembly_loads->len > 0) {
4146 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4147 g_ptr_array_remove_index (pending_assembly_loads, 0);
4149 dbg_unlock ();
4151 if (assembly) {
4152 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4153 } else {
4154 break;
4158 send_type_load (method->klass);
4160 if (jinfo)
4161 add_pending_breakpoints (method, jinfo);
4165 * BREAKPOINTS/SINGLE STEPPING
4169 * Contains information about an inserted breakpoint.
4171 typedef struct {
4172 long il_offset, native_offset;
4173 guint8 *ip;
4174 MonoJitInfo *ji;
4175 MonoDomain *domain;
4176 } BreakpointInstance;
4179 * Contains generic information about a breakpoint.
4181 typedef struct {
4183 * The method where the breakpoint is placed. Can be NULL in which case it
4184 * is inserted into every method. This is used to implement method entry/
4185 * exit events. Can be a generic method definition, in which case the
4186 * breakpoint is inserted into every instance.
4188 MonoMethod *method;
4189 long il_offset;
4190 EventRequest *req;
4192 * A list of BreakpointInstance structures describing where the breakpoint
4193 * was inserted. There could be more than one because of
4194 * generics/appdomains/method entry/exit.
4196 GPtrArray *children;
4197 } MonoBreakpoint;
4199 /* List of breakpoints */
4200 /* Protected by the loader lock */
4201 static GPtrArray *breakpoints;
4202 /* Maps breakpoint locations to the number of breakpoints at that location */
4203 static GHashTable *bp_locs;
4205 static void
4206 breakpoints_init (void)
4208 breakpoints = g_ptr_array_new ();
4209 bp_locs = g_hash_table_new (NULL, NULL);
4213 * insert_breakpoint:
4215 * Insert the breakpoint described by BP into the method described by
4216 * JI.
4218 static void
4219 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4221 int count;
4222 BreakpointInstance *inst;
4223 SeqPointIterator it;
4224 gboolean it_has_sp = FALSE;
4226 if (error)
4227 error_init (error);
4229 mono_seq_point_iterator_init (&it, seq_points);
4230 while (mono_seq_point_iterator_next (&it)) {
4231 if (it.seq_point.il_offset == bp->il_offset) {
4232 it_has_sp = TRUE;
4233 break;
4237 if (!it_has_sp) {
4239 * The set of IL offsets with seq points doesn't completely match the
4240 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4242 mono_seq_point_iterator_init (&it, seq_points);
4243 while (mono_seq_point_iterator_next (&it)) {
4244 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4245 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4246 it.seq_point.il_offset + 1 == bp->il_offset) {
4247 it_has_sp = TRUE;
4248 break;
4253 if (!it_has_sp) {
4254 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4256 mono_seq_point_iterator_init (&it, seq_points);
4257 while (mono_seq_point_iterator_next (&it))
4258 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4260 if (error) {
4261 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4262 g_warning ("%s", s);
4263 g_free (s);
4264 return;
4265 } else {
4266 g_warning ("%s", s);
4267 g_free (s);
4268 return;
4272 inst = g_new0 (BreakpointInstance, 1);
4273 inst->il_offset = it.seq_point.il_offset;
4274 inst->native_offset = it.seq_point.native_offset;
4275 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4276 inst->ji = ji;
4277 inst->domain = domain;
4279 mono_loader_lock ();
4281 g_ptr_array_add (bp->children, inst);
4283 mono_loader_unlock ();
4285 dbg_lock ();
4286 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4287 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4288 dbg_unlock ();
4290 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4291 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4292 } else if (count == 0) {
4293 if (ji->is_interp) {
4294 mini_get_interp_callbacks ()->set_breakpoint (ji, inst->ip);
4295 } else {
4296 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4297 mono_arch_set_breakpoint (ji, inst->ip);
4298 #else
4299 NOT_IMPLEMENTED;
4300 #endif
4304 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 static void
4308 remove_breakpoint (BreakpointInstance *inst)
4310 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4311 int count;
4312 MonoJitInfo *ji = inst->ji;
4313 guint8 *ip = inst->ip;
4315 dbg_lock ();
4316 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4317 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4318 dbg_unlock ();
4320 g_assert (count > 0);
4322 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4323 if (ji->is_interp)
4324 mini_get_interp_callbacks ()->clear_breakpoint (ji, ip);
4325 else
4326 mono_arch_clear_breakpoint (ji, ip);
4327 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4329 #else
4330 NOT_IMPLEMENTED;
4331 #endif
4335 * This doesn't take any locks.
4337 static inline gboolean
4338 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4340 int i;
4342 if (!bp->method)
4343 return TRUE;
4344 if (method == bp->method)
4345 return TRUE;
4346 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4347 return TRUE;
4349 if (bp->method->is_inflated && method->is_inflated) {
4350 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4351 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4353 /* Open generic methods should match closed generic methods of the same class */
4354 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4355 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4356 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4358 /* FIXME: Handle !mvar */
4359 if (t1->type != MONO_TYPE_MVAR)
4360 return FALSE;
4362 return TRUE;
4366 return FALSE;
4370 * add_pending_breakpoints:
4372 * Insert pending breakpoints into the newly JITted method METHOD.
4374 static void
4375 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4377 int i, j;
4378 MonoSeqPointInfo *seq_points;
4379 MonoDomain *domain;
4380 MonoMethod *jmethod;
4382 if (!breakpoints)
4383 return;
4385 domain = mono_domain_get ();
4387 mono_loader_lock ();
4389 for (i = 0; i < breakpoints->len; ++i) {
4390 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4391 gboolean found = FALSE;
4393 if (!bp_matches_method (bp, method))
4394 continue;
4396 for (j = 0; j < bp->children->len; ++j) {
4397 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4399 if (inst->ji == ji)
4400 found = TRUE;
4403 if (!found) {
4404 MonoMethod *declaring = NULL;
4406 jmethod = jinfo_get_method (ji);
4407 if (jmethod->is_inflated)
4408 declaring = mono_method_get_declaring_generic_method (jmethod);
4410 mono_domain_lock (domain);
4411 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4412 if (!seq_points && declaring)
4413 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4414 mono_domain_unlock (domain);
4415 if (!seq_points)
4416 /* Could be AOT code */
4417 continue;
4418 g_assert (seq_points);
4420 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4424 mono_loader_unlock ();
4427 static void
4428 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4430 gpointer code;
4431 MonoJitInfo *ji;
4433 if (error)
4434 error_init (error);
4436 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4437 if (!code) {
4438 ERROR_DECL_VALUE (oerror);
4440 /* Might be AOTed code */
4441 mono_class_init (method->klass);
4442 code = mono_aot_get_method (domain, method, &oerror);
4443 if (code) {
4444 mono_error_assert_ok (&oerror);
4445 ji = mono_jit_info_table_find (domain, code);
4446 } else {
4447 /* Might be interpreted */
4448 ji = mini_get_interp_callbacks ()->find_jit_info (domain, method);
4450 g_assert (ji);
4453 insert_breakpoint (seq_points, domain, ji, bp, error);
4456 static void
4457 clear_breakpoint (MonoBreakpoint *bp);
4460 * set_breakpoint:
4462 * Set a breakpoint at IL_OFFSET in METHOD.
4463 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4464 * METHOD can also be a generic method definition, in which case a breakpoint
4465 * is placed in all instances of the method.
4466 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4467 * inserted.
4469 static MonoBreakpoint*
4470 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4472 MonoBreakpoint *bp;
4473 GHashTableIter iter, iter2;
4474 MonoDomain *domain;
4475 MonoMethod *m;
4476 MonoSeqPointInfo *seq_points;
4477 GPtrArray *methods;
4478 GPtrArray *method_domains;
4479 GPtrArray *method_seq_points;
4480 int i;
4482 if (error)
4483 error_init (error);
4485 // FIXME:
4486 // - suspend/resume the vm to prevent code patching problems
4487 // - multiple breakpoints on the same location
4488 // - dynamic methods
4489 // - races
4491 bp = g_new0 (MonoBreakpoint, 1);
4492 bp->method = method;
4493 bp->il_offset = il_offset;
4494 bp->req = req;
4495 bp->children = g_ptr_array_new ();
4497 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);
4499 methods = g_ptr_array_new ();
4500 method_domains = g_ptr_array_new ();
4501 method_seq_points = g_ptr_array_new ();
4503 mono_loader_lock ();
4504 g_hash_table_iter_init (&iter, domains);
4505 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4506 mono_domain_lock (domain);
4507 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4508 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4509 if (bp_matches_method (bp, m)) {
4510 /* Save the info locally to simplify the code inside the domain lock */
4511 g_ptr_array_add (methods, m);
4512 g_ptr_array_add (method_domains, domain);
4513 g_ptr_array_add (method_seq_points, seq_points);
4516 mono_domain_unlock (domain);
4519 for (i = 0; i < methods->len; ++i) {
4520 m = (MonoMethod *)g_ptr_array_index (methods, i);
4521 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4522 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4523 set_bp_in_method (domain, m, seq_points, bp, error);
4526 g_ptr_array_add (breakpoints, bp);
4527 mono_loader_unlock ();
4529 g_ptr_array_free (methods, TRUE);
4530 g_ptr_array_free (method_domains, TRUE);
4531 g_ptr_array_free (method_seq_points, TRUE);
4533 if (error && !mono_error_ok (error)) {
4534 clear_breakpoint (bp);
4535 return NULL;
4538 return bp;
4541 static void
4542 clear_breakpoint (MonoBreakpoint *bp)
4544 int i;
4546 // FIXME: locking, races
4547 for (i = 0; i < bp->children->len; ++i) {
4548 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4550 remove_breakpoint (inst);
4552 g_free (inst);
4555 mono_loader_lock ();
4556 g_ptr_array_remove (breakpoints, bp);
4557 mono_loader_unlock ();
4559 g_ptr_array_free (bp->children, TRUE);
4560 g_free (bp);
4563 static void
4564 breakpoints_cleanup (void)
4566 int i;
4568 mono_loader_lock ();
4569 i = 0;
4570 while (i < event_requests->len) {
4571 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4573 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4574 clear_breakpoint ((MonoBreakpoint *)req->info);
4575 g_ptr_array_remove_index_fast (event_requests, i);
4576 g_free (req);
4577 } else {
4578 i ++;
4582 for (i = 0; i < breakpoints->len; ++i)
4583 g_free (g_ptr_array_index (breakpoints, i));
4585 g_ptr_array_free (breakpoints, TRUE);
4586 g_hash_table_destroy (bp_locs);
4588 breakpoints = NULL;
4589 bp_locs = NULL;
4591 mono_loader_unlock ();
4595 * clear_breakpoints_for_domain:
4597 * Clear breakpoint instances which reference DOMAIN.
4599 static void
4600 clear_breakpoints_for_domain (MonoDomain *domain)
4602 int i, j;
4604 /* This could be called after shutdown */
4605 if (!breakpoints)
4606 return;
4608 mono_loader_lock ();
4609 for (i = 0; i < breakpoints->len; ++i) {
4610 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4612 j = 0;
4613 while (j < bp->children->len) {
4614 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4616 if (inst->domain == domain) {
4617 remove_breakpoint (inst);
4619 g_free (inst);
4621 g_ptr_array_remove_index_fast (bp->children, j);
4622 } else {
4623 j ++;
4627 mono_loader_unlock ();
4631 * ss_calculate_framecount:
4633 * Ensure DebuggerTlsData fields are filled out.
4635 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4637 if (!tls->context.valid)
4638 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4639 compute_frame_info (tls->thread, tls);
4642 static gboolean
4643 ensure_jit (StackFrame* frame)
4645 if (!frame->jit) {
4646 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4647 if (!frame->jit && frame->api_method->is_inflated)
4648 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4649 if (!frame->jit) {
4650 char *s;
4652 /* This could happen for aot images with no jit debug info */
4653 s = mono_method_full_name (frame->api_method, TRUE);
4654 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4655 g_free (s);
4656 return FALSE;
4659 return TRUE;
4663 * ss_update:
4665 * Return FALSE if single stepping needs to continue.
4667 static gboolean
4668 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4670 MonoDebugMethodInfo *minfo;
4671 MonoDebugSourceLocation *loc = NULL;
4672 gboolean hit = TRUE;
4674 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR)) {
4675 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4676 compute_frame_info (tls->thread, tls);
4678 gboolean ret = FALSE;
4679 gboolean method_in_stack = FALSE;
4681 for (int i=0; i < tls->frame_count; i++) {
4682 MonoMethod *external_method = tls->frames [i]->method;
4683 if (method == external_method)
4684 method_in_stack = TRUE;
4686 if (!ret) {
4687 ret = (external_method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME);
4688 ret = ret && !strcmp (external_method->name, ".cctor");
4689 ret = ret && (external_method != req->start_method);
4693 if (!method_in_stack) {
4694 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);
4695 /*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);*/
4697 for (int i=0; i < tls->frame_count; i++)
4698 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));
4700 g_assert (method_in_stack);
4702 tls->context.valid = FALSE;
4703 tls->async_state.valid = FALSE;
4704 invalidate_frames (tls);
4706 if (ret)
4707 return FALSE;
4710 if (req->async_stepout_method == method) {
4711 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);
4712 return FALSE;
4715 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4717 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4719 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);
4720 return FALSE;
4723 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4724 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4726 ss_calculate_framecount (tls, ctx);
4728 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4729 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4730 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4731 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4732 /* Hit the breakpoint in a recursive call, don't halt */
4733 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");
4734 return FALSE;
4738 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4739 ss_calculate_framecount (tls, ctx);
4740 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4741 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);
4742 return FALSE;
4746 MonoDebugMethodAsyncInfo* async_method = mono_debug_lookup_method_async_debug_info (method);
4747 if (async_method) {
4748 for (int i = 0; i < async_method->num_awaits; i++) {
4749 if (async_method->yield_offsets[i] == sp->il_offset || async_method->resume_offsets[i] == sp->il_offset) {
4750 mono_debug_free_method_async_debug_info (async_method);
4751 return FALSE;
4754 mono_debug_free_method_async_debug_info (async_method);
4757 if (req->size != STEP_SIZE_LINE)
4758 return TRUE;
4760 /* Have to check whenever a different source line was reached */
4761 minfo = mono_debug_lookup_method (method);
4763 if (minfo)
4764 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4766 if (!loc) {
4767 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);
4768 ss_req->last_method = method;
4769 hit = FALSE;
4770 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4771 ss_calculate_framecount (tls, ctx);
4772 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4773 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4774 hit = FALSE;
4778 if (loc) {
4779 ss_req->last_method = method;
4780 ss_req->last_line = loc->row;
4781 mono_debug_free_source_location (loc);
4784 return hit;
4787 static gboolean
4788 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4790 return bp->method && bp->method->klass->image->assembly == assembly;
4793 static gpointer
4794 get_this_addr (StackFrame *frame)
4796 if (frame->ji->is_interp)
4797 return mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
4799 MonoDebugVarInfo *var = frame->jit->this_var;
4800 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4801 return NULL;
4803 guint8 *addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4804 addr += (gint32)var->offset;
4805 return addr;
4808 static MonoMethod*
4809 get_set_notification_method (MonoClass* async_builder_class)
4811 ERROR_DECL (error);
4812 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, error);
4813 mono_error_assert_ok (error);
4814 if (array->len == 0) {
4815 g_ptr_array_free (array, TRUE);
4816 return NULL;
4818 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4819 g_ptr_array_free (array, TRUE);
4820 return set_notification_method;
4823 static MonoMethod*
4824 get_object_id_for_debugger_method (MonoClass* async_builder_class)
4826 ERROR_DECL (error);
4827 GPtrArray *array = mono_class_get_methods_by_name (async_builder_class, "get_ObjectIdForDebugger", 0x24, FALSE, FALSE, error);
4828 mono_error_assert_ok (error);
4829 g_assert (array->len == 1);
4830 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, 0);
4831 g_ptr_array_free (array, TRUE);
4832 return method;
4835 /* Return the address of the AsyncMethodBuilder struct belonging to the state machine method pointed to by FRAME */
4836 static gpointer
4837 get_async_method_builder (StackFrame *frame)
4839 MonoObject *this_obj;
4840 MonoClassField *builder_field;
4841 gpointer builder;
4842 guint8 *this_addr;
4844 builder_field = mono_class_get_field_from_name (frame->method->klass, "<>t__builder");
4845 g_assert (builder_field);
4847 this_addr = get_this_addr (frame);
4848 if (!this_addr)
4849 return NULL;
4851 if (frame->method->klass->valuetype) {
4852 guint8 *vtaddr = *(guint8**)this_addr;
4853 builder = (char*)vtaddr + builder_field->offset - sizeof (MonoObject);
4854 } else {
4855 this_obj = *(MonoObject**)this_addr;
4856 builder = (char*)this_obj + builder_field->offset;
4859 return builder;
4862 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4863 //since thread probably changed...
4864 static int
4865 get_this_async_id (StackFrame *frame)
4867 MonoClassField *builder_field;
4868 gpointer builder;
4869 MonoMethod *method;
4870 MonoObject *ex;
4871 ERROR_DECL (error);
4872 MonoObject *obj;
4873 gboolean old_disable_breakpoints = FALSE;
4874 DebuggerTlsData *tls;
4877 * FRAME points to a method in a state machine class/struct.
4878 * Call the ObjectIdForDebugger method of the associated method builder type.
4880 builder = get_async_method_builder (frame);
4881 if (!builder)
4882 return 0;
4884 builder_field = mono_class_get_field_from_name (frame->method->klass, "<>t__builder");
4885 g_assert (builder_field);
4887 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4888 if (tls) {
4889 old_disable_breakpoints = tls->disable_breakpoints;
4890 tls->disable_breakpoints = TRUE;
4893 method = get_object_id_for_debugger_method (mono_class_from_mono_type (builder_field->type));
4894 obj = mono_runtime_try_invoke (method, builder, NULL, &ex, error);
4895 mono_error_assert_ok (error);
4897 if (tls)
4898 tls->disable_breakpoints = old_disable_breakpoints;
4900 return get_objid (obj);
4903 // Returns true if TaskBuilder has NotifyDebuggerOfWaitCompletion method
4904 // false if not(AsyncVoidBuilder)
4905 static gboolean
4906 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4908 MonoClassField *builder_field = mono_class_get_field_from_name (frame->method->klass, "<>t__builder");
4909 g_assert (builder_field);
4910 gpointer builder = get_async_method_builder (frame);
4911 g_assert (builder);
4913 void* args [1];
4914 gboolean arg = TRUE;
4915 ERROR_DECL (error);
4916 args [0] = &arg;
4917 MonoMethod* method = get_set_notification_method (mono_class_from_mono_type (builder_field->type));
4918 if (method == NULL)
4919 return FALSE;
4920 mono_runtime_invoke_checked (method, builder, args, error);
4921 mono_error_assert_ok (error);
4922 return TRUE;
4925 static MonoMethod* notify_debugger_of_wait_completion_method_cache;
4927 static MonoMethod*
4928 get_notify_debugger_of_wait_completion_method (void)
4930 if (notify_debugger_of_wait_completion_method_cache != NULL)
4931 return notify_debugger_of_wait_completion_method_cache;
4932 ERROR_DECL (error);
4933 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4934 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, error);
4935 mono_error_assert_ok (error);
4936 g_assert (array->len == 1);
4937 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4938 g_ptr_array_free (array, TRUE);
4939 return notify_debugger_of_wait_completion_method_cache;
4942 static void
4943 process_breakpoint (DebuggerTlsData *tls, gboolean from_signal)
4945 MonoJitInfo *ji;
4946 guint8 *ip;
4947 int i, j, suspend_policy;
4948 guint32 native_offset;
4949 MonoBreakpoint *bp;
4950 BreakpointInstance *inst;
4951 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4952 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4953 EventKind kind = EVENT_KIND_BREAKPOINT;
4954 MonoContext *ctx = &tls->restore_state.ctx;
4955 MonoMethod *method;
4956 MonoSeqPointInfo *info;
4957 SeqPoint sp;
4958 gboolean found_sp;
4960 // FIXME: Speed this up
4962 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4963 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4965 if (!ji) {
4966 /* Interpreter */
4967 // FIXME: Pass a flag instead to detect this
4968 MonoLMF *lmf = mono_get_lmf ();
4969 MonoInterpFrameHandle *frame;
4971 g_assert (((guint64)lmf->previous_lmf) & 2);
4972 MonoLMFExt *ext = (MonoLMFExt*)lmf;
4974 g_assert (ext->interp_exit);
4975 frame = ext->interp_exit_data;
4976 ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame);
4977 ip = mini_get_interp_callbacks ()->frame_get_ip (frame);
4980 g_assert (ji && !ji->is_trampoline);
4981 method = jinfo_get_method (ji);
4983 /* Compute the native offset of the breakpoint from the ip */
4984 native_offset = ip - (guint8*)ji->code_start;
4987 * Skip the instruction causing the breakpoint signal.
4989 if (from_signal)
4990 mono_arch_skip_breakpoint (ctx, ji);
4992 if (method->wrapper_type || tls->disable_breakpoints)
4993 return;
4995 bp_reqs = g_ptr_array_new ();
4996 ss_reqs = g_ptr_array_new ();
4997 ss_reqs_orig = g_ptr_array_new ();
4999 mono_loader_lock ();
5002 * The ip points to the instruction causing the breakpoint event, which is after
5003 * the offset recorded in the seq point map, so find the prev seq point before ip.
5005 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
5007 if (!found_sp)
5008 no_seq_points_found (method, native_offset);
5010 g_assert (found_sp);
5012 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);
5014 bp = NULL;
5015 for (i = 0; i < breakpoints->len; ++i) {
5016 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
5018 if (!bp->method)
5019 continue;
5021 for (j = 0; j < bp->children->len; ++j) {
5022 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
5023 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
5024 if (bp->req->event_kind == EVENT_KIND_STEP) {
5025 g_ptr_array_add (ss_reqs_orig, bp->req);
5026 } else {
5027 g_ptr_array_add (bp_reqs, bp->req);
5032 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
5033 /* Maybe a method entry/exit event */
5034 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
5035 kind = EVENT_KIND_METHOD_ENTRY;
5036 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
5037 kind = EVENT_KIND_METHOD_EXIT;
5040 /* Process single step requests */
5041 for (i = 0; i < ss_reqs_orig->len; ++i) {
5042 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
5043 SingleStepReq *ss_req = (SingleStepReq *)req->info;
5044 gboolean hit;
5046 //if we hit async_stepout_method, it's our no matter which thread
5047 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
5048 //We have different thread and we don't have async stepping in progress
5049 //it's breakpoint in parallel thread, ignore it
5050 if (ss_req->async_id == 0)
5051 continue;
5053 tls->context.valid = FALSE;
5054 tls->async_state.valid = FALSE;
5055 invalidate_frames (tls);
5056 ss_calculate_framecount(tls, ctx);
5057 //make sure we have enough data to get current async method instance id
5058 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
5059 continue;
5061 //Check method is async before calling get_this_async_id
5062 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5063 if (!asyncMethod)
5064 continue;
5065 else
5066 mono_debug_free_method_async_debug_info (asyncMethod);
5068 //breakpoint was hit in parallelly executing async method, ignore it
5069 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
5070 continue;
5073 //Update stepping request to new thread/frame_count that we are continuing on
5074 //so continuing with normal stepping works as expected
5075 if (ss_req->async_stepout_method || ss_req->async_id) {
5076 tls->context.valid = FALSE;
5077 tls->async_state.valid = FALSE;
5078 invalidate_frames (tls);
5079 ss_calculate_framecount (tls, ctx);
5080 ss_req->thread = mono_thread_internal_current ();
5081 ss_req->nframes = tls->frame_count;
5084 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
5085 if (hit)
5086 g_ptr_array_add (ss_reqs, req);
5088 /* Start single stepping again from the current sequence point */
5089 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5092 if (ss_reqs->len > 0)
5093 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
5094 if (bp_reqs->len > 0)
5095 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
5096 if (kind != EVENT_KIND_BREAKPOINT)
5097 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
5099 mono_loader_unlock ();
5101 g_ptr_array_free (bp_reqs, TRUE);
5102 g_ptr_array_free (ss_reqs, TRUE);
5105 * FIXME: The first event will suspend, so the second will only be sent after the
5106 * resume.
5108 if (ss_events)
5109 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
5110 if (bp_events)
5111 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
5112 if (enter_leave_events)
5113 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
5116 /* Process a breakpoint/single step event after resuming from a signal handler */
5117 static void
5118 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
5120 DebuggerTlsData *tls;
5121 MonoThreadUnwindState orig_restore_state;
5122 MonoContext ctx;
5124 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5125 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5126 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5127 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
5129 func (tls, TRUE);
5131 /* This is called when resuming from a signal handler, so it shouldn't return */
5132 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5133 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5134 mono_restore_context (&ctx);
5135 g_assert_not_reached ();
5138 static void
5139 process_breakpoint_from_signal (void)
5141 process_signal_event (process_breakpoint);
5144 static void
5145 resume_from_signal_handler (void *sigctx, void *func)
5147 DebuggerTlsData *tls;
5148 MonoContext ctx;
5150 /* Save the original context in TLS */
5151 // FIXME: This might not work on an altstack ?
5152 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5153 if (!tls)
5154 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
5155 g_assert (tls);
5157 // FIXME: MonoContext usually doesn't include the fp registers, so these are
5158 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
5159 // clob:c could be added to op_seq_point.
5161 mono_sigctx_to_monoctx (sigctx, &ctx);
5162 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
5163 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
5164 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
5165 #else
5166 MONO_CONTEXT_SET_IP (&ctx, func);
5167 #endif
5168 mono_monoctx_to_sigctx (&ctx, sigctx);
5171 void
5172 mono_debugger_agent_breakpoint_hit (void *sigctx)
5175 * We are called from a signal handler, and running code there causes all kinds of
5176 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
5177 * So set up the signal context to return to the real breakpoint handler function.
5179 resume_from_signal_handler (sigctx, process_breakpoint_from_signal);
5182 typedef struct {
5183 gboolean found;
5184 MonoContext *ctx;
5185 } UserBreakCbData;
5187 static gboolean
5188 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
5190 UserBreakCbData *data = user_data;
5192 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED) {
5193 data->found = TRUE;
5194 return TRUE;
5196 if (frame->managed) {
5197 data->found = TRUE;
5198 *data->ctx = *ctx;
5200 return TRUE;
5202 return FALSE;
5206 * Called by System.Diagnostics.Debugger:Break ().
5208 void
5209 mono_debugger_agent_user_break (void)
5211 if (agent_config.enabled) {
5212 MonoContext ctx;
5213 int suspend_policy;
5214 GSList *events;
5215 UserBreakCbData data;
5217 memset (&data, 0, sizeof (UserBreakCbData));
5218 data.ctx = &ctx;
5220 /* Obtain a context */
5221 MONO_CONTEXT_SET_IP (&ctx, NULL);
5222 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
5223 g_assert (data.found);
5225 mono_loader_lock ();
5226 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5227 mono_loader_unlock ();
5229 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5230 } else if (debug_options.native_debugger_break) {
5231 G_BREAKPOINT ();
5235 static const char*
5236 ss_depth_to_string (StepDepth depth)
5238 switch (depth) {
5239 case STEP_DEPTH_OVER:
5240 return "over";
5241 case STEP_DEPTH_OUT:
5242 return "out";
5243 case STEP_DEPTH_INTO:
5244 return "into";
5245 default:
5246 g_assert_not_reached ();
5247 return NULL;
5251 static void
5252 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5254 MonoJitInfo *ji;
5255 guint8 *ip;
5256 GPtrArray *reqs;
5257 int il_offset, suspend_policy;
5258 MonoDomain *domain;
5259 GSList *events;
5260 MonoContext *ctx = &tls->restore_state.ctx;
5261 MonoMethod *method;
5262 SeqPoint sp;
5263 MonoSeqPointInfo *info;
5265 /* Skip the instruction causing the single step */
5266 if (from_signal)
5267 mono_arch_skip_single_step (ctx);
5269 if (suspend_count > 0) {
5270 /* Fastpath during invokes, see in process_suspend () */
5271 if (suspend_count - tls->resume_count == 0)
5272 return;
5273 process_suspend (tls, ctx);
5274 return;
5277 if (!ss_req)
5278 // FIXME: A suspend race
5279 return;
5281 if (mono_thread_internal_current () != ss_req->thread)
5282 return;
5284 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5286 ji = get_top_method_ji (ip, &domain, (gpointer*)&ip);
5287 g_assert (ji && !ji->is_trampoline);
5289 if (log_level > 0) {
5290 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);
5293 method = jinfo_get_method (ji);
5294 g_assert (method);
5296 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5297 return;
5300 * FIXME:
5301 * Stopping in memset makes half-initialized vtypes visible.
5302 * Stopping in memcpy makes half-copied vtypes visible.
5304 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5305 return;
5308 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5309 * hence we prefer this check here.
5311 if (ss_req->user_assemblies) {
5312 gboolean found = FALSE;
5313 for (int k = 0; ss_req->user_assemblies[k]; k++)
5314 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5315 found = TRUE;
5316 break;
5318 if (!found)
5319 return;
5324 * The ip points to the instruction causing the single step event, which is before
5325 * the offset recorded in the seq point map, so find the next seq point after ip.
5327 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp)) {
5328 g_assert_not_reached ();
5329 return;
5332 il_offset = sp.il_offset;
5334 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5335 return;
5337 /* Start single stepping again from the current sequence point */
5338 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5340 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5341 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5342 !strcmp (method->name, ".cctor"))
5343 return;
5345 // FIXME: Has to lock earlier
5347 reqs = g_ptr_array_new ();
5349 mono_loader_lock ();
5351 g_ptr_array_add (reqs, ss_req->req);
5353 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5355 g_ptr_array_free (reqs, TRUE);
5357 mono_loader_unlock ();
5359 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5362 static void
5363 process_single_step (void)
5365 process_signal_event (process_single_step_inner);
5369 * mono_debugger_agent_single_step_event:
5371 * Called from a signal handler to handle a single step event.
5373 void
5374 mono_debugger_agent_single_step_event (void *sigctx)
5376 /* Resume to process_single_step through the signal context */
5378 // FIXME: Since step out/over is implemented using step in, the step in case should
5379 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5380 // here
5382 if (is_debugger_thread ()) {
5384 * This could happen despite our best effors when the runtime calls
5385 * assembly/type resolve hooks.
5386 * FIXME: Breakpoints too.
5388 MonoContext ctx;
5390 mono_sigctx_to_monoctx (sigctx, &ctx);
5391 mono_arch_skip_single_step (&ctx);
5392 mono_monoctx_to_sigctx (&ctx, sigctx);
5393 return;
5396 resume_from_signal_handler (sigctx, process_single_step);
5399 void
5400 debugger_agent_single_step_from_context (MonoContext *ctx)
5402 DebuggerTlsData *tls;
5403 MonoThreadUnwindState orig_restore_state;
5405 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5406 /* Fastpath during invokes, see in process_suspend () */
5407 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5408 return;
5410 if (is_debugger_thread ())
5411 return;
5413 g_assert (tls);
5415 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5416 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5417 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5418 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5420 process_single_step_inner (tls, FALSE);
5422 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5423 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5426 void
5427 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5429 DebuggerTlsData *tls;
5430 MonoThreadUnwindState orig_restore_state;
5431 guint8 *orig_ip;
5433 if (is_debugger_thread ())
5434 return;
5436 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5437 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5439 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5440 g_assert (tls);
5441 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5442 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5443 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5445 process_breakpoint (tls, FALSE);
5447 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5448 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5449 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5450 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5454 * start_single_stepping:
5456 * Turn on single stepping. Can be called multiple times, for example,
5457 * by a single step event request + a suspend.
5459 static void
5460 start_single_stepping (void)
5462 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5463 int val = mono_atomic_inc_i32 (&ss_count);
5465 if (val == 1) {
5466 mono_arch_start_single_stepping ();
5467 mini_get_interp_callbacks ()->start_single_stepping ();
5469 #else
5470 g_assert_not_reached ();
5471 #endif
5474 static void
5475 stop_single_stepping (void)
5477 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5478 int val = mono_atomic_dec_i32 (&ss_count);
5480 if (val == 0) {
5481 mono_arch_stop_single_stepping ();
5482 mini_get_interp_callbacks ()->stop_single_stepping ();
5484 #else
5485 g_assert_not_reached ();
5486 #endif
5490 * ss_stop:
5492 * Stop the single stepping operation given by SS_REQ.
5494 static void
5495 ss_stop (SingleStepReq *ss_req)
5497 if (ss_req->bps) {
5498 GSList *l;
5500 for (l = ss_req->bps; l; l = l->next) {
5501 clear_breakpoint ((MonoBreakpoint *)l->data);
5503 g_slist_free (ss_req->bps);
5504 ss_req->bps = NULL;
5507 ss_req->async_id = 0;
5508 ss_req->async_stepout_method = NULL;
5509 if (ss_req->global) {
5510 stop_single_stepping ();
5511 ss_req->global = FALSE;
5516 * ss_bp_is_unique:
5518 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5520 static gboolean
5521 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5523 if (ss_req_bp_cache) {
5524 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5525 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5527 for (GSList *l = bps; l; l = l->next) {
5528 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5529 if (bp->method == method && bp->il_offset == il_offset)
5530 return FALSE;
5532 return TRUE;
5536 * ss_bp_eq:
5538 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5540 static gint
5541 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5543 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5544 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5545 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5549 * ss_bp_eq:
5551 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5553 static guint
5554 ss_bp_hash (gconstpointer data)
5556 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5557 guint hash = (guint) (uintptr_t) s->method;
5558 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5559 hash ^= ((guint)s->il_offset) >> 16;
5560 return hash;
5563 #define MAX_LINEAR_SCAN_BPS 7
5566 * ss_bp_add_one:
5568 * Create a new breakpoint and add it to a step request.
5569 * Will adjust the bp count and cache used by ss_start.
5571 static void
5572 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5573 MonoMethod *method, guint32 il_offset)
5575 // This list is getting too long, switch to using the hash table
5576 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5577 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5578 for (GSList *l = ss_req->bps; l; l = l->next)
5579 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5582 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5583 // Create and add breakpoint
5584 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5585 ss_req->bps = g_slist_append (ss_req->bps, bp);
5586 if (*ss_req_bp_cache)
5587 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5588 (*ss_req_bp_count)++;
5589 } else {
5590 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);
5594 static gboolean
5595 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5597 if (!sp->next_len)
5598 return TRUE;
5599 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5600 mono_seq_point_init_next (info, *sp, next);
5601 for (int i = 0; i < sp->next_len; i++) {
5602 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5603 if (!is_last_non_empty (&next [i], info)) {
5604 g_free (next);
5605 return FALSE;
5607 } else {
5608 g_free (next);
5609 return FALSE;
5612 g_free (next);
5613 return TRUE;
5617 * ss_start:
5619 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5620 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5621 * belong to the same thread as CTX.
5622 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5624 static void
5625 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5626 gboolean step_to_catch, StackFrame **frames, int nframes)
5628 int i, j, frame_index;
5629 SeqPoint *next_sp, *parent_sp = NULL;
5630 SeqPoint local_sp, local_parent_sp;
5631 gboolean found_sp;
5632 MonoSeqPointInfo *parent_info;
5633 MonoMethod *parent_sp_method = NULL;
5634 gboolean enable_global = FALSE;
5636 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5637 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5638 int ss_req_bp_count = g_slist_length (ss_req->bps);
5639 GHashTable *ss_req_bp_cache = NULL;
5641 /* Stop the previous operation */
5642 ss_stop (ss_req);
5645 * Implement single stepping using breakpoints if possible.
5647 if (step_to_catch) {
5648 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5649 } else {
5650 frame_index = 1;
5652 if (ctx && !frames) {
5653 /* Need parent frames */
5654 if (!tls->context.valid)
5655 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5656 compute_frame_info (tls->thread, tls);
5657 frames = tls->frames;
5658 nframes = tls->frame_count;
5661 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5663 /* Need to stop in catch clauses as well */
5664 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5665 StackFrame *frame = frames [i];
5667 if (frame->ji) {
5668 MonoJitInfo *jinfo = frame->ji;
5669 for (j = 0; j < jinfo->num_clauses; ++j) {
5670 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5671 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5672 break;
5673 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5675 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5676 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5681 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5682 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5684 // Check if we hit yield_offset during normal stepping, because if we did...
5685 // Go into special async stepping mode which places breakpoint on resumeOffset
5686 // of this await call and sets async_id so we can distinguish it from parallel executions
5687 for (i = 0; i < asyncMethod->num_awaits; i++) {
5688 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5689 ss_req->async_id = get_this_async_id (frames [0]);
5690 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5691 if (ss_req_bp_cache)
5692 g_hash_table_destroy (ss_req_bp_cache);
5693 mono_debug_free_method_async_debug_info (asyncMethod);
5694 return;
5697 //If we are at end of async method and doing step-in or step-over...
5698 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5699 if (is_last_non_empty (sp, info)) {
5700 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5702 if (ss_req->depth == STEP_DEPTH_OUT) {
5703 //If we are inside `async void` method, do normal step-out
5704 if (set_set_notification_for_wait_completion_flag (frames [0])) {
5705 ss_req->async_id = get_this_async_id (frames [0]);
5706 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5707 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5708 if (ss_req_bp_cache)
5709 g_hash_table_destroy (ss_req_bp_cache);
5710 mono_debug_free_method_async_debug_info (asyncMethod);
5711 return;
5716 if (asyncMethod)
5717 mono_debug_free_method_async_debug_info (asyncMethod);
5720 * Find the first sequence point in the current or in a previous frame which
5721 * is not the last in its method.
5723 if (ss_req->depth == STEP_DEPTH_OUT) {
5724 /* Ignore seq points in current method */
5725 while (frame_index < nframes) {
5726 StackFrame *frame = frames [frame_index];
5728 method = frame->method;
5729 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5730 sp = (found_sp)? &local_sp : NULL;
5731 frame_index ++;
5732 if (sp && sp->next_len != 0)
5733 break;
5735 // There could be method calls before the next seq point in the caller when using nested calls
5736 //enable_global = TRUE;
5737 } else {
5738 if (sp && sp->next_len == 0) {
5739 sp = NULL;
5740 while (frame_index < nframes) {
5741 StackFrame *frame = frames [frame_index];
5743 method = frame->method;
5744 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5745 sp = (found_sp)? &local_sp : NULL;
5746 if (sp && sp->next_len != 0)
5747 break;
5748 sp = NULL;
5749 frame_index ++;
5751 } else {
5752 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5753 while (frame_index < nframes) {
5754 StackFrame *frame = frames [frame_index];
5756 parent_sp_method = frame->method;
5757 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5758 parent_sp = found_sp ? &local_parent_sp : NULL;
5759 if (found_sp && parent_sp->next_len != 0)
5760 break;
5761 parent_sp = NULL;
5762 frame_index ++;
5767 if (sp && sp->next_len > 0) {
5768 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5770 mono_seq_point_init_next (info, *sp, next);
5771 for (i = 0; i < sp->next_len; i++) {
5772 next_sp = &next[i];
5774 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5776 g_free (next);
5779 if (parent_sp) {
5780 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5782 mono_seq_point_init_next (parent_info, *parent_sp, next);
5783 for (i = 0; i < parent_sp->next_len; i++) {
5784 next_sp = &next[i];
5786 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5788 g_free (next);
5791 if (ss_req->nframes == 0)
5792 ss_req->nframes = nframes;
5794 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5795 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5797 * This is needed since if we leave managed code, and later return to it, step over
5798 * is not going to stop.
5799 * This approach is a bit ugly, since we change the step depth, but it only affects
5800 * clients who reuse the same step request, and only in this special case.
5802 ss_req->depth = STEP_DEPTH_INTO;
5805 if (ss_req->depth == STEP_DEPTH_INTO) {
5806 /* Enable global stepping so we stop at method entry too */
5807 enable_global = TRUE;
5811 * The ctx/frame info computed above will become invalid when we continue.
5813 tls->context.valid = FALSE;
5814 tls->async_state.valid = FALSE;
5815 invalidate_frames (tls);
5818 if (enable_global) {
5819 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5820 ss_req->global = TRUE;
5821 start_single_stepping ();
5822 } else if (!ss_req->bps) {
5823 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5824 ss_req->global = TRUE;
5825 start_single_stepping ();
5826 } else {
5827 ss_req->global = FALSE;
5830 if (ss_req_bp_cache)
5831 g_hash_table_destroy (ss_req_bp_cache);
5835 * Start single stepping of thread THREAD
5837 static ErrorCode
5838 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5840 DebuggerTlsData *tls;
5841 MonoSeqPointInfo *info = NULL;
5842 SeqPoint *sp = NULL;
5843 SeqPoint local_sp;
5844 gboolean found_sp;
5845 MonoMethod *method = NULL;
5846 MonoDebugMethodInfo *minfo;
5847 gboolean step_to_catch = FALSE;
5848 gboolean set_ip = FALSE;
5849 StackFrame **frames = NULL;
5850 int nframes = 0;
5852 if (suspend_count == 0)
5853 return ERR_NOT_SUSPENDED;
5855 wait_for_suspend ();
5857 // FIXME: Multiple requests
5858 if (ss_req) {
5859 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5860 return ERR_NOT_IMPLEMENTED;
5863 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5865 ss_req = g_new0 (SingleStepReq, 1);
5866 ss_req->req = req;
5867 ss_req->thread = thread;
5868 ss_req->size = size;
5869 ss_req->depth = depth;
5870 ss_req->filter = filter;
5871 req->info = ss_req;
5873 for (int i = 0; i < req->nmodifiers; i++) {
5874 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5875 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5876 break;
5880 mono_loader_lock ();
5881 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5882 mono_loader_unlock ();
5883 g_assert (tls);
5884 if (!tls->context.valid) {
5885 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5886 return ERR_INVALID_ARGUMENT;
5889 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5891 * Need to start single stepping from restore_state and not from the current state
5893 set_ip = TRUE;
5894 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5897 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5899 if (tls->has_catch_frame) {
5900 StackFrameInfo frame;
5903 * We are stopped at a throw site. Stepping should go to the catch site.
5905 frame = tls->catch_frame;
5906 g_assert (frame.type == FRAME_TYPE_MANAGED || frame.type == FRAME_TYPE_INTERP);
5909 * Find the seq point corresponding to the landing site ip, which is the first seq
5910 * point after ip.
5912 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5913 sp = (found_sp)? &local_sp : NULL;
5914 if (!sp)
5915 no_seq_points_found (frame.method, frame.native_offset);
5916 g_assert (sp);
5918 method = frame.method;
5920 step_to_catch = TRUE;
5921 /* This make sure the seq point is not skipped by process_single_step () */
5922 ss_req->last_sp = NULL;
5925 if (!step_to_catch) {
5926 StackFrame *frame = NULL;
5928 if (set_ip) {
5929 if (frames && nframes)
5930 frame = frames [0];
5931 } else {
5932 compute_frame_info (thread, tls);
5934 if (tls->frame_count)
5935 frame = tls->frames [0];
5938 if (ss_req->size == STEP_SIZE_LINE) {
5939 if (frame) {
5940 ss_req->last_method = frame->method;
5941 ss_req->last_line = -1;
5943 minfo = mono_debug_lookup_method (frame->method);
5944 if (minfo && frame->il_offset != -1) {
5945 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5947 if (loc) {
5948 ss_req->last_line = loc->row;
5949 g_free (loc);
5955 if (frame) {
5956 if (!method && frame->il_offset != -1) {
5957 /* FIXME: Sort the table and use a binary search */
5958 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5959 sp = (found_sp)? &local_sp : NULL;
5960 if (!sp)
5961 no_seq_points_found (frame->method, frame->native_offset);
5962 g_assert (sp);
5963 method = frame->method;
5968 ss_req->start_method = method;
5970 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5972 if (frames)
5973 free_frames (frames, nframes);
5975 return ERR_NONE;
5978 static void
5979 ss_destroy (SingleStepReq *req)
5981 // FIXME: Locking
5982 g_assert (ss_req == req);
5984 ss_stop (ss_req);
5986 g_free (ss_req);
5987 ss_req = NULL;
5990 static void
5991 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5993 GSList *l;
5994 gboolean found = TRUE;
5996 while (found) {
5997 found = FALSE;
5998 for (l = ss_req->bps; l; l = l->next) {
5999 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
6000 clear_breakpoint ((MonoBreakpoint *)l->data);
6001 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
6002 found = TRUE;
6003 break;
6010 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
6012 void
6013 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
6015 ERROR_DECL (error);
6016 int suspend_policy;
6017 GSList *events;
6018 EventInfo ei;
6020 if (!agent_config.enabled)
6021 return;
6023 mono_loader_lock ();
6024 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
6025 mono_loader_unlock ();
6027 ei.level = level;
6028 ei.category = NULL;
6029 if (category) {
6030 ei.category = mono_string_to_utf8_checked (category, error);
6031 mono_error_cleanup (error);
6033 ei.message = NULL;
6034 if (message) {
6035 ei.message = mono_string_to_utf8_checked (message, error);
6036 mono_error_cleanup (error);
6039 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
6041 g_free (ei.category);
6042 g_free (ei.message);
6045 gboolean
6046 mono_debugger_agent_debug_log_is_enabled (void)
6048 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
6049 return agent_config.enabled;
6052 #if defined(HOST_ANDROID) || defined(TARGET_ANDROID)
6053 void
6054 mono_debugger_agent_unhandled_exception (MonoException *exc)
6056 int suspend_policy;
6057 GSList *events;
6058 EventInfo ei;
6060 if (!inited)
6061 return;
6063 memset (&ei, 0, sizeof (EventInfo));
6064 ei.exc = (MonoObject*)exc;
6066 mono_loader_lock ();
6067 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
6068 mono_loader_unlock ();
6070 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
6072 #endif
6074 void
6075 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
6076 MonoContext *catch_ctx, StackFrameInfo *catch_frame)
6078 int i, j, suspend_policy;
6079 GSList *events;
6080 MonoJitInfo *ji, *catch_ji;
6081 EventInfo ei;
6082 DebuggerTlsData *tls = NULL;
6084 if (thread_to_tls != NULL) {
6085 MonoInternalThread *thread = mono_thread_internal_current ();
6087 mono_loader_lock ();
6088 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6089 mono_loader_unlock ();
6091 if (tls && tls->abort_requested)
6092 return;
6093 if (tls && tls->disable_breakpoints)
6094 return;
6097 memset (&ei, 0, sizeof (EventInfo));
6099 /* Just-In-Time debugging */
6100 if (!catch_ctx) {
6101 if (agent_config.onuncaught && !inited) {
6102 finish_agent_init (FALSE);
6105 * Send an unsolicited EXCEPTION event with a dummy request id.
6107 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
6108 ei.exc = (MonoObject*)exc;
6109 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
6110 return;
6112 } else if (agent_config.onthrow && !inited) {
6113 GSList *l;
6114 gboolean found = FALSE;
6116 for (l = agent_config.onthrow; l; l = l->next) {
6117 char *ex_type = (char *)l->data;
6118 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
6120 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
6121 found = TRUE;
6123 g_free (f);
6126 if (found) {
6127 finish_agent_init (FALSE);
6130 * Send an unsolicited EXCEPTION event with a dummy request id.
6132 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
6133 ei.exc = (MonoObject*)exc;
6134 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
6135 return;
6139 if (!inited)
6140 return;
6142 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
6143 if (catch_frame)
6144 catch_ji = catch_frame->ji;
6145 else
6146 catch_ji = NULL;
6148 ei.exc = (MonoObject*)exc;
6149 ei.caught = catch_ctx != NULL;
6151 mono_loader_lock ();
6153 /* Treat exceptions which are caught in non-user code as unhandled */
6154 for (i = 0; i < event_requests->len; ++i) {
6155 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6156 if (req->event_kind != EVENT_KIND_EXCEPTION)
6157 continue;
6159 for (j = 0; j < req->nmodifiers; ++j) {
6160 Modifier *mod = &req->modifiers [j];
6162 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
6163 int k;
6164 gboolean found = FALSE;
6165 MonoAssembly **assemblies = mod->data.assemblies;
6167 if (assemblies) {
6168 for (k = 0; assemblies [k]; ++k)
6169 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
6170 found = TRUE;
6172 if (!found)
6173 ei.caught = FALSE;
6178 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
6179 mono_loader_unlock ();
6181 if (tls && ei.caught && catch_ctx) {
6182 if (catch_frame) {
6183 tls->has_catch_frame = TRUE;
6184 tls->catch_frame = *catch_frame;
6185 } else {
6186 memset (&tls->catch_frame, 0, sizeof (tls->catch_frame));
6190 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
6192 if (tls)
6193 tls->has_catch_frame = FALSE;
6196 void
6197 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6199 DebuggerTlsData *tls;
6201 if (!inited)
6202 return;
6204 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6205 if (!tls)
6206 return;
6209 * We're about to invoke an exception filter during the first pass of exception handling.
6211 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
6212 * 'orig_ctx' is the context where the exception has been thrown.
6215 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6217 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6218 * the call site (line 37) and then continue to Main(), but it would never
6219 * include the throw site (line 32).
6221 * Since exception filters are invoked during the first pass of exception handling,
6222 * the stack frames of the throw site are still intact, so we should include them
6223 * in a stack trace.
6225 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6227 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6228 * but report the location of the 'throw' to the user.
6232 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6235 void
6236 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6238 DebuggerTlsData *tls;
6240 if (!inited)
6241 return;
6243 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6244 if (!tls)
6245 return;
6247 tls->filter_state.valid = FALSE;
6251 * buffer_add_value_full:
6253 * Add the encoding of the value at ADDR described by T to the buffer.
6254 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6255 * vtypes.
6257 static void
6258 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6259 gboolean as_vtype, GHashTable *parent_vtypes)
6261 MonoObject *obj;
6262 gboolean boxed_vtype = FALSE;
6264 if (t->byref) {
6265 if (!(*(void**)addr)) {
6266 /* This can happen with compiler generated locals */
6267 //printf ("%s\n", mono_type_full_name (t));
6268 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6269 return;
6271 g_assert (*(void**)addr);
6272 addr = *(void**)addr;
6275 if (as_vtype) {
6276 switch (t->type) {
6277 case MONO_TYPE_BOOLEAN:
6278 case MONO_TYPE_I1:
6279 case MONO_TYPE_U1:
6280 case MONO_TYPE_CHAR:
6281 case MONO_TYPE_I2:
6282 case MONO_TYPE_U2:
6283 case MONO_TYPE_I4:
6284 case MONO_TYPE_U4:
6285 case MONO_TYPE_R4:
6286 case MONO_TYPE_I8:
6287 case MONO_TYPE_U8:
6288 case MONO_TYPE_R8:
6289 case MONO_TYPE_I:
6290 case MONO_TYPE_U:
6291 case MONO_TYPE_PTR:
6292 goto handle_vtype;
6293 break;
6294 default:
6295 break;
6299 switch (t->type) {
6300 case MONO_TYPE_VOID:
6301 buffer_add_byte (buf, t->type);
6302 break;
6303 case MONO_TYPE_BOOLEAN:
6304 case MONO_TYPE_I1:
6305 case MONO_TYPE_U1:
6306 buffer_add_byte (buf, t->type);
6307 buffer_add_int (buf, *(gint8*)addr);
6308 break;
6309 case MONO_TYPE_CHAR:
6310 case MONO_TYPE_I2:
6311 case MONO_TYPE_U2:
6312 buffer_add_byte (buf, t->type);
6313 buffer_add_int (buf, *(gint16*)addr);
6314 break;
6315 case MONO_TYPE_I4:
6316 case MONO_TYPE_U4:
6317 case MONO_TYPE_R4:
6318 buffer_add_byte (buf, t->type);
6319 buffer_add_int (buf, *(gint32*)addr);
6320 break;
6321 case MONO_TYPE_I8:
6322 case MONO_TYPE_U8:
6323 case MONO_TYPE_R8:
6324 buffer_add_byte (buf, t->type);
6325 buffer_add_long (buf, *(gint64*)addr);
6326 break;
6327 case MONO_TYPE_I:
6328 case MONO_TYPE_U:
6329 /* Treat it as a vtype */
6330 goto handle_vtype;
6331 case MONO_TYPE_PTR: {
6332 gssize val = *(gssize*)addr;
6334 buffer_add_byte (buf, t->type);
6335 buffer_add_long (buf, val);
6336 break;
6338 handle_ref:
6339 case MONO_TYPE_STRING:
6340 case MONO_TYPE_SZARRAY:
6341 case MONO_TYPE_OBJECT:
6342 case MONO_TYPE_CLASS:
6343 case MONO_TYPE_ARRAY:
6344 obj = *(MonoObject**)addr;
6346 if (!obj) {
6347 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6348 } else {
6349 if (obj->vtable->klass->valuetype) {
6350 t = &obj->vtable->klass->byval_arg;
6351 addr = mono_object_unbox (obj);
6352 boxed_vtype = TRUE;
6353 goto handle_vtype;
6354 } else if (obj->vtable->klass->rank) {
6355 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6356 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6357 buffer_add_byte (buf, MONO_TYPE_CLASS);
6358 } else {
6359 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6361 buffer_add_objid (buf, obj);
6363 break;
6364 handle_vtype:
6365 case MONO_TYPE_VALUETYPE:
6366 case MONO_TYPE_TYPEDBYREF: {
6367 int nfields;
6368 gpointer iter;
6369 MonoClassField *f;
6370 MonoClass *klass = mono_class_from_mono_type (t);
6371 int vtype_index;
6373 if (boxed_vtype) {
6375 * Handle boxed vtypes recursively referencing themselves using fields.
6377 if (!parent_vtypes)
6378 parent_vtypes = g_hash_table_new (NULL, NULL);
6379 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6380 if (vtype_index) {
6381 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6382 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6383 buffer_add_int (buf, vtype_index - 1);
6384 } else {
6385 /* The client can't handle PARENT_VTYPE */
6386 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6388 break;
6389 } else {
6390 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6394 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6395 buffer_add_byte (buf, klass->enumtype);
6396 buffer_add_typeid (buf, domain, klass);
6398 nfields = 0;
6399 iter = NULL;
6400 while ((f = mono_class_get_fields (klass, &iter))) {
6401 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6402 continue;
6403 if (mono_field_is_deleted (f))
6404 continue;
6405 nfields ++;
6407 buffer_add_int (buf, nfields);
6409 iter = NULL;
6410 while ((f = mono_class_get_fields (klass, &iter))) {
6411 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6412 continue;
6413 if (mono_field_is_deleted (f))
6414 continue;
6415 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6418 if (boxed_vtype) {
6419 g_hash_table_remove (parent_vtypes, addr);
6420 if (g_hash_table_size (parent_vtypes) == 0) {
6421 g_hash_table_destroy (parent_vtypes);
6422 parent_vtypes = NULL;
6425 break;
6427 case MONO_TYPE_GENERICINST:
6428 if (mono_type_generic_inst_is_valuetype (t)) {
6429 goto handle_vtype;
6430 } else {
6431 goto handle_ref;
6433 break;
6434 default:
6435 NOT_IMPLEMENTED;
6439 static void
6440 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6442 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6445 static gboolean
6446 obj_is_of_type (MonoObject *obj, MonoType *t)
6448 MonoClass *klass = obj->vtable->klass;
6449 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6450 if (mono_class_is_transparent_proxy (klass)) {
6451 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6452 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6453 return TRUE;
6456 return FALSE;
6458 return TRUE;
6461 static ErrorCode
6462 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6464 static ErrorCode
6465 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6467 gboolean is_enum;
6468 MonoClass *klass;
6469 MonoClassField *f;
6470 int nfields;
6471 gpointer iter = NULL;
6472 MonoDomain *d;
6473 ErrorCode err;
6475 is_enum = decode_byte (buf, &buf, limit);
6476 /* Enums are sent as a normal vtype */
6477 if (is_enum)
6478 return ERR_NOT_IMPLEMENTED;
6479 klass = decode_typeid (buf, &buf, limit, &d, &err);
6480 if (err != ERR_NONE)
6481 return err;
6483 if (t && klass != mono_class_from_mono_type (t)) {
6484 char *name = mono_type_full_name (t);
6485 char *name2 = mono_type_full_name (&klass->byval_arg);
6486 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6487 g_free (name);
6488 g_free (name2);
6489 return ERR_INVALID_ARGUMENT;
6492 nfields = decode_int (buf, &buf, limit);
6493 while ((f = mono_class_get_fields (klass, &iter))) {
6494 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6495 continue;
6496 if (mono_field_is_deleted (f))
6497 continue;
6498 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6499 if (err != ERR_NONE)
6500 return err;
6501 nfields --;
6503 g_assert (nfields == 0);
6505 *endbuf = buf;
6507 return ERR_NONE;
6510 static ErrorCode
6511 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6513 ErrorCode err;
6515 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6516 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6517 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6518 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6519 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6520 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6521 char *name = mono_type_full_name (t);
6522 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6523 g_free (name);
6524 return ERR_INVALID_ARGUMENT;
6527 switch (t->type) {
6528 case MONO_TYPE_BOOLEAN:
6529 *(guint8*)addr = decode_int (buf, &buf, limit);
6530 break;
6531 case MONO_TYPE_CHAR:
6532 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6533 break;
6534 case MONO_TYPE_I1:
6535 *(gint8*)addr = decode_int (buf, &buf, limit);
6536 break;
6537 case MONO_TYPE_U1:
6538 *(guint8*)addr = decode_int (buf, &buf, limit);
6539 break;
6540 case MONO_TYPE_I2:
6541 *(gint16*)addr = decode_int (buf, &buf, limit);
6542 break;
6543 case MONO_TYPE_U2:
6544 *(guint16*)addr = decode_int (buf, &buf, limit);
6545 break;
6546 case MONO_TYPE_I4:
6547 *(gint32*)addr = decode_int (buf, &buf, limit);
6548 break;
6549 case MONO_TYPE_U4:
6550 *(guint32*)addr = decode_int (buf, &buf, limit);
6551 break;
6552 case MONO_TYPE_I8:
6553 *(gint64*)addr = decode_long (buf, &buf, limit);
6554 break;
6555 case MONO_TYPE_U8:
6556 *(guint64*)addr = decode_long (buf, &buf, limit);
6557 break;
6558 case MONO_TYPE_R4:
6559 *(guint32*)addr = decode_int (buf, &buf, limit);
6560 break;
6561 case MONO_TYPE_R8:
6562 *(guint64*)addr = decode_long (buf, &buf, limit);
6563 break;
6564 case MONO_TYPE_PTR:
6565 /* We send these as I8, so we get them back as such */
6566 g_assert (type == MONO_TYPE_I8);
6567 *(gssize*)addr = decode_long (buf, &buf, limit);
6568 break;
6569 case MONO_TYPE_GENERICINST:
6570 if (MONO_TYPE_ISSTRUCT (t)) {
6571 /* The client sends these as a valuetype */
6572 goto handle_vtype;
6573 } else {
6574 goto handle_ref;
6576 break;
6577 case MONO_TYPE_I:
6578 case MONO_TYPE_U:
6579 /* We send these as vtypes, so we get them back as such */
6580 g_assert (type == MONO_TYPE_VALUETYPE);
6581 /* Fall through */
6582 handle_vtype:
6583 case MONO_TYPE_VALUETYPE:
6584 if (type == MONO_TYPE_OBJECT) {
6585 /* Boxed vtype */
6586 int objid = decode_objid (buf, &buf, limit);
6587 ErrorCode err;
6588 MonoObject *obj;
6590 err = get_object (objid, (MonoObject**)&obj);
6591 if (err != ERR_NONE)
6592 return err;
6593 if (!obj)
6594 return ERR_INVALID_ARGUMENT;
6595 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6596 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6597 return ERR_INVALID_ARGUMENT;
6599 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6600 } else {
6601 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6602 if (err != ERR_NONE)
6603 return err;
6605 break;
6606 handle_ref:
6607 default:
6608 if (MONO_TYPE_IS_REFERENCE (t)) {
6609 if (type == MONO_TYPE_OBJECT) {
6610 int objid = decode_objid (buf, &buf, limit);
6611 ErrorCode err;
6612 MonoObject *obj;
6614 err = get_object (objid, (MonoObject**)&obj);
6615 if (err != ERR_NONE)
6616 return err;
6618 if (obj) {
6619 if (!obj_is_of_type (obj, t)) {
6620 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6621 return ERR_INVALID_ARGUMENT;
6624 if (obj && obj->vtable->domain != domain)
6625 return ERR_INVALID_ARGUMENT;
6627 mono_gc_wbarrier_generic_store (addr, obj);
6628 } else if (type == VALUE_TYPE_ID_NULL) {
6629 *(MonoObject**)addr = NULL;
6630 } else if (type == MONO_TYPE_VALUETYPE) {
6631 ERROR_DECL (error);
6632 guint8 *buf2;
6633 gboolean is_enum;
6634 MonoClass *klass;
6635 MonoDomain *d;
6636 guint8 *vtype_buf;
6637 int vtype_buf_size;
6639 /* This can happen when round-tripping boxed vtypes */
6641 * Obtain vtype class.
6642 * Same as the beginning of the handle_vtype case above.
6644 buf2 = buf;
6645 is_enum = decode_byte (buf, &buf, limit);
6646 if (is_enum)
6647 return ERR_NOT_IMPLEMENTED;
6648 klass = decode_typeid (buf, &buf, limit, &d, &err);
6649 if (err != ERR_NONE)
6650 return err;
6652 /* Decode the vtype into a temporary buffer, then box it. */
6653 vtype_buf_size = mono_class_value_size (klass, NULL);
6654 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6655 g_assert (vtype_buf);
6657 buf = buf2;
6658 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6659 if (err != ERR_NONE) {
6660 g_free (vtype_buf);
6661 return err;
6663 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, error);
6664 mono_error_cleanup (error);
6665 g_free (vtype_buf);
6666 } else {
6667 char *name = mono_type_full_name (t);
6668 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6669 g_free (name);
6670 return ERR_INVALID_ARGUMENT;
6672 } else {
6673 NOT_IMPLEMENTED;
6675 break;
6678 *endbuf = buf;
6680 return ERR_NONE;
6683 static ErrorCode
6684 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6686 ERROR_DECL (error);
6687 ErrorCode err;
6688 int type = decode_byte (buf, &buf, limit);
6690 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6691 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6692 guint8 *nullable_buf;
6695 * First try decoding it as a Nullable`1
6697 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6698 if (err == ERR_NONE)
6699 return err;
6702 * Then try decoding as a primitive value or null.
6704 if (targ->type == type) {
6705 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6706 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6707 if (err != ERR_NONE) {
6708 g_free (nullable_buf);
6709 return err;
6711 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, error);
6712 if (!is_ok (error)) {
6713 mono_error_cleanup (error);
6714 return ERR_INVALID_OBJECT;
6716 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6717 g_free (nullable_buf);
6718 *endbuf = buf;
6719 return ERR_NONE;
6720 } else if (type == VALUE_TYPE_ID_NULL) {
6721 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6722 *endbuf = buf;
6723 return ERR_NONE;
6727 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6730 static void
6731 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6733 guint32 flags;
6734 int reg;
6735 guint8 *addr, *gaddr;
6736 mgreg_t reg_val;
6738 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6739 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6741 switch (flags) {
6742 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6743 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6745 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL);
6746 break;
6747 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6748 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6749 addr += (gint32)var->offset;
6751 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6753 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6754 break;
6755 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6756 NOT_IMPLEMENTED;
6757 break;
6758 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6759 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6760 /* Same as regoffset, but with an indirection */
6761 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6762 addr += (gint32)var->offset;
6764 gaddr = (guint8 *)*(gpointer*)addr;
6765 g_assert (gaddr);
6766 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6767 break;
6768 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6769 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6770 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6771 MonoGSharedVtMethodRuntimeInfo *info;
6772 guint8 *locals;
6773 int idx;
6775 idx = reg;
6777 g_assert (info_var);
6778 g_assert (locals_var);
6780 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6781 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6782 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6783 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6784 addr += (gint32)info_var->offset;
6785 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6786 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6787 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6788 } else {
6789 g_assert_not_reached ();
6791 g_assert (info);
6793 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6794 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6795 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6796 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6797 addr += (gint32)locals_var->offset;
6798 locals = (guint8 *)*(gpointer*)addr;
6799 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6800 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6801 } else {
6802 g_assert_not_reached ();
6804 g_assert (locals);
6806 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6808 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6809 break;
6812 default:
6813 g_assert_not_reached ();
6817 static void
6818 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6820 guint32 flags;
6821 int reg, size;
6822 guint8 *addr, *gaddr;
6824 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6825 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6827 if (MONO_TYPE_IS_REFERENCE (t))
6828 size = sizeof (gpointer);
6829 else
6830 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6832 switch (flags) {
6833 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6834 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6835 mgreg_t v;
6836 gboolean is_signed = FALSE;
6838 if (t->byref) {
6839 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6841 if (addr) {
6842 // FIXME: Write barriers
6843 mono_gc_memmove_atomic (addr, val, size);
6845 break;
6848 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6849 is_signed = TRUE;
6851 switch (size) {
6852 case 1:
6853 v = is_signed ? *(gint8*)val : *(guint8*)val;
6854 break;
6855 case 2:
6856 v = is_signed ? *(gint16*)val : *(guint16*)val;
6857 break;
6858 case 4:
6859 v = is_signed ? *(gint32*)val : *(guint32*)val;
6860 break;
6861 case 8:
6862 v = is_signed ? *(gint64*)val : *(guint64*)val;
6863 break;
6864 default:
6865 g_assert_not_reached ();
6868 /* Set value on the stack or in the return ctx */
6869 if (reg_locations [reg]) {
6870 /* Saved on the stack */
6871 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6872 *(reg_locations [reg]) = v;
6873 } else {
6874 /* Not saved yet */
6875 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6876 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6879 // FIXME: Move these to mono-context.h/c.
6880 mono_arch_context_set_int_reg (ctx, reg, v);
6881 #else
6882 // FIXME: Can't set registers, so we disable linears
6883 NOT_IMPLEMENTED;
6884 #endif
6885 break;
6887 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6888 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6889 addr += (gint32)var->offset;
6891 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6893 if (t->byref) {
6894 addr = *(guint8**)addr;
6896 if (!addr)
6897 break;
6900 // FIXME: Write barriers
6901 mono_gc_memmove_atomic (addr, val, size);
6902 break;
6903 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6904 /* Same as regoffset, but with an indirection */
6905 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6906 addr += (gint32)var->offset;
6908 gaddr = (guint8 *)*(gpointer*)addr;
6909 g_assert (gaddr);
6910 // FIXME: Write barriers
6911 mono_gc_memmove_atomic (gaddr, val, size);
6912 break;
6913 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6914 NOT_IMPLEMENTED;
6915 break;
6916 default:
6917 g_assert_not_reached ();
6921 static void
6922 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6924 int size;
6926 if (t->byref) {
6927 addr = *(gpointer*)addr;
6928 g_assert (addr);
6931 if (MONO_TYPE_IS_REFERENCE (t))
6932 size = sizeof (gpointer);
6933 else
6934 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6936 memcpy (addr, val_buf, size);
6939 static void
6940 clear_event_request (int req_id, int etype)
6942 int i;
6944 mono_loader_lock ();
6945 for (i = 0; i < event_requests->len; ++i) {
6946 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6948 if (req->id == req_id && req->event_kind == etype) {
6949 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6950 clear_breakpoint ((MonoBreakpoint *)req->info);
6951 if (req->event_kind == EVENT_KIND_STEP)
6952 ss_destroy ((SingleStepReq *)req->info);
6953 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6954 clear_breakpoint ((MonoBreakpoint *)req->info);
6955 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6956 clear_breakpoint ((MonoBreakpoint *)req->info);
6957 g_ptr_array_remove_index_fast (event_requests, i);
6958 g_free (req);
6959 break;
6962 mono_loader_unlock ();
6965 static void
6966 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6968 int i;
6970 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6971 m->kind = MOD_KIND_NONE;
6972 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6973 int count = 0, match_count = 0, pos;
6974 MonoAssembly **newassemblies;
6976 for (i = 0; m->data.assemblies [i]; ++i) {
6977 count ++;
6978 if (m->data.assemblies [i] == assembly)
6979 match_count ++;
6982 if (match_count) {
6983 // +1 because we don't know length and we use last element to check for end
6984 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6986 pos = 0;
6987 for (i = 0; i < count; ++i)
6988 if (m->data.assemblies [i] != assembly)
6989 newassemblies [pos ++] = m->data.assemblies [i];
6990 g_assert (pos == count - match_count);
6991 g_free (m->data.assemblies);
6992 m->data.assemblies = newassemblies;
6997 static void
6998 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
7000 int i;
7002 for (i = 0; i < req->nmodifiers; ++i) {
7003 Modifier *m = &req->modifiers [i];
7005 clear_assembly_from_modifier (req, m, assembly);
7010 * clear_event_requests_for_assembly:
7012 * Clear all events requests which reference ASSEMBLY.
7014 static void
7015 clear_event_requests_for_assembly (MonoAssembly *assembly)
7017 int i;
7018 gboolean found;
7020 mono_loader_lock ();
7021 found = TRUE;
7022 while (found) {
7023 found = FALSE;
7024 for (i = 0; i < event_requests->len; ++i) {
7025 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7027 clear_assembly_from_modifiers (req, assembly);
7029 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
7030 clear_event_request (req->id, req->event_kind);
7031 found = TRUE;
7032 break;
7035 if (req->event_kind == EVENT_KIND_STEP)
7036 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
7039 mono_loader_unlock ();
7043 * type_comes_from_assembly:
7045 * GHRFunc that returns TRUE if klass comes from assembly
7047 static gboolean
7048 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
7050 return mono_type_in_image (mono_class_get_type ((MonoClass*)klass), mono_assembly_get_image ((MonoAssembly*)assembly));
7054 * clear_types_for_assembly:
7056 * Clears types from loaded_classes for a given assembly
7058 static void
7059 clear_types_for_assembly (MonoAssembly *assembly)
7061 MonoDomain *domain = mono_domain_get ();
7062 AgentDomainInfo *info = NULL;
7064 if (!domain || !domain_jit_info (domain))
7065 /* Can happen during shutdown */
7066 return;
7068 info = get_agent_domain_info (domain);
7070 mono_loader_lock ();
7071 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
7072 mono_loader_unlock ();
7075 static void
7076 add_thread (gpointer key, gpointer value, gpointer user_data)
7078 MonoInternalThread *thread = (MonoInternalThread *)value;
7079 Buffer *buf = (Buffer *)user_data;
7081 buffer_add_objid (buf, (MonoObject*)thread);
7084 static ErrorCode
7085 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
7087 ERROR_DECL (error);
7088 guint8 *end = invoke->endp;
7089 MonoMethod *m;
7090 int i, nargs;
7091 ErrorCode err;
7092 MonoMethodSignature *sig;
7093 guint8 **arg_buf;
7094 void **args;
7095 MonoObject *this_arg, *res, *exc = NULL;
7096 MonoDomain *domain;
7097 guint8 *this_buf;
7098 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7099 MonoLMFExt ext;
7100 #endif
7101 MonoStopwatch watch;
7103 if (invoke->method) {
7105 * Invoke this method directly, currently only Environment.Exit () is supported.
7107 this_arg = NULL;
7108 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>");
7110 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, error);
7111 mono_error_assert_ok (error);
7113 g_assert_not_reached ();
7116 m = decode_methodid (p, &p, end, &domain, &err);
7117 if (err != ERR_NONE)
7118 return err;
7119 sig = mono_method_signature (m);
7121 if (m->klass->valuetype)
7122 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7123 else
7124 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
7125 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
7126 /* Should be null */
7127 int type = decode_byte (p, &p, end);
7128 if (type != VALUE_TYPE_ID_NULL) {
7129 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7130 return ERR_INVALID_ARGUMENT;
7132 memset (this_buf, 0, mono_class_instance_size (m->klass));
7133 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
7134 /* Could be null */
7135 guint8 *tmp_p;
7137 int type = decode_byte (p, &tmp_p, end);
7138 if (type == VALUE_TYPE_ID_NULL) {
7139 memset (this_buf, 0, mono_class_instance_size (m->klass));
7140 p = tmp_p;
7141 } else {
7142 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
7143 if (err != ERR_NONE)
7144 return err;
7146 } else {
7147 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
7148 if (err != ERR_NONE)
7149 return err;
7152 if (!m->klass->valuetype)
7153 this_arg = *(MonoObject**)this_buf;
7154 else
7155 this_arg = NULL;
7157 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
7158 if (!this_arg) {
7159 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7160 return ERR_INVALID_ARGUMENT;
7162 m = mono_object_get_virtual_method (this_arg, m);
7163 /* Transform this to the format the rest of the code expects it to be */
7164 if (m->klass->valuetype) {
7165 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7166 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
7168 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
7169 if (!this_arg) {
7170 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7171 return ERR_INVALID_ARGUMENT;
7173 m = mono_object_get_virtual_method (this_arg, m);
7174 if (m->klass->valuetype) {
7175 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7176 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
7180 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>");
7182 if (this_arg && this_arg->vtable->domain != domain)
7183 NOT_IMPLEMENTED;
7185 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
7186 if (!strcmp (m->name, ".ctor")) {
7187 if (mono_class_is_abstract (m->klass))
7188 return ERR_INVALID_ARGUMENT;
7189 else {
7190 ERROR_DECL (error);
7191 this_arg = mono_object_new_checked (domain, m->klass, error);
7192 mono_error_assert_ok (error);
7194 } else {
7195 return ERR_INVALID_ARGUMENT;
7199 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
7200 return ERR_INVALID_ARGUMENT;
7202 nargs = decode_int (p, &p, end);
7203 if (nargs != sig->param_count)
7204 return ERR_INVALID_ARGUMENT;
7205 /* Use alloca to get gc tracking */
7206 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
7207 memset (arg_buf, 0, nargs * sizeof (gpointer));
7208 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
7209 for (i = 0; i < nargs; ++i) {
7210 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
7211 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
7212 if (err != ERR_NONE)
7213 break;
7214 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
7215 NOT_IMPLEMENTED;
7217 if (sig->params [i]->byref) {
7218 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
7219 *(gpointer*)arg_buf [i] = args [i];
7220 args [i] = arg_buf [i];
7222 } else {
7223 MonoClass *arg_class = mono_class_from_mono_type (sig->params [i]);
7224 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
7225 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
7226 if (err != ERR_NONE)
7227 break;
7228 if (mono_class_is_nullable (arg_class)) {
7229 args [i] = mono_nullable_box (arg_buf [i], arg_class, error);
7230 mono_error_assert_ok (error);
7231 } else {
7232 args [i] = arg_buf [i];
7237 if (i < nargs)
7238 return err;
7240 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7241 tls->disable_breakpoints = TRUE;
7242 else
7243 tls->disable_breakpoints = FALSE;
7246 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7248 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7249 if (invoke->has_ctx) {
7250 /* Setup our lmf */
7251 memset (&ext, 0, sizeof (ext));
7252 ext.debugger_invoke = TRUE;
7253 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7255 mono_push_lmf (&ext);
7257 #endif
7259 mono_stopwatch_start (&watch);
7260 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, error);
7261 if (!mono_error_ok (error) && exc == NULL) {
7262 exc = (MonoObject*) mono_error_convert_to_exception (error);
7263 } else {
7264 mono_error_cleanup (error); /* FIXME report error */
7266 mono_stopwatch_stop (&watch);
7267 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));
7268 if (exc) {
7269 buffer_add_byte (buf, 0);
7270 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7271 } else {
7272 gboolean out_this = FALSE;
7273 gboolean out_args = FALSE;
7275 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7276 out_this = TRUE;
7277 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7278 out_args = TRUE;
7279 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7280 if (m->string_ctor) {
7281 buffer_add_value (buf, &mono_get_string_class ()->byval_arg, &res, domain);
7282 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
7283 if (!strcmp (m->name, ".ctor")) {
7284 if (!m->klass->valuetype)
7285 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7286 else
7287 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7288 } else {
7289 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7291 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7292 buffer_add_value (buf, sig->ret, &res, domain);
7293 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7294 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7295 MonoClass *k = mono_class_from_mono_type (sig->ret);
7296 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7298 g_assert (nullable_buf);
7299 mono_nullable_init (nullable_buf, res, k);
7300 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7301 } else {
7302 g_assert (res);
7303 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7305 } else {
7306 NOT_IMPLEMENTED;
7308 if (out_this)
7309 /* Return the new value of the receiver after the call */
7310 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7311 if (out_args) {
7312 buffer_add_int (buf, nargs);
7313 for (i = 0; i < nargs; ++i) {
7314 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7315 buffer_add_value (buf, sig->params [i], &args [i], domain);
7316 else if (sig->params [i]->byref)
7317 /* add_value () does an indirection */
7318 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7319 else
7320 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7325 tls->disable_breakpoints = FALSE;
7327 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7328 if (invoke->has_ctx)
7329 mono_pop_lmf ((MonoLMF*)&ext);
7330 #endif
7332 *endp = p;
7333 // FIXME: byref arguments
7334 // FIXME: varargs
7335 return ERR_NONE;
7339 * invoke_method:
7341 * Invoke the method given by tls->pending_invoke in the current thread.
7343 static void
7344 invoke_method (void)
7346 DebuggerTlsData *tls;
7347 InvokeData *invoke;
7348 int id;
7349 int i, mindex;
7350 ErrorCode err;
7351 Buffer buf;
7352 MonoContext restore_ctx;
7353 guint8 *p;
7355 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7356 g_assert (tls);
7359 * Store the `InvokeData *' in `tls->invoke' until we're done with
7360 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7363 mono_loader_lock ();
7365 invoke = tls->pending_invoke;
7366 g_assert (invoke);
7367 tls->pending_invoke = NULL;
7369 invoke->last_invoke = tls->invoke;
7370 tls->invoke = invoke;
7372 mono_loader_unlock ();
7374 tls->frames_up_to_date = FALSE;
7376 id = invoke->id;
7378 p = invoke->p;
7379 err = ERR_NONE;
7380 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7381 buffer_init (&buf, 128);
7383 if (err) {
7384 /* Fail the other invokes as well */
7385 } else {
7386 err = do_invoke_method (tls, &buf, invoke, p, &p);
7389 if (tls->abort_requested) {
7390 if (CHECK_PROTOCOL_VERSION (2, 42))
7391 err = ERR_INVOKE_ABORTED;
7394 /* Start suspending before sending the reply */
7395 if (mindex == invoke->nmethods - 1) {
7396 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7397 for (i = 0; i < invoke->suspend_count; ++i)
7398 suspend_vm ();
7402 send_reply_packet (id, err, &buf);
7404 buffer_free (&buf);
7407 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7409 if (invoke->has_ctx)
7410 save_thread_context (&restore_ctx);
7412 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7413 g_assert (tls->resume_count);
7414 tls->resume_count -= invoke->suspend_count;
7417 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7420 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7422 * It is possible that mono_thread_internal_abort () was called
7423 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7424 * because we reset the abort here.
7427 mono_loader_lock ();
7429 if (tls->abort_requested)
7430 mono_thread_internal_reset_abort (tls->thread);
7432 tls->invoke = tls->invoke->last_invoke;
7433 tls->abort_requested = FALSE;
7435 mono_loader_unlock ();
7437 g_free (invoke->p);
7438 g_free (invoke);
7440 suspend_current ();
7443 static gboolean
7444 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7446 MonoThread *thread = (MonoThread *)value;
7447 DebuggerTlsData *tls;
7448 gboolean res;
7450 mono_loader_lock ();
7451 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7452 g_assert (tls);
7453 res = tls->really_suspended;
7454 mono_loader_unlock ();
7456 return res;
7459 static GPtrArray*
7460 get_source_files_for_type (MonoClass *klass)
7462 gpointer iter = NULL;
7463 MonoMethod *method;
7464 MonoDebugSourceInfo *sinfo;
7465 GPtrArray *files;
7466 int i, j;
7468 files = g_ptr_array_new ();
7470 while ((method = mono_class_get_methods (klass, &iter))) {
7471 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7472 GPtrArray *source_file_list;
7474 if (minfo) {
7475 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7476 for (j = 0; j < source_file_list->len; ++j) {
7477 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7478 for (i = 0; i < files->len; ++i)
7479 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7480 break;
7481 if (i == files->len)
7482 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7484 g_ptr_array_free (source_file_list, TRUE);
7488 return files;
7491 static ErrorCode
7492 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7494 switch (command) {
7495 case CMD_VM_VERSION: {
7496 char *build_info, *version;
7498 build_info = mono_get_runtime_build_info ();
7499 version = g_strdup_printf ("mono %s", build_info);
7501 buffer_add_string (buf, version); /* vm version */
7502 buffer_add_int (buf, MAJOR_VERSION);
7503 buffer_add_int (buf, MINOR_VERSION);
7504 g_free (build_info);
7505 g_free (version);
7506 break;
7508 case CMD_VM_SET_PROTOCOL_VERSION: {
7509 major_version = decode_int (p, &p, end);
7510 minor_version = decode_int (p, &p, end);
7511 protocol_version_set = TRUE;
7512 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7513 break;
7515 case CMD_VM_ALL_THREADS: {
7516 // FIXME: Domains
7517 mono_loader_lock ();
7518 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7519 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7520 mono_loader_unlock ();
7521 break;
7523 case CMD_VM_SUSPEND:
7524 suspend_vm ();
7525 wait_for_suspend ();
7526 break;
7527 case CMD_VM_RESUME:
7528 if (suspend_count == 0)
7529 return ERR_NOT_SUSPENDED;
7530 resume_vm ();
7531 clear_suspended_objs ();
7532 break;
7533 case CMD_VM_DISPOSE:
7534 /* Clear all event requests */
7535 mono_loader_lock ();
7536 while (event_requests->len > 0) {
7537 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7539 clear_event_request (req->id, req->event_kind);
7541 mono_loader_unlock ();
7543 while (suspend_count > 0)
7544 resume_vm ();
7545 disconnected = TRUE;
7546 vm_start_event_sent = FALSE;
7547 break;
7548 case CMD_VM_EXIT: {
7549 MonoInternalThread *thread;
7550 DebuggerTlsData *tls;
7551 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7552 MonoClass *env_class;
7553 #endif
7554 MonoMethod *exit_method = NULL;
7555 gpointer *args;
7556 int exit_code;
7558 exit_code = decode_int (p, &p, end);
7560 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7562 /* Have to send a reply before exiting */
7563 send_reply_packet (id, 0, buf);
7565 /* Clear all event requests */
7566 mono_loader_lock ();
7567 while (event_requests->len > 0) {
7568 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7570 clear_event_request (req->id, req->event_kind);
7572 mono_loader_unlock ();
7575 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7576 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7577 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7578 * better than doing the shutdown ourselves, since it avoids various races.
7581 suspend_vm ();
7582 wait_for_suspend ();
7584 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7585 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7586 if (env_class)
7587 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7588 #endif
7590 mono_loader_lock ();
7591 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7592 mono_loader_unlock ();
7594 if (thread && exit_method) {
7595 mono_loader_lock ();
7596 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7597 mono_loader_unlock ();
7599 args = g_new0 (gpointer, 1);
7600 args [0] = g_malloc (sizeof (int));
7601 *(int*)(args [0]) = exit_code;
7603 tls->pending_invoke = g_new0 (InvokeData, 1);
7604 tls->pending_invoke->method = exit_method;
7605 tls->pending_invoke->args = args;
7606 tls->pending_invoke->nmethods = 1;
7608 while (suspend_count > 0)
7609 resume_vm ();
7610 } else {
7612 * No thread found, do it ourselves.
7613 * FIXME: This can race with normal shutdown etc.
7615 while (suspend_count > 0)
7616 resume_vm ();
7618 if (!mono_runtime_try_shutdown ())
7619 break;
7621 mono_environment_exitcode_set (exit_code);
7623 /* Suspend all managed threads since the runtime is going away */
7624 DEBUG_PRINTF (1, "Suspending all threads...\n");
7625 mono_thread_suspend_all_other_threads ();
7626 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7627 mono_runtime_quit ();
7628 transport_close2 ();
7629 DEBUG_PRINTF (1, "Exiting...\n");
7631 exit (exit_code);
7633 break;
7635 case CMD_VM_INVOKE_METHOD:
7636 case CMD_VM_INVOKE_METHODS: {
7637 int objid = decode_objid (p, &p, end);
7638 MonoThread *thread;
7639 DebuggerTlsData *tls;
7640 int i, count, flags, nmethods;
7641 ErrorCode err;
7643 err = get_object (objid, (MonoObject**)&thread);
7644 if (err != ERR_NONE)
7645 return err;
7647 flags = decode_int (p, &p, end);
7649 if (command == CMD_VM_INVOKE_METHODS)
7650 nmethods = decode_int (p, &p, end);
7651 else
7652 nmethods = 1;
7654 // Wait for suspending if it already started
7655 if (suspend_count)
7656 wait_for_suspend ();
7657 if (!is_suspended ())
7658 return ERR_NOT_SUSPENDED;
7660 mono_loader_lock ();
7661 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7662 mono_loader_unlock ();
7663 g_assert (tls);
7665 if (!tls->really_suspended)
7666 /* The thread is still running native code, can't do invokes */
7667 return ERR_NOT_SUSPENDED;
7670 * Store the invoke data into tls, the thread will execute it after it is
7671 * resumed.
7673 if (tls->pending_invoke)
7674 return ERR_NOT_SUSPENDED;
7675 tls->pending_invoke = g_new0 (InvokeData, 1);
7676 tls->pending_invoke->id = id;
7677 tls->pending_invoke->flags = flags;
7678 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7679 memcpy (tls->pending_invoke->p, p, end - p);
7680 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7681 tls->pending_invoke->suspend_count = suspend_count;
7682 tls->pending_invoke->nmethods = nmethods;
7684 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7685 resume_thread (THREAD_TO_INTERNAL (thread));
7687 else {
7688 count = suspend_count;
7689 for (i = 0; i < count; ++i)
7690 resume_vm ();
7692 break;
7694 case CMD_VM_ABORT_INVOKE: {
7695 int objid = decode_objid (p, &p, end);
7696 MonoThread *thread;
7697 DebuggerTlsData *tls;
7698 int invoke_id;
7699 ErrorCode err;
7701 err = get_object (objid, (MonoObject**)&thread);
7702 if (err != ERR_NONE)
7703 return err;
7705 invoke_id = decode_int (p, &p, end);
7707 mono_loader_lock ();
7708 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7709 g_assert (tls);
7711 if (tls->abort_requested) {
7712 DEBUG_PRINTF (1, "Abort already requested.\n");
7713 mono_loader_unlock ();
7714 break;
7718 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7719 * actually the correct invocation.
7721 * Careful, we do not stop the thread that's doing the invocation, so we can't
7722 * inspect its stack. However, invoke_method() also acquires the loader lock
7723 * when it's done, so we're safe here.
7727 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7728 mono_loader_unlock ();
7729 return ERR_NO_INVOCATION;
7732 tls->abort_requested = TRUE;
7734 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread), FALSE);
7735 mono_loader_unlock ();
7736 break;
7739 case CMD_VM_SET_KEEPALIVE: {
7740 int timeout = decode_int (p, &p, end);
7741 agent_config.keepalive = timeout;
7742 // FIXME:
7743 #ifndef DISABLE_SOCKET_TRANSPORT
7744 set_keepalive ();
7745 #else
7746 NOT_IMPLEMENTED;
7747 #endif
7748 break;
7750 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7751 GHashTableIter iter, kiter;
7752 MonoDomain *domain;
7753 MonoClass *klass;
7754 GPtrArray *files;
7755 int i;
7756 char *fname, *basename;
7757 gboolean ignore_case;
7758 GSList *class_list, *l;
7759 GPtrArray *res_classes, *res_domains;
7761 fname = decode_string (p, &p, end);
7762 ignore_case = decode_byte (p, &p, end);
7764 basename = dbg_path_get_basename (fname);
7766 res_classes = g_ptr_array_new ();
7767 res_domains = g_ptr_array_new ();
7769 mono_loader_lock ();
7770 g_hash_table_iter_init (&iter, domains);
7771 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7772 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7774 /* Update 'source_file_to_class' cache */
7775 g_hash_table_iter_init (&kiter, info->loaded_classes);
7776 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7777 if (!g_hash_table_lookup (info->source_files, klass)) {
7778 files = get_source_files_for_type (klass);
7779 g_hash_table_insert (info->source_files, klass, files);
7781 for (i = 0; i < files->len; ++i) {
7782 char *s = (char *)g_ptr_array_index (files, i);
7783 char *s2 = dbg_path_get_basename (s);
7784 char *s3;
7786 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7787 if (!class_list) {
7788 class_list = g_slist_prepend (class_list, klass);
7789 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7790 } else {
7791 class_list = g_slist_prepend (class_list, klass);
7792 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7795 /* The _ignorecase hash contains the lowercase path */
7796 s3 = strdup_tolower (s2);
7797 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7798 if (!class_list) {
7799 class_list = g_slist_prepend (class_list, klass);
7800 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7801 } else {
7802 class_list = g_slist_prepend (class_list, klass);
7803 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7806 g_free (s2);
7807 g_free (s3);
7812 if (ignore_case) {
7813 char *s;
7815 s = strdup_tolower (basename);
7816 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7817 g_free (s);
7818 } else {
7819 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7822 for (l = class_list; l; l = l->next) {
7823 klass = (MonoClass *)l->data;
7825 g_ptr_array_add (res_classes, klass);
7826 g_ptr_array_add (res_domains, domain);
7829 mono_loader_unlock ();
7831 g_free (fname);
7832 g_free (basename);
7834 buffer_add_int (buf, res_classes->len);
7835 for (i = 0; i < res_classes->len; ++i)
7836 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7837 g_ptr_array_free (res_classes, TRUE);
7838 g_ptr_array_free (res_domains, TRUE);
7839 break;
7841 case CMD_VM_GET_TYPES: {
7842 ERROR_DECL (error);
7843 GHashTableIter iter;
7844 MonoDomain *domain;
7845 int i;
7846 char *name;
7847 gboolean ignore_case;
7848 GPtrArray *res_classes, *res_domains;
7849 MonoTypeNameParse info;
7851 name = decode_string (p, &p, end);
7852 ignore_case = decode_byte (p, &p, end);
7854 if (!mono_reflection_parse_type_checked (name, &info, error)) {
7855 mono_error_cleanup (error);
7856 g_free (name);
7857 mono_reflection_free_type_info (&info);
7858 return ERR_INVALID_ARGUMENT;
7861 res_classes = g_ptr_array_new ();
7862 res_domains = g_ptr_array_new ();
7864 mono_loader_lock ();
7865 g_hash_table_iter_init (&iter, domains);
7866 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7867 MonoAssembly *ass;
7868 gboolean type_resolve;
7869 MonoType *t;
7870 GSList *tmp;
7872 mono_domain_assemblies_lock (domain);
7873 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7874 ass = (MonoAssembly *)tmp->data;
7876 if (ass->image) {
7877 ERROR_DECL_VALUE (probe_type_error);
7878 /* FIXME really okay to call while holding locks? */
7879 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &probe_type_error);
7880 mono_error_cleanup (&probe_type_error);
7881 if (t) {
7882 g_ptr_array_add (res_classes, mono_type_get_class (t));
7883 g_ptr_array_add (res_domains, domain);
7887 mono_domain_assemblies_unlock (domain);
7889 mono_loader_unlock ();
7891 g_free (name);
7892 mono_reflection_free_type_info (&info);
7894 buffer_add_int (buf, res_classes->len);
7895 for (i = 0; i < res_classes->len; ++i)
7896 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7897 g_ptr_array_free (res_classes, TRUE);
7898 g_ptr_array_free (res_domains, TRUE);
7899 break;
7901 case CMD_VM_START_BUFFERING:
7902 case CMD_VM_STOP_BUFFERING:
7903 /* Handled in the main loop */
7904 break;
7905 default:
7906 return ERR_NOT_IMPLEMENTED;
7909 return ERR_NONE;
7912 static ErrorCode
7913 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7915 ErrorCode err;
7916 ERROR_DECL (error);
7918 switch (command) {
7919 case CMD_EVENT_REQUEST_SET: {
7920 EventRequest *req;
7921 int i, event_kind, suspend_policy, nmodifiers;
7922 ModifierKind mod;
7923 MonoMethod *method;
7924 long location = 0;
7925 MonoThread *step_thread;
7926 int step_thread_id = 0;
7927 StepDepth depth = STEP_DEPTH_INTO;
7928 StepSize size = STEP_SIZE_MIN;
7929 StepFilter filter = STEP_FILTER_NONE;
7930 MonoDomain *domain;
7931 Modifier *modifier;
7933 event_kind = decode_byte (p, &p, end);
7934 suspend_policy = decode_byte (p, &p, end);
7935 nmodifiers = decode_byte (p, &p, end);
7937 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7938 req->id = mono_atomic_inc_i32 (&event_request_id);
7939 req->event_kind = event_kind;
7940 req->suspend_policy = suspend_policy;
7941 req->nmodifiers = nmodifiers;
7943 method = NULL;
7944 for (i = 0; i < nmodifiers; ++i) {
7945 mod = (ModifierKind)decode_byte (p, &p, end);
7947 req->modifiers [i].kind = mod;
7948 if (mod == MOD_KIND_COUNT) {
7949 req->modifiers [i].data.count = decode_int (p, &p, end);
7950 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7951 method = decode_methodid (p, &p, end, &domain, &err);
7952 if (err != ERR_NONE)
7953 return err;
7954 location = decode_long (p, &p, end);
7955 } else if (mod == MOD_KIND_STEP) {
7956 step_thread_id = decode_id (p, &p, end);
7957 size = (StepSize)decode_int (p, &p, end);
7958 depth = (StepDepth)decode_int (p, &p, end);
7959 if (CHECK_PROTOCOL_VERSION (2, 16))
7960 filter = (StepFilter)decode_int (p, &p, end);
7961 req->modifiers [i].data.filter = filter;
7962 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7963 /* Treat STEP_THOUGH the same as HIDDEN */
7964 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7965 } else if (mod == MOD_KIND_THREAD_ONLY) {
7966 int id = decode_id (p, &p, end);
7968 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7969 if (err != ERR_NONE) {
7970 g_free (req);
7971 return err;
7973 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7974 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7976 if (err != ERR_NONE)
7977 return err;
7978 req->modifiers [i].caught = decode_byte (p, &p, end);
7979 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7980 if (CHECK_PROTOCOL_VERSION (2, 25))
7981 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7982 else
7983 req->modifiers [i].subclasses = TRUE;
7984 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" : "");
7985 if (exc_class) {
7986 req->modifiers [i].data.exc_class = exc_class;
7988 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7989 g_free (req);
7990 return ERR_INVALID_ARGUMENT;
7993 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7994 int n = decode_int (p, &p, end);
7995 int j;
7997 // +1 because we don't know length and we use last element to check for end
7998 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7999 for (j = 0; j < n; ++j) {
8000 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
8001 if (err != ERR_NONE) {
8002 g_free (req->modifiers [i].data.assemblies);
8003 return err;
8006 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
8007 int n = decode_int (p, &p, end);
8008 int j;
8010 modifier = &req->modifiers [i];
8011 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
8012 for (j = 0; j < n; ++j) {
8013 char *s = decode_string (p, &p, end);
8014 char *s2;
8016 if (s) {
8017 s2 = strdup_tolower (s);
8018 g_hash_table_insert (modifier->data.source_files, s2, s2);
8019 g_free (s);
8022 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
8023 int n = decode_int (p, &p, end);
8024 int j;
8026 modifier = &req->modifiers [i];
8027 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
8028 for (j = 0; j < n; ++j) {
8029 char *s = decode_string (p, &p, end);
8031 if (s)
8032 g_hash_table_insert (modifier->data.type_names, s, s);
8034 } else {
8035 g_free (req);
8036 return ERR_NOT_IMPLEMENTED;
8040 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
8041 g_assert (method);
8043 req->info = set_breakpoint (method, location, req, error);
8044 if (!mono_error_ok (error)) {
8045 g_free (req);
8046 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (error));
8047 mono_error_cleanup (error);
8048 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
8050 } else if (req->event_kind == EVENT_KIND_STEP) {
8051 g_assert (step_thread_id);
8053 err = get_object (step_thread_id, (MonoObject**)&step_thread);
8054 if (err != ERR_NONE) {
8055 g_free (req);
8056 return err;
8059 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
8060 if (err != ERR_NONE) {
8061 g_free (req);
8062 return err;
8064 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
8065 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
8066 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
8067 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
8068 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
8069 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
8070 } else {
8071 if (req->nmodifiers) {
8072 g_free (req);
8073 return ERR_NOT_IMPLEMENTED;
8077 mono_loader_lock ();
8078 g_ptr_array_add (event_requests, req);
8080 if (agent_config.defer) {
8081 /* Transmit cached data to the client on receipt of the event request */
8082 switch (req->event_kind) {
8083 case EVENT_KIND_APPDOMAIN_CREATE:
8084 /* Emit load events for currently loaded domains */
8085 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
8086 break;
8087 case EVENT_KIND_ASSEMBLY_LOAD:
8088 /* Emit load events for currently loaded assemblies */
8089 mono_domain_foreach (send_assemblies_for_domain, NULL);
8090 break;
8091 case EVENT_KIND_THREAD_START:
8092 /* Emit start events for currently started threads */
8093 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
8094 break;
8095 case EVENT_KIND_TYPE_LOAD:
8096 /* Emit type load events for currently loaded types */
8097 mono_domain_foreach (send_types_for_domain, NULL);
8098 break;
8099 default:
8100 break;
8103 mono_loader_unlock ();
8105 buffer_add_int (buf, req->id);
8106 break;
8108 case CMD_EVENT_REQUEST_CLEAR: {
8109 int etype = decode_byte (p, &p, end);
8110 int req_id = decode_int (p, &p, end);
8112 // FIXME: Make a faster mapping from req_id to request
8113 mono_loader_lock ();
8114 clear_event_request (req_id, etype);
8115 mono_loader_unlock ();
8116 break;
8118 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
8119 int i;
8121 mono_loader_lock ();
8122 i = 0;
8123 while (i < event_requests->len) {
8124 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
8126 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
8127 clear_breakpoint ((MonoBreakpoint *)req->info);
8129 g_ptr_array_remove_index_fast (event_requests, i);
8130 g_free (req);
8131 } else {
8132 i ++;
8135 mono_loader_unlock ();
8136 break;
8138 default:
8139 return ERR_NOT_IMPLEMENTED;
8142 return ERR_NONE;
8145 static ErrorCode
8146 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8148 ErrorCode err;
8149 MonoDomain *domain;
8151 switch (command) {
8152 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
8153 buffer_add_domainid (buf, mono_get_root_domain ());
8154 break;
8156 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
8157 domain = decode_domainid (p, &p, end, NULL, &err);
8158 if (err != ERR_NONE)
8159 return err;
8160 buffer_add_string (buf, domain->friendly_name);
8161 break;
8163 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
8164 GSList *tmp;
8165 MonoAssembly *ass;
8166 int count;
8168 domain = decode_domainid (p, &p, end, NULL, &err);
8169 if (err != ERR_NONE)
8170 return err;
8171 mono_loader_lock ();
8172 count = 0;
8173 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
8174 count ++;
8176 buffer_add_int (buf, count);
8177 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
8178 ass = (MonoAssembly *)tmp->data;
8179 buffer_add_assemblyid (buf, domain, ass);
8181 mono_loader_unlock ();
8182 break;
8184 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
8185 domain = decode_domainid (p, &p, end, NULL, &err);
8186 if (err != ERR_NONE)
8187 return err;
8189 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
8190 break;
8192 case CMD_APPDOMAIN_GET_CORLIB: {
8193 domain = decode_domainid (p, &p, end, NULL, &err);
8194 if (err != ERR_NONE)
8195 return err;
8197 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
8198 break;
8200 case CMD_APPDOMAIN_CREATE_STRING: {
8201 char *s;
8202 MonoString *o;
8203 ERROR_DECL (error);
8205 domain = decode_domainid (p, &p, end, NULL, &err);
8206 if (err != ERR_NONE)
8207 return err;
8208 s = decode_string (p, &p, end);
8210 o = mono_string_new_checked (domain, s, error);
8211 if (!is_ok (error)) {
8212 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (error));
8213 mono_error_cleanup (error);
8214 return ERR_INVALID_OBJECT;
8216 buffer_add_objid (buf, (MonoObject*)o);
8217 break;
8219 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
8220 ERROR_DECL (error);
8221 MonoClass *klass;
8222 MonoDomain *domain2;
8223 MonoObject *o;
8225 domain = decode_domainid (p, &p, end, NULL, &err);
8226 if (err != ERR_NONE)
8227 return err;
8228 klass = decode_typeid (p, &p, end, &domain2, &err);
8229 if (err != ERR_NONE)
8230 return err;
8232 // FIXME:
8233 g_assert (domain == domain2);
8235 o = mono_object_new_checked (domain, klass, error);
8236 mono_error_assert_ok (error);
8238 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
8239 if (err != ERR_NONE)
8240 return err;
8242 buffer_add_objid (buf, o);
8243 break;
8245 default:
8246 return ERR_NOT_IMPLEMENTED;
8249 return ERR_NONE;
8252 static ErrorCode
8253 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8255 HANDLE_FUNCTION_ENTER();
8256 ErrorCode err = ERR_NONE;
8257 error_init (error);
8258 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8259 if (MONO_HANDLE_IS_NULL (o)) {
8260 err = ERR_INVALID_OBJECT;
8261 goto leave;
8263 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8264 leave:
8265 HANDLE_FUNCTION_RETURN_VAL (err);
8269 static ErrorCode
8270 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8272 ErrorCode err;
8273 MonoAssembly *ass;
8274 MonoDomain *domain;
8276 ass = decode_assemblyid (p, &p, end, &domain, &err);
8277 if (err != ERR_NONE)
8278 return err;
8280 switch (command) {
8281 case CMD_ASSEMBLY_GET_LOCATION: {
8282 buffer_add_string (buf, mono_image_get_filename (ass->image));
8283 break;
8285 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8286 guint32 token;
8287 MonoMethod *m;
8289 if (ass->image->dynamic) {
8290 buffer_add_id (buf, 0);
8291 } else {
8292 token = mono_image_get_entry_point (ass->image);
8293 if (token == 0) {
8294 buffer_add_id (buf, 0);
8295 } else {
8296 ERROR_DECL (error);
8297 m = mono_get_method_checked (ass->image, token, NULL, NULL, error);
8298 if (!m)
8299 mono_error_cleanup (error); /* FIXME don't swallow the error */
8300 buffer_add_methodid (buf, domain, m);
8303 break;
8305 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8306 buffer_add_moduleid (buf, domain, ass->image);
8307 break;
8309 case CMD_ASSEMBLY_GET_OBJECT: {
8310 ERROR_DECL (error);
8311 err = get_assembly_object_command (domain, ass, buf, error);
8312 mono_error_cleanup (error);
8313 return err;
8315 case CMD_ASSEMBLY_GET_DOMAIN: {
8316 buffer_add_domainid (buf, domain);
8317 break;
8319 case CMD_ASSEMBLY_GET_TYPE: {
8320 ERROR_DECL (error);
8321 char *s = decode_string (p, &p, end);
8322 gboolean ignorecase = decode_byte (p, &p, end);
8323 MonoTypeNameParse info;
8324 MonoType *t;
8325 gboolean type_resolve, res;
8326 MonoDomain *d = mono_domain_get ();
8328 /* This is needed to be able to find referenced assemblies */
8329 res = mono_domain_set (domain, FALSE);
8330 g_assert (res);
8332 if (!mono_reflection_parse_type_checked (s, &info, error)) {
8333 mono_error_cleanup (error);
8334 t = NULL;
8335 } else {
8336 if (info.assembly.name)
8337 NOT_IMPLEMENTED;
8338 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, error);
8339 if (!is_ok (error)) {
8340 mono_error_cleanup (error); /* FIXME don't swallow the error */
8341 mono_reflection_free_type_info (&info);
8342 g_free (s);
8343 return ERR_INVALID_ARGUMENT;
8346 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8347 mono_reflection_free_type_info (&info);
8348 g_free (s);
8350 mono_domain_set (d, TRUE);
8352 break;
8354 case CMD_ASSEMBLY_GET_NAME: {
8355 gchar *name;
8356 MonoAssembly *mass = ass;
8358 name = g_strdup_printf (
8359 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8360 mass->aname.name,
8361 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8362 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8363 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8364 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8366 buffer_add_string (buf, name);
8367 g_free (name);
8368 break;
8370 default:
8371 return ERR_NOT_IMPLEMENTED;
8374 return ERR_NONE;
8377 static ErrorCode
8378 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8380 ErrorCode err;
8381 MonoDomain *domain;
8383 switch (command) {
8384 case CMD_MODULE_GET_INFO: {
8385 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8386 char *basename;
8388 basename = g_path_get_basename (image->name);
8389 buffer_add_string (buf, basename); // name
8390 buffer_add_string (buf, image->module_name); // scopename
8391 buffer_add_string (buf, image->name); // fqname
8392 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8393 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8394 g_free (basename);
8395 break;
8397 default:
8398 return ERR_NOT_IMPLEMENTED;
8401 return ERR_NONE;
8404 static ErrorCode
8405 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8407 ErrorCode err;
8408 MonoDomain *domain;
8410 switch (command) {
8411 case CMD_FIELD_GET_INFO: {
8412 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8414 buffer_add_string (buf, f->name);
8415 buffer_add_typeid (buf, domain, f->parent);
8416 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8417 buffer_add_int (buf, f->type->attrs);
8418 break;
8420 default:
8421 return ERR_NOT_IMPLEMENTED;
8424 return ERR_NONE;
8427 static void
8428 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8430 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8431 /* Special case these so the client doesn't have to handle Type objects */
8433 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8434 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8435 } else if (MONO_TYPE_IS_REFERENCE (t))
8436 buffer_add_value (buf, t, &val, domain);
8437 else
8438 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8441 static ErrorCode
8442 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8444 int i, j;
8445 int nattrs = 0;
8447 if (!cinfo) {
8448 buffer_add_int (buf, 0);
8449 return ERR_NONE;
8452 for (i = 0; i < cinfo->num_attrs; ++i) {
8453 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8454 nattrs ++;
8456 buffer_add_int (buf, nattrs);
8458 for (i = 0; i < cinfo->num_attrs; ++i) {
8459 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8460 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8461 MonoArray *typed_args, *named_args;
8462 MonoType *t;
8463 CattrNamedArg *arginfo = NULL;
8464 ERROR_DECL (error);
8466 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, error);
8467 if (!mono_error_ok (error)) {
8468 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (error));
8469 mono_error_cleanup (error);
8470 return ERR_LOADER_ERROR;
8473 buffer_add_methodid (buf, domain, attr->ctor);
8475 /* Ctor args */
8476 if (typed_args) {
8477 buffer_add_int (buf, mono_array_length (typed_args));
8478 for (j = 0; j < mono_array_length (typed_args); ++j) {
8479 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8481 t = mono_method_signature (attr->ctor)->params [j];
8483 buffer_add_cattr_arg (buf, t, domain, val);
8485 } else {
8486 buffer_add_int (buf, 0);
8489 /* Named args */
8490 if (named_args) {
8491 buffer_add_int (buf, mono_array_length (named_args));
8493 for (j = 0; j < mono_array_length (named_args); ++j) {
8494 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8496 if (arginfo [j].prop) {
8497 buffer_add_byte (buf, 0x54);
8498 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8499 } else if (arginfo [j].field) {
8500 buffer_add_byte (buf, 0x53);
8501 buffer_add_fieldid (buf, domain, arginfo [j].field);
8502 } else {
8503 g_assert_not_reached ();
8506 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8508 } else {
8509 buffer_add_int (buf, 0);
8511 g_free (arginfo);
8515 return ERR_NONE;
8518 /* FIXME: Code duplication with icall.c */
8519 static void
8520 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8522 int i;
8523 MonoClass *ic;
8525 mono_class_setup_interfaces (klass, error);
8526 if (!mono_error_ok (error))
8527 return;
8529 for (i = 0; i < klass->interface_count; i++) {
8530 ic = klass->interfaces [i];
8531 g_hash_table_insert (ifaces, ic, ic);
8533 collect_interfaces (ic, ifaces, error);
8534 if (!mono_error_ok (error))
8535 return;
8539 static ErrorCode
8540 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8542 ERROR_DECL (error);
8543 MonoClass *nested;
8544 MonoType *type;
8545 gpointer iter;
8546 guint8 b;
8547 int nnested;
8548 ErrorCode err;
8549 char *name;
8551 switch (command) {
8552 case CMD_TYPE_GET_INFO: {
8553 buffer_add_string (buf, klass->name_space);
8554 buffer_add_string (buf, klass->name);
8555 // FIXME: byref
8556 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8557 buffer_add_string (buf, name);
8558 g_free (name);
8559 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8560 buffer_add_moduleid (buf, domain, klass->image);
8561 buffer_add_typeid (buf, domain, klass->parent);
8562 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8563 buffer_add_typeid (buf, domain, klass->element_class);
8564 else
8565 buffer_add_id (buf, 0);
8566 buffer_add_int (buf, klass->type_token);
8567 buffer_add_byte (buf, klass->rank);
8568 buffer_add_int (buf, mono_class_get_flags (klass));
8569 b = 0;
8570 type = &klass->byval_arg;
8571 // FIXME: Can't decide whenever a class represents a byref type
8572 if (FALSE)
8573 b |= (1 << 0);
8574 if (type->type == MONO_TYPE_PTR)
8575 b |= (1 << 1);
8576 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8577 b |= (1 << 2);
8578 if (type->type == MONO_TYPE_VALUETYPE)
8579 b |= (1 << 3);
8580 if (klass->enumtype)
8581 b |= (1 << 4);
8582 if (mono_class_is_gtd (klass))
8583 b |= (1 << 5);
8584 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8585 b |= (1 << 6);
8586 buffer_add_byte (buf, b);
8587 nnested = 0;
8588 iter = NULL;
8589 while ((nested = mono_class_get_nested_types (klass, &iter)))
8590 nnested ++;
8591 buffer_add_int (buf, nnested);
8592 iter = NULL;
8593 while ((nested = mono_class_get_nested_types (klass, &iter)))
8594 buffer_add_typeid (buf, domain, nested);
8595 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8596 if (mono_class_is_gtd (klass))
8597 buffer_add_typeid (buf, domain, klass);
8598 else if (mono_class_is_ginst (klass))
8599 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8600 else
8601 buffer_add_id (buf, 0);
8603 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8604 int count, i;
8606 if (mono_class_is_ginst (klass)) {
8607 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8609 count = inst->type_argc;
8610 buffer_add_int (buf, count);
8611 for (i = 0; i < count; i++)
8612 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8613 } else if (mono_class_is_gtd (klass)) {
8614 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8615 MonoClass *pklass;
8617 count = container->type_argc;
8618 buffer_add_int (buf, count);
8619 for (i = 0; i < count; i++) {
8620 pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
8621 buffer_add_typeid (buf, domain, pklass);
8623 } else {
8624 buffer_add_int (buf, 0);
8627 break;
8629 case CMD_TYPE_GET_METHODS: {
8630 int nmethods;
8631 int i = 0;
8632 gpointer iter = NULL;
8633 MonoMethod *m;
8635 mono_class_setup_methods (klass);
8637 nmethods = mono_class_num_methods (klass);
8639 buffer_add_int (buf, nmethods);
8641 while ((m = mono_class_get_methods (klass, &iter))) {
8642 buffer_add_methodid (buf, domain, m);
8643 i ++;
8645 g_assert (i == nmethods);
8646 break;
8648 case CMD_TYPE_GET_FIELDS: {
8649 int nfields;
8650 int i = 0;
8651 gpointer iter = NULL;
8652 MonoClassField *f;
8654 nfields = mono_class_num_fields (klass);
8656 buffer_add_int (buf, nfields);
8658 while ((f = mono_class_get_fields (klass, &iter))) {
8659 buffer_add_fieldid (buf, domain, f);
8660 buffer_add_string (buf, f->name);
8661 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8662 buffer_add_int (buf, f->type->attrs);
8663 i ++;
8665 g_assert (i == nfields);
8666 break;
8668 case CMD_TYPE_GET_PROPERTIES: {
8669 int nprops;
8670 int i = 0;
8671 gpointer iter = NULL;
8672 MonoProperty *p;
8674 nprops = mono_class_num_properties (klass);
8676 buffer_add_int (buf, nprops);
8678 while ((p = mono_class_get_properties (klass, &iter))) {
8679 buffer_add_propertyid (buf, domain, p);
8680 buffer_add_string (buf, p->name);
8681 buffer_add_methodid (buf, domain, p->get);
8682 buffer_add_methodid (buf, domain, p->set);
8683 buffer_add_int (buf, p->attrs);
8684 i ++;
8686 g_assert (i == nprops);
8687 break;
8689 case CMD_TYPE_GET_CATTRS: {
8690 MonoClass *attr_klass;
8691 MonoCustomAttrInfo *cinfo;
8693 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8694 /* attr_klass can be NULL */
8695 if (err != ERR_NONE)
8696 return err;
8698 cinfo = mono_custom_attrs_from_class_checked (klass, error);
8699 if (!is_ok (error)) {
8700 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8701 return ERR_LOADER_ERROR;
8704 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8705 if (err != ERR_NONE)
8706 return err;
8707 break;
8709 case CMD_TYPE_GET_FIELD_CATTRS: {
8710 MonoClass *attr_klass;
8711 MonoCustomAttrInfo *cinfo;
8712 MonoClassField *field;
8714 field = decode_fieldid (p, &p, end, NULL, &err);
8715 if (err != ERR_NONE)
8716 return err;
8717 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8718 if (err != ERR_NONE)
8719 return err;
8721 cinfo = mono_custom_attrs_from_field_checked (klass, field, error);
8722 if (!is_ok (error)) {
8723 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8724 return ERR_LOADER_ERROR;
8727 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8728 if (err != ERR_NONE)
8729 return err;
8730 break;
8732 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8733 MonoClass *attr_klass;
8734 MonoCustomAttrInfo *cinfo;
8735 MonoProperty *prop;
8737 prop = decode_propertyid (p, &p, end, NULL, &err);
8738 if (err != ERR_NONE)
8739 return err;
8740 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8741 if (err != ERR_NONE)
8742 return err;
8744 cinfo = mono_custom_attrs_from_property_checked (klass, prop, error);
8745 if (!is_ok (error)) {
8746 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8747 return ERR_LOADER_ERROR;
8750 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8751 if (err != ERR_NONE)
8752 return err;
8753 break;
8755 case CMD_TYPE_GET_VALUES:
8756 case CMD_TYPE_GET_VALUES_2: {
8757 guint8 *val;
8758 MonoClassField *f;
8759 MonoVTable *vtable;
8760 MonoClass *k;
8761 int len, i;
8762 gboolean found;
8763 MonoThread *thread_obj;
8764 MonoInternalThread *thread = NULL;
8765 guint32 special_static_type;
8767 if (command == CMD_TYPE_GET_VALUES_2) {
8768 int objid = decode_objid (p, &p, end);
8769 ErrorCode err;
8771 err = get_object (objid, (MonoObject**)&thread_obj);
8772 if (err != ERR_NONE)
8773 return err;
8775 thread = THREAD_TO_INTERNAL (thread_obj);
8778 len = decode_int (p, &p, end);
8779 for (i = 0; i < len; ++i) {
8780 f = decode_fieldid (p, &p, end, NULL, &err);
8781 if (err != ERR_NONE)
8782 return err;
8784 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8785 return ERR_INVALID_FIELDID;
8786 special_static_type = mono_class_field_get_special_static_type (f);
8787 if (special_static_type != SPECIAL_STATIC_NONE) {
8788 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8789 return ERR_INVALID_FIELDID;
8792 /* Check that the field belongs to the object */
8793 found = FALSE;
8794 for (k = klass; k; k = k->parent) {
8795 if (k == f->parent) {
8796 found = TRUE;
8797 break;
8800 if (!found)
8801 return ERR_INVALID_FIELDID;
8803 vtable = mono_class_vtable_checked (domain, f->parent, error);
8804 if (!is_ok (error))
8805 return ERR_INVALID_FIELDID;
8806 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8807 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, error);
8808 if (!is_ok (error))
8809 return ERR_INVALID_FIELDID;
8810 buffer_add_value (buf, f->type, val, domain);
8811 g_free (val);
8813 break;
8815 case CMD_TYPE_SET_VALUES: {
8816 guint8 *val;
8817 MonoClassField *f;
8818 MonoVTable *vtable;
8819 MonoClass *k;
8820 int len, i;
8821 gboolean found;
8823 len = decode_int (p, &p, end);
8824 for (i = 0; i < len; ++i) {
8825 f = decode_fieldid (p, &p, end, NULL, &err);
8826 if (err != ERR_NONE)
8827 return err;
8829 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8830 return ERR_INVALID_FIELDID;
8831 if (mono_class_field_is_special_static (f))
8832 return ERR_INVALID_FIELDID;
8834 /* Check that the field belongs to the object */
8835 found = FALSE;
8836 for (k = klass; k; k = k->parent) {
8837 if (k == f->parent) {
8838 found = TRUE;
8839 break;
8842 if (!found)
8843 return ERR_INVALID_FIELDID;
8845 // FIXME: Check for literal/const
8847 vtable = mono_class_vtable_checked (domain, f->parent, error);
8848 if (!is_ok (error))
8849 return ERR_INVALID_FIELDID;
8850 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8851 err = decode_value (f->type, domain, val, p, &p, end);
8852 if (err != ERR_NONE) {
8853 g_free (val);
8854 return err;
8856 if (MONO_TYPE_IS_REFERENCE (f->type))
8857 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8858 else
8859 mono_field_static_set_value (vtable, f, val);
8860 g_free (val);
8862 break;
8864 case CMD_TYPE_GET_OBJECT: {
8865 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, error);
8866 if (!mono_error_ok (error)) {
8867 mono_error_cleanup (error);
8868 return ERR_INVALID_OBJECT;
8870 buffer_add_objid (buf, o);
8871 break;
8873 case CMD_TYPE_GET_SOURCE_FILES:
8874 case CMD_TYPE_GET_SOURCE_FILES_2: {
8875 char *source_file, *base;
8876 GPtrArray *files;
8877 int i;
8879 files = get_source_files_for_type (klass);
8881 buffer_add_int (buf, files->len);
8882 for (i = 0; i < files->len; ++i) {
8883 source_file = (char *)g_ptr_array_index (files, i);
8884 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8885 buffer_add_string (buf, source_file);
8886 } else {
8887 base = dbg_path_get_basename (source_file);
8888 buffer_add_string (buf, base);
8889 g_free (base);
8891 g_free (source_file);
8893 g_ptr_array_free (files, TRUE);
8894 break;
8896 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8897 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8899 if (err != ERR_NONE)
8900 return err;
8901 if (mono_class_is_assignable_from (klass, oklass))
8902 buffer_add_byte (buf, 1);
8903 else
8904 buffer_add_byte (buf, 0);
8905 break;
8907 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8908 char *name = decode_string (p, &p, end);
8909 int i, flags = decode_int (p, &p, end);
8910 ERROR_DECL (error);
8911 GPtrArray *array;
8913 error_init (error);
8914 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, error);
8915 if (!is_ok (error)) {
8916 mono_error_cleanup (error);
8917 return ERR_LOADER_ERROR;
8919 buffer_add_int (buf, array->len);
8920 for (i = 0; i < array->len; ++i) {
8921 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8922 buffer_add_methodid (buf, domain, method);
8925 g_ptr_array_free (array, TRUE);
8926 g_free (name);
8927 break;
8929 case CMD_TYPE_GET_INTERFACES: {
8930 MonoClass *parent;
8931 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8932 MonoClass *tclass, *iface;
8933 GHashTableIter iter;
8935 tclass = klass;
8937 for (parent = tclass; parent; parent = parent->parent) {
8938 mono_class_setup_interfaces (parent, error);
8939 if (!mono_error_ok (error))
8940 return ERR_LOADER_ERROR;
8941 collect_interfaces (parent, iface_hash, error);
8942 if (!mono_error_ok (error))
8943 return ERR_LOADER_ERROR;
8946 buffer_add_int (buf, g_hash_table_size (iface_hash));
8948 g_hash_table_iter_init (&iter, iface_hash);
8949 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8950 buffer_add_typeid (buf, domain, iface);
8951 g_hash_table_destroy (iface_hash);
8952 break;
8954 case CMD_TYPE_GET_INTERFACE_MAP: {
8955 int tindex, ioffset;
8956 gboolean variance_used;
8957 MonoClass *iclass;
8958 int len, nmethods, i;
8959 gpointer iter;
8960 MonoMethod *method;
8962 len = decode_int (p, &p, end);
8963 mono_class_setup_vtable (klass);
8965 for (tindex = 0; tindex < len; ++tindex) {
8966 iclass = decode_typeid (p, &p, end, NULL, &err);
8967 if (err != ERR_NONE)
8968 return err;
8970 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8971 if (ioffset == -1)
8972 return ERR_INVALID_ARGUMENT;
8974 nmethods = mono_class_num_methods (iclass);
8975 buffer_add_int (buf, nmethods);
8977 iter = NULL;
8978 while ((method = mono_class_get_methods (iclass, &iter))) {
8979 buffer_add_methodid (buf, domain, method);
8981 for (i = 0; i < nmethods; ++i)
8982 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8984 break;
8986 case CMD_TYPE_IS_INITIALIZED: {
8987 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
8988 if (!is_ok (error))
8989 return ERR_LOADER_ERROR;
8991 if (vtable)
8992 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8993 else
8994 buffer_add_int (buf, 0);
8995 break;
8997 case CMD_TYPE_CREATE_INSTANCE: {
8998 ERROR_DECL (error);
8999 MonoObject *obj;
9001 obj = mono_object_new_checked (domain, klass, error);
9002 mono_error_assert_ok (error);
9003 buffer_add_objid (buf, obj);
9004 break;
9006 default:
9007 return ERR_NOT_IMPLEMENTED;
9010 return ERR_NONE;
9013 static ErrorCode
9014 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9016 MonoClass *klass;
9017 MonoDomain *old_domain;
9018 MonoDomain *domain;
9019 ErrorCode err;
9021 klass = decode_typeid (p, &p, end, &domain, &err);
9022 if (err != ERR_NONE)
9023 return err;
9025 old_domain = mono_domain_get ();
9027 mono_domain_set (domain, TRUE);
9029 err = type_commands_internal (command, klass, domain, p, end, buf);
9031 mono_domain_set (old_domain, TRUE);
9033 return err;
9036 static ErrorCode
9037 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
9039 MonoMethodHeader *header;
9040 ErrorCode err;
9042 switch (command) {
9043 case CMD_METHOD_GET_NAME: {
9044 buffer_add_string (buf, method->name);
9045 break;
9047 case CMD_METHOD_GET_DECLARING_TYPE: {
9048 buffer_add_typeid (buf, domain, method->klass);
9049 break;
9051 case CMD_METHOD_GET_DEBUG_INFO: {
9052 ERROR_DECL (error);
9053 MonoDebugMethodInfo *minfo;
9054 char *source_file;
9055 int i, j, n_il_offsets;
9056 int *source_files;
9057 GPtrArray *source_file_list;
9058 MonoSymSeqPoint *sym_seq_points;
9060 header = mono_method_get_header_checked (method, error);
9061 if (!header) {
9062 mono_error_cleanup (error); /* FIXME don't swallow the error */
9063 buffer_add_int (buf, 0);
9064 buffer_add_string (buf, "");
9065 buffer_add_int (buf, 0);
9066 break;
9069 minfo = mono_debug_lookup_method (method);
9070 if (!minfo) {
9071 buffer_add_int (buf, header->code_size);
9072 buffer_add_string (buf, "");
9073 buffer_add_int (buf, 0);
9074 mono_metadata_free_mh (header);
9075 break;
9078 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
9079 buffer_add_int (buf, header->code_size);
9080 if (CHECK_PROTOCOL_VERSION (2, 13)) {
9081 buffer_add_int (buf, source_file_list->len);
9082 for (i = 0; i < source_file_list->len; ++i) {
9083 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
9084 buffer_add_string (buf, sinfo->source_file);
9085 if (CHECK_PROTOCOL_VERSION (2, 14)) {
9086 for (j = 0; j < 16; ++j)
9087 buffer_add_byte (buf, sinfo->hash [j]);
9090 } else {
9091 buffer_add_string (buf, source_file);
9093 buffer_add_int (buf, n_il_offsets);
9094 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
9095 for (i = 0; i < n_il_offsets; ++i) {
9096 MonoSymSeqPoint *sp = &sym_seq_points [i];
9097 const char *srcfile = "";
9099 if (source_files [i] != -1) {
9100 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
9101 srcfile = sinfo->source_file;
9103 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);
9104 buffer_add_int (buf, sp->il_offset);
9105 buffer_add_int (buf, sp->line);
9106 if (CHECK_PROTOCOL_VERSION (2, 13))
9107 buffer_add_int (buf, source_files [i]);
9108 if (CHECK_PROTOCOL_VERSION (2, 19))
9109 buffer_add_int (buf, sp->column);
9110 if (CHECK_PROTOCOL_VERSION (2, 32)) {
9111 buffer_add_int (buf, sp->end_line);
9112 buffer_add_int (buf, sp->end_column);
9115 g_free (source_file);
9116 g_free (source_files);
9117 g_free (sym_seq_points);
9118 g_ptr_array_free (source_file_list, TRUE);
9119 mono_metadata_free_mh (header);
9120 break;
9122 case CMD_METHOD_GET_PARAM_INFO: {
9123 MonoMethodSignature *sig = mono_method_signature (method);
9124 guint32 i;
9125 char **names;
9127 /* FIXME: mono_class_from_mono_type () and byrefs */
9129 /* FIXME: Use a smaller encoding */
9130 buffer_add_int (buf, sig->call_convention);
9131 buffer_add_int (buf, sig->param_count);
9132 buffer_add_int (buf, sig->generic_param_count);
9133 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
9134 for (i = 0; i < sig->param_count; ++i) {
9135 /* FIXME: vararg */
9136 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
9139 /* Emit parameter names */
9140 names = g_new (char *, sig->param_count);
9141 mono_method_get_param_names (method, (const char **) names);
9142 for (i = 0; i < sig->param_count; ++i)
9143 buffer_add_string (buf, names [i]);
9144 g_free (names);
9146 break;
9148 case CMD_METHOD_GET_LOCALS_INFO: {
9149 ERROR_DECL (error);
9150 int i, num_locals;
9151 MonoDebugLocalsInfo *locals;
9152 int *locals_map = NULL;
9154 header = mono_method_get_header_checked (method, error);
9155 if (!header) {
9156 mono_error_cleanup (error); /* FIXME don't swallow the error */
9157 return ERR_INVALID_ARGUMENT;
9160 locals = mono_debug_lookup_locals (method);
9161 if (!locals) {
9162 if (CHECK_PROTOCOL_VERSION (2, 43)) {
9163 /* Scopes */
9164 buffer_add_int (buf, 1);
9165 buffer_add_int (buf, 0);
9166 buffer_add_int (buf, header->code_size);
9168 buffer_add_int (buf, header->num_locals);
9169 /* Types */
9170 for (i = 0; i < header->num_locals; ++i) {
9171 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
9173 /* Names */
9174 for (i = 0; i < header->num_locals; ++i) {
9175 char lname [128];
9176 sprintf (lname, "V_%d", i);
9177 buffer_add_string (buf, lname);
9179 /* Scopes */
9180 for (i = 0; i < header->num_locals; ++i) {
9181 buffer_add_int (buf, 0);
9182 buffer_add_int (buf, header->code_size);
9184 } else {
9185 if (CHECK_PROTOCOL_VERSION (2, 43)) {
9186 /* Scopes */
9187 buffer_add_int (buf, locals->num_blocks);
9188 int last_start = 0;
9189 for (i = 0; i < locals->num_blocks; ++i) {
9190 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
9191 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
9192 last_start = locals->code_blocks [i].start_offset;
9196 num_locals = locals->num_locals;
9197 buffer_add_int (buf, num_locals);
9199 /* Types */
9200 for (i = 0; i < num_locals; ++i) {
9201 g_assert (locals->locals [i].index < header->num_locals);
9202 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
9204 /* Names */
9205 for (i = 0; i < num_locals; ++i)
9206 buffer_add_string (buf, locals->locals [i].name);
9207 /* Scopes */
9208 for (i = 0; i < num_locals; ++i) {
9209 if (locals->locals [i].block) {
9210 buffer_add_int (buf, locals->locals [i].block->start_offset);
9211 buffer_add_int (buf, locals->locals [i].block->end_offset);
9212 } else {
9213 buffer_add_int (buf, 0);
9214 buffer_add_int (buf, header->code_size);
9218 mono_metadata_free_mh (header);
9220 if (locals)
9221 mono_debug_free_locals (locals);
9222 g_free (locals_map);
9224 break;
9226 case CMD_METHOD_GET_INFO:
9227 buffer_add_int (buf, method->flags);
9228 buffer_add_int (buf, method->iflags);
9229 buffer_add_int (buf, method->token);
9230 if (CHECK_PROTOCOL_VERSION (2, 12)) {
9231 guint8 attrs = 0;
9232 if (method->is_generic)
9233 attrs |= (1 << 0);
9234 if (mono_method_signature (method)->generic_param_count)
9235 attrs |= (1 << 1);
9236 buffer_add_byte (buf, attrs);
9237 if (method->is_generic || method->is_inflated) {
9238 MonoMethod *result;
9240 if (method->is_generic) {
9241 result = method;
9242 } else {
9243 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
9245 result = imethod->declaring;
9246 if (imethod->context.class_inst) {
9247 MonoClass *klass = ((MonoMethod *) imethod)->klass;
9248 /*Generic methods gets the context of the GTD.*/
9249 if (mono_class_get_context (klass)) {
9250 ERROR_DECL (error);
9251 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
9252 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
9257 buffer_add_methodid (buf, domain, result);
9258 } else {
9259 buffer_add_id (buf, 0);
9261 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9262 if (mono_method_signature (method)->generic_param_count) {
9263 int count, i;
9265 if (method->is_inflated) {
9266 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9267 if (inst) {
9268 count = inst->type_argc;
9269 buffer_add_int (buf, count);
9271 for (i = 0; i < count; i++)
9272 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9273 } else {
9274 buffer_add_int (buf, 0);
9276 } else if (method->is_generic) {
9277 MonoGenericContainer *container = mono_method_get_generic_container (method);
9279 count = mono_method_signature (method)->generic_param_count;
9280 buffer_add_int (buf, count);
9281 for (i = 0; i < count; i++) {
9282 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9283 MonoClass *pklass = mono_class_create_generic_parameter (param);
9284 buffer_add_typeid (buf, domain, pklass);
9286 } else {
9287 buffer_add_int (buf, 0);
9289 } else {
9290 buffer_add_int (buf, 0);
9294 break;
9295 case CMD_METHOD_GET_BODY: {
9296 ERROR_DECL (error);
9297 int i;
9299 header = mono_method_get_header_checked (method, error);
9300 if (!header) {
9301 mono_error_cleanup (error); /* FIXME don't swallow the error */
9302 buffer_add_int (buf, 0);
9304 if (CHECK_PROTOCOL_VERSION (2, 18))
9305 buffer_add_int (buf, 0);
9306 } else {
9307 buffer_add_int (buf, header->code_size);
9308 for (i = 0; i < header->code_size; ++i)
9309 buffer_add_byte (buf, header->code [i]);
9311 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9312 buffer_add_int (buf, header->num_clauses);
9313 for (i = 0; i < header->num_clauses; ++i) {
9314 MonoExceptionClause *clause = &header->clauses [i];
9316 buffer_add_int (buf, clause->flags);
9317 buffer_add_int (buf, clause->try_offset);
9318 buffer_add_int (buf, clause->try_len);
9319 buffer_add_int (buf, clause->handler_offset);
9320 buffer_add_int (buf, clause->handler_len);
9321 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9322 buffer_add_typeid (buf, domain, clause->data.catch_class);
9323 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9324 buffer_add_int (buf, clause->data.filter_offset);
9328 mono_metadata_free_mh (header);
9331 break;
9333 case CMD_METHOD_RESOLVE_TOKEN: {
9334 guint32 token = decode_int (p, &p, end);
9336 // FIXME: Generics
9337 switch (mono_metadata_token_code (token)) {
9338 case MONO_TOKEN_STRING: {
9339 ERROR_DECL (error);
9340 MonoString *s;
9341 char *s2;
9343 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), error);
9344 mono_error_assert_ok (error); /* FIXME don't swallow the error */
9346 s2 = mono_string_to_utf8_checked (s, error);
9347 mono_error_assert_ok (error);
9349 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9350 buffer_add_string (buf, s2);
9351 g_free (s2);
9352 break;
9354 default: {
9355 ERROR_DECL (error);
9356 gpointer val;
9357 MonoClass *handle_class;
9359 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9360 val = mono_method_get_wrapper_data (method, token);
9361 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9363 if (handle_class == NULL) {
9364 // Can't figure out the token type
9365 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9366 break;
9368 } else {
9369 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, error);
9370 if (!val)
9371 g_error ("Could not load token due to %s", mono_error_get_message (error));
9374 if (handle_class == mono_defaults.typehandle_class) {
9375 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9376 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9377 buffer_add_typeid (buf, domain, (MonoClass *) val);
9378 else
9379 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9380 } else if (handle_class == mono_defaults.fieldhandle_class) {
9381 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9382 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9383 } else if (handle_class == mono_defaults.methodhandle_class) {
9384 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9385 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9386 } else if (handle_class == mono_defaults.string_class) {
9387 char *s;
9389 s = mono_string_to_utf8_checked ((MonoString *)val, error);
9390 mono_error_assert_ok (error);
9391 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9392 buffer_add_string (buf, s);
9393 g_free (s);
9394 } else {
9395 g_assert_not_reached ();
9397 break;
9400 break;
9402 case CMD_METHOD_GET_CATTRS: {
9403 ERROR_DECL (error);
9404 MonoClass *attr_klass;
9405 MonoCustomAttrInfo *cinfo;
9407 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9408 /* attr_klass can be NULL */
9409 if (err != ERR_NONE)
9410 return err;
9412 cinfo = mono_custom_attrs_from_method_checked (method, error);
9413 if (!is_ok (error)) {
9414 mono_error_cleanup (error); /* FIXME don't swallow the error message */
9415 return ERR_LOADER_ERROR;
9418 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9419 if (err != ERR_NONE)
9420 return err;
9421 break;
9423 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9424 ERROR_DECL (error);
9425 MonoType **type_argv;
9426 int i, type_argc;
9427 MonoDomain *d;
9428 MonoClass *klass;
9429 MonoGenericInst *ginst;
9430 MonoGenericContext tmp_context;
9431 MonoMethod *inflated;
9433 type_argc = decode_int (p, &p, end);
9434 type_argv = g_new0 (MonoType*, type_argc);
9435 for (i = 0; i < type_argc; ++i) {
9436 klass = decode_typeid (p, &p, end, &d, &err);
9437 if (err != ERR_NONE) {
9438 g_free (type_argv);
9439 return err;
9441 if (domain != d) {
9442 g_free (type_argv);
9443 return ERR_INVALID_ARGUMENT;
9445 type_argv [i] = &klass->byval_arg;
9447 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9448 g_free (type_argv);
9449 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9450 tmp_context.method_inst = ginst;
9452 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
9453 g_assert (mono_error_ok (error)); /* FIXME don't swallow the error */
9454 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9455 return ERR_INVALID_ARGUMENT;
9456 buffer_add_methodid (buf, domain, inflated);
9457 break;
9459 default:
9460 return ERR_NOT_IMPLEMENTED;
9463 return ERR_NONE;
9466 static ErrorCode
9467 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9469 ErrorCode err;
9470 MonoDomain *old_domain;
9471 MonoDomain *domain;
9472 MonoMethod *method;
9474 method = decode_methodid (p, &p, end, &domain, &err);
9475 if (err != ERR_NONE)
9476 return err;
9478 old_domain = mono_domain_get ();
9480 mono_domain_set (domain, TRUE);
9482 err = method_commands_internal (command, method, domain, p, end, buf);
9484 mono_domain_set (old_domain, TRUE);
9486 return err;
9489 static ErrorCode
9490 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9492 int objid = decode_objid (p, &p, end);
9493 ErrorCode err;
9494 MonoThread *thread_obj;
9495 MonoInternalThread *thread;
9497 err = get_object (objid, (MonoObject**)&thread_obj);
9498 if (err != ERR_NONE)
9499 return err;
9501 thread = THREAD_TO_INTERNAL (thread_obj);
9503 switch (command) {
9504 case CMD_THREAD_GET_NAME: {
9505 guint32 name_len;
9506 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9508 if (!s) {
9509 buffer_add_int (buf, 0);
9510 } else {
9511 char *name;
9512 glong len;
9514 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9515 g_assert (name);
9516 buffer_add_int (buf, len);
9517 buffer_add_data (buf, (guint8*)name, len);
9518 g_free (s);
9520 break;
9522 case CMD_THREAD_GET_FRAME_INFO: {
9523 DebuggerTlsData *tls;
9524 int i, start_frame, length;
9526 // Wait for suspending if it already started
9527 // FIXME: Races with suspend_count
9528 while (!is_suspended ()) {
9529 if (suspend_count)
9530 wait_for_suspend ();
9533 if (suspend_count)
9534 wait_for_suspend ();
9535 if (!is_suspended ())
9536 return ERR_NOT_SUSPENDED;
9539 start_frame = decode_int (p, &p, end);
9540 length = decode_int (p, &p, end);
9542 if (start_frame != 0 || length != -1)
9543 return ERR_NOT_IMPLEMENTED;
9545 mono_loader_lock ();
9546 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9547 mono_loader_unlock ();
9548 g_assert (tls);
9550 compute_frame_info (thread, tls);
9552 buffer_add_int (buf, tls->frame_count);
9553 for (i = 0; i < tls->frame_count; ++i) {
9554 buffer_add_int (buf, tls->frames [i]->id);
9555 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9556 buffer_add_int (buf, tls->frames [i]->il_offset);
9558 * Instead of passing the frame type directly to the client, we associate
9559 * it with the previous frame using a set of flags. This avoids lots of
9560 * conditional code in the client, since a frame whose type isn't
9561 * FRAME_TYPE_MANAGED has no method, location, etc.
9563 buffer_add_byte (buf, tls->frames [i]->flags);
9566 break;
9568 case CMD_THREAD_GET_STATE:
9569 buffer_add_int (buf, thread->state);
9570 break;
9571 case CMD_THREAD_GET_INFO:
9572 buffer_add_byte (buf, thread->threadpool_thread);
9573 break;
9574 case CMD_THREAD_GET_ID:
9575 buffer_add_long (buf, (guint64)(gsize)thread);
9576 break;
9577 case CMD_THREAD_GET_TID:
9578 buffer_add_long (buf, (guint64)thread->tid);
9579 break;
9580 case CMD_THREAD_SET_IP: {
9581 DebuggerTlsData *tls;
9582 MonoMethod *method;
9583 MonoDomain *domain;
9584 MonoSeqPointInfo *seq_points;
9585 SeqPoint sp;
9586 gboolean found_sp;
9587 gint64 il_offset;
9589 method = decode_methodid (p, &p, end, &domain, &err);
9590 if (err != ERR_NONE)
9591 return err;
9592 il_offset = decode_long (p, &p, end);
9594 while (!is_suspended ()) {
9595 if (suspend_count)
9596 wait_for_suspend ();
9599 mono_loader_lock ();
9600 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9601 mono_loader_unlock ();
9602 g_assert (tls);
9604 compute_frame_info (thread, tls);
9605 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9606 return ERR_INVALID_ARGUMENT;
9608 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9610 g_assert (seq_points);
9612 if (!found_sp)
9613 return ERR_INVALID_ARGUMENT;
9615 // FIXME: Check that the ip change is safe
9617 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);
9619 if (tls->frames [0]->ji->is_interp) {
9620 MonoJitTlsData *jit_data = ((MonoThreadInfo*)thread->thread_info)->jit_data;
9621 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);
9622 } else {
9623 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9625 break;
9627 default:
9628 return ERR_NOT_IMPLEMENTED;
9631 return ERR_NONE;
9634 static ErrorCode
9635 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9637 int objid;
9638 ErrorCode err;
9639 MonoThread *thread_obj;
9640 MonoInternalThread *thread;
9641 int pos, i, len, frame_idx;
9642 DebuggerTlsData *tls;
9643 StackFrame *frame;
9644 MonoDebugMethodJitInfo *jit;
9645 MonoMethodSignature *sig;
9646 gssize id;
9647 MonoMethodHeader *header;
9649 objid = decode_objid (p, &p, end);
9650 err = get_object (objid, (MonoObject**)&thread_obj);
9651 if (err != ERR_NONE)
9652 return err;
9654 thread = THREAD_TO_INTERNAL (thread_obj);
9656 id = decode_id (p, &p, end);
9658 mono_loader_lock ();
9659 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9660 mono_loader_unlock ();
9661 g_assert (tls);
9663 for (i = 0; i < tls->frame_count; ++i) {
9664 if (tls->frames [i]->id == id)
9665 break;
9667 if (i == tls->frame_count)
9668 return ERR_INVALID_FRAMEID;
9670 frame_idx = i;
9671 frame = tls->frames [frame_idx];
9673 /* This is supported for frames without has_ctx etc. set */
9674 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9675 if (CHECK_PROTOCOL_VERSION (2, 38))
9676 buffer_add_domainid (buf, frame->domain);
9677 return ERR_NONE;
9680 if (!frame->has_ctx)
9681 return ERR_ABSENT_INFORMATION;
9683 if (!ensure_jit (frame))
9684 return ERR_ABSENT_INFORMATION;
9686 jit = frame->jit;
9688 sig = mono_method_signature (frame->actual_method);
9690 if (!(jit->has_var_info || frame->ji->is_interp) || !mono_get_seq_points (frame->domain, frame->actual_method))
9692 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9694 return ERR_ABSENT_INFORMATION;
9696 switch (command) {
9697 case CMD_STACK_FRAME_GET_VALUES: {
9698 ERROR_DECL (error);
9699 len = decode_int (p, &p, end);
9700 header = mono_method_get_header_checked (frame->actual_method, error);
9701 mono_error_assert_ok (error); /* FIXME report error */
9703 for (i = 0; i < len; ++i) {
9704 pos = decode_int (p, &p, end);
9706 if (pos < 0) {
9707 pos = - pos - 1;
9709 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9711 if (frame->ji->is_interp) {
9712 guint8 *addr;
9714 addr = mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9716 buffer_add_value_full (buf, sig->params [pos], addr, frame->domain, FALSE, NULL);
9717 } else {
9718 g_assert (pos >= 0 && pos < jit->num_params);
9720 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9722 } else {
9723 MonoDebugLocalsInfo *locals;
9725 locals = mono_debug_lookup_locals (frame->method);
9726 if (locals) {
9727 g_assert (pos < locals->num_locals);
9728 pos = locals->locals [pos].index;
9729 mono_debug_free_locals (locals);
9732 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9734 if (frame->ji->is_interp) {
9735 guint8 *addr;
9737 addr = mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9739 buffer_add_value_full (buf, header->locals [pos], addr, frame->domain, FALSE, NULL);
9740 } else {
9741 g_assert (pos >= 0 && pos < jit->num_locals);
9743 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9747 mono_metadata_free_mh (header);
9748 break;
9750 case CMD_STACK_FRAME_GET_THIS: {
9751 if (frame->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9752 return ERR_ABSENT_INFORMATION;
9753 if (frame->api_method->klass->valuetype) {
9754 if (!sig->hasthis) {
9755 MonoObject *p = NULL;
9756 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9757 } else {
9758 if (frame->ji->is_interp) {
9759 guint8 *addr;
9761 addr = mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9763 buffer_add_value_full (buf, &frame->actual_method->klass->this_arg, addr, frame->domain, FALSE, NULL);
9764 } else {
9765 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9768 } else {
9769 if (!sig->hasthis) {
9770 MonoObject *p = NULL;
9771 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9772 } else {
9773 if (frame->ji->is_interp) {
9774 guint8 *addr;
9776 addr = mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9778 buffer_add_value_full (buf, &frame->api_method->klass->byval_arg, addr, frame->domain, FALSE, NULL);
9779 } else {
9780 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9784 break;
9786 case CMD_STACK_FRAME_SET_VALUES: {
9787 ERROR_DECL (error);
9788 guint8 *val_buf;
9789 MonoType *t;
9790 MonoDebugVarInfo *var = NULL;
9791 gboolean is_arg = FALSE;
9793 len = decode_int (p, &p, end);
9794 header = mono_method_get_header_checked (frame->actual_method, error);
9795 mono_error_assert_ok (error); /* FIXME report error */
9797 for (i = 0; i < len; ++i) {
9798 pos = decode_int (p, &p, end);
9800 if (pos < 0) {
9801 pos = - pos - 1;
9803 g_assert (pos >= 0 && pos < jit->num_params);
9805 t = sig->params [pos];
9806 var = &jit->params [pos];
9807 is_arg = TRUE;
9808 } else {
9809 MonoDebugLocalsInfo *locals;
9811 locals = mono_debug_lookup_locals (frame->method);
9812 if (locals) {
9813 g_assert (pos < locals->num_locals);
9814 pos = locals->locals [pos].index;
9815 mono_debug_free_locals (locals);
9817 g_assert (pos >= 0 && pos < jit->num_locals);
9819 t = header->locals [pos];
9820 var = &jit->locals [pos];
9823 if (MONO_TYPE_IS_REFERENCE (t))
9824 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9825 else
9826 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9827 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9828 if (err != ERR_NONE)
9829 return err;
9831 if (frame->ji->is_interp) {
9832 guint8 *addr;
9834 if (is_arg)
9835 addr = mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9836 else
9837 addr = mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9838 set_interp_var (t, addr, val_buf);
9839 } else {
9840 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9843 mono_metadata_free_mh (header);
9844 break;
9846 case CMD_STACK_FRAME_GET_DOMAIN: {
9847 if (CHECK_PROTOCOL_VERSION (2, 38))
9848 buffer_add_domainid (buf, frame->domain);
9849 break;
9851 case CMD_STACK_FRAME_SET_THIS: {
9852 guint8 *val_buf;
9853 MonoType *t;
9854 MonoDebugVarInfo *var;
9856 t = &frame->actual_method->klass->byval_arg;
9857 /* Checked by the sender */
9858 g_assert (MONO_TYPE_ISSTRUCT (t));
9860 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9861 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9862 if (err != ERR_NONE)
9863 return err;
9865 if (frame->ji->is_interp) {
9866 guint8 *addr;
9868 addr = mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9869 set_interp_var (&frame->actual_method->klass->this_arg, addr, val_buf);
9870 } else {
9871 var = jit->this_var;
9872 g_assert (var);
9874 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9876 break;
9878 default:
9879 return ERR_NOT_IMPLEMENTED;
9882 return ERR_NONE;
9885 static ErrorCode
9886 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9888 MonoArray *arr;
9889 int objid, index, len, i, esize;
9890 ErrorCode err;
9891 gpointer elem;
9893 objid = decode_objid (p, &p, end);
9894 err = get_object (objid, (MonoObject**)&arr);
9895 if (err != ERR_NONE)
9896 return err;
9898 switch (command) {
9899 case CMD_ARRAY_REF_GET_LENGTH:
9900 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9901 if (!arr->bounds) {
9902 buffer_add_int (buf, arr->max_length);
9903 buffer_add_int (buf, 0);
9904 } else {
9905 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9906 buffer_add_int (buf, arr->bounds [i].length);
9907 buffer_add_int (buf, arr->bounds [i].lower_bound);
9910 break;
9911 case CMD_ARRAY_REF_GET_VALUES:
9912 index = decode_int (p, &p, end);
9913 len = decode_int (p, &p, end);
9915 g_assert (index >= 0 && len >= 0);
9916 // Reordered to avoid integer overflow
9917 g_assert (!(index > arr->max_length - len));
9919 esize = mono_array_element_size (arr->obj.vtable->klass);
9920 for (i = index; i < index + len; ++i) {
9921 elem = (gpointer*)((char*)arr->vector + (i * esize));
9922 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9924 break;
9925 case CMD_ARRAY_REF_SET_VALUES:
9926 index = decode_int (p, &p, end);
9927 len = decode_int (p, &p, end);
9929 g_assert (index >= 0 && len >= 0);
9930 // Reordered to avoid integer overflow
9931 g_assert (!(index > arr->max_length - len));
9933 esize = mono_array_element_size (arr->obj.vtable->klass);
9934 for (i = index; i < index + len; ++i) {
9935 elem = (gpointer*)((char*)arr->vector + (i * esize));
9937 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9939 break;
9940 default:
9941 return ERR_NOT_IMPLEMENTED;
9944 return ERR_NONE;
9947 static ErrorCode
9948 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9950 int objid;
9951 ErrorCode err;
9952 MonoString *str;
9953 char *s;
9954 int i, index, length;
9955 gunichar2 *c;
9956 gboolean use_utf16 = FALSE;
9958 objid = decode_objid (p, &p, end);
9959 err = get_object (objid, (MonoObject**)&str);
9960 if (err != ERR_NONE)
9961 return err;
9963 switch (command) {
9964 case CMD_STRING_REF_GET_VALUE:
9965 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9966 for (i = 0; i < mono_string_length (str); ++i)
9967 if (mono_string_chars (str)[i] == 0)
9968 use_utf16 = TRUE;
9969 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9971 if (use_utf16) {
9972 buffer_add_int (buf, mono_string_length (str) * 2);
9973 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9974 } else {
9975 ERROR_DECL (error);
9976 s = mono_string_to_utf8_checked (str, error);
9977 mono_error_assert_ok (error);
9978 buffer_add_string (buf, s);
9979 g_free (s);
9981 break;
9982 case CMD_STRING_REF_GET_LENGTH:
9983 buffer_add_long (buf, mono_string_length (str));
9984 break;
9985 case CMD_STRING_REF_GET_CHARS:
9986 index = decode_long (p, &p, end);
9987 length = decode_long (p, &p, end);
9988 if (index > mono_string_length (str) - length)
9989 return ERR_INVALID_ARGUMENT;
9990 c = mono_string_chars (str) + index;
9991 for (i = 0; i < length; ++i)
9992 buffer_add_short (buf, c [i]);
9993 break;
9994 default:
9995 return ERR_NOT_IMPLEMENTED;
9998 return ERR_NONE;
10001 static ErrorCode
10002 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
10004 ERROR_DECL (error);
10005 int objid;
10006 ErrorCode err;
10007 MonoObject *obj;
10008 int len, i;
10009 MonoClassField *f;
10010 MonoClass *k;
10011 gboolean found;
10013 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
10014 objid = decode_objid (p, &p, end);
10015 err = get_object (objid, &obj);
10016 if (err != ERR_NONE)
10017 buffer_add_int (buf, 1);
10018 else
10019 buffer_add_int (buf, 0);
10020 return ERR_NONE;
10023 objid = decode_objid (p, &p, end);
10024 err = get_object (objid, &obj);
10025 if (err != ERR_NONE)
10026 return err;
10028 MonoClass *obj_type;
10029 gboolean remote_obj = FALSE;
10031 obj_type = obj->vtable->klass;
10032 if (mono_class_is_transparent_proxy (obj_type)) {
10033 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
10034 remote_obj = TRUE;
10037 g_assert (obj_type);
10039 switch (command) {
10040 case CMD_OBJECT_REF_GET_TYPE:
10041 /* This handles transparent proxies too */
10042 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
10043 break;
10044 case CMD_OBJECT_REF_GET_VALUES:
10045 len = decode_int (p, &p, end);
10047 for (i = 0; i < len; ++i) {
10048 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
10049 if (err != ERR_NONE)
10050 return err;
10052 /* Check that the field belongs to the object */
10053 found = FALSE;
10054 for (k = obj_type; k; k = k->parent) {
10055 if (k == f->parent) {
10056 found = TRUE;
10057 break;
10060 if (!found)
10061 return ERR_INVALID_FIELDID;
10063 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
10064 guint8 *val;
10065 MonoVTable *vtable;
10067 if (mono_class_field_is_special_static (f))
10068 return ERR_INVALID_FIELDID;
10070 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
10071 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
10072 if (!is_ok (error)) {
10073 mono_error_cleanup (error);
10074 return ERR_INVALID_OBJECT;
10076 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
10077 mono_field_static_get_value_checked (vtable, f, val, error);
10078 if (!is_ok (error)) {
10079 mono_error_cleanup (error); /* FIXME report the error */
10080 return ERR_INVALID_OBJECT;
10082 buffer_add_value (buf, f->type, val, obj->vtable->domain);
10083 g_free (val);
10084 } else {
10085 guint8 *field_value = NULL;
10087 if (remote_obj) {
10088 #ifndef DISABLE_REMOTING
10089 void *field_storage = NULL;
10090 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, error);
10091 if (!is_ok (error)) {
10092 mono_error_cleanup (error); /* FIXME report the error */
10093 return ERR_INVALID_OBJECT;
10095 #else
10096 g_assert_not_reached ();
10097 #endif
10098 } else
10099 field_value = (guint8*)obj + f->offset;
10101 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
10104 break;
10105 case CMD_OBJECT_REF_SET_VALUES:
10106 len = decode_int (p, &p, end);
10108 for (i = 0; i < len; ++i) {
10109 f = decode_fieldid (p, &p, end, NULL, &err);
10110 if (err != ERR_NONE)
10111 return err;
10113 /* Check that the field belongs to the object */
10114 found = FALSE;
10115 for (k = obj_type; k; k = k->parent) {
10116 if (k == f->parent) {
10117 found = TRUE;
10118 break;
10121 if (!found)
10122 return ERR_INVALID_FIELDID;
10124 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
10125 guint8 *val;
10126 MonoVTable *vtable;
10128 if (mono_class_field_is_special_static (f))
10129 return ERR_INVALID_FIELDID;
10131 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
10132 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
10133 if (!is_ok (error)) {
10134 mono_error_cleanup (error);
10135 return ERR_INVALID_FIELDID;
10138 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
10139 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
10140 if (err != ERR_NONE) {
10141 g_free (val);
10142 return err;
10144 mono_field_static_set_value (vtable, f, val);
10145 g_free (val);
10146 } else {
10147 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
10148 if (err != ERR_NONE)
10149 return err;
10152 break;
10153 case CMD_OBJECT_REF_GET_ADDRESS:
10154 buffer_add_long (buf, (gssize)obj);
10155 break;
10156 case CMD_OBJECT_REF_GET_DOMAIN:
10157 buffer_add_domainid (buf, obj->vtable->domain);
10158 break;
10159 case CMD_OBJECT_REF_GET_INFO:
10160 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
10161 buffer_add_domainid (buf, obj->vtable->domain);
10162 break;
10163 default:
10164 return ERR_NOT_IMPLEMENTED;
10167 return ERR_NONE;
10170 static const char*
10171 command_set_to_string (CommandSet command_set)
10173 switch (command_set) {
10174 case CMD_SET_VM:
10175 return "VM";
10176 case CMD_SET_OBJECT_REF:
10177 return "OBJECT_REF";
10178 case CMD_SET_STRING_REF:
10179 return "STRING_REF";
10180 case CMD_SET_THREAD:
10181 return "THREAD";
10182 case CMD_SET_ARRAY_REF:
10183 return "ARRAY_REF";
10184 case CMD_SET_EVENT_REQUEST:
10185 return "EVENT_REQUEST";
10186 case CMD_SET_STACK_FRAME:
10187 return "STACK_FRAME";
10188 case CMD_SET_APPDOMAIN:
10189 return "APPDOMAIN";
10190 case CMD_SET_ASSEMBLY:
10191 return "ASSEMBLY";
10192 case CMD_SET_METHOD:
10193 return "METHOD";
10194 case CMD_SET_TYPE:
10195 return "TYPE";
10196 case CMD_SET_MODULE:
10197 return "MODULE";
10198 case CMD_SET_FIELD:
10199 return "FIELD";
10200 case CMD_SET_EVENT:
10201 return "EVENT";
10202 default:
10203 return "";
10207 static const char* vm_cmds_str [] = {
10208 "VERSION",
10209 "ALL_THREADS",
10210 "SUSPEND",
10211 "RESUME",
10212 "EXIT",
10213 "DISPOSE",
10214 "INVOKE_METHOD",
10215 "SET_PROTOCOL_VERSION",
10216 "ABORT_INVOKE",
10217 "SET_KEEPALIVE"
10218 "GET_TYPES_FOR_SOURCE_FILE",
10219 "GET_TYPES",
10220 "INVOKE_METHODS"
10223 static const char* thread_cmds_str[] = {
10224 "GET_FRAME_INFO",
10225 "GET_NAME",
10226 "GET_STATE",
10227 "GET_INFO",
10228 "GET_ID",
10229 "GET_TID",
10230 "SET_IP"
10233 static const char* event_cmds_str[] = {
10234 "REQUEST_SET",
10235 "REQUEST_CLEAR",
10236 "REQUEST_CLEAR_ALL_BREAKPOINTS"
10239 static const char* appdomain_cmds_str[] = {
10240 "GET_ROOT_DOMAIN",
10241 "GET_FRIENDLY_NAME",
10242 "GET_ASSEMBLIES",
10243 "GET_ENTRY_ASSEMBLY",
10244 "CREATE_STRING",
10245 "GET_CORLIB",
10246 "CREATE_BOXED_VALUE"
10249 static const char* assembly_cmds_str[] = {
10250 "GET_LOCATION",
10251 "GET_ENTRY_POINT",
10252 "GET_MANIFEST_MODULE",
10253 "GET_OBJECT",
10254 "GET_TYPE",
10255 "GET_NAME",
10256 "GET_DOMAIN"
10259 static const char* module_cmds_str[] = {
10260 "GET_INFO",
10263 static const char* field_cmds_str[] = {
10264 "GET_INFO",
10267 static const char* method_cmds_str[] = {
10268 "GET_NAME",
10269 "GET_DECLARING_TYPE",
10270 "GET_DEBUG_INFO",
10271 "GET_PARAM_INFO",
10272 "GET_LOCALS_INFO",
10273 "GET_INFO",
10274 "GET_BODY",
10275 "RESOLVE_TOKEN",
10276 "GET_CATTRS ",
10277 "MAKE_GENERIC_METHOD"
10280 static const char* type_cmds_str[] = {
10281 "GET_INFO",
10282 "GET_METHODS",
10283 "GET_FIELDS",
10284 "GET_VALUES",
10285 "GET_OBJECT",
10286 "GET_SOURCE_FILES",
10287 "SET_VALUES",
10288 "IS_ASSIGNABLE_FROM",
10289 "GET_PROPERTIES ",
10290 "GET_CATTRS",
10291 "GET_FIELD_CATTRS",
10292 "GET_PROPERTY_CATTRS",
10293 "GET_SOURCE_FILES_2",
10294 "GET_VALUES_2",
10295 "GET_METHODS_BY_NAME_FLAGS",
10296 "GET_INTERFACES",
10297 "GET_INTERFACE_MAP",
10298 "IS_INITIALIZED"
10301 static const char* stack_frame_cmds_str[] = {
10302 "GET_VALUES",
10303 "GET_THIS",
10304 "SET_VALUES",
10305 "GET_DOMAIN",
10306 "SET_THIS"
10309 static const char* array_cmds_str[] = {
10310 "GET_LENGTH",
10311 "GET_VALUES",
10312 "SET_VALUES",
10315 static const char* string_cmds_str[] = {
10316 "GET_VALUE",
10317 "GET_LENGTH",
10318 "GET_CHARS"
10321 static const char* object_cmds_str[] = {
10322 "GET_TYPE",
10323 "GET_VALUES",
10324 "IS_COLLECTED",
10325 "GET_ADDRESS",
10326 "GET_DOMAIN",
10327 "SET_VALUES",
10328 "GET_INFO",
10331 static const char*
10332 cmd_to_string (CommandSet set, int command)
10334 const char **cmds;
10335 int cmds_len = 0;
10337 switch (set) {
10338 case CMD_SET_VM:
10339 cmds = vm_cmds_str;
10340 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10341 break;
10342 case CMD_SET_OBJECT_REF:
10343 cmds = object_cmds_str;
10344 cmds_len = G_N_ELEMENTS (object_cmds_str);
10345 break;
10346 case CMD_SET_STRING_REF:
10347 cmds = string_cmds_str;
10348 cmds_len = G_N_ELEMENTS (string_cmds_str);
10349 break;
10350 case CMD_SET_THREAD:
10351 cmds = thread_cmds_str;
10352 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10353 break;
10354 case CMD_SET_ARRAY_REF:
10355 cmds = array_cmds_str;
10356 cmds_len = G_N_ELEMENTS (array_cmds_str);
10357 break;
10358 case CMD_SET_EVENT_REQUEST:
10359 cmds = event_cmds_str;
10360 cmds_len = G_N_ELEMENTS (event_cmds_str);
10361 break;
10362 case CMD_SET_STACK_FRAME:
10363 cmds = stack_frame_cmds_str;
10364 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10365 break;
10366 case CMD_SET_APPDOMAIN:
10367 cmds = appdomain_cmds_str;
10368 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10369 break;
10370 case CMD_SET_ASSEMBLY:
10371 cmds = assembly_cmds_str;
10372 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10373 break;
10374 case CMD_SET_METHOD:
10375 cmds = method_cmds_str;
10376 cmds_len = G_N_ELEMENTS (method_cmds_str);
10377 break;
10378 case CMD_SET_TYPE:
10379 cmds = type_cmds_str;
10380 cmds_len = G_N_ELEMENTS (type_cmds_str);
10381 break;
10382 case CMD_SET_MODULE:
10383 cmds = module_cmds_str;
10384 cmds_len = G_N_ELEMENTS (module_cmds_str);
10385 break;
10386 case CMD_SET_FIELD:
10387 cmds = field_cmds_str;
10388 cmds_len = G_N_ELEMENTS (field_cmds_str);
10389 break;
10390 case CMD_SET_EVENT:
10391 cmds = event_cmds_str;
10392 cmds_len = G_N_ELEMENTS (event_cmds_str);
10393 break;
10394 default:
10395 return NULL;
10397 if (command > 0 && command <= cmds_len)
10398 return cmds [command - 1];
10399 else
10400 return NULL;
10403 static gboolean
10404 wait_for_attach (void)
10406 #ifndef DISABLE_SOCKET_TRANSPORT
10407 if (listen_fd == -1) {
10408 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10409 return FALSE;
10412 /* Block and wait for client connection */
10413 conn_fd = socket_transport_accept (listen_fd);
10415 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10416 if (conn_fd == -1) {
10417 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10418 return FALSE;
10420 #else
10421 g_assert_not_reached ();
10422 #endif
10424 /* Handshake */
10425 disconnected = !transport_handshake ();
10426 if (disconnected) {
10427 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10428 return FALSE;
10431 return TRUE;
10435 * debugger_thread:
10437 * This thread handles communication with the debugger client using a JDWP
10438 * like protocol.
10440 static gsize WINAPI
10441 debugger_thread (void *arg)
10443 ERROR_DECL (error);
10444 int res, len, id, flags, command = 0;
10445 CommandSet command_set = (CommandSet)0;
10446 guint8 header [HEADER_LENGTH];
10447 guint8 *data, *p, *end;
10448 Buffer buf;
10449 ErrorCode err;
10450 gboolean no_reply;
10451 gboolean attach_failed = FALSE;
10453 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10455 debugger_thread_id = mono_native_thread_id_get ();
10457 MonoInternalThread *internal = mono_thread_internal_current ();
10458 MonoString *str = mono_string_new_checked (mono_domain_get (), "Debugger agent", error);
10459 mono_error_assert_ok (error);
10460 mono_thread_set_name_internal (internal, str, TRUE, FALSE, error);
10461 mono_error_assert_ok (error);
10463 internal->state |= ThreadState_Background;
10464 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10466 if (agent_config.defer) {
10467 if (!wait_for_attach ()) {
10468 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10469 attach_failed = TRUE; // Don't abort process when we can't listen
10470 } else {
10471 mono_set_is_debugger_attached (TRUE);
10472 /* Send start event to client */
10473 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10475 } else {
10476 mono_set_is_debugger_attached (TRUE);
10479 while (!attach_failed) {
10480 res = transport_recv (header, HEADER_LENGTH);
10482 /* This will break if the socket is closed during shutdown too */
10483 if (res != HEADER_LENGTH) {
10484 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10485 break;
10488 p = header;
10489 end = header + HEADER_LENGTH;
10491 len = decode_int (p, &p, end);
10492 id = decode_int (p, &p, end);
10493 flags = decode_byte (p, &p, end);
10494 command_set = (CommandSet)decode_byte (p, &p, end);
10495 command = decode_byte (p, &p, end);
10497 g_assert (flags == 0);
10499 if (log_level) {
10500 const char *cmd_str;
10501 char cmd_num [256];
10503 cmd_str = cmd_to_string (command_set, command);
10504 if (!cmd_str) {
10505 sprintf (cmd_num, "%d", command);
10506 cmd_str = cmd_num;
10509 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);
10512 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10513 if (len - HEADER_LENGTH > 0)
10515 res = transport_recv (data, len - HEADER_LENGTH);
10516 if (res != len - HEADER_LENGTH) {
10517 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10518 break;
10522 p = data;
10523 end = data + (len - HEADER_LENGTH);
10525 buffer_init (&buf, 128);
10527 err = ERR_NONE;
10528 no_reply = FALSE;
10530 /* Process the request */
10531 switch (command_set) {
10532 case CMD_SET_VM:
10533 err = vm_commands (command, id, p, end, &buf);
10534 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10535 /* Sent after the invoke is complete */
10536 no_reply = TRUE;
10537 break;
10538 case CMD_SET_EVENT_REQUEST:
10539 err = event_commands (command, p, end, &buf);
10540 break;
10541 case CMD_SET_APPDOMAIN:
10542 err = domain_commands (command, p, end, &buf);
10543 break;
10544 case CMD_SET_ASSEMBLY:
10545 err = assembly_commands (command, p, end, &buf);
10546 break;
10547 case CMD_SET_MODULE:
10548 err = module_commands (command, p, end, &buf);
10549 break;
10550 case CMD_SET_FIELD:
10551 err = field_commands (command, p, end, &buf);
10552 break;
10553 case CMD_SET_TYPE:
10554 err = type_commands (command, p, end, &buf);
10555 break;
10556 case CMD_SET_METHOD:
10557 err = method_commands (command, p, end, &buf);
10558 break;
10559 case CMD_SET_THREAD:
10560 err = thread_commands (command, p, end, &buf);
10561 break;
10562 case CMD_SET_STACK_FRAME:
10563 err = frame_commands (command, p, end, &buf);
10564 break;
10565 case CMD_SET_ARRAY_REF:
10566 err = array_commands (command, p, end, &buf);
10567 break;
10568 case CMD_SET_STRING_REF:
10569 err = string_commands (command, p, end, &buf);
10570 break;
10571 case CMD_SET_OBJECT_REF:
10572 err = object_commands (command, p, end, &buf);
10573 break;
10574 default:
10575 err = ERR_NOT_IMPLEMENTED;
10578 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10579 buffer_replies = TRUE;
10582 if (!no_reply) {
10583 if (buffer_replies) {
10584 buffer_reply_packet (id, err, &buf);
10585 } else {
10586 send_reply_packet (id, err, &buf);
10587 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10591 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10592 send_buffered_reply_packets ();
10593 buffer_replies = FALSE;
10596 g_free (data);
10597 buffer_free (&buf);
10599 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10600 break;
10603 mono_set_is_debugger_attached (FALSE);
10605 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10606 debugger_thread_exited = TRUE;
10607 mono_coop_cond_signal (&debugger_thread_exited_cond);
10608 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10610 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10612 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10613 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10614 start_debugger_thread ();
10617 return 0;
10620 #else /* DISABLE_DEBUGGER_AGENT */
10622 void
10623 mono_debugger_agent_parse_options (char *options)
10625 g_error ("This runtime is configured with the debugger agent disabled.");
10628 void
10629 mono_debugger_agent_init (void)
10633 void
10634 mono_debugger_agent_breakpoint_hit (void *sigctx)
10638 void
10639 mono_debugger_agent_single_step_event (void *sigctx)
10643 void
10644 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10648 void
10649 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
10650 MonoContext *catch_ctx, StackFrameInfo *catch_frame)
10654 void
10655 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10659 void
10660 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10664 void
10665 mono_debugger_agent_user_break (void)
10667 G_BREAKPOINT ();
10670 void
10671 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10675 gboolean
10676 mono_debugger_agent_debug_log_is_enabled (void)
10678 return FALSE;
10681 void
10682 mono_debugger_agent_unhandled_exception (MonoException *exc)
10684 g_assert_not_reached ();
10687 void
10688 debugger_agent_single_step_from_context (MonoContext *ctx)
10690 g_assert_not_reached ();
10693 void
10694 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10696 g_assert_not_reached ();
10699 #endif