2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
48 #ifdef PLATFORM_ANDROID
50 #include <linux/tcp.h>
51 #include <sys/endian.h>
54 #include <mono/metadata/mono-debug.h>
55 #include <mono/metadata/mono-debug-debugger.h>
56 #include <mono/metadata/debug-mono-symfile.h>
57 #include <mono/metadata/gc-internal.h>
58 #include <mono/metadata/environment.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/metadata/threadpool-ms.h>
61 #include <mono/metadata/socket-io.h>
62 #include <mono/metadata/assembly.h>
63 #include <mono/metadata/runtime.h>
64 #include <mono/metadata/verify-internals.h>
65 #include <mono/utils/mono-semaphore.h>
66 #include <mono/utils/mono-error-internals.h>
67 #include <mono/utils/mono-stack-unwinding.h>
68 #include <mono/utils/mono-time.h>
69 #include <mono/utils/mono-threads.h>
70 #include <mono/utils/networking.h>
71 #include "debugger-agent.h"
73 #include "seq-points.h"
76 * On iOS we can't use System.Environment.Exit () as it will do the wrong
79 #if !defined (TARGET_IOS)
80 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
84 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
85 #define DISABLE_DEBUGGER_AGENT 1
88 #ifdef DISABLE_SOFT_DEBUG
89 #define DISABLE_DEBUGGER_AGENT 1
92 #ifndef DISABLE_DEBUGGER_AGENT
94 #include <mono/utils/mono-mutex.h>
96 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
119 guint32 il_offset, native_offset;
123 * If method is gshared, this is the actual instance, otherwise this is equal to
126 MonoMethod *actual_method;
128 * This is the method which is visible to debugger clients. Same as method,
129 * except for native-to-managed wrappers.
131 MonoMethod *api_method;
133 MonoDebugMethodJitInfo *jit;
136 mgreg_t *reg_locations [MONO_MAX_IREGS];
138 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
139 * the frame can become invalid.
144 typedef struct _InvokeData InvokeData;
152 /* This is the context which needs to be restored after the invoke */
156 * If this is set, invoke this method with the arguments given by ARGS.
160 guint32 suspend_count;
163 InvokeData *last_invoke;
167 MonoThreadUnwindState context;
169 /* This is computed on demand when it is requested using the wire protocol */
170 /* It is freed up when the thread is resumed */
174 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
177 gboolean frames_up_to_date;
179 * Points to data about a pending invoke which needs to be executed after the thread
182 InvokeData *pending_invoke;
184 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
189 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
190 * within a finite amount of time.
194 * Set to TRUE if this thread is suspended in suspend_current ().
196 gboolean really_suspended;
197 /* Used to pass the context to the breakpoint/single step handler */
198 MonoContext handler_ctx;
199 /* Whenever thread_stop () was called for this thread */
202 /* Whenever to disable breakpoints (used during invokes) */
203 gboolean disable_breakpoints;
206 * Number of times this thread has been resumed using resume_thread ().
208 guint32 resume_count;
210 MonoInternalThread *thread;
213 * Information about the frame which transitioned to native code for running
216 StackFrameInfo async_last_frame;
219 * The context where the stack walk can be started for running threads.
221 MonoThreadUnwindState async_state;
224 * The context used for filter clauses
226 MonoThreadUnwindState filter_state;
228 gboolean abort_requested;
231 * The current mono_runtime_invoke invocation.
236 * The context where single stepping should resume while the thread is suspended because
237 * of an EXCEPTION event.
239 MonoThreadUnwindState catch_state;
242 * The context which needs to be restored after handling a single step/breakpoint
243 * event. This is the same as the ctx at step/breakpoint site, but includes changes
244 * to caller saved registers done by set_var ().
246 MonoThreadUnwindState restore_state;
247 /* Frames computed from restore_state */
248 int restore_frame_count;
249 StackFrame **restore_frames;
251 /* The currently unloading appdomain */
252 MonoDomain *domain_unloading;
257 void (*connect) (const char *address);
258 void (*close1) (void);
259 void (*close2) (void);
260 gboolean (*send) (void *buf, int len);
261 int (*recv) (void *buf, int len);
265 * Wire Protocol definitions
268 #define HEADER_LENGTH 11
270 #define MAJOR_VERSION 2
271 #define MINOR_VERSION 42
275 CMD_SET_OBJECT_REF = 9,
276 CMD_SET_STRING_REF = 10,
278 CMD_SET_ARRAY_REF = 13,
279 CMD_SET_EVENT_REQUEST = 15,
280 CMD_SET_STACK_FRAME = 16,
281 CMD_SET_APPDOMAIN = 20,
282 CMD_SET_ASSEMBLY = 21,
291 EVENT_KIND_VM_START = 0,
292 EVENT_KIND_VM_DEATH = 1,
293 EVENT_KIND_THREAD_START = 2,
294 EVENT_KIND_THREAD_DEATH = 3,
295 EVENT_KIND_APPDOMAIN_CREATE = 4,
296 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
297 EVENT_KIND_METHOD_ENTRY = 6,
298 EVENT_KIND_METHOD_EXIT = 7,
299 EVENT_KIND_ASSEMBLY_LOAD = 8,
300 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
301 EVENT_KIND_BREAKPOINT = 10,
302 EVENT_KIND_STEP = 11,
303 EVENT_KIND_TYPE_LOAD = 12,
304 EVENT_KIND_EXCEPTION = 13,
305 EVENT_KIND_KEEPALIVE = 14,
306 EVENT_KIND_USER_BREAK = 15,
307 EVENT_KIND_USER_LOG = 16
311 SUSPEND_POLICY_NONE = 0,
312 SUSPEND_POLICY_EVENT_THREAD = 1,
313 SUSPEND_POLICY_ALL = 2
318 ERR_INVALID_OBJECT = 20,
319 ERR_INVALID_FIELDID = 25,
320 ERR_INVALID_FRAMEID = 30,
321 ERR_NOT_IMPLEMENTED = 100,
322 ERR_NOT_SUSPENDED = 101,
323 ERR_INVALID_ARGUMENT = 102,
325 ERR_NO_INVOCATION = 104,
326 ERR_ABSENT_INFORMATION = 105,
327 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
328 ERR_INVOKE_ABORTED = 107,
329 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
334 MOD_KIND_THREAD_ONLY = 3,
335 MOD_KIND_LOCATION_ONLY = 7,
336 MOD_KIND_EXCEPTION_ONLY = 8,
338 MOD_KIND_ASSEMBLY_ONLY = 11,
339 MOD_KIND_SOURCE_FILE_ONLY = 12,
340 MOD_KIND_TYPE_NAME_ONLY = 13,
356 STEP_FILTER_NONE = 0,
357 STEP_FILTER_STATIC_CTOR = 1,
358 STEP_FILTER_DEBUGGER_HIDDEN = 2,
359 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
360 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
364 TOKEN_TYPE_STRING = 0,
366 TOKEN_TYPE_FIELD = 2,
367 TOKEN_TYPE_METHOD = 3,
368 TOKEN_TYPE_UNKNOWN = 4
372 VALUE_TYPE_ID_NULL = 0xf0,
373 VALUE_TYPE_ID_TYPE = 0xf1,
374 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
378 FRAME_FLAG_DEBUGGER_INVOKE = 1,
379 FRAME_FLAG_NATIVE_TRANSITION = 2
383 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
384 INVOKE_FLAG_SINGLE_THREADED = 2,
385 INVOKE_FLAG_RETURN_OUT_THIS = 4,
386 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
387 INVOKE_FLAG_VIRTUAL = 16
391 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
392 } BindingFlagsExtensions;
396 CMD_VM_ALL_THREADS = 2,
401 CMD_VM_INVOKE_METHOD = 7,
402 CMD_VM_SET_PROTOCOL_VERSION = 8,
403 CMD_VM_ABORT_INVOKE = 9,
404 CMD_VM_SET_KEEPALIVE = 10,
405 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
406 CMD_VM_GET_TYPES = 12,
407 CMD_VM_INVOKE_METHODS = 13,
408 CMD_VM_START_BUFFERING = 14,
409 CMD_VM_STOP_BUFFERING = 15
413 CMD_THREAD_GET_FRAME_INFO = 1,
414 CMD_THREAD_GET_NAME = 2,
415 CMD_THREAD_GET_STATE = 3,
416 CMD_THREAD_GET_INFO = 4,
417 CMD_THREAD_GET_ID = 5,
418 CMD_THREAD_GET_TID = 6,
419 CMD_THREAD_SET_IP = 7
423 CMD_EVENT_REQUEST_SET = 1,
424 CMD_EVENT_REQUEST_CLEAR = 2,
425 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
433 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
434 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
435 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
436 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
437 CMD_APPDOMAIN_CREATE_STRING = 5,
438 CMD_APPDOMAIN_GET_CORLIB = 6,
439 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
443 CMD_ASSEMBLY_GET_LOCATION = 1,
444 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
445 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
446 CMD_ASSEMBLY_GET_OBJECT = 4,
447 CMD_ASSEMBLY_GET_TYPE = 5,
448 CMD_ASSEMBLY_GET_NAME = 6
452 CMD_MODULE_GET_INFO = 1,
456 CMD_FIELD_GET_INFO = 1,
460 CMD_METHOD_GET_NAME = 1,
461 CMD_METHOD_GET_DECLARING_TYPE = 2,
462 CMD_METHOD_GET_DEBUG_INFO = 3,
463 CMD_METHOD_GET_PARAM_INFO = 4,
464 CMD_METHOD_GET_LOCALS_INFO = 5,
465 CMD_METHOD_GET_INFO = 6,
466 CMD_METHOD_GET_BODY = 7,
467 CMD_METHOD_RESOLVE_TOKEN = 8,
468 CMD_METHOD_GET_CATTRS = 9,
469 CMD_METHOD_MAKE_GENERIC_METHOD = 10
473 CMD_TYPE_GET_INFO = 1,
474 CMD_TYPE_GET_METHODS = 2,
475 CMD_TYPE_GET_FIELDS = 3,
476 CMD_TYPE_GET_VALUES = 4,
477 CMD_TYPE_GET_OBJECT = 5,
478 CMD_TYPE_GET_SOURCE_FILES = 6,
479 CMD_TYPE_SET_VALUES = 7,
480 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
481 CMD_TYPE_GET_PROPERTIES = 9,
482 CMD_TYPE_GET_CATTRS = 10,
483 CMD_TYPE_GET_FIELD_CATTRS = 11,
484 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
485 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
486 CMD_TYPE_GET_VALUES_2 = 14,
487 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
488 CMD_TYPE_GET_INTERFACES = 16,
489 CMD_TYPE_GET_INTERFACE_MAP = 17,
490 CMD_TYPE_IS_INITIALIZED = 18,
491 CMD_TYPE_CREATE_INSTANCE = 19
495 CMD_STACK_FRAME_GET_VALUES = 1,
496 CMD_STACK_FRAME_GET_THIS = 2,
497 CMD_STACK_FRAME_SET_VALUES = 3,
498 CMD_STACK_FRAME_GET_DOMAIN = 4,
502 CMD_ARRAY_REF_GET_LENGTH = 1,
503 CMD_ARRAY_REF_GET_VALUES = 2,
504 CMD_ARRAY_REF_SET_VALUES = 3,
508 CMD_STRING_REF_GET_VALUE = 1,
509 CMD_STRING_REF_GET_LENGTH = 2,
510 CMD_STRING_REF_GET_CHARS = 3
514 CMD_OBJECT_REF_GET_TYPE = 1,
515 CMD_OBJECT_REF_GET_VALUES = 2,
516 CMD_OBJECT_REF_IS_COLLECTED = 3,
517 CMD_OBJECT_REF_GET_ADDRESS = 4,
518 CMD_OBJECT_REF_GET_DOMAIN = 5,
519 CMD_OBJECT_REF_SET_VALUES = 6,
520 CMD_OBJECT_REF_GET_INFO = 7,
526 int count; /* For kind == MOD_KIND_COUNT */
527 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
528 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
529 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
530 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
531 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
532 StepFilter filter; /* For kind == MOD_KIND_STEP */
534 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
543 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
547 * Describes a single step request.
551 MonoInternalThread *thread;
557 MonoMethod *start_method;
558 MonoMethod *last_method;
560 /* Whenever single stepping is performed using start/stop_single_stepping () */
562 /* The list of breakpoints used to implement step-over */
564 /* The number of frames at the start of a step-over */
569 * Contains additional information for an event
572 /* For EVENT_KIND_EXCEPTION */
574 MonoContext catch_ctx;
576 /* For EVENT_KIND_USER_LOG */
578 char *category, *message;
579 /* For EVENT_KIND_TYPE_LOAD */
583 /* Dummy structure used for the profiler callbacks */
589 guint8 *buf, *p, *end;
592 typedef struct ReplyPacket {
598 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
600 #ifdef PLATFORM_ANDROID
601 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
603 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
607 #define get_last_sock_error() WSAGetLastError()
608 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
609 #define MONO_EINTR WSAEINTR
611 #define get_last_sock_error() errno
612 #define MONO_EWOULDBLOCK EWOULDBLOCK
613 #define MONO_EINTR EINTR
616 #define CHECK_PROTOCOL_VERSION(major,minor) \
617 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
623 static AgentConfig agent_config;
626 * Whenever the agent is fully initialized.
627 * When using the onuncaught or onthrow options, only some parts of the agent are
628 * initialized on startup, and the full initialization which includes connection
629 * establishment and the startup of the agent thread is only done in response to
632 static gint32 inited;
634 #ifndef DISABLE_SOCKET_TRANSPORT
636 static int listen_fd;
639 static int packet_id = 0;
641 static int objref_id = 0;
643 static int event_request_id = 0;
645 static int frame_id = 0;
647 static GPtrArray *event_requests;
649 static MonoNativeTlsKey debugger_tls_id;
651 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
653 /* Maps MonoInternalThread -> DebuggerTlsData */
654 /* Protected by the loader lock */
655 static MonoGHashTable *thread_to_tls;
657 /* Maps tid -> MonoInternalThread */
658 /* Protected by the loader lock */
659 static MonoGHashTable *tid_to_thread;
661 /* Maps tid -> MonoThread (not MonoInternalThread) */
662 /* Protected by the loader lock */
663 static MonoGHashTable *tid_to_thread_obj;
665 static MonoNativeThreadId debugger_thread_id;
667 static HANDLE debugger_thread_handle;
669 static int log_level;
671 static gboolean embedding;
673 static FILE *log_file;
675 /* Assemblies whose assembly load event has no been sent yet */
676 /* Protected by the dbg lock */
677 static GPtrArray *pending_assembly_loads;
679 /* Whenever the debugger thread has exited */
680 static gboolean debugger_thread_exited;
682 /* Cond variable used to wait for debugger_thread_exited becoming true */
683 static mono_cond_t debugger_thread_exited_cond;
685 /* Mutex for the cond var above */
686 static mono_mutex_t debugger_thread_exited_mutex;
688 static DebuggerProfiler debugger_profiler;
690 /* The single step request instance */
691 static SingleStepReq *ss_req;
693 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
694 /* Number of single stepping operations in progress */
698 /* The protocol version of the client */
699 static int major_version, minor_version;
701 /* Whenever the variables above are set by the client */
702 static gboolean protocol_version_set;
704 /* A hash table containing all active domains */
705 /* Protected by the loader lock */
706 static GHashTable *domains;
708 /* The number of times the runtime is suspended */
709 static gint32 suspend_count;
711 /* Whenever to buffer reply messages and send them together */
712 static gboolean buffer_replies;
714 /* Buffered reply packets */
715 static ReplyPacket reply_packets [128];
718 #define dbg_lock() do { \
720 mono_mutex_lock (&debug_mutex); \
721 MONO_FINISH_TRY_BLOCKING; \
724 #define dbg_unlock() mono_mutex_unlock (&debug_mutex)
725 static mono_mutex_t debug_mutex;
727 static void transport_init (void);
728 static void transport_connect (const char *address);
729 static gboolean transport_handshake (void);
730 static void register_transport (DebuggerTransport *trans);
732 static guint32 WINAPI debugger_thread (void *arg);
734 static void runtime_initialized (MonoProfiler *prof);
736 static void runtime_shutdown (MonoProfiler *prof);
738 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
740 static void thread_end (MonoProfiler *prof, uintptr_t tid);
742 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
744 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
746 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
748 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
750 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
752 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
754 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
756 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
758 static void emit_assembly_load (gpointer assembly, gpointer user_data);
760 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
762 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
764 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
766 static void start_single_stepping (void);
768 static void stop_single_stepping (void);
770 static void suspend_current (void);
772 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
774 static void clear_types_for_assembly (MonoAssembly *assembly);
776 static void clear_breakpoints_for_domain (MonoDomain *domain);
778 static void process_profiler_event (EventKind event, gpointer arg);
780 /* Submodule init/cleanup */
781 static void breakpoints_init (void);
782 static void breakpoints_cleanup (void);
784 static void objrefs_init (void);
785 static void objrefs_cleanup (void);
787 static void ids_init (void);
788 static void ids_cleanup (void);
790 static void suspend_init (void);
792 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
793 StackFrame **frames, int nframes);
794 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
795 static void ss_destroy (SingleStepReq *req);
797 static void start_debugger_thread (void);
798 static void stop_debugger_thread (void);
800 static void finish_agent_init (gboolean on_startup);
802 static void process_profiler_event (EventKind event, gpointer arg);
804 static void invalidate_frames (DebuggerTlsData *tls);
806 #ifndef DISABLE_SOCKET_TRANSPORT
808 register_socket_transport (void);
811 static inline gboolean
812 is_debugger_thread (void)
814 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
818 parse_address (char *address, char **host, int *port)
820 char *pos = strchr (address, ':');
822 if (pos == NULL || pos == address)
825 *host = g_malloc (pos - address + 1);
826 strncpy (*host, address, pos - address);
827 (*host) [pos - address] = '\0';
829 *port = atoi (pos + 1);
837 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
838 fprintf (stderr, "Available options:\n");
839 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
840 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
841 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
842 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
843 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
844 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
845 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
846 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
847 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
848 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
852 parse_flag (const char *option, char *flag)
854 if (!strcmp (flag, "y"))
856 else if (!strcmp (flag, "n"))
859 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
866 mono_debugger_agent_parse_options (char *options)
873 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
874 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
878 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
880 options = g_strdup_printf ("%s,%s", options, extra);
882 agent_config.enabled = TRUE;
883 agent_config.suspend = TRUE;
884 agent_config.server = FALSE;
885 agent_config.defer = FALSE;
886 agent_config.address = NULL;
888 //agent_config.log_level = 10;
890 args = g_strsplit (options, ",", -1);
891 for (ptr = args; ptr && *ptr; ptr ++) {
894 if (strncmp (arg, "transport=", 10) == 0) {
895 agent_config.transport = g_strdup (arg + 10);
896 } else if (strncmp (arg, "address=", 8) == 0) {
897 agent_config.address = g_strdup (arg + 8);
898 } else if (strncmp (arg, "loglevel=", 9) == 0) {
899 agent_config.log_level = atoi (arg + 9);
900 } else if (strncmp (arg, "logfile=", 8) == 0) {
901 agent_config.log_file = g_strdup (arg + 8);
902 } else if (strncmp (arg, "suspend=", 8) == 0) {
903 agent_config.suspend = parse_flag ("suspend", arg + 8);
904 } else if (strncmp (arg, "server=", 7) == 0) {
905 agent_config.server = parse_flag ("server", arg + 7);
906 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
907 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
908 } else if (strncmp (arg, "onthrow=", 8) == 0) {
909 /* We support multiple onthrow= options */
910 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
911 } else if (strncmp (arg, "onthrow", 7) == 0) {
912 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
913 } else if (strncmp (arg, "help", 4) == 0) {
916 } else if (strncmp (arg, "timeout=", 8) == 0) {
917 agent_config.timeout = atoi (arg + 8);
918 } else if (strncmp (arg, "launch=", 7) == 0) {
919 agent_config.launch = g_strdup (arg + 7);
920 } else if (strncmp (arg, "embedding=", 10) == 0) {
921 agent_config.embedding = atoi (arg + 10) == 1;
922 } else if (strncmp (arg, "keepalive=", 10) == 0) {
923 agent_config.keepalive = atoi (arg + 10);
924 } else if (strncmp (arg, "setpgid=", 8) == 0) {
925 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
932 if (agent_config.server && !agent_config.suspend) {
933 /* Waiting for deferred attachment */
934 agent_config.defer = TRUE;
935 if (agent_config.address == NULL) {
936 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
940 //agent_config.log_level = 0;
942 if (agent_config.transport == NULL) {
943 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
947 if (agent_config.address == NULL && !agent_config.server) {
948 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
953 if (!strcmp (agent_config.transport, "dt_socket")) {
954 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
955 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
962 mono_debugger_agent_init (void)
964 mono_mutex_init_recursive (&debug_mutex);
966 if (!agent_config.enabled)
971 /* Need to know whenever a thread has acquired the loader mutex */
972 mono_loader_lock_track_ownership (TRUE);
974 event_requests = g_ptr_array_new ();
976 mono_mutex_init (&debugger_thread_exited_mutex);
977 mono_cond_init (&debugger_thread_exited_cond, 0);
979 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
980 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
981 mono_profiler_install_runtime_initialized (runtime_initialized);
982 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
983 mono_profiler_install_thread (thread_startup, thread_end);
984 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
985 mono_profiler_install_jit_end (jit_end);
987 mono_native_tls_alloc (&debugger_tls_id, NULL);
989 /* Needed by the hash_table_new_type () call below */
990 mono_gc_base_init ();
992 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
993 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
995 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
996 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
998 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
999 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
1001 pending_assembly_loads = g_ptr_array_new ();
1002 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1004 log_level = agent_config.log_level;
1006 embedding = agent_config.embedding;
1007 disconnected = TRUE;
1009 if (agent_config.log_file) {
1010 log_file = fopen (agent_config.log_file, "w+");
1012 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1021 breakpoints_init ();
1024 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1026 * This is needed because currently we don't handle liveness info.
1028 mini_get_debug_options ()->mdb_optimizations = TRUE;
1030 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1031 /* This is needed because we can't set local variables in registers yet */
1032 mono_disable_optimizations (MONO_OPT_LINEARS);
1036 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1037 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1038 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1041 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1044 if (agent_config.setpgid)
1048 if (!agent_config.onuncaught && !agent_config.onthrow)
1049 finish_agent_init (TRUE);
1053 * finish_agent_init:
1055 * Finish the initialization of the agent. This involves connecting the transport
1056 * and starting the agent thread. This is either done at startup, or
1057 * in response to some event like an unhandled exception.
1060 finish_agent_init (gboolean on_startup)
1064 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1067 if (agent_config.launch) {
1070 // FIXME: Generated address
1071 // FIXME: Races with transport_connect ()
1073 argv [0] = agent_config.launch;
1074 argv [1] = agent_config.transport;
1075 argv [2] = agent_config.address;
1078 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1080 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1085 MONO_PREPARE_BLOCKING;
1086 transport_connect (agent_config.address);
1087 MONO_FINISH_BLOCKING;
1090 /* Do some which is usually done after sending the VMStart () event */
1091 vm_start_event_sent = TRUE;
1092 start_debugger_thread ();
1097 mono_debugger_agent_cleanup (void)
1102 stop_debugger_thread ();
1104 breakpoints_cleanup ();
1108 mono_mutex_destroy (&debugger_thread_exited_mutex);
1109 mono_cond_destroy (&debugger_thread_exited_cond);
1116 #ifndef DISABLE_SOCKET_TRANSPORT
1121 * recv() + handle incomplete reads and EINTR
1124 socket_transport_recv (void *buf, int len)
1130 static gint32 last_keepalive;
1135 res = recv (fd, (char *) buf + total, len - total, flags);
1138 if (agent_config.keepalive) {
1139 gboolean need_keepalive = FALSE;
1140 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1141 need_keepalive = TRUE;
1142 } else if (res == -1) {
1143 /* This could happen if recv () is interrupted repeatedly */
1144 msecs = mono_msec_ticks ();
1145 if (msecs - last_keepalive >= agent_config.keepalive) {
1146 need_keepalive = TRUE;
1147 last_keepalive = msecs;
1150 if (need_keepalive) {
1151 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1155 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1160 set_keepalive (void)
1165 if (!agent_config.keepalive || !conn_fd)
1168 tv.tv_sec = agent_config.keepalive / 1000;
1169 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1171 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1172 g_assert (result >= 0);
1176 socket_transport_accept (int socket_fd)
1178 conn_fd = accept (socket_fd, NULL, NULL);
1179 if (conn_fd == -1) {
1180 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1182 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1189 socket_transport_send (void *data, int len)
1194 res = send (conn_fd, data, len, 0);
1195 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1203 * socket_transport_connect:
1205 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1208 socket_transport_connect (const char *address)
1210 MonoAddressInfo *result;
1211 MonoAddressEntry *rp;
1212 int sfd = -1, s, res;
1216 if (agent_config.address) {
1217 res = parse_address (agent_config.address, &host, &port);
1218 g_assert (res == 0);
1229 mono_network_init ();
1231 /* Obtain address(es) matching host/port */
1232 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1234 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1239 if (agent_config.server) {
1240 /* Wait for a connection */
1242 struct sockaddr_in addr;
1245 /* No address, generate one */
1246 sfd = socket (AF_INET, SOCK_STREAM, 0);
1249 /* This will bind the socket to a random port */
1250 res = listen (sfd, 16);
1252 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1257 addrlen = sizeof (addr);
1258 memset (&addr, 0, sizeof (addr));
1259 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1260 g_assert (res == 0);
1262 host = (char*)"127.0.0.1";
1263 port = ntohs (addr.sin_port);
1265 /* Emit the address to stdout */
1266 /* FIXME: Should print another interface, not localhost */
1267 printf ("%s:%d\n", host, port);
1269 /* Listen on the provided address */
1270 for (rp = result->entries; rp != NULL; rp = rp->next) {
1271 MonoSocketAddress sockaddr;
1275 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1277 sfd = socket (rp->family, rp->socktype,
1282 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1285 res = bind (sfd, &sockaddr.addr, sock_len);
1289 res = listen (sfd, 16);
1296 mono_free_address_info (result);
1299 if (agent_config.defer)
1302 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1304 if (agent_config.timeout) {
1309 tv.tv_usec = agent_config.timeout * 1000;
1311 FD_SET (sfd, &readfds);
1312 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1314 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1319 MONO_PREPARE_BLOCKING;
1320 conn_fd = socket_transport_accept (sfd);
1321 MONO_FINISH_BLOCKING;
1325 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1327 /* Connect to the specified address */
1328 /* FIXME: Respect the timeout */
1329 for (rp = result->entries; rp != NULL; rp = rp->next) {
1330 MonoSocketAddress sockaddr;
1333 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1335 sfd = socket (rp->family, rp->socktype,
1340 if (connect (sfd, &sockaddr.addr, sock_len) != -1)
1341 break; /* Success */
1347 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1353 mono_free_address_info (result);
1356 if (!transport_handshake ())
1361 socket_transport_close1 (void)
1363 /* This will interrupt the agent thread */
1364 /* Close the read part only so it can still send back replies */
1365 /* Also shut down the connection listener so that we can exit normally */
1367 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1368 shutdown (conn_fd, SD_BOTH);
1369 shutdown (listen_fd, SD_BOTH);
1370 closesocket (listen_fd);
1372 shutdown (conn_fd, SHUT_RD);
1373 shutdown (listen_fd, SHUT_RDWR);
1379 socket_transport_close2 (void)
1382 shutdown (conn_fd, SD_BOTH);
1384 shutdown (conn_fd, SHUT_RDWR);
1389 register_socket_transport (void)
1391 DebuggerTransport trans;
1393 trans.name = "dt_socket";
1394 trans.connect = socket_transport_connect;
1395 trans.close1 = socket_transport_close1;
1396 trans.close2 = socket_transport_close2;
1397 trans.send = socket_transport_send;
1398 trans.recv = socket_transport_recv;
1400 register_transport (&trans);
1404 * socket_fd_transport_connect:
1408 socket_fd_transport_connect (const char *address)
1412 res = sscanf (address, "%d", &conn_fd);
1414 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1418 if (!transport_handshake ())
1423 register_socket_fd_transport (void)
1425 DebuggerTransport trans;
1427 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1428 trans.name = "socket-fd";
1429 trans.connect = socket_fd_transport_connect;
1430 trans.close1 = socket_transport_close1;
1431 trans.close2 = socket_transport_close2;
1432 trans.send = socket_transport_send;
1433 trans.recv = socket_transport_recv;
1435 register_transport (&trans);
1438 #endif /* DISABLE_SOCKET_TRANSPORT */
1444 #define MAX_TRANSPORTS 16
1446 static DebuggerTransport *transport;
1448 static DebuggerTransport transports [MAX_TRANSPORTS];
1449 static int ntransports;
1452 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1455 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1457 register_transport (trans);
1461 register_transport (DebuggerTransport *trans)
1463 g_assert (ntransports < MAX_TRANSPORTS);
1465 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1470 transport_init (void)
1474 #ifndef DISABLE_SOCKET_TRANSPORT
1475 register_socket_transport ();
1476 register_socket_fd_transport ();
1479 for (i = 0; i < ntransports; ++i) {
1480 if (!strcmp (agent_config.transport, transports [i].name))
1483 if (i == ntransports) {
1484 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1485 for (i = 0; i < ntransports; ++i)
1486 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1487 fprintf (stderr, "\n");
1490 transport = &transports [i];
1494 transport_connect (const char *address)
1496 transport->connect (address);
1500 transport_close1 (void)
1502 transport->close1 ();
1506 transport_close2 (void)
1508 transport->close2 ();
1512 transport_send (void *buf, int len)
1514 return transport->send (buf, len);
1518 transport_recv (void *buf, int len)
1520 return transport->recv (buf, len);
1524 mono_debugger_agent_transport_handshake (void)
1526 return transport_handshake ();
1530 transport_handshake (void)
1532 char handshake_msg [128];
1536 disconnected = TRUE;
1538 /* Write handshake message */
1539 sprintf (handshake_msg, "DWP-Handshake");
1540 /* Must use try blocking as this can nest into code that runs blocking */
1543 res = transport_send (handshake_msg, strlen (handshake_msg));
1544 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1545 MONO_FINISH_TRY_BLOCKING;
1547 g_assert (res != -1);
1551 res = transport_recv (buf, strlen (handshake_msg));
1552 MONO_FINISH_TRY_BLOCKING;
1553 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1554 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1559 * To support older clients, the client sends its protocol version after connecting
1560 * using a command. Until that is received, default to our protocol version.
1562 major_version = MAJOR_VERSION;
1563 minor_version = MINOR_VERSION;
1564 protocol_version_set = FALSE;
1566 #ifndef DISABLE_SOCKET_TRANSPORT
1567 // FIXME: Move this somewhere else
1569 * Set TCP_NODELAY on the socket so the client receives events/command
1570 * results immediately.
1574 int result = setsockopt (conn_fd,
1579 g_assert (result >= 0);
1585 disconnected = FALSE;
1590 stop_debugger_thread (void)
1595 MONO_PREPARE_BLOCKING;
1596 transport_close1 ();
1597 MONO_FINISH_BLOCKING;
1600 * Wait for the thread to exit.
1602 * If we continue with the shutdown without waiting for it, then the client might
1603 * not receive an answer to its last command like a resume.
1605 if (!is_debugger_thread ()) {
1608 mono_mutex_lock (&debugger_thread_exited_mutex);
1609 if (!debugger_thread_exited)
1610 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1611 mono_mutex_unlock (&debugger_thread_exited_mutex);
1612 MONO_FINISH_TRY_BLOCKING;
1613 } while (!debugger_thread_exited);
1616 MONO_PREPARE_BLOCKING;
1617 transport_close2 ();
1618 MONO_FINISH_BLOCKING;
1622 start_debugger_thread (void)
1624 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1625 g_assert (debugger_thread_handle);
1629 * Functions to decode protocol data
1633 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1636 g_assert (*endbuf <= limit);
1641 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1644 g_assert (*endbuf <= limit);
1646 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1649 static inline gint64
1650 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1652 guint32 high = decode_int (buf, &buf, limit);
1653 guint32 low = decode_int (buf, &buf, limit);
1657 return ((((guint64)high) << 32) | ((guint64)low));
1661 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1663 return decode_int (buf, endbuf, limit);
1667 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1669 int len = decode_int (buf, &buf, limit);
1677 s = g_malloc (len + 1);
1680 memcpy (s, buf, len);
1689 * Functions to encode protocol data
1693 buffer_init (Buffer *buf, int size)
1695 buf->buf = g_malloc (size);
1697 buf->end = buf->buf + size;
1701 buffer_len (Buffer *buf)
1703 return buf->p - buf->buf;
1707 buffer_make_room (Buffer *buf, int size)
1709 if (buf->end - buf->p < size) {
1710 int new_size = buf->end - buf->buf + size + 32;
1711 guint8 *p = g_realloc (buf->buf, new_size);
1712 size = buf->p - buf->buf;
1715 buf->end = buf->buf + new_size;
1720 buffer_add_byte (Buffer *buf, guint8 val)
1722 buffer_make_room (buf, 1);
1728 buffer_add_short (Buffer *buf, guint32 val)
1730 buffer_make_room (buf, 2);
1731 buf->p [0] = (val >> 8) & 0xff;
1732 buf->p [1] = (val >> 0) & 0xff;
1737 buffer_add_int (Buffer *buf, guint32 val)
1739 buffer_make_room (buf, 4);
1740 buf->p [0] = (val >> 24) & 0xff;
1741 buf->p [1] = (val >> 16) & 0xff;
1742 buf->p [2] = (val >> 8) & 0xff;
1743 buf->p [3] = (val >> 0) & 0xff;
1748 buffer_add_long (Buffer *buf, guint64 l)
1750 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1751 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1755 buffer_add_id (Buffer *buf, int id)
1757 buffer_add_int (buf, (guint64)id);
1761 buffer_add_data (Buffer *buf, guint8 *data, int len)
1763 buffer_make_room (buf, len);
1764 memcpy (buf->p, data, len);
1769 buffer_add_string (Buffer *buf, const char *str)
1774 buffer_add_int (buf, 0);
1777 buffer_add_int (buf, len);
1778 buffer_add_data (buf, (guint8*)str, len);
1783 buffer_add_buffer (Buffer *buf, Buffer *data)
1785 buffer_add_data (buf, data->buf, buffer_len (data));
1789 buffer_free (Buffer *buf)
1795 send_packet (int command_set, int command, Buffer *data)
1801 id = InterlockedIncrement (&packet_id);
1803 len = data->p - data->buf + 11;
1804 buffer_init (&buf, len);
1805 buffer_add_int (&buf, len);
1806 buffer_add_int (&buf, id);
1807 buffer_add_byte (&buf, 0); /* flags */
1808 buffer_add_byte (&buf, command_set);
1809 buffer_add_byte (&buf, command);
1810 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1812 MONO_PREPARE_BLOCKING;
1813 res = transport_send (buf.buf, len);
1814 MONO_FINISH_BLOCKING;
1822 send_reply_packets (int npackets, ReplyPacket *packets)
1829 for (i = 0; i < npackets; ++i)
1830 len += buffer_len (packets [i].data) + 11;
1831 buffer_init (&buf, len);
1832 for (i = 0; i < npackets; ++i) {
1833 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1834 buffer_add_int (&buf, packets [i].id);
1835 buffer_add_byte (&buf, 0x80); /* flags */
1836 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1837 buffer_add_byte (&buf, packets [i].error);
1838 buffer_add_buffer (&buf, packets [i].data);
1841 MONO_PREPARE_BLOCKING;
1842 res = transport_send (buf.buf, len);
1843 MONO_FINISH_BLOCKING;
1851 send_reply_packet (int id, int error, Buffer *data)
1855 memset (&packet, 0, sizeof (ReplyPacket));
1857 packet.error = error;
1860 return send_reply_packets (1, &packet);
1864 send_buffered_reply_packets (void)
1868 send_reply_packets (nreply_packets, reply_packets);
1869 for (i = 0; i < nreply_packets; ++i)
1870 buffer_free (reply_packets [i].data);
1871 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1876 buffer_reply_packet (int id, int error, Buffer *data)
1880 if (nreply_packets == 128)
1881 send_buffered_reply_packets ();
1883 p = &reply_packets [nreply_packets];
1886 p->data = g_new0 (Buffer, 1);
1887 buffer_init (p->data, buffer_len (data));
1888 buffer_add_buffer (p->data, data);
1897 * Represents an object accessible by the debugger client.
1900 /* Unique id used in the wire protocol to refer to objects */
1903 * A weakref gc handle pointing to the object. The gc handle is used to
1904 * detect if the object was garbage collected.
1909 /* Maps objid -> ObjRef */
1910 /* Protected by the loader lock */
1911 static GHashTable *objrefs;
1912 /* Protected by the loader lock */
1913 static GHashTable *obj_to_objref;
1914 /* Protected by the dbg lock */
1915 static MonoGHashTable *suspended_objs;
1918 free_objref (gpointer value)
1922 mono_gchandle_free (o->handle);
1930 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1931 obj_to_objref = g_hash_table_new (NULL, NULL);
1932 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1933 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1937 objrefs_cleanup (void)
1939 g_hash_table_destroy (objrefs);
1944 * Return an ObjRef for OBJ.
1947 get_objref (MonoObject *obj)
1950 GSList *reflist = NULL, *l;
1956 if (suspend_count) {
1958 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1961 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1965 mono_loader_lock ();
1967 /* FIXME: The tables can grow indefinitely */
1969 if (mono_gc_is_moving ()) {
1971 * Objects can move, so use a hash table mapping hash codes to lists of
1972 * ObjRef structures.
1974 hash = mono_object_hash (obj);
1976 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1977 for (l = reflist; l; l = l->next) {
1979 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1980 mono_loader_unlock ();
1985 /* Use a hash table with masked pointers to internalize object references */
1986 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1987 /* ref might refer to a different object with the same addr which was GCd */
1988 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1989 mono_loader_unlock ();
1994 ref = g_new0 (ObjRef, 1);
1995 ref->id = InterlockedIncrement (&objref_id);
1996 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1998 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2000 if (mono_gc_is_moving ()) {
2001 reflist = g_slist_append (reflist, ref);
2002 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2004 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2007 mono_loader_unlock ();
2013 true_pred (gpointer key, gpointer value, gpointer user_data)
2019 clear_suspended_objs (void)
2022 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2027 get_objid (MonoObject *obj)
2029 return get_objref (obj)->id;
2033 * Set OBJ to the object identified by OBJID.
2034 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2038 get_object_allow_null (int objid, MonoObject **obj)
2048 return ERR_INVALID_OBJECT;
2050 mono_loader_lock ();
2052 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2055 *obj = mono_gchandle_get_target (ref->handle);
2056 mono_loader_unlock ();
2058 return ERR_INVALID_OBJECT;
2061 mono_loader_unlock ();
2062 return ERR_INVALID_OBJECT;
2067 get_object (int objid, MonoObject **obj)
2069 int err = get_object_allow_null (objid, obj);
2074 return ERR_INVALID_OBJECT;
2079 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2081 return decode_id (buf, endbuf, limit);
2085 buffer_add_objid (Buffer *buf, MonoObject *o)
2087 buffer_add_id (buf, get_objid (o));
2106 * Represents a runtime structure accessible to the debugger client
2109 /* Unique id used in the wire protocol */
2111 /* Domain of the runtime structure, NULL if the domain was unloaded */
2118 MonoAssembly *assembly;
2119 MonoClassField *field;
2121 MonoProperty *property;
2126 /* Maps runtime structure -> Id */
2127 /* Protected by the dbg lock */
2128 GHashTable *val_to_id [ID_NUM];
2129 /* Classes whose class load event has been sent */
2130 /* Protected by the loader lock */
2131 GHashTable *loaded_classes;
2132 /* Maps MonoClass->GPtrArray of file names */
2133 GHashTable *source_files;
2134 /* Maps source file basename -> GSList of classes */
2135 GHashTable *source_file_to_class;
2136 /* Same with ignore-case */
2137 GHashTable *source_file_to_class_ignorecase;
2141 /* Protected by the dbg lock */
2142 static GPtrArray *ids [ID_NUM];
2149 for (i = 0; i < ID_NUM; ++i)
2150 ids [i] = g_ptr_array_new ();
2158 for (i = 0; i < ID_NUM; ++i) {
2160 for (j = 0; j < ids [i]->len; ++j)
2161 g_free (g_ptr_array_index (ids [i], j));
2162 g_ptr_array_free (ids [i], TRUE);
2169 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2171 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2173 GHashTableIter iter;
2174 GPtrArray *file_names;
2179 for (i = 0; i < ID_NUM; ++i)
2180 if (info->val_to_id [i])
2181 g_hash_table_destroy (info->val_to_id [i]);
2182 g_hash_table_destroy (info->loaded_classes);
2184 g_hash_table_iter_init (&iter, info->source_files);
2185 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2186 for (i = 0; i < file_names->len; ++i)
2187 g_free (g_ptr_array_index (file_names, i));
2188 g_ptr_array_free (file_names, TRUE);
2191 g_hash_table_iter_init (&iter, info->source_file_to_class);
2192 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2197 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2198 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2206 domain_jit_info (domain)->agent_info = NULL;
2208 /* Clear ids referencing structures in the domain */
2210 for (i = 0; i < ID_NUM; ++i) {
2212 for (j = 0; j < ids [i]->len; ++j) {
2213 Id *id = g_ptr_array_index (ids [i], j);
2214 if (id->domain == domain)
2221 mono_loader_lock ();
2222 g_hash_table_remove (domains, domain);
2223 mono_loader_unlock ();
2226 static AgentDomainInfo*
2227 get_agent_domain_info (MonoDomain *domain)
2229 AgentDomainInfo *info = NULL;
2231 mono_domain_lock (domain);
2233 info = domain_jit_info (domain)->agent_info;
2235 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2236 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2237 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2238 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2239 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2242 mono_domain_unlock (domain);
2248 get_id (MonoDomain *domain, IdType type, gpointer val)
2251 AgentDomainInfo *info;
2256 info = get_agent_domain_info (domain);
2260 if (info->val_to_id [type] == NULL)
2261 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2263 id = g_hash_table_lookup (info->val_to_id [type], val);
2269 id = g_new0 (Id, 1);
2271 id->id = ids [type]->len + 1;
2272 id->domain = domain;
2275 g_hash_table_insert (info->val_to_id [type], val, id);
2276 g_ptr_array_add (ids [type], id);
2283 static inline gpointer
2284 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2288 int id = decode_id (buf, endbuf, limit);
2297 // FIXME: error handling
2299 g_assert (id > 0 && id <= ids [type]->len);
2301 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2304 if (res->domain == NULL) {
2305 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2306 *err = ERR_UNLOADED;
2311 *domain = res->domain;
2313 return res->data.val;
2317 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2319 int id = get_id (domain, type, val);
2321 buffer_add_id (buf, id);
2325 static inline MonoClass*
2326 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2330 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2331 if (G_UNLIKELY (log_level >= 2) && klass) {
2334 s = mono_type_full_name (&klass->byval_arg);
2335 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2341 static inline MonoAssembly*
2342 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2344 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2347 static inline MonoImage*
2348 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2350 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2353 static inline MonoMethod*
2354 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2358 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2359 if (G_UNLIKELY (log_level >= 2) && m) {
2362 s = mono_method_full_name (m, TRUE);
2363 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2369 static inline MonoClassField*
2370 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2372 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2375 static inline MonoDomain*
2376 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2378 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2381 static inline MonoProperty*
2382 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2384 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2388 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2390 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2391 if (G_UNLIKELY (log_level >= 2) && klass) {
2394 s = mono_type_full_name (&klass->byval_arg);
2395 if (is_debugger_thread ())
2396 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2398 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer)mono_native_thread_id_get (), s);
2404 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2406 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2407 if (G_UNLIKELY (log_level >= 2) && method) {
2410 s = mono_method_full_name (method, 1);
2411 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2417 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2421 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2422 if (G_UNLIKELY (log_level >= 2) && assembly)
2423 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2427 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2429 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2433 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2435 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2439 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2441 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2445 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2447 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2450 static void invoke_method (void);
2457 * save_thread_context:
2459 * Set CTX as the current threads context which is used for computing stack traces.
2460 * This function is signal-safe.
2463 save_thread_context (MonoContext *ctx)
2465 DebuggerTlsData *tls;
2467 tls = mono_native_tls_get_value (debugger_tls_id);
2471 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2473 mono_thread_state_init_from_current (&tls->context);
2476 /* Number of threads suspended */
2478 * If this is equal to the size of thread_to_tls, the runtime is considered
2481 static gint32 threads_suspend_count;
2483 static mono_mutex_t suspend_mutex;
2485 /* Cond variable used to wait for suspend_count becoming 0 */
2486 static mono_cond_t suspend_cond;
2488 /* Semaphore used to wait for a thread becoming suspended */
2489 static MonoSemType suspend_sem;
2494 mono_mutex_init (&suspend_mutex);
2495 mono_cond_init (&suspend_cond, 0);
2496 MONO_SEM_INIT (&suspend_sem, 0);
2501 StackFrameInfo last_frame;
2502 gboolean last_frame_set;
2506 } GetLastFrameUserData;
2509 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2511 GetLastFrameUserData *data = user_data;
2513 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2516 if (!data->last_frame_set) {
2517 /* Store the last frame */
2518 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2519 data->last_frame_set = TRUE;
2522 /* Store the context/lmf for the frame above the last frame */
2523 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2524 data->lmf = info->lmf;
2525 data->domain = info->domain;
2531 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2533 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2535 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2536 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2537 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2544 * Process interruption of a thread. This should be signal safe.
2546 * This always runs in the debugger thread.
2549 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2552 MonoNativeThreadId tid;
2556 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2557 tid = mono_thread_info_get_tid (info);
2559 // FIXME: Races when the thread leaves managed code before hitting a single step
2562 if (ji && !ji->is_trampoline) {
2563 /* Running managed code, will be suspended by the single step code */
2564 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2567 * Running native code, will be suspended when it returns to/enters
2568 * managed code. Treat it as already suspended.
2569 * This might interrupt the code in process_single_step_inner (), we use the
2570 * tls->suspending flag to avoid races when that happens.
2572 if (!tls->suspended && !tls->suspending) {
2573 GetLastFrameUserData data;
2575 // FIXME: printf is not signal safe, but this is only used during
2576 // debugger debugging
2578 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2579 //save_thread_context (&ctx);
2582 /* Already terminated */
2586 * We are in a difficult position: we want to be able to provide stack
2587 * traces for this thread, but we can't use the current ctx+lmf, since
2588 * the thread is still running, so it might return to managed code,
2589 * making these invalid.
2590 * So we start a stack walk and save the first frame, along with the
2591 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2592 * suspended when it returns to managed code, so the parent's ctx should
2595 data.last_frame_set = FALSE;
2596 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2597 if (data.last_frame_set) {
2598 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2600 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2602 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2603 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2605 tls->async_state.valid = FALSE;
2608 mono_memory_barrier ();
2610 tls->suspended = TRUE;
2611 MONO_SEM_POST (&suspend_sem);
2617 * reset_native_thread_suspend_state:
2619 * Reset the suspended flag and state on native threads
2622 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2624 DebuggerTlsData *tls = value;
2626 if (!tls->really_suspended && tls->suspended) {
2627 tls->suspended = FALSE;
2629 * The thread might still be running if it was executing native code, so the state won't be invalided by
2630 * suspend_current ().
2632 tls->context.valid = FALSE;
2633 tls->async_state.valid = FALSE;
2634 invalidate_frames (tls);
2639 DebuggerTlsData *tls;
2640 gboolean valid_info;
2643 static SuspendThreadResult
2644 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2646 InterruptData *data = user_data;
2649 data->valid_info = TRUE;
2650 ji = mono_jit_info_table_find_internal (
2651 mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2652 MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2656 /* This is signal safe */
2657 thread_interrupt (data->tls, info, ji);
2658 return MonoResumeThread;
2664 * Notify a thread that it needs to suspend.
2667 notify_thread (gpointer key, gpointer value, gpointer user_data)
2669 MonoInternalThread *thread = key;
2670 DebuggerTlsData *tls = value;
2671 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2673 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2676 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer)mono_native_thread_id_get (), (gpointer)tid);
2678 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2679 InterruptData interrupt_data = { 0 };
2680 interrupt_data.tls = tls;
2682 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2683 if (!interrupt_data.valid_info) {
2684 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)mono_native_thread_id_get (), (gpointer)tid);
2686 * Attached thread which died without detaching.
2688 tls->terminated = TRUE;
2693 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2695 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2699 if (mono_loader_lock_is_owned_by_self ()) {
2701 * Shortcut for the check in suspend_current (). This speeds up processing
2702 * when executing long running code inside the loader lock, i.e. assembly load
2708 if (is_debugger_thread ())
2711 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2712 if (suspend_count - tls->resume_count > 0)
2713 tls->suspending = TRUE;
2715 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer)mono_native_thread_id_get ());
2717 if (suspend_count - tls->resume_count == 0) {
2719 * We are executing a single threaded invoke but the single step for
2720 * suspending is still active.
2721 * FIXME: This slows down single threaded invokes.
2723 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer)mono_native_thread_id_get ());
2727 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2729 /* Can't suspend in these methods */
2730 method = jinfo_get_method (ji);
2731 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2734 save_thread_context (ctx);
2742 * Increase the suspend count of the VM. While the suspend count is greater
2743 * than 0, runtime threads are suspended at certain points during execution.
2748 mono_loader_lock ();
2751 mono_mutex_lock (&suspend_mutex);
2752 MONO_FINISH_TRY_BLOCKING;
2756 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer)mono_native_thread_id_get ());
2758 if (suspend_count == 1) {
2759 // FIXME: Is it safe to call this inside the lock ?
2760 start_single_stepping ();
2761 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2764 mono_mutex_unlock (&suspend_mutex);
2766 if (suspend_count == 1)
2768 * Suspend creation of new threadpool threads, since they cannot run
2770 mono_threadpool_ms_suspend ();
2772 mono_loader_unlock ();
2778 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2786 g_assert (is_debugger_thread ());
2788 mono_loader_lock ();
2791 mono_mutex_lock (&suspend_mutex);
2792 MONO_FINISH_TRY_BLOCKING;
2794 g_assert (suspend_count > 0);
2797 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)mono_native_thread_id_get (), suspend_count);
2799 if (suspend_count == 0) {
2800 // FIXME: Is it safe to call this inside the lock ?
2801 stop_single_stepping ();
2802 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2805 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2806 err = mono_cond_broadcast (&suspend_cond);
2807 g_assert (err == 0);
2809 mono_mutex_unlock (&suspend_mutex);
2810 //g_assert (err == 0);
2812 if (suspend_count == 0)
2813 mono_threadpool_ms_resume ();
2815 mono_loader_unlock ();
2821 * Resume just one thread.
2824 resume_thread (MonoInternalThread *thread)
2827 DebuggerTlsData *tls;
2829 g_assert (is_debugger_thread ());
2831 mono_loader_lock ();
2833 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2837 mono_mutex_lock (&suspend_mutex);
2838 MONO_FINISH_TRY_BLOCKING;
2840 g_assert (suspend_count > 0);
2842 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2844 tls->resume_count += suspend_count;
2847 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2848 * but only the one whose resume_count field is > 0 will be resumed.
2850 err = mono_cond_broadcast (&suspend_cond);
2851 g_assert (err == 0);
2853 mono_mutex_unlock (&suspend_mutex);
2854 //g_assert (err == 0);
2856 mono_loader_unlock ();
2860 free_frames (StackFrame **frames, int nframes)
2864 for (i = 0; i < nframes; ++i) {
2865 if (frames [i]->jit)
2866 mono_debug_free_method_jit_info (frames [i]->jit);
2867 g_free (frames [i]);
2873 invalidate_frames (DebuggerTlsData *tls)
2876 tls = mono_native_tls_get_value (debugger_tls_id);
2879 free_frames (tls->frames, tls->frame_count);
2880 tls->frame_count = 0;
2883 free_frames (tls->restore_frames, tls->restore_frame_count);
2884 tls->restore_frame_count = 0;
2885 tls->restore_frames = NULL;
2891 * Suspend the current thread until the runtime is resumed. If the thread has a
2892 * pending invoke, then the invoke is executed before this function returns.
2895 suspend_current (void)
2897 DebuggerTlsData *tls;
2900 g_assert (!is_debugger_thread ());
2902 if (mono_loader_lock_is_owned_by_self ()) {
2904 * If we own the loader mutex, can't suspend until we release it, since the
2905 * whole runtime can deadlock otherwise.
2910 tls = mono_native_tls_get_value (debugger_tls_id);
2914 mono_mutex_lock (&suspend_mutex);
2915 MONO_FINISH_TRY_BLOCKING;
2917 tls->suspending = FALSE;
2918 tls->really_suspended = TRUE;
2920 if (!tls->suspended) {
2921 tls->suspended = TRUE;
2922 MONO_SEM_POST (&suspend_sem);
2925 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer)mono_native_thread_id_get ());
2928 while (suspend_count - tls->resume_count > 0) {
2929 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2930 g_assert (err == 0);
2932 MONO_FINISH_TRY_BLOCKING;
2934 tls->suspended = FALSE;
2935 tls->really_suspended = FALSE;
2937 threads_suspend_count --;
2939 mono_mutex_unlock (&suspend_mutex);
2941 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer)mono_native_thread_id_get ());
2943 if (tls->pending_invoke) {
2944 /* Save the original context */
2945 tls->pending_invoke->has_ctx = TRUE;
2946 tls->pending_invoke->ctx = tls->context.ctx;
2951 /* The frame info becomes invalid after a resume */
2952 tls->context.valid = FALSE;
2953 tls->async_state.valid = FALSE;
2954 invalidate_frames (tls);
2958 count_thread (gpointer key, gpointer value, gpointer user_data)
2960 DebuggerTlsData *tls = value;
2962 if (!tls->suspended && !tls->terminated)
2963 *(int*)user_data = *(int*)user_data + 1;
2967 count_threads_to_wait_for (void)
2971 mono_loader_lock ();
2972 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2973 mono_loader_unlock ();
2981 * Wait until the runtime is completely suspended.
2984 wait_for_suspend (void)
2986 int nthreads, nwait, err;
2987 gboolean waited = FALSE;
2989 // FIXME: Threads starting/stopping ?
2990 mono_loader_lock ();
2991 nthreads = mono_g_hash_table_size (thread_to_tls);
2992 mono_loader_unlock ();
2995 nwait = count_threads_to_wait_for ();
2997 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2998 err = MONO_SEM_WAIT (&suspend_sem);
2999 g_assert (err == 0);
3007 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3013 * Return whenever the runtime is suspended.
3018 return count_threads_to_wait_for () == 0;
3022 no_seq_points_found (MonoMethod *method, int offset)
3025 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3027 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3031 DebuggerTlsData *tls;
3033 } ComputeFramesUserData;
3036 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3038 ComputeFramesUserData *ud = user_data;
3040 MonoMethod *method, *actual_method, *api_method;
3044 if (info->type != FRAME_TYPE_MANAGED) {
3045 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3046 /* Mark the last frame as an invoke frame */
3048 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3054 method = jinfo_get_method (info->ji);
3056 method = info->method;
3057 actual_method = info->actual_method;
3058 api_method = method;
3063 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3066 if (info->il_offset == -1) {
3067 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3068 if (ud->frames == NULL) {
3069 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3070 info->il_offset = sp.il_offset;
3072 if (info->il_offset == -1)
3073 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3076 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);
3078 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3079 if (!CHECK_PROTOCOL_VERSION (2, 17))
3080 /* Older clients can't handle this flag */
3082 api_method = mono_marshal_method_from_wrapper (method);
3085 actual_method = api_method;
3086 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3089 frame = g_new0 (StackFrame, 1);
3090 frame->method = method;
3091 frame->actual_method = actual_method;
3092 frame->api_method = api_method;
3093 frame->il_offset = info->il_offset;
3094 frame->native_offset = info->native_offset;
3095 frame->flags = flags;
3096 frame->ji = info->ji;
3097 if (info->reg_locations)
3098 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3101 frame->has_ctx = TRUE;
3103 frame->domain = info->domain;
3105 ud->frames = g_slist_append (ud->frames, frame);
3111 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3113 ComputeFramesUserData *ud = user_data;
3116 * 'tls->filter_ctx' is the location of the throw site.
3118 * mono_walk_stack() will never actually hit the throw site, but unwind
3119 * directly from the filter to the call site; we abort stack unwinding here
3120 * once this happens and resume from the throw site.
3123 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3126 return process_frame (info, ctx, user_data);
3130 * Return a malloc-ed list of StackFrame structures.
3133 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3135 ComputeFramesUserData user_data;
3136 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3141 user_data.tls = tls;
3142 user_data.frames = NULL;
3144 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3146 nframes = g_slist_length (user_data.frames);
3147 res = g_new0 (StackFrame*, nframes);
3148 l = user_data.frames;
3149 for (i = 0; i < nframes; ++i) {
3153 *out_nframes = nframes;
3159 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3161 ComputeFramesUserData user_data;
3163 int i, findex, new_frame_count;
3164 StackFrame **new_frames, *f;
3165 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3167 // FIXME: Locking on tls
3168 if (tls->frames && tls->frames_up_to_date)
3171 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3173 user_data.tls = tls;
3174 user_data.frames = NULL;
3175 if (tls->terminated) {
3176 tls->frame_count = 0;
3178 } if (!tls->really_suspended && tls->async_state.valid) {
3179 /* Have to use the state saved by the signal handler */
3180 process_frame (&tls->async_last_frame, NULL, &user_data);
3181 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3182 } else if (tls->filter_state.valid) {
3184 * We are inside an exception filter.
3186 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3188 if (tls->context.valid)
3189 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3191 * After that, we resume unwinding from the location where the exception has been thrown.
3193 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3194 } else if (tls->context.valid) {
3195 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3198 tls->frame_count = 0;
3202 new_frame_count = g_slist_length (user_data.frames);
3203 new_frames = g_new0 (StackFrame*, new_frame_count);
3205 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3209 * Reuse the id for already existing stack frames, so invokes don't invalidate
3210 * the still valid stack frames.
3212 for (i = 0; i < tls->frame_count; ++i) {
3213 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3214 f->id = tls->frames [i]->id;
3219 if (i >= tls->frame_count)
3220 f->id = InterlockedIncrement (&frame_id);
3222 new_frames [findex ++] = f;
3225 g_slist_free (user_data.frames);
3227 invalidate_frames (tls);
3229 tls->frames = new_frames;
3230 tls->frame_count = new_frame_count;
3231 tls->frames_up_to_date = TRUE;
3235 * GHFunc to emit an appdomain creation event
3236 * @param key Don't care
3237 * @param value A loaded appdomain
3238 * @param user_data Don't care
3241 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3243 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3244 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3248 * GHFunc to emit a thread start event
3249 * @param key A thread id
3250 * @param value A thread object
3251 * @param user_data Don't care
3254 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3256 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3257 process_profiler_event (EVENT_KIND_THREAD_START, value);
3261 * GFunc to emit an assembly load event
3262 * @param value A loaded assembly
3263 * @param user_data Don't care
3266 emit_assembly_load (gpointer value, gpointer user_data)
3268 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3272 * GFunc to emit a type load event
3273 * @param value A loaded type
3274 * @param user_data Don't care
3277 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3279 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3283 strdup_tolower (char *s)
3288 for (p = s2; *p; ++p)
3294 * Same as g_path_get_basename () but handles windows paths as well,
3295 * which can occur in .mdb files created by pdb2mdb.
3298 dbg_path_get_basename (const char *filename)
3302 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3303 return g_path_get_basename (filename);
3307 /* No separator -> filename */
3308 r = strrchr (filename, '\\');
3310 return g_strdup (filename);
3312 /* Trailing slash, remove component */
3314 char *copy = g_strdup (filename);
3315 copy [r-filename] = 0;
3316 r = strrchr (copy, '\\');
3320 return g_strdup ("/");
3322 r = g_strdup (&r[1]);
3327 return g_strdup (&r[1]);
3331 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3333 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3334 MonoCustomAttrInfo *ainfo;
3336 if (ji->dbg_attrs_inited)
3339 if (!hidden_klass) {
3340 hidden_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3341 g_assert (hidden_klass);
3343 if (!step_through_klass) {
3344 step_through_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3345 g_assert (step_through_klass);
3347 if (!non_user_klass) {
3348 non_user_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3349 g_assert (non_user_klass);
3352 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3354 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3355 ji->dbg_hidden = TRUE;
3356 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3357 ji->dbg_step_through = TRUE;
3358 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3359 ji->dbg_non_user_code = TRUE;
3360 mono_custom_attrs_free (ainfo);
3363 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3365 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3366 ji->dbg_step_through = TRUE;
3367 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3368 ji->dbg_non_user_code = TRUE;
3369 mono_custom_attrs_free (ainfo);
3372 mono_memory_barrier ();
3373 ji->dbg_attrs_inited = TRUE;
3381 * create_event_list:
3383 * Return a list of event request ids matching EVENT, starting from REQS, which
3384 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3386 * We return request ids, instead of requests, to simplify threading, since
3387 * requests could be deleted anytime when the loader lock is not held.
3388 * LOCKING: Assumes the loader lock is held.
3391 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3394 GSList *events = NULL;
3396 *suspend_policy = SUSPEND_POLICY_NONE;
3399 reqs = event_requests;
3404 for (i = 0; i < reqs->len; ++i) {
3405 EventRequest *req = g_ptr_array_index (reqs, i);
3406 if (req->event_kind == event) {
3407 gboolean filtered = FALSE;
3410 for (j = 0; j < req->nmodifiers; ++j) {
3411 Modifier *mod = &req->modifiers [j];
3413 if (mod->kind == MOD_KIND_COUNT) {
3415 if (mod->data.count > 0) {
3416 if (mod->data.count > 0) {
3418 if (mod->data.count == 0)
3422 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3423 if (mod->data.thread != mono_thread_internal_current ())
3425 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3426 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3428 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3430 if (ei->caught && !mod->caught)
3432 if (!ei->caught && !mod->uncaught)
3434 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3436 gboolean found = FALSE;
3437 MonoAssembly **assemblies = mod->data.assemblies;
3440 for (k = 0; assemblies [k]; ++k)
3441 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3446 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3447 gpointer iter = NULL;
3449 MonoDebugSourceInfo *sinfo;
3450 char *source_file, *s;
3451 gboolean found = FALSE;
3453 GPtrArray *source_file_list;
3455 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3456 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3459 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3460 for (i = 0; i < source_file_list->len; ++i) {
3461 sinfo = g_ptr_array_index (source_file_list, i);
3463 * Do a case-insesitive match by converting the file name to
3466 s = strdup_tolower (sinfo->source_file);
3467 if (g_hash_table_lookup (mod->data.source_files, s))
3470 char *s2 = dbg_path_get_basename (sinfo->source_file);
3471 char *s3 = strdup_tolower (s2);
3473 if (g_hash_table_lookup (mod->data.source_files, s3))
3480 g_ptr_array_free (source_file_list, TRUE);
3485 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3488 s = mono_type_full_name (&ei->klass->byval_arg);
3489 if (!g_hash_table_lookup (mod->data.type_names, s))
3492 } else if (mod->kind == MOD_KIND_STEP) {
3493 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3494 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3495 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3496 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3498 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3499 init_jit_info_dbg_attrs (ji);
3503 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3504 init_jit_info_dbg_attrs (ji);
3505 if (ji->dbg_step_through)
3508 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3509 init_jit_info_dbg_attrs (ji);
3510 if (ji->dbg_non_user_code)
3517 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3518 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3523 /* Send a VM START/DEATH event by default */
3524 if (event == EVENT_KIND_VM_START)
3525 events = g_slist_append (events, GINT_TO_POINTER (0));
3526 if (event == EVENT_KIND_VM_DEATH)
3527 events = g_slist_append (events, GINT_TO_POINTER (0));
3532 static G_GNUC_UNUSED const char*
3533 event_to_string (EventKind event)
3536 case EVENT_KIND_VM_START: return "VM_START";
3537 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3538 case EVENT_KIND_THREAD_START: return "THREAD_START";
3539 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3540 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3541 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3542 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3543 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3544 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3545 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3546 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3547 case EVENT_KIND_STEP: return "STEP";
3548 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3549 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3550 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3551 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3552 case EVENT_KIND_USER_LOG: return "USER_LOG";
3554 g_assert_not_reached ();
3562 * Send an event to the client, suspending the vm if needed.
3563 * LOCKING: Since this can suspend the calling thread, no locks should be held
3565 * The EVENTS list is freed by this function.
3568 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3572 MonoDomain *domain = mono_domain_get ();
3573 MonoThread *thread = NULL;
3574 MonoObject *keepalive_obj = NULL;
3575 gboolean send_success = FALSE;
3580 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3584 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3585 // FIXME: We miss those events
3586 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3590 if (vm_death_event_sent) {
3591 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3595 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3596 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3601 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3605 if (event == EVENT_KIND_KEEPALIVE)
3606 suspend_policy = SUSPEND_POLICY_NONE;
3611 if (agent_config.defer) {
3612 /* Make sure the thread id is always set when doing deferred debugging */
3613 if (is_debugger_thread ()) {
3614 /* Don't suspend on events from the debugger thread */
3615 suspend_policy = SUSPEND_POLICY_NONE;
3616 thread = mono_thread_get_main ();
3618 else thread = mono_thread_current ();
3620 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3621 // FIXME: Send these with a NULL thread, don't suspend the current thread
3626 nevents = g_slist_length (events);
3627 buffer_init (&buf, 128);
3628 buffer_add_byte (&buf, suspend_policy);
3629 buffer_add_int (&buf, nevents);
3631 for (l = events; l; l = l->next) {
3632 buffer_add_byte (&buf, event); // event kind
3633 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3638 thread = mono_thread_current ();
3640 if (event == EVENT_KIND_VM_START && arg != NULL)
3643 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3646 case EVENT_KIND_THREAD_START:
3647 case EVENT_KIND_THREAD_DEATH:
3649 case EVENT_KIND_APPDOMAIN_CREATE:
3650 case EVENT_KIND_APPDOMAIN_UNLOAD:
3651 buffer_add_domainid (&buf, arg);
3653 case EVENT_KIND_METHOD_ENTRY:
3654 case EVENT_KIND_METHOD_EXIT:
3655 buffer_add_methodid (&buf, domain, arg);
3657 case EVENT_KIND_ASSEMBLY_LOAD:
3658 buffer_add_assemblyid (&buf, domain, arg);
3660 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3661 DebuggerTlsData *tls;
3663 /* The domain the assembly belonged to is not equal to the current domain */
3664 tls = mono_native_tls_get_value (debugger_tls_id);
3666 g_assert (tls->domain_unloading);
3668 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3671 case EVENT_KIND_TYPE_LOAD:
3672 buffer_add_typeid (&buf, domain, arg);
3674 case EVENT_KIND_BREAKPOINT:
3675 case EVENT_KIND_STEP:
3676 buffer_add_methodid (&buf, domain, arg);
3677 buffer_add_long (&buf, il_offset);
3679 case EVENT_KIND_VM_START:
3680 buffer_add_domainid (&buf, mono_get_root_domain ());
3682 case EVENT_KIND_VM_DEATH:
3683 if (CHECK_PROTOCOL_VERSION (2, 27))
3684 buffer_add_int (&buf, mono_environment_exitcode_get ());
3686 case EVENT_KIND_EXCEPTION: {
3687 EventInfo *ei = arg;
3688 buffer_add_objid (&buf, ei->exc);
3690 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3691 * later after the suspension. (#12494).
3693 keepalive_obj = ei->exc;
3696 case EVENT_KIND_USER_BREAK:
3698 case EVENT_KIND_USER_LOG: {
3699 EventInfo *ei = arg;
3700 buffer_add_int (&buf, ei->level);
3701 buffer_add_string (&buf, ei->category ? ei->category : "");
3702 buffer_add_string (&buf, ei->message ? ei->message : "");
3705 case EVENT_KIND_KEEPALIVE:
3706 suspend_policy = SUSPEND_POLICY_NONE;
3709 g_assert_not_reached ();
3713 if (event == EVENT_KIND_VM_START) {
3714 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3715 if (!agent_config.defer)
3716 start_debugger_thread ();
3719 if (event == EVENT_KIND_VM_DEATH) {
3720 vm_death_event_sent = TRUE;
3721 suspend_policy = SUSPEND_POLICY_NONE;
3724 if (mono_runtime_is_shutting_down ())
3725 suspend_policy = SUSPEND_POLICY_NONE;
3727 if (suspend_policy != SUSPEND_POLICY_NONE) {
3729 * Save the thread context and start suspending before sending the packet,
3730 * since we could be receiving the resume request before send_packet ()
3733 save_thread_context (ctx);
3737 /* This will keep this object alive */
3738 get_objref (keepalive_obj);
3741 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3745 g_slist_free (events);
3748 if (!send_success) {
3749 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3753 if (event == EVENT_KIND_VM_START) {
3754 vm_start_event_sent = TRUE;
3757 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)mono_native_thread_id_get (), nevents, event_to_string (event), ecount, suspend_policy);
3759 switch (suspend_policy) {
3760 case SUSPEND_POLICY_NONE:
3762 case SUSPEND_POLICY_ALL:
3765 case SUSPEND_POLICY_EVENT_THREAD:
3769 g_assert_not_reached ();
3774 process_profiler_event (EventKind event, gpointer arg)
3778 EventInfo ei, *ei_arg = NULL;
3780 if (event == EVENT_KIND_TYPE_LOAD) {
3785 mono_loader_lock ();
3786 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3787 mono_loader_unlock ();
3789 process_event (event, arg, 0, NULL, events, suspend_policy);
3793 runtime_initialized (MonoProfiler *prof)
3795 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3796 if (agent_config.defer)
3797 start_debugger_thread ();
3801 runtime_shutdown (MonoProfiler *prof)
3803 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3805 mono_debugger_agent_cleanup ();
3809 thread_startup (MonoProfiler *prof, uintptr_t tid)
3811 MonoInternalThread *thread = mono_thread_internal_current ();
3812 MonoInternalThread *old_thread;
3813 DebuggerTlsData *tls;
3815 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3818 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3820 mono_loader_lock ();
3821 old_thread = mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3822 mono_loader_unlock ();
3824 if (thread == old_thread) {
3826 * For some reason, thread_startup () might be called for the same thread
3827 * multiple times (attach ?).
3829 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3833 * thread_end () might not be called for some threads, and the tid could
3836 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3837 mono_loader_lock ();
3838 mono_g_hash_table_remove (thread_to_tls, old_thread);
3839 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3840 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3841 mono_loader_unlock ();
3845 tls = mono_native_tls_get_value (debugger_tls_id);
3847 // FIXME: Free this somewhere
3848 tls = g_new0 (DebuggerTlsData, 1);
3849 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3850 tls->thread = thread;
3851 mono_native_tls_set_value (debugger_tls_id, tls);
3853 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3855 mono_loader_lock ();
3856 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3857 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3858 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3859 mono_loader_unlock ();
3861 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3864 * suspend_vm () could have missed this thread, so wait for a resume.
3870 thread_end (MonoProfiler *prof, uintptr_t tid)
3872 MonoInternalThread *thread;
3873 DebuggerTlsData *tls = NULL;
3875 mono_loader_lock ();
3876 thread = mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3878 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3879 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3881 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3882 tls->terminated = TRUE;
3883 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3884 MONO_GC_UNREGISTER_ROOT (tls->thread);
3888 mono_loader_unlock ();
3890 /* We might be called for threads started before we registered the start callback */
3892 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3894 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3895 && !mono_native_tls_get_value (debugger_tls_id)
3898 * This can happen on darwin since we deregister threads using pthread dtors.
3899 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3904 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3909 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3911 mono_loader_lock ();
3912 g_hash_table_insert (domains, domain, domain);
3913 mono_loader_unlock ();
3915 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3919 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3921 DebuggerTlsData *tls;
3923 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3924 if (is_debugger_thread ())
3928 * Remember the currently unloading appdomain as it is needed to generate
3929 * proper ids for unloading assemblies.
3931 tls = mono_native_tls_get_value (debugger_tls_id);
3933 tls->domain_unloading = domain;
3937 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3939 DebuggerTlsData *tls;
3941 if (is_debugger_thread ())
3944 tls = mono_native_tls_get_value (debugger_tls_id);
3946 tls->domain_unloading = NULL;
3948 clear_breakpoints_for_domain (domain);
3950 mono_loader_lock ();
3951 /* Invalidate each thread's frame stack */
3952 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3953 mono_loader_unlock ();
3955 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3959 * invalidate_each_thread:
3961 * A GHFunc to invalidate frames.
3962 * value must be a DebuggerTlsData*
3965 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3967 invalidate_frames (value);
3971 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3973 /* Sent later in jit_end () */
3975 g_ptr_array_add (pending_assembly_loads, assembly);
3980 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3982 if (is_debugger_thread ())
3985 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3987 clear_event_requests_for_assembly (assembly);
3988 clear_types_for_assembly (assembly);
3992 send_type_load (MonoClass *klass)
3994 gboolean type_load = FALSE;
3995 MonoDomain *domain = mono_domain_get ();
3996 AgentDomainInfo *info = NULL;
3998 info = get_agent_domain_info (domain);
4000 mono_loader_lock ();
4002 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4004 g_hash_table_insert (info->loaded_classes, klass, klass);
4007 mono_loader_unlock ();
4010 emit_type_load (klass, klass, NULL);
4014 * Emit load events for all types currently loaded in the domain.
4015 * Takes the loader and domain locks.
4016 * user_data is unused.
4019 send_types_for_domain (MonoDomain *domain, void *user_data)
4021 AgentDomainInfo *info = NULL;
4023 info = get_agent_domain_info (domain);
4026 mono_loader_lock ();
4027 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4028 mono_loader_unlock ();
4032 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4035 * We emit type load events when the first method of the type is JITted,
4036 * since the class load profiler callbacks might be called with the
4037 * loader lock held. They could also occur in the debugger thread.
4038 * Same for assembly load events.
4041 MonoAssembly *assembly = NULL;
4043 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4045 if (pending_assembly_loads->len > 0) {
4046 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4047 g_ptr_array_remove_index (pending_assembly_loads, 0);
4052 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4058 send_type_load (method->klass);
4061 add_pending_breakpoints (method, jinfo);
4065 * BREAKPOINTS/SINGLE STEPPING
4069 * Contains information about an inserted breakpoint.
4072 long il_offset, native_offset;
4076 } BreakpointInstance;
4079 * Contains generic information about a breakpoint.
4083 * The method where the breakpoint is placed. Can be NULL in which case it
4084 * is inserted into every method. This is used to implement method entry/
4085 * exit events. Can be a generic method definition, in which case the
4086 * breakpoint is inserted into every instance.
4092 * A list of BreakpointInstance structures describing where the breakpoint
4093 * was inserted. There could be more than one because of
4094 * generics/appdomains/method entry/exit.
4096 GPtrArray *children;
4099 /* List of breakpoints */
4100 /* Protected by the loader lock */
4101 static GPtrArray *breakpoints;
4102 /* Maps breakpoint locations to the number of breakpoints at that location */
4103 static GHashTable *bp_locs;
4106 breakpoints_init (void)
4108 breakpoints = g_ptr_array_new ();
4109 bp_locs = g_hash_table_new (NULL, NULL);
4113 * insert_breakpoint:
4115 * Insert the breakpoint described by BP into the method described by
4119 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4122 BreakpointInstance *inst;
4123 SeqPointIterator it;
4124 gboolean it_has_sp = FALSE;
4127 mono_error_init (error);
4129 mono_seq_point_iterator_init (&it, seq_points);
4130 while (mono_seq_point_iterator_next (&it)) {
4131 if (it.seq_point.il_offset == bp->il_offset) {
4139 * The set of IL offsets with seq points doesn't completely match the
4140 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4142 mono_seq_point_iterator_init (&it, seq_points);
4143 while (mono_seq_point_iterator_next (&it)) {
4144 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4145 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4146 it.seq_point.il_offset + 1 == bp->il_offset) {
4154 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4156 mono_seq_point_iterator_init (&it, seq_points);
4157 while (mono_seq_point_iterator_next (&it))
4158 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4161 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4162 g_warning ("%s", s);
4166 g_warning ("%s", s);
4172 inst = g_new0 (BreakpointInstance, 1);
4173 inst->il_offset = it.seq_point.il_offset;
4174 inst->native_offset = it.seq_point.native_offset;
4175 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4177 inst->domain = domain;
4179 mono_loader_lock ();
4181 g_ptr_array_add (bp->children, inst);
4183 mono_loader_unlock ();
4186 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4187 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4190 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4191 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4192 } else if (count == 0) {
4193 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4194 mono_arch_set_breakpoint (ji, inst->ip);
4200 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);
4204 remove_breakpoint (BreakpointInstance *inst)
4206 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4208 MonoJitInfo *ji = inst->ji;
4209 guint8 *ip = inst->ip;
4212 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4213 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4216 g_assert (count > 0);
4218 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4219 mono_arch_clear_breakpoint (ji, ip);
4220 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4228 * This doesn't take any locks.
4230 static inline gboolean
4231 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4237 if (method == bp->method)
4239 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4242 if (bp->method->is_inflated && method->is_inflated) {
4243 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4244 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4246 /* Open generic methods should match closed generic methods of the same class */
4247 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4248 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4249 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4251 /* FIXME: Handle !mvar */
4252 if (t1->type != MONO_TYPE_MVAR)
4263 * add_pending_breakpoints:
4265 * Insert pending breakpoints into the newly JITted method METHOD.
4268 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4271 MonoSeqPointInfo *seq_points;
4273 MonoMethod *jmethod;
4278 domain = mono_domain_get ();
4280 mono_loader_lock ();
4282 for (i = 0; i < breakpoints->len; ++i) {
4283 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4284 gboolean found = FALSE;
4286 if (!bp_matches_method (bp, method))
4289 for (j = 0; j < bp->children->len; ++j) {
4290 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4297 MonoMethod *declaring = NULL;
4299 jmethod = jinfo_get_method (ji);
4300 if (jmethod->is_inflated)
4301 declaring = mono_method_get_declaring_generic_method (jmethod);
4303 mono_domain_lock (domain);
4304 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4305 if (!seq_points && declaring)
4306 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4307 mono_domain_unlock (domain);
4309 /* Could be AOT code */
4311 g_assert (seq_points);
4313 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4317 mono_loader_unlock ();
4321 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4327 mono_error_init (error);
4329 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4331 /* Might be AOTed code */
4332 code = mono_aot_get_method (domain, method);
4334 ji = mono_jit_info_table_find (domain, code);
4339 insert_breakpoint (seq_points, domain, ji, bp, error);
4343 clear_breakpoint (MonoBreakpoint *bp);
4348 * Set a breakpoint at IL_OFFSET in METHOD.
4349 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4350 * METHOD can also be a generic method definition, in which case a breakpoint
4351 * is placed in all instances of the method.
4352 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4355 static MonoBreakpoint*
4356 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4359 GHashTableIter iter, iter2;
4362 MonoSeqPointInfo *seq_points;
4364 GPtrArray *method_domains;
4365 GPtrArray *method_seq_points;
4369 mono_error_init (error);
4372 // - suspend/resume the vm to prevent code patching problems
4373 // - multiple breakpoints on the same location
4374 // - dynamic methods
4377 bp = g_new0 (MonoBreakpoint, 1);
4378 bp->method = method;
4379 bp->il_offset = il_offset;
4381 bp->children = g_ptr_array_new ();
4383 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);
4385 methods = g_ptr_array_new ();
4386 method_domains = g_ptr_array_new ();
4387 method_seq_points = g_ptr_array_new ();
4389 mono_loader_lock ();
4390 g_hash_table_iter_init (&iter, domains);
4391 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4392 mono_domain_lock (domain);
4393 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4394 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4395 if (bp_matches_method (bp, m)) {
4396 /* Save the info locally to simplify the code inside the domain lock */
4397 g_ptr_array_add (methods, m);
4398 g_ptr_array_add (method_domains, domain);
4399 g_ptr_array_add (method_seq_points, seq_points);
4402 mono_domain_unlock (domain);
4405 for (i = 0; i < methods->len; ++i) {
4406 m = g_ptr_array_index (methods, i);
4407 domain = g_ptr_array_index (method_domains, i);
4408 seq_points = g_ptr_array_index (method_seq_points, i);
4409 set_bp_in_method (domain, m, seq_points, bp, error);
4412 g_ptr_array_add (breakpoints, bp);
4413 mono_loader_unlock ();
4415 g_ptr_array_free (methods, TRUE);
4416 g_ptr_array_free (method_domains, TRUE);
4417 g_ptr_array_free (method_seq_points, TRUE);
4419 if (error && !mono_error_ok (error)) {
4420 clear_breakpoint (bp);
4428 clear_breakpoint (MonoBreakpoint *bp)
4432 // FIXME: locking, races
4433 for (i = 0; i < bp->children->len; ++i) {
4434 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4436 remove_breakpoint (inst);
4441 mono_loader_lock ();
4442 g_ptr_array_remove (breakpoints, bp);
4443 mono_loader_unlock ();
4445 g_ptr_array_free (bp->children, TRUE);
4450 breakpoints_cleanup (void)
4454 mono_loader_lock ();
4456 while (i < event_requests->len) {
4457 EventRequest *req = g_ptr_array_index (event_requests, i);
4459 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4460 clear_breakpoint (req->info);
4461 g_ptr_array_remove_index_fast (event_requests, i);
4468 for (i = 0; i < breakpoints->len; ++i)
4469 g_free (g_ptr_array_index (breakpoints, i));
4471 g_ptr_array_free (breakpoints, TRUE);
4472 g_hash_table_destroy (bp_locs);
4477 mono_loader_unlock ();
4481 * clear_breakpoints_for_domain:
4483 * Clear breakpoint instances which reference DOMAIN.
4486 clear_breakpoints_for_domain (MonoDomain *domain)
4490 /* This could be called after shutdown */
4494 mono_loader_lock ();
4495 for (i = 0; i < breakpoints->len; ++i) {
4496 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4499 while (j < bp->children->len) {
4500 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4502 if (inst->domain == domain) {
4503 remove_breakpoint (inst);
4507 g_ptr_array_remove_index_fast (bp->children, j);
4513 mono_loader_unlock ();
4519 * Return FALSE if single stepping needs to continue.
4522 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4524 MonoDebugMethodInfo *minfo;
4525 MonoDebugSourceLocation *loc = NULL;
4526 gboolean hit = TRUE;
4529 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4531 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4533 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)mono_native_thread_id_get (), sp->il_offset);
4537 if (req->depth == STEP_DEPTH_OVER && hit) {
4538 if (!tls->context.valid)
4539 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4540 compute_frame_info (tls->thread, tls);
4541 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4542 /* Hit the breakpoint in a recursive call */
4543 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)mono_native_thread_id_get ());
4548 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4549 method = jinfo_get_method (ji);
4550 if (!tls->context.valid)
4551 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4552 compute_frame_info (tls->thread, tls);
4553 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4554 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer)mono_native_thread_id_get (), sp->il_offset);
4559 if (req->size != STEP_SIZE_LINE)
4562 /* Have to check whenever a different source line was reached */
4563 method = jinfo_get_method (ji);
4564 minfo = mono_debug_lookup_method (method);
4567 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4570 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)mono_native_thread_id_get (), sp->il_offset);
4571 ss_req->last_method = method;
4573 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4574 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)mono_native_thread_id_get (), loc->row);
4579 ss_req->last_method = method;
4580 ss_req->last_line = loc->row;
4581 mono_debug_free_source_location (loc);
4588 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4590 return bp->method && bp->method->klass->image->assembly == assembly;
4594 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4598 int i, j, suspend_policy;
4599 guint32 native_offset;
4601 BreakpointInstance *inst;
4602 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4603 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4604 EventKind kind = EVENT_KIND_BREAKPOINT;
4605 MonoContext *ctx = &tls->restore_state.ctx;
4607 MonoSeqPointInfo *info;
4611 // FIXME: Speed this up
4613 ip = MONO_CONTEXT_GET_IP (ctx);
4614 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4615 g_assert (ji && !ji->is_trampoline);
4616 method = jinfo_get_method (ji);
4618 /* Compute the native offset of the breakpoint from the ip */
4619 native_offset = ip - (guint8*)ji->code_start;
4622 * Skip the instruction causing the breakpoint signal.
4625 mono_arch_skip_breakpoint (ctx, ji);
4627 if (method->wrapper_type || tls->disable_breakpoints)
4630 bp_reqs = g_ptr_array_new ();
4631 ss_reqs = g_ptr_array_new ();
4632 ss_reqs_orig = g_ptr_array_new ();
4634 mono_loader_lock ();
4637 * The ip points to the instruction causing the breakpoint event, which is after
4638 * the offset recorded in the seq point map, so find the prev seq point before ip.
4640 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4643 no_seq_points_found (method, native_offset);
4645 g_assert (found_sp);
4647 DEBUG_PRINTF (1, "[%p] Breakpoint hit, method=%s, ip=%p, [il=0x%x,native=0x%x].\n", (gpointer)mono_native_thread_id_get (), method->name, ip, sp.il_offset, native_offset);
4650 for (i = 0; i < breakpoints->len; ++i) {
4651 bp = g_ptr_array_index (breakpoints, i);
4656 for (j = 0; j < bp->children->len; ++j) {
4657 inst = g_ptr_array_index (bp->children, j);
4658 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4659 if (bp->req->event_kind == EVENT_KIND_STEP) {
4660 g_ptr_array_add (ss_reqs_orig, bp->req);
4662 g_ptr_array_add (bp_reqs, bp->req);
4667 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4668 /* Maybe a method entry/exit event */
4669 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4670 kind = EVENT_KIND_METHOD_ENTRY;
4671 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4672 kind = EVENT_KIND_METHOD_EXIT;
4675 /* Process single step requests */
4676 for (i = 0; i < ss_reqs_orig->len; ++i) {
4677 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4678 SingleStepReq *ss_req = req->info;
4681 if (mono_thread_internal_current () != ss_req->thread)
4684 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4686 g_ptr_array_add (ss_reqs, req);
4688 /* Start single stepping again from the current sequence point */
4689 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4692 if (ss_reqs->len > 0)
4693 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4694 if (bp_reqs->len > 0)
4695 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4696 if (kind != EVENT_KIND_BREAKPOINT)
4697 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4699 mono_loader_unlock ();
4701 g_ptr_array_free (bp_reqs, TRUE);
4702 g_ptr_array_free (ss_reqs, TRUE);
4705 * FIXME: The first event will suspend, so the second will only be sent after the
4709 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4711 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4712 if (enter_leave_events)
4713 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4716 /* Process a breakpoint/single step event after resuming from a signal handler */
4718 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4720 DebuggerTlsData *tls;
4721 MonoThreadUnwindState orig_restore_state;
4724 tls = mono_native_tls_get_value (debugger_tls_id);
4725 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4726 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4727 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4731 /* This is called when resuming from a signal handler, so it shouldn't return */
4732 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4733 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4734 mono_restore_context (&ctx);
4735 g_assert_not_reached ();
4739 process_breakpoint (void)
4741 process_signal_event (process_breakpoint_inner);
4745 resume_from_signal_handler (void *sigctx, void *func)
4747 DebuggerTlsData *tls;
4750 /* Save the original context in TLS */
4751 // FIXME: This might not work on an altstack ?
4752 tls = mono_native_tls_get_value (debugger_tls_id);
4754 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)mono_native_thread_id_get ());
4757 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4758 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4759 // clob:c could be added to op_seq_point.
4761 mono_sigctx_to_monoctx (sigctx, &ctx);
4762 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4763 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4764 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4766 MONO_CONTEXT_SET_IP (&ctx, func);
4768 mono_monoctx_to_sigctx (&ctx, sigctx);
4770 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4771 mono_ppc_set_func_into_sigctx (sigctx, func);
4776 mono_debugger_agent_breakpoint_hit (void *sigctx)
4779 * We are called from a signal handler, and running code there causes all kinds of
4780 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4781 * So set up the signal context to return to the real breakpoint handler function.
4783 resume_from_signal_handler (sigctx, process_breakpoint);
4787 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4789 if (frame->managed) {
4790 *(MonoContext*)data = *ctx;
4799 * Called by System.Diagnostics.Debugger:Break ().
4802 mono_debugger_agent_user_break (void)
4804 if (agent_config.enabled) {
4809 /* Obtain a context */
4810 MONO_CONTEXT_SET_IP (&ctx, NULL);
4811 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4812 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4814 mono_loader_lock ();
4815 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4816 mono_loader_unlock ();
4818 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4819 } else if (debug_options.native_debugger_break) {
4825 ss_depth_to_string (StepDepth depth)
4828 case STEP_DEPTH_OVER:
4830 case STEP_DEPTH_OUT:
4832 case STEP_DEPTH_INTO:
4835 g_assert_not_reached ();
4841 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4846 int il_offset, suspend_policy;
4849 MonoContext *ctx = &tls->restore_state.ctx;
4852 MonoSeqPointInfo *info;
4854 ip = MONO_CONTEXT_GET_IP (ctx);
4856 /* Skip the instruction causing the single step */
4858 mono_arch_skip_single_step (ctx);
4860 if (suspend_count > 0) {
4861 /* Fastpath during invokes, see in process_suspend () */
4862 if (suspend_count - tls->resume_count == 0)
4864 process_suspend (tls, ctx);
4869 // FIXME: A suspend race
4872 if (mono_thread_internal_current () != ss_req->thread)
4875 if (log_level > 0) {
4876 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4878 DEBUG_PRINTF (1, "[%p] Single step event (depth=%s) at %s (%p)[0x%x], sp %p, last sp %p\n", (gpointer)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);
4881 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4882 g_assert (ji && !ji->is_trampoline);
4883 method = jinfo_get_method (ji);
4886 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4891 * Stopping in memset makes half-initialized vtypes visible.
4892 * Stopping in memcpy makes half-copied vtypes visible.
4894 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4898 * The ip points to the instruction causing the single step event, which is before
4899 * the offset recorded in the seq point map, so find the next seq point after ip.
4901 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4904 il_offset = sp.il_offset;
4906 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4909 /* Start single stepping again from the current sequence point */
4910 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4912 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4913 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4914 !strcmp (method->name, ".cctor"))
4917 // FIXME: Has to lock earlier
4919 reqs = g_ptr_array_new ();
4921 mono_loader_lock ();
4923 g_ptr_array_add (reqs, ss_req->req);
4925 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4927 g_ptr_array_free (reqs, TRUE);
4929 mono_loader_unlock ();
4931 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4935 process_single_step (void)
4937 process_signal_event (process_single_step_inner);
4941 * mono_debugger_agent_single_step_event:
4943 * Called from a signal handler to handle a single step event.
4946 mono_debugger_agent_single_step_event (void *sigctx)
4948 /* Resume to process_single_step through the signal context */
4950 // FIXME: Since step out/over is implemented using step in, the step in case should
4951 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4954 if (is_debugger_thread ()) {
4956 * This could happen despite our best effors when the runtime calls
4957 * assembly/type resolve hooks.
4958 * FIXME: Breakpoints too.
4962 mono_sigctx_to_monoctx (sigctx, &ctx);
4963 mono_arch_skip_single_step (&ctx);
4964 mono_monoctx_to_sigctx (&ctx, sigctx);
4968 resume_from_signal_handler (sigctx, process_single_step);
4972 debugger_agent_single_step_from_context (MonoContext *ctx)
4974 DebuggerTlsData *tls;
4975 MonoThreadUnwindState orig_restore_state;
4977 tls = mono_native_tls_get_value (debugger_tls_id);
4978 /* Fastpath during invokes, see in process_suspend () */
4979 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4982 if (is_debugger_thread ())
4987 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4988 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4989 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4990 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4992 process_single_step_inner (tls, FALSE);
4994 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4995 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4999 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5001 DebuggerTlsData *tls;
5002 MonoThreadUnwindState orig_restore_state;
5005 if (is_debugger_thread ())
5008 orig_ip = MONO_CONTEXT_GET_IP (ctx);
5009 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5011 tls = mono_native_tls_get_value (debugger_tls_id);
5013 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5014 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5015 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5017 process_breakpoint_inner (tls, FALSE);
5019 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5020 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5021 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5022 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5026 * start_single_stepping:
5028 * Turn on single stepping. Can be called multiple times, for example,
5029 * by a single step event request + a suspend.
5032 start_single_stepping (void)
5034 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5035 int val = InterlockedIncrement (&ss_count);
5038 mono_arch_start_single_stepping ();
5040 g_assert_not_reached ();
5045 stop_single_stepping (void)
5047 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5048 int val = InterlockedDecrement (&ss_count);
5051 mono_arch_stop_single_stepping ();
5053 g_assert_not_reached ();
5060 * Stop the single stepping operation given by SS_REQ.
5063 ss_stop (SingleStepReq *ss_req)
5068 for (l = ss_req->bps; l; l = l->next) {
5069 clear_breakpoint (l->data);
5071 g_slist_free (ss_req->bps);
5075 if (ss_req->global) {
5076 stop_single_stepping ();
5077 ss_req->global = FALSE;
5084 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5085 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5086 * belong to the same thread as CTX.
5087 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5090 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5091 gboolean step_to_catch, StackFrame **frames, int nframes)
5093 int i, j, frame_index;
5094 SeqPoint *next_sp, *parent_sp = NULL;
5095 SeqPoint local_sp, local_parent_sp;
5098 MonoSeqPointInfo *parent_info;
5099 MonoMethod *parent_sp_method = NULL;
5100 gboolean enable_global = FALSE;
5102 /* Stop the previous operation */
5106 * Implement single stepping using breakpoints if possible.
5108 if (step_to_catch) {
5109 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5110 ss_req->bps = g_slist_append (ss_req->bps, bp);
5114 if (ctx && !frames) {
5115 /* Need parent frames */
5116 if (!tls->context.valid)
5117 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5118 compute_frame_info (tls->thread, tls);
5119 frames = tls->frames;
5120 nframes = tls->frame_count;
5124 * Find the first sequence point in the current or in a previous frame which
5125 * is not the last in its method.
5127 if (ss_req->depth == STEP_DEPTH_OUT) {
5128 /* Ignore seq points in current method */
5129 while (frame_index < nframes) {
5130 StackFrame *frame = frames [frame_index];
5132 method = frame->method;
5133 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5134 sp = (found_sp)? &local_sp : NULL;
5136 if (sp && sp->next_len != 0)
5139 // There could be method calls before the next seq point in the caller when using nested calls
5140 //enable_global = TRUE;
5142 if (sp && sp->next_len == 0) {
5144 while (frame_index < nframes) {
5145 StackFrame *frame = frames [frame_index];
5147 method = frame->method;
5148 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5149 sp = (found_sp)? &local_sp : NULL;
5150 if (sp && sp->next_len != 0)
5156 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5157 while (frame_index < nframes) {
5158 StackFrame *frame = frames [frame_index];
5160 parent_sp_method = frame->method;
5161 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5162 parent_sp = found_sp ? &local_parent_sp : NULL;
5163 if (found_sp && parent_sp->next_len != 0)
5171 if (sp && sp->next_len > 0) {
5172 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5174 mono_seq_point_init_next (info, *sp, next);
5175 for (i = 0; i < sp->next_len; i++) {
5178 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5179 ss_req->bps = g_slist_append (ss_req->bps, bp);
5185 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5187 mono_seq_point_init_next (parent_info, *parent_sp, next);
5188 for (i = 0; i < parent_sp->next_len; i++) {
5191 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5192 ss_req->bps = g_slist_append (ss_req->bps, bp);
5197 if (ss_req->nframes == 0)
5198 ss_req->nframes = nframes;
5200 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5201 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5203 * This is needed since if we leave managed code, and later return to it, step over
5204 * is not going to stop.
5205 * This approach is a bit ugly, since we change the step depth, but it only affects
5206 * clients who reuse the same step request, and only in this special case.
5208 ss_req->depth = STEP_DEPTH_INTO;
5211 if (ss_req->depth == STEP_DEPTH_OVER) {
5212 /* Need to stop in catch clauses as well */
5213 for (i = 0; i < nframes; ++i) {
5214 StackFrame *frame = frames [i];
5217 MonoJitInfo *jinfo = frame->ji;
5218 for (j = 0; j < jinfo->num_clauses; ++j) {
5219 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5221 found_sp = mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp);
5222 sp = (found_sp)? &local_sp : NULL;
5224 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5225 ss_req->bps = g_slist_append (ss_req->bps, bp);
5232 if (ss_req->depth == STEP_DEPTH_INTO) {
5233 /* Enable global stepping so we stop at method entry too */
5234 enable_global = TRUE;
5238 * The ctx/frame info computed above will become invalid when we continue.
5240 tls->context.valid = FALSE;
5241 tls->async_state.valid = FALSE;
5242 invalidate_frames (tls);
5245 if (enable_global) {
5246 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5247 ss_req->global = TRUE;
5248 start_single_stepping ();
5249 } else if (!ss_req->bps) {
5250 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5251 ss_req->global = TRUE;
5252 start_single_stepping ();
5254 ss_req->global = FALSE;
5259 * Start single stepping of thread THREAD
5262 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5264 DebuggerTlsData *tls;
5265 MonoSeqPointInfo *info = NULL;
5266 SeqPoint *sp = NULL;
5269 MonoMethod *method = NULL;
5270 MonoDebugMethodInfo *minfo;
5271 gboolean step_to_catch = FALSE;
5272 gboolean set_ip = FALSE;
5273 StackFrame **frames = NULL;
5276 if (suspend_count == 0)
5277 return ERR_NOT_SUSPENDED;
5279 wait_for_suspend ();
5281 // FIXME: Multiple requests
5283 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5284 return ERR_NOT_IMPLEMENTED;
5287 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5289 ss_req = g_new0 (SingleStepReq, 1);
5291 ss_req->thread = thread;
5292 ss_req->size = size;
5293 ss_req->depth = depth;
5294 ss_req->filter = filter;
5297 mono_loader_lock ();
5298 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5299 mono_loader_unlock ();
5301 g_assert (tls->context.valid);
5303 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5305 * Need to start single stepping from restore_state and not from the current state
5308 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5311 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5313 if (tls->catch_state.valid) {
5315 StackFrameInfo frame;
5316 MonoContext new_ctx;
5317 MonoLMF *lmf = NULL;
5320 * We are stopped at a throw site. Stepping should go to the catch site.
5323 /* Find the the jit info for the catch context */
5324 res = mono_find_jit_info_ext (tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], ((MonoThreadInfo*)thread->thread_info)->jit_data, NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5326 g_assert (frame.type == FRAME_TYPE_MANAGED);
5329 * Find the seq point corresponding to the landing site ip, which is the first seq
5332 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5333 sp = (found_sp)? &local_sp : NULL;
5335 no_seq_points_found (frame.method, frame.native_offset);
5338 method = frame.method;
5340 step_to_catch = TRUE;
5341 /* This make sure the seq point is not skipped by process_single_step () */
5342 ss_req->last_sp = NULL;
5345 if (!step_to_catch) {
5346 StackFrame *frame = NULL;
5349 if (frames && nframes)
5352 compute_frame_info (thread, tls);
5354 if (tls->frame_count)
5355 frame = tls->frames [0];
5358 if (ss_req->size == STEP_SIZE_LINE) {
5360 ss_req->last_method = frame->method;
5361 ss_req->last_line = -1;
5363 minfo = mono_debug_lookup_method (frame->method);
5364 if (minfo && frame->il_offset != -1) {
5365 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5368 ss_req->last_line = loc->row;
5376 if (!method && frame->il_offset != -1) {
5377 /* FIXME: Sort the table and use a binary search */
5378 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5379 sp = (found_sp)? &local_sp : NULL;
5381 no_seq_points_found (frame->method, frame->native_offset);
5383 method = frame->method;
5388 ss_req->start_method = method;
5390 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5393 free_frames (frames, nframes);
5399 ss_destroy (SingleStepReq *req)
5402 g_assert (ss_req == req);
5411 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5414 gboolean found = TRUE;
5418 for (l = ss_req->bps; l; l = l->next) {
5419 if (breakpoint_matches_assembly (l->data, assembly)) {
5420 clear_breakpoint (l->data);
5421 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5430 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5433 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5439 if (!agent_config.enabled)
5442 mono_loader_lock ();
5443 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5444 mono_loader_unlock ();
5447 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5448 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5450 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5452 g_free (ei.category);
5453 g_free (ei.message);
5457 mono_debugger_agent_debug_log_is_enabled (void)
5459 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5460 return agent_config.enabled;
5463 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5465 mono_debugger_agent_unhandled_exception (MonoException *exc)
5474 memset (&ei, 0, sizeof (EventInfo));
5475 ei.exc = (MonoObject*)exc;
5477 mono_loader_lock ();
5478 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5479 mono_loader_unlock ();
5481 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5486 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5487 MonoContext *catch_ctx)
5489 int i, j, suspend_policy;
5491 MonoJitInfo *ji, *catch_ji;
5493 DebuggerTlsData *tls = NULL;
5495 if (thread_to_tls != NULL) {
5496 MonoInternalThread *thread = mono_thread_internal_current ();
5498 mono_loader_lock ();
5499 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5500 mono_loader_unlock ();
5502 if (tls && tls->abort_requested)
5504 if (tls && tls->disable_breakpoints)
5508 memset (&ei, 0, sizeof (EventInfo));
5510 /* Just-In-Time debugging */
5512 if (agent_config.onuncaught && !inited) {
5513 finish_agent_init (FALSE);
5516 * Send an unsolicited EXCEPTION event with a dummy request id.
5518 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5519 ei.exc = (MonoObject*)exc;
5520 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5523 } else if (agent_config.onthrow && !inited) {
5525 gboolean found = FALSE;
5527 for (l = agent_config.onthrow; l; l = l->next) {
5528 char *ex_type = l->data;
5529 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5531 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5538 finish_agent_init (FALSE);
5541 * Send an unsolicited EXCEPTION event with a dummy request id.
5543 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5544 ei.exc = (MonoObject*)exc;
5545 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5553 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5555 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5559 ei.exc = (MonoObject*)exc;
5560 ei.caught = catch_ctx != NULL;
5562 mono_loader_lock ();
5564 /* Treat exceptions which are caught in non-user code as unhandled */
5565 for (i = 0; i < event_requests->len; ++i) {
5566 EventRequest *req = g_ptr_array_index (event_requests, i);
5567 if (req->event_kind != EVENT_KIND_EXCEPTION)
5570 for (j = 0; j < req->nmodifiers; ++j) {
5571 Modifier *mod = &req->modifiers [j];
5573 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5575 gboolean found = FALSE;
5576 MonoAssembly **assemblies = mod->data.assemblies;
5579 for (k = 0; assemblies [k]; ++k)
5580 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5589 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5590 mono_loader_unlock ();
5592 if (tls && ei.caught && catch_ctx) {
5593 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5594 tls->catch_state.ctx = *catch_ctx;
5595 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5596 tls->catch_state.valid = TRUE;
5599 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5602 tls->catch_state.valid = FALSE;
5606 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5608 DebuggerTlsData *tls;
5613 tls = mono_native_tls_get_value (debugger_tls_id);
5618 * We're about to invoke an exception filter during the first pass of exception handling.
5620 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5621 * 'orig_ctx' is the context where the exception has been thrown.
5624 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5626 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5627 * the call site (line 37) and then continue to Main(), but it would never
5628 * include the throw site (line 32).
5630 * Since exception filters are invoked during the first pass of exception handling,
5631 * the stack frames of the throw site are still intact, so we should include them
5634 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5636 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5637 * but report the location of the 'throw' to the user.
5641 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5645 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5647 DebuggerTlsData *tls;
5652 tls = mono_native_tls_get_value (debugger_tls_id);
5656 tls->filter_state.valid = FALSE;
5660 * buffer_add_value_full:
5662 * Add the encoding of the value at ADDR described by T to the buffer.
5663 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5667 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5668 gboolean as_vtype, GHashTable *parent_vtypes)
5671 gboolean boxed_vtype = FALSE;
5674 if (!(*(void**)addr)) {
5675 /* This can happen with compiler generated locals */
5676 //printf ("%s\n", mono_type_full_name (t));
5677 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5680 g_assert (*(void**)addr);
5681 addr = *(void**)addr;
5686 case MONO_TYPE_BOOLEAN:
5689 case MONO_TYPE_CHAR:
5709 case MONO_TYPE_VOID:
5710 buffer_add_byte (buf, t->type);
5712 case MONO_TYPE_BOOLEAN:
5715 buffer_add_byte (buf, t->type);
5716 buffer_add_int (buf, *(gint8*)addr);
5718 case MONO_TYPE_CHAR:
5721 buffer_add_byte (buf, t->type);
5722 buffer_add_int (buf, *(gint16*)addr);
5727 buffer_add_byte (buf, t->type);
5728 buffer_add_int (buf, *(gint32*)addr);
5733 buffer_add_byte (buf, t->type);
5734 buffer_add_long (buf, *(gint64*)addr);
5738 /* Treat it as a vtype */
5740 case MONO_TYPE_PTR: {
5741 gssize val = *(gssize*)addr;
5743 buffer_add_byte (buf, t->type);
5744 buffer_add_long (buf, val);
5748 case MONO_TYPE_STRING:
5749 case MONO_TYPE_SZARRAY:
5750 case MONO_TYPE_OBJECT:
5751 case MONO_TYPE_CLASS:
5752 case MONO_TYPE_ARRAY:
5753 obj = *(MonoObject**)addr;
5756 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5758 if (obj->vtable->klass->valuetype) {
5759 t = &obj->vtable->klass->byval_arg;
5760 addr = mono_object_unbox (obj);
5763 } else if (obj->vtable->klass->rank) {
5764 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5765 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5766 buffer_add_byte (buf, MONO_TYPE_CLASS);
5768 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5770 buffer_add_objid (buf, obj);
5774 case MONO_TYPE_VALUETYPE:
5775 case MONO_TYPE_TYPEDBYREF: {
5779 MonoClass *klass = mono_class_from_mono_type (t);
5784 * Handle boxed vtypes recursively referencing themselves using fields.
5787 parent_vtypes = g_hash_table_new (NULL, NULL);
5788 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5790 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5791 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5792 buffer_add_int (buf, vtype_index - 1);
5794 /* The client can't handle PARENT_VTYPE */
5795 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5799 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5803 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5804 buffer_add_byte (buf, klass->enumtype);
5805 buffer_add_typeid (buf, domain, klass);
5809 while ((f = mono_class_get_fields (klass, &iter))) {
5810 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5812 if (mono_field_is_deleted (f))
5816 buffer_add_int (buf, nfields);
5819 while ((f = mono_class_get_fields (klass, &iter))) {
5820 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5822 if (mono_field_is_deleted (f))
5824 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5828 g_hash_table_remove (parent_vtypes, addr);
5829 if (g_hash_table_size (parent_vtypes) == 0) {
5830 g_hash_table_destroy (parent_vtypes);
5831 parent_vtypes = NULL;
5836 case MONO_TYPE_GENERICINST:
5837 if (mono_type_generic_inst_is_valuetype (t)) {
5849 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5851 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5855 obj_is_of_type (MonoObject *obj, MonoType *t)
5857 MonoClass *klass = obj->vtable->klass;
5858 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5859 if (mono_class_is_transparent_proxy (klass)) {
5860 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5861 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5871 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5874 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5880 gpointer iter = NULL;
5884 is_enum = decode_byte (buf, &buf, limit);
5885 /* Enums are sent as a normal vtype */
5887 return ERR_NOT_IMPLEMENTED;
5888 klass = decode_typeid (buf, &buf, limit, &d, &err);
5892 if (t && klass != mono_class_from_mono_type (t)) {
5893 char *name = mono_type_full_name (t);
5894 char *name2 = mono_type_full_name (&klass->byval_arg);
5895 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer)mono_native_thread_id_get (), name, name2);
5898 return ERR_INVALID_ARGUMENT;
5901 nfields = decode_int (buf, &buf, limit);
5902 while ((f = mono_class_get_fields (klass, &iter))) {
5903 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5905 if (mono_field_is_deleted (f))
5907 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5912 g_assert (nfields == 0);
5920 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5924 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5925 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5926 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5927 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5928 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5929 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5930 char *name = mono_type_full_name (t);
5931 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)mono_native_thread_id_get (), name, type);
5933 return ERR_INVALID_ARGUMENT;
5937 case MONO_TYPE_BOOLEAN:
5938 *(guint8*)addr = decode_int (buf, &buf, limit);
5940 case MONO_TYPE_CHAR:
5941 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5944 *(gint8*)addr = decode_int (buf, &buf, limit);
5947 *(guint8*)addr = decode_int (buf, &buf, limit);
5950 *(gint16*)addr = decode_int (buf, &buf, limit);
5953 *(guint16*)addr = decode_int (buf, &buf, limit);
5956 *(gint32*)addr = decode_int (buf, &buf, limit);
5959 *(guint32*)addr = decode_int (buf, &buf, limit);
5962 *(gint64*)addr = decode_long (buf, &buf, limit);
5965 *(guint64*)addr = decode_long (buf, &buf, limit);
5968 *(guint32*)addr = decode_int (buf, &buf, limit);
5971 *(guint64*)addr = decode_long (buf, &buf, limit);
5974 /* We send these as I8, so we get them back as such */
5975 g_assert (type == MONO_TYPE_I8);
5976 *(gssize*)addr = decode_long (buf, &buf, limit);
5978 case MONO_TYPE_GENERICINST:
5979 if (MONO_TYPE_ISSTRUCT (t)) {
5980 /* The client sends these as a valuetype */
5988 /* We send these as vtypes, so we get them back as such */
5989 g_assert (type == MONO_TYPE_VALUETYPE);
5992 case MONO_TYPE_VALUETYPE:
5993 if (type == MONO_TYPE_OBJECT) {
5995 int objid = decode_objid (buf, &buf, limit);
5999 err = get_object (objid, (MonoObject**)&obj);
6003 return ERR_INVALID_ARGUMENT;
6004 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6005 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6006 return ERR_INVALID_ARGUMENT;
6008 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6010 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6017 if (MONO_TYPE_IS_REFERENCE (t)) {
6018 if (type == MONO_TYPE_OBJECT) {
6019 int objid = decode_objid (buf, &buf, limit);
6023 err = get_object (objid, (MonoObject**)&obj);
6028 if (!obj_is_of_type (obj, t)) {
6029 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6030 return ERR_INVALID_ARGUMENT;
6033 if (obj && obj->vtable->domain != domain)
6034 return ERR_INVALID_ARGUMENT;
6036 mono_gc_wbarrier_generic_store (addr, obj);
6037 } else if (type == VALUE_TYPE_ID_NULL) {
6038 *(MonoObject**)addr = NULL;
6039 } else if (type == MONO_TYPE_VALUETYPE) {
6047 /* This can happen when round-tripping boxed vtypes */
6049 * Obtain vtype class.
6050 * Same as the beginning of the handle_vtype case above.
6053 is_enum = decode_byte (buf, &buf, limit);
6055 return ERR_NOT_IMPLEMENTED;
6056 klass = decode_typeid (buf, &buf, limit, &d, &err);
6060 /* Decode the vtype into a temporary buffer, then box it. */
6061 vtype_buf_size = mono_class_value_size (klass, NULL);
6062 vtype_buf = g_malloc0 (vtype_buf_size);
6063 g_assert (vtype_buf);
6066 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6071 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6074 char *name = mono_type_full_name (t);
6075 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)mono_native_thread_id_get (), name, type);
6077 return ERR_INVALID_ARGUMENT;
6091 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6094 int type = decode_byte (buf, &buf, limit);
6096 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6097 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6098 guint8 *nullable_buf;
6101 * First try decoding it as a Nullable`1
6103 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6108 * Then try decoding as a primitive value or null.
6110 if (targ->type == type) {
6111 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6112 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6114 g_free (nullable_buf);
6117 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6118 g_free (nullable_buf);
6121 } else if (type == VALUE_TYPE_ID_NULL) {
6122 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6128 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6132 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6136 guint8 *addr, *gaddr;
6139 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6140 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6143 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6144 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6146 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6148 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6149 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6150 addr += (gint32)var->offset;
6152 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6154 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6156 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6159 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6160 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6161 /* Same as regoffset, but with an indirection */
6162 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6163 addr += (gint32)var->offset;
6165 gaddr = *(gpointer*)addr;
6167 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6169 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6170 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6171 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6172 MonoGSharedVtMethodRuntimeInfo *info;
6178 g_assert (info_var);
6179 g_assert (locals_var);
6181 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6182 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6183 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6184 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6185 addr += (gint32)info_var->offset;
6186 info = *(gpointer*)addr;
6187 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6188 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6190 g_assert_not_reached ();
6194 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6195 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6196 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6197 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6198 addr += (gint32)locals_var->offset;
6199 locals = *(gpointer*)addr;
6200 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6201 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6203 g_assert_not_reached ();
6207 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6209 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6214 g_assert_not_reached ();
6219 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6223 guint8 *addr, *gaddr;
6225 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6226 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6228 if (MONO_TYPE_IS_REFERENCE (t))
6229 size = sizeof (gpointer);
6231 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6234 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6235 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6237 gboolean is_signed = FALSE;
6240 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6243 // FIXME: Write barriers
6244 mono_gc_memmove_atomic (addr, val, size);
6249 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6254 v = is_signed ? *(gint8*)val : *(guint8*)val;
6257 v = is_signed ? *(gint16*)val : *(guint16*)val;
6260 v = is_signed ? *(gint32*)val : *(guint32*)val;
6263 v = is_signed ? *(gint64*)val : *(guint64*)val;
6266 g_assert_not_reached ();
6269 /* Set value on the stack or in the return ctx */
6270 if (reg_locations [reg]) {
6271 /* Saved on the stack */
6272 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6273 *(reg_locations [reg]) = v;
6276 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6277 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6280 // FIXME: Move these to mono-context.h/c.
6281 mono_arch_context_set_int_reg (ctx, reg, v);
6283 // FIXME: Can't set registers, so we disable linears
6288 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6289 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6290 addr += (gint32)var->offset;
6292 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6295 addr = *(guint8**)addr;
6301 // FIXME: Write barriers
6302 mono_gc_memmove_atomic (addr, val, size);
6304 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6305 /* Same as regoffset, but with an indirection */
6306 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6307 addr += (gint32)var->offset;
6309 gaddr = *(gpointer*)addr;
6311 // FIXME: Write barriers
6312 mono_gc_memmove_atomic (gaddr, val, size);
6314 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6318 g_assert_not_reached ();
6323 clear_event_request (int req_id, int etype)
6327 mono_loader_lock ();
6328 for (i = 0; i < event_requests->len; ++i) {
6329 EventRequest *req = g_ptr_array_index (event_requests, i);
6331 if (req->id == req_id && req->event_kind == etype) {
6332 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6333 clear_breakpoint (req->info);
6334 if (req->event_kind == EVENT_KIND_STEP)
6335 ss_destroy (req->info);
6336 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6337 clear_breakpoint (req->info);
6338 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6339 clear_breakpoint (req->info);
6340 g_ptr_array_remove_index_fast (event_requests, i);
6345 mono_loader_unlock ();
6349 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6353 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6354 m->kind = MOD_KIND_NONE;
6355 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6356 int count = 0, match_count = 0, pos;
6357 MonoAssembly **newassemblies;
6359 for (i = 0; m->data.assemblies [i]; ++i) {
6361 if (m->data.assemblies [i] == assembly)
6366 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6369 for (i = 0; i < count; ++i)
6370 if (m->data.assemblies [i] != assembly)
6371 newassemblies [pos ++] = m->data.assemblies [i];
6372 g_assert (pos == count - match_count);
6373 g_free (m->data.assemblies);
6374 m->data.assemblies = newassemblies;
6380 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6384 for (i = 0; i < req->nmodifiers; ++i) {
6385 Modifier *m = &req->modifiers [i];
6387 clear_assembly_from_modifier (req, m, assembly);
6392 * clear_event_requests_for_assembly:
6394 * Clear all events requests which reference ASSEMBLY.
6397 clear_event_requests_for_assembly (MonoAssembly *assembly)
6402 mono_loader_lock ();
6406 for (i = 0; i < event_requests->len; ++i) {
6407 EventRequest *req = g_ptr_array_index (event_requests, i);
6409 clear_assembly_from_modifiers (req, assembly);
6411 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6412 clear_event_request (req->id, req->event_kind);
6417 if (req->event_kind == EVENT_KIND_STEP)
6418 ss_clear_for_assembly (req->info, assembly);
6421 mono_loader_unlock ();
6425 * type_comes_from_assembly:
6427 * GHRFunc that returns TRUE if klass comes from assembly
6430 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6432 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6436 * clear_types_for_assembly:
6438 * Clears types from loaded_classes for a given assembly
6441 clear_types_for_assembly (MonoAssembly *assembly)
6443 MonoDomain *domain = mono_domain_get ();
6444 AgentDomainInfo *info = NULL;
6446 if (!domain || !domain_jit_info (domain))
6447 /* Can happen during shutdown */
6450 info = get_agent_domain_info (domain);
6452 mono_loader_lock ();
6453 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6454 mono_loader_unlock ();
6458 add_thread (gpointer key, gpointer value, gpointer user_data)
6460 MonoInternalThread *thread = value;
6461 Buffer *buf = user_data;
6463 buffer_add_objid (buf, (MonoObject*)thread);
6467 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6469 guint8 *end = invoke->endp;
6472 MonoMethodSignature *sig;
6475 MonoObject *this_arg, *res, *exc;
6478 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6481 MonoStopwatch watch;
6483 if (invoke->method) {
6485 * Invoke this method directly, currently only Environment.Exit () is supported.
6488 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)mono_native_thread_id_get (), mono_method_full_name (invoke->method, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6489 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6490 g_assert_not_reached ();
6493 m = decode_methodid (p, &p, end, &domain, &err);
6496 sig = mono_method_signature (m);
6498 if (m->klass->valuetype)
6499 this_buf = g_alloca (mono_class_instance_size (m->klass));
6501 this_buf = g_alloca (sizeof (MonoObject*));
6502 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6503 /* Should be null */
6504 int type = decode_byte (p, &p, end);
6505 if (type != VALUE_TYPE_ID_NULL) {
6506 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)mono_native_thread_id_get ());
6507 return ERR_INVALID_ARGUMENT;
6509 memset (this_buf, 0, mono_class_instance_size (m->klass));
6510 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6514 int type = decode_byte (p, &tmp_p, end);
6515 if (type == VALUE_TYPE_ID_NULL) {
6516 memset (this_buf, 0, mono_class_instance_size (m->klass));
6519 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6524 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6529 if (!m->klass->valuetype)
6530 this_arg = *(MonoObject**)this_buf;
6534 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6536 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)mono_native_thread_id_get ());
6537 return ERR_INVALID_ARGUMENT;
6539 m = mono_object_get_virtual_method (this_arg, m);
6540 /* Transform this to the format the rest of the code expects it to be */
6541 if (m->klass->valuetype) {
6542 this_buf = g_alloca (mono_class_instance_size (m->klass));
6543 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6545 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6547 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer)mono_native_thread_id_get ());
6548 return ERR_INVALID_ARGUMENT;
6550 m = mono_object_get_virtual_method (this_arg, m);
6551 if (m->klass->valuetype) {
6552 this_buf = g_alloca (mono_class_instance_size (m->klass));
6553 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6557 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)mono_native_thread_id_get (), mono_method_full_name (m, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6559 if (this_arg && this_arg->vtable->domain != domain)
6562 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6563 if (!strcmp (m->name, ".ctor")) {
6564 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6565 return ERR_INVALID_ARGUMENT;
6567 this_arg = mono_object_new (domain, m->klass);
6569 return ERR_INVALID_ARGUMENT;
6573 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6574 return ERR_INVALID_ARGUMENT;
6576 nargs = decode_int (p, &p, end);
6577 if (nargs != sig->param_count)
6578 return ERR_INVALID_ARGUMENT;
6579 /* Use alloca to get gc tracking */
6580 arg_buf = g_alloca (nargs * sizeof (gpointer));
6581 memset (arg_buf, 0, nargs * sizeof (gpointer));
6582 args = g_alloca (nargs * sizeof (gpointer));
6583 for (i = 0; i < nargs; ++i) {
6584 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6585 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6588 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6591 if (sig->params [i]->byref) {
6592 arg_buf [i] = g_alloca (sizeof (mgreg_t));
6593 *(gpointer*)arg_buf [i] = args [i];
6594 args [i] = arg_buf [i];
6597 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6598 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6601 args [i] = arg_buf [i];
6608 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6609 tls->disable_breakpoints = TRUE;
6611 tls->disable_breakpoints = FALSE;
6614 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6616 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6617 if (invoke->has_ctx) {
6620 lmf_addr = mono_get_lmf_addr ();
6623 memset (&ext, 0, sizeof (ext));
6624 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6626 ext.debugger_invoke = TRUE;
6627 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6629 mono_set_lmf ((MonoLMF*)&ext);
6633 mono_stopwatch_start (&watch);
6634 if (m->klass->valuetype)
6635 res = mono_runtime_invoke (m, this_buf, args, &exc);
6637 res = mono_runtime_invoke (m, this_arg, args, &exc);
6638 mono_stopwatch_stop (&watch);
6639 DEBUG_PRINTF (1, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer)mono_native_thread_id_get (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch));
6641 buffer_add_byte (buf, 0);
6642 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6644 gboolean out_this = FALSE;
6645 gboolean out_args = FALSE;
6647 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6649 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6651 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6652 if (sig->ret->type == MONO_TYPE_VOID) {
6653 if (!strcmp (m->name, ".ctor")) {
6654 if (!m->klass->valuetype)
6655 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6657 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6659 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6661 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6662 buffer_add_value (buf, sig->ret, &res, domain);
6663 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6664 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6665 MonoClass *k = mono_class_from_mono_type (sig->ret);
6666 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6668 g_assert (nullable_buf);
6669 mono_nullable_init (nullable_buf, res, k);
6670 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6673 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6679 /* Return the new value of the receiver after the call */
6680 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6682 buffer_add_int (buf, nargs);
6683 for (i = 0; i < nargs; ++i) {
6684 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6685 buffer_add_value (buf, sig->params [i], &args [i], domain);
6686 else if (sig->params [i]->byref)
6687 /* add_value () does an indirection */
6688 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6690 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6695 tls->disable_breakpoints = FALSE;
6697 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6698 if (invoke->has_ctx)
6699 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6703 // FIXME: byref arguments
6711 * Invoke the method given by tls->pending_invoke in the current thread.
6714 invoke_method (void)
6716 DebuggerTlsData *tls;
6721 MonoContext restore_ctx;
6724 tls = mono_native_tls_get_value (debugger_tls_id);
6728 * Store the `InvokeData *' in `tls->invoke' until we're done with
6729 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6732 mono_loader_lock ();
6734 invoke = tls->pending_invoke;
6736 tls->pending_invoke = NULL;
6738 invoke->last_invoke = tls->invoke;
6739 tls->invoke = invoke;
6741 mono_loader_unlock ();
6743 tls->frames_up_to_date = FALSE;
6749 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6750 buffer_init (&buf, 128);
6753 /* Fail the other invokes as well */
6755 err = do_invoke_method (tls, &buf, invoke, p, &p);
6758 if (tls->abort_requested) {
6759 if (CHECK_PROTOCOL_VERSION (2, 42))
6760 err = ERR_INVOKE_ABORTED;
6763 /* Start suspending before sending the reply */
6764 if (mindex == invoke->nmethods - 1) {
6765 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6766 for (i = 0; i < invoke->suspend_count; ++i)
6771 send_reply_packet (id, err, &buf);
6776 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6778 if (invoke->has_ctx)
6779 save_thread_context (&restore_ctx);
6781 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6782 g_assert (tls->resume_count);
6783 tls->resume_count -= invoke->suspend_count;
6786 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)mono_native_thread_id_get (), err, tls->resume_count);
6789 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6791 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6792 * after the mono_runtime_invoke() already returned, but it doesn't matter
6793 * because we reset the abort here.
6796 mono_loader_lock ();
6798 if (tls->abort_requested)
6799 mono_thread_internal_reset_abort (tls->thread);
6801 tls->invoke = tls->invoke->last_invoke;
6802 tls->abort_requested = FALSE;
6804 mono_loader_unlock ();
6813 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6815 MonoThread *thread = value;
6816 DebuggerTlsData *tls;
6819 mono_loader_lock ();
6820 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6822 res = tls->really_suspended;
6823 mono_loader_unlock ();
6829 get_source_files_for_type (MonoClass *klass)
6831 gpointer iter = NULL;
6833 MonoDebugSourceInfo *sinfo;
6837 files = g_ptr_array_new ();
6839 while ((method = mono_class_get_methods (klass, &iter))) {
6840 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6841 GPtrArray *source_file_list;
6844 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6845 for (j = 0; j < source_file_list->len; ++j) {
6846 sinfo = g_ptr_array_index (source_file_list, j);
6847 for (i = 0; i < files->len; ++i)
6848 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6850 if (i == files->len)
6851 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6853 g_ptr_array_free (source_file_list, TRUE);
6861 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6864 case CMD_VM_VERSION: {
6865 char *build_info, *version;
6867 build_info = mono_get_runtime_build_info ();
6868 version = g_strdup_printf ("mono %s", build_info);
6870 buffer_add_string (buf, version); /* vm version */
6871 buffer_add_int (buf, MAJOR_VERSION);
6872 buffer_add_int (buf, MINOR_VERSION);
6873 g_free (build_info);
6877 case CMD_VM_SET_PROTOCOL_VERSION: {
6878 major_version = decode_int (p, &p, end);
6879 minor_version = decode_int (p, &p, end);
6880 protocol_version_set = TRUE;
6881 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6884 case CMD_VM_ALL_THREADS: {
6886 mono_loader_lock ();
6887 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6888 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6889 mono_loader_unlock ();
6892 case CMD_VM_SUSPEND:
6894 wait_for_suspend ();
6897 if (suspend_count == 0)
6898 return ERR_NOT_SUSPENDED;
6900 clear_suspended_objs ();
6902 case CMD_VM_DISPOSE:
6903 /* Clear all event requests */
6904 mono_loader_lock ();
6905 while (event_requests->len > 0) {
6906 EventRequest *req = g_ptr_array_index (event_requests, 0);
6908 clear_event_request (req->id, req->event_kind);
6910 mono_loader_unlock ();
6912 while (suspend_count > 0)
6914 disconnected = TRUE;
6915 vm_start_event_sent = FALSE;
6918 MonoInternalThread *thread;
6919 DebuggerTlsData *tls;
6920 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6921 MonoClass *env_class;
6923 MonoMethod *exit_method = NULL;
6927 exit_code = decode_int (p, &p, end);
6929 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6931 /* Have to send a reply before exiting */
6932 send_reply_packet (id, 0, buf);
6934 /* Clear all event requests */
6935 mono_loader_lock ();
6936 while (event_requests->len > 0) {
6937 EventRequest *req = g_ptr_array_index (event_requests, 0);
6939 clear_event_request (req->id, req->event_kind);
6941 mono_loader_unlock ();
6944 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6945 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6946 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6947 * better than doing the shutdown ourselves, since it avoids various races.
6951 wait_for_suspend ();
6953 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6954 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6956 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6959 mono_loader_lock ();
6960 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6961 mono_loader_unlock ();
6963 if (thread && exit_method) {
6964 mono_loader_lock ();
6965 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6966 mono_loader_unlock ();
6968 args = g_new0 (gpointer, 1);
6969 args [0] = g_malloc (sizeof (int));
6970 *(int*)(args [0]) = exit_code;
6972 tls->pending_invoke = g_new0 (InvokeData, 1);
6973 tls->pending_invoke->method = exit_method;
6974 tls->pending_invoke->args = args;
6975 tls->pending_invoke->nmethods = 1;
6977 while (suspend_count > 0)
6981 * No thread found, do it ourselves.
6982 * FIXME: This can race with normal shutdown etc.
6984 while (suspend_count > 0)
6987 if (!mono_runtime_try_shutdown ())
6990 mono_environment_exitcode_set (exit_code);
6992 /* Suspend all managed threads since the runtime is going away */
6993 DEBUG_PRINTF (1, "Suspending all threads...\n");
6994 mono_thread_suspend_all_other_threads ();
6995 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
6996 mono_runtime_quit ();
6997 transport_close2 ();
6998 DEBUG_PRINTF (1, "Exiting...\n");
7004 case CMD_VM_INVOKE_METHOD:
7005 case CMD_VM_INVOKE_METHODS: {
7006 int objid = decode_objid (p, &p, end);
7008 DebuggerTlsData *tls;
7009 int i, count, err, flags, nmethods;
7011 err = get_object (objid, (MonoObject**)&thread);
7015 flags = decode_int (p, &p, end);
7017 if (command == CMD_VM_INVOKE_METHODS)
7018 nmethods = decode_int (p, &p, end);
7022 // Wait for suspending if it already started
7024 wait_for_suspend ();
7025 if (!is_suspended ())
7026 return ERR_NOT_SUSPENDED;
7028 mono_loader_lock ();
7029 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7030 mono_loader_unlock ();
7033 if (!tls->really_suspended)
7034 /* The thread is still running native code, can't do invokes */
7035 return ERR_NOT_SUSPENDED;
7038 * Store the invoke data into tls, the thread will execute it after it is
7041 if (tls->pending_invoke)
7042 return ERR_NOT_SUSPENDED;
7043 tls->pending_invoke = g_new0 (InvokeData, 1);
7044 tls->pending_invoke->id = id;
7045 tls->pending_invoke->flags = flags;
7046 tls->pending_invoke->p = g_malloc (end - p);
7047 memcpy (tls->pending_invoke->p, p, end - p);
7048 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7049 tls->pending_invoke->suspend_count = suspend_count;
7050 tls->pending_invoke->nmethods = nmethods;
7052 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7053 resume_thread (THREAD_TO_INTERNAL (thread));
7056 count = suspend_count;
7057 for (i = 0; i < count; ++i)
7062 case CMD_VM_ABORT_INVOKE: {
7063 int objid = decode_objid (p, &p, end);
7065 DebuggerTlsData *tls;
7068 err = get_object (objid, (MonoObject**)&thread);
7072 invoke_id = decode_int (p, &p, end);
7074 mono_loader_lock ();
7075 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7078 if (tls->abort_requested) {
7079 DEBUG_PRINTF (1, "Abort already requested.\n");
7080 mono_loader_unlock ();
7085 * Check whether we're still inside the mono_runtime_invoke() and that it's
7086 * actually the correct invocation.
7088 * Careful, we do not stop the thread that's doing the invocation, so we can't
7089 * inspect its stack. However, invoke_method() also acquires the loader lock
7090 * when it's done, so we're safe here.
7094 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7095 mono_loader_unlock ();
7096 return ERR_NO_INVOCATION;
7099 tls->abort_requested = TRUE;
7101 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7102 mono_loader_unlock ();
7106 case CMD_VM_SET_KEEPALIVE: {
7107 int timeout = decode_int (p, &p, end);
7108 agent_config.keepalive = timeout;
7110 #ifndef DISABLE_SOCKET_TRANSPORT
7117 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7118 GHashTableIter iter, kiter;
7123 char *fname, *basename;
7124 gboolean ignore_case;
7125 GSList *class_list, *l;
7126 GPtrArray *res_classes, *res_domains;
7128 fname = decode_string (p, &p, end);
7129 ignore_case = decode_byte (p, &p, end);
7131 basename = dbg_path_get_basename (fname);
7133 res_classes = g_ptr_array_new ();
7134 res_domains = g_ptr_array_new ();
7136 mono_loader_lock ();
7137 g_hash_table_iter_init (&iter, domains);
7138 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7139 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7141 /* Update 'source_file_to_class' cache */
7142 g_hash_table_iter_init (&kiter, info->loaded_classes);
7143 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7144 if (!g_hash_table_lookup (info->source_files, klass)) {
7145 files = get_source_files_for_type (klass);
7146 g_hash_table_insert (info->source_files, klass, files);
7148 for (i = 0; i < files->len; ++i) {
7149 char *s = g_ptr_array_index (files, i);
7150 char *s2 = dbg_path_get_basename (s);
7153 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7155 class_list = g_slist_prepend (class_list, klass);
7156 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7158 class_list = g_slist_prepend (class_list, klass);
7159 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7162 /* The _ignorecase hash contains the lowercase path */
7163 s3 = strdup_tolower (s2);
7164 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7166 class_list = g_slist_prepend (class_list, klass);
7167 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7169 class_list = g_slist_prepend (class_list, klass);
7170 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7182 s = strdup_tolower (basename);
7183 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7186 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7189 for (l = class_list; l; l = l->next) {
7192 g_ptr_array_add (res_classes, klass);
7193 g_ptr_array_add (res_domains, domain);
7196 mono_loader_unlock ();
7201 buffer_add_int (buf, res_classes->len);
7202 for (i = 0; i < res_classes->len; ++i)
7203 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7204 g_ptr_array_free (res_classes, TRUE);
7205 g_ptr_array_free (res_domains, TRUE);
7208 case CMD_VM_GET_TYPES: {
7209 GHashTableIter iter;
7213 gboolean ignore_case;
7214 GPtrArray *res_classes, *res_domains;
7215 MonoTypeNameParse info;
7217 name = decode_string (p, &p, end);
7218 ignore_case = decode_byte (p, &p, end);
7220 if (!mono_reflection_parse_type (name, &info)) {
7222 mono_reflection_free_type_info (&info);
7223 return ERR_INVALID_ARGUMENT;
7226 res_classes = g_ptr_array_new ();
7227 res_domains = g_ptr_array_new ();
7229 mono_loader_lock ();
7230 g_hash_table_iter_init (&iter, domains);
7231 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7233 gboolean type_resolve;
7237 mono_domain_assemblies_lock (domain);
7238 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7242 type_resolve = TRUE;
7243 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7245 g_ptr_array_add (res_classes, mono_type_get_class (t));
7246 g_ptr_array_add (res_domains, domain);
7250 mono_domain_assemblies_unlock (domain);
7252 mono_loader_unlock ();
7255 mono_reflection_free_type_info (&info);
7257 buffer_add_int (buf, res_classes->len);
7258 for (i = 0; i < res_classes->len; ++i)
7259 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7260 g_ptr_array_free (res_classes, TRUE);
7261 g_ptr_array_free (res_domains, TRUE);
7264 case CMD_VM_START_BUFFERING:
7265 case CMD_VM_STOP_BUFFERING:
7266 /* Handled in the main loop */
7269 return ERR_NOT_IMPLEMENTED;
7276 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7282 case CMD_EVENT_REQUEST_SET: {
7284 int i, event_kind, suspend_policy, nmodifiers, mod;
7287 MonoThread *step_thread;
7288 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7292 event_kind = decode_byte (p, &p, end);
7293 suspend_policy = decode_byte (p, &p, end);
7294 nmodifiers = decode_byte (p, &p, end);
7296 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7297 req->id = InterlockedIncrement (&event_request_id);
7298 req->event_kind = event_kind;
7299 req->suspend_policy = suspend_policy;
7300 req->nmodifiers = nmodifiers;
7303 for (i = 0; i < nmodifiers; ++i) {
7304 mod = decode_byte (p, &p, end);
7306 req->modifiers [i].kind = mod;
7307 if (mod == MOD_KIND_COUNT) {
7308 req->modifiers [i].data.count = decode_int (p, &p, end);
7309 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7310 method = decode_methodid (p, &p, end, &domain, &err);
7313 location = decode_long (p, &p, end);
7314 } else if (mod == MOD_KIND_STEP) {
7315 step_thread_id = decode_id (p, &p, end);
7316 size = decode_int (p, &p, end);
7317 depth = decode_int (p, &p, end);
7318 if (CHECK_PROTOCOL_VERSION (2, 16))
7319 filter = decode_int (p, &p, end);
7320 req->modifiers [i].data.filter = filter;
7321 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7322 /* Treat STEP_THOUGH the same as HIDDEN */
7323 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7324 } else if (mod == MOD_KIND_THREAD_ONLY) {
7325 int id = decode_id (p, &p, end);
7327 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7332 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7333 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7337 req->modifiers [i].caught = decode_byte (p, &p, end);
7338 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7339 if (CHECK_PROTOCOL_VERSION (2, 25))
7340 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7342 req->modifiers [i].subclasses = TRUE;
7343 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" : "");
7345 req->modifiers [i].data.exc_class = exc_class;
7347 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7349 return ERR_INVALID_ARGUMENT;
7352 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7353 int n = decode_int (p, &p, end);
7356 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7357 for (j = 0; j < n; ++j) {
7358 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7360 g_free (req->modifiers [i].data.assemblies);
7364 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7365 int n = decode_int (p, &p, end);
7368 modifier = &req->modifiers [i];
7369 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7370 for (j = 0; j < n; ++j) {
7371 char *s = decode_string (p, &p, end);
7375 s2 = strdup_tolower (s);
7376 g_hash_table_insert (modifier->data.source_files, s2, s2);
7380 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7381 int n = decode_int (p, &p, end);
7384 modifier = &req->modifiers [i];
7385 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7386 for (j = 0; j < n; ++j) {
7387 char *s = decode_string (p, &p, end);
7390 g_hash_table_insert (modifier->data.type_names, s, s);
7394 return ERR_NOT_IMPLEMENTED;
7398 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7401 req->info = set_breakpoint (method, location, req, &error);
7402 if (!mono_error_ok (&error)) {
7404 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7405 mono_error_cleanup (&error);
7406 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7408 } else if (req->event_kind == EVENT_KIND_STEP) {
7409 g_assert (step_thread_id);
7411 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7417 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7422 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7423 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7424 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7425 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7426 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7427 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7429 if (req->nmodifiers) {
7431 return ERR_NOT_IMPLEMENTED;
7435 mono_loader_lock ();
7436 g_ptr_array_add (event_requests, req);
7438 if (agent_config.defer) {
7439 /* Transmit cached data to the client on receipt of the event request */
7440 switch (req->event_kind) {
7441 case EVENT_KIND_APPDOMAIN_CREATE:
7442 /* Emit load events for currently loaded domains */
7443 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7445 case EVENT_KIND_ASSEMBLY_LOAD:
7446 /* Emit load events for currently loaded assemblies */
7447 mono_assembly_foreach (emit_assembly_load, NULL);
7449 case EVENT_KIND_THREAD_START:
7450 /* Emit start events for currently started threads */
7451 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7453 case EVENT_KIND_TYPE_LOAD:
7454 /* Emit type load events for currently loaded types */
7455 mono_domain_foreach (send_types_for_domain, NULL);
7461 mono_loader_unlock ();
7463 buffer_add_int (buf, req->id);
7466 case CMD_EVENT_REQUEST_CLEAR: {
7467 int etype = decode_byte (p, &p, end);
7468 int req_id = decode_int (p, &p, end);
7470 // FIXME: Make a faster mapping from req_id to request
7471 mono_loader_lock ();
7472 clear_event_request (req_id, etype);
7473 mono_loader_unlock ();
7476 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7479 mono_loader_lock ();
7481 while (i < event_requests->len) {
7482 EventRequest *req = g_ptr_array_index (event_requests, i);
7484 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7485 clear_breakpoint (req->info);
7487 g_ptr_array_remove_index_fast (event_requests, i);
7493 mono_loader_unlock ();
7497 return ERR_NOT_IMPLEMENTED;
7504 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7510 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7511 buffer_add_domainid (buf, mono_get_root_domain ());
7514 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7515 domain = decode_domainid (p, &p, end, NULL, &err);
7518 buffer_add_string (buf, domain->friendly_name);
7521 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7526 domain = decode_domainid (p, &p, end, NULL, &err);
7529 mono_loader_lock ();
7531 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7534 buffer_add_int (buf, count);
7535 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7537 buffer_add_assemblyid (buf, domain, ass);
7539 mono_loader_unlock ();
7542 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7543 domain = decode_domainid (p, &p, end, NULL, &err);
7547 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7550 case CMD_APPDOMAIN_GET_CORLIB: {
7551 domain = decode_domainid (p, &p, end, NULL, &err);
7555 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7558 case CMD_APPDOMAIN_CREATE_STRING: {
7562 domain = decode_domainid (p, &p, end, NULL, &err);
7565 s = decode_string (p, &p, end);
7567 o = mono_string_new (domain, s);
7568 buffer_add_objid (buf, (MonoObject*)o);
7571 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7573 MonoDomain *domain2;
7576 domain = decode_domainid (p, &p, end, NULL, &err);
7579 klass = decode_typeid (p, &p, end, &domain2, &err);
7584 g_assert (domain == domain2);
7586 o = mono_object_new (domain, klass);
7588 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7592 buffer_add_objid (buf, o);
7596 return ERR_NOT_IMPLEMENTED;
7603 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7609 ass = decode_assemblyid (p, &p, end, &domain, &err);
7614 case CMD_ASSEMBLY_GET_LOCATION: {
7615 buffer_add_string (buf, mono_image_get_filename (ass->image));
7618 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7622 if (ass->image->dynamic) {
7623 buffer_add_id (buf, 0);
7625 token = mono_image_get_entry_point (ass->image);
7627 buffer_add_id (buf, 0);
7629 m = mono_get_method (ass->image, token, NULL);
7630 buffer_add_methodid (buf, domain, m);
7635 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7636 buffer_add_moduleid (buf, domain, ass->image);
7639 case CMD_ASSEMBLY_GET_OBJECT: {
7640 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7641 buffer_add_objid (buf, o);
7644 case CMD_ASSEMBLY_GET_TYPE: {
7645 char *s = decode_string (p, &p, end);
7646 gboolean ignorecase = decode_byte (p, &p, end);
7647 MonoTypeNameParse info;
7649 gboolean type_resolve, res;
7650 MonoDomain *d = mono_domain_get ();
7652 /* This is needed to be able to find referenced assemblies */
7653 res = mono_domain_set (domain, FALSE);
7656 if (!mono_reflection_parse_type (s, &info)) {
7659 if (info.assembly.name)
7661 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7663 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7664 mono_reflection_free_type_info (&info);
7667 mono_domain_set (d, TRUE);
7671 case CMD_ASSEMBLY_GET_NAME: {
7673 MonoAssembly *mass = ass;
7675 name = g_strdup_printf (
7676 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7678 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7679 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7680 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7681 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7683 buffer_add_string (buf, name);
7688 return ERR_NOT_IMPLEMENTED;
7695 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7701 case CMD_MODULE_GET_INFO: {
7702 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7705 basename = g_path_get_basename (image->name);
7706 buffer_add_string (buf, basename); // name
7707 buffer_add_string (buf, image->module_name); // scopename
7708 buffer_add_string (buf, image->name); // fqname
7709 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7710 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7715 return ERR_NOT_IMPLEMENTED;
7722 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7728 case CMD_FIELD_GET_INFO: {
7729 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7731 buffer_add_string (buf, f->name);
7732 buffer_add_typeid (buf, domain, f->parent);
7733 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7734 buffer_add_int (buf, f->type->attrs);
7738 return ERR_NOT_IMPLEMENTED;
7745 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7747 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7748 /* Special case these so the client doesn't have to handle Type objects */
7750 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7751 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7752 } else if (MONO_TYPE_IS_REFERENCE (t))
7753 buffer_add_value (buf, t, &val, domain);
7755 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7759 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7765 buffer_add_int (buf, 0);
7769 for (i = 0; i < cinfo->num_attrs; ++i) {
7770 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7773 buffer_add_int (buf, nattrs);
7775 for (i = 0; i < cinfo->num_attrs; ++i) {
7776 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7777 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7778 MonoArray *typed_args, *named_args;
7780 CattrNamedArg *arginfo = NULL;
7783 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7784 if (!mono_error_ok (&error)) {
7785 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7786 mono_error_cleanup (&error);
7787 return ERR_LOADER_ERROR;
7790 buffer_add_methodid (buf, domain, attr->ctor);
7794 buffer_add_int (buf, mono_array_length (typed_args));
7795 for (j = 0; j < mono_array_length (typed_args); ++j) {
7796 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7798 t = mono_method_signature (attr->ctor)->params [j];
7800 buffer_add_cattr_arg (buf, t, domain, val);
7803 buffer_add_int (buf, 0);
7808 buffer_add_int (buf, mono_array_length (named_args));
7810 for (j = 0; j < mono_array_length (named_args); ++j) {
7811 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7813 if (arginfo [j].prop) {
7814 buffer_add_byte (buf, 0x54);
7815 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7816 } else if (arginfo [j].field) {
7817 buffer_add_byte (buf, 0x53);
7818 buffer_add_fieldid (buf, domain, arginfo [j].field);
7820 g_assert_not_reached ();
7823 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7826 buffer_add_int (buf, 0);
7835 /* FIXME: Code duplication with icall.c */
7837 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7842 mono_class_setup_interfaces (klass, error);
7843 if (!mono_error_ok (error))
7846 for (i = 0; i < klass->interface_count; i++) {
7847 ic = klass->interfaces [i];
7848 g_hash_table_insert (ifaces, ic, ic);
7850 collect_interfaces (ic, ifaces, error);
7851 if (!mono_error_ok (error))
7857 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7867 case CMD_TYPE_GET_INFO: {
7868 buffer_add_string (buf, klass->name_space);
7869 buffer_add_string (buf, klass->name);
7871 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7872 buffer_add_string (buf, name);
7874 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7875 buffer_add_moduleid (buf, domain, klass->image);
7876 buffer_add_typeid (buf, domain, klass->parent);
7877 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7878 buffer_add_typeid (buf, domain, klass->element_class);
7880 buffer_add_id (buf, 0);
7881 buffer_add_int (buf, klass->type_token);
7882 buffer_add_byte (buf, klass->rank);
7883 buffer_add_int (buf, klass->flags);
7885 type = &klass->byval_arg;
7886 // FIXME: Can't decide whenever a class represents a byref type
7889 if (type->type == MONO_TYPE_PTR)
7891 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7893 if (type->type == MONO_TYPE_VALUETYPE)
7895 if (klass->enumtype)
7897 if (klass->generic_container)
7899 if (klass->generic_container || klass->generic_class)
7901 buffer_add_byte (buf, b);
7904 while ((nested = mono_class_get_nested_types (klass, &iter)))
7906 buffer_add_int (buf, nnested);
7908 while ((nested = mono_class_get_nested_types (klass, &iter)))
7909 buffer_add_typeid (buf, domain, nested);
7910 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7911 if (klass->generic_container)
7912 buffer_add_typeid (buf, domain, klass);
7913 else if (klass->generic_class)
7914 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7916 buffer_add_id (buf, 0);
7918 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7921 if (klass->generic_class) {
7922 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7924 count = inst->type_argc;
7925 buffer_add_int (buf, count);
7926 for (i = 0; i < count; i++)
7927 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7928 } else if (klass->generic_container) {
7929 MonoGenericContainer *container = klass->generic_container;
7932 count = container->type_argc;
7933 buffer_add_int (buf, count);
7934 for (i = 0; i < count; i++) {
7935 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7936 buffer_add_typeid (buf, domain, pklass);
7939 buffer_add_int (buf, 0);
7944 case CMD_TYPE_GET_METHODS: {
7947 gpointer iter = NULL;
7950 mono_class_setup_methods (klass);
7952 nmethods = mono_class_num_methods (klass);
7954 buffer_add_int (buf, nmethods);
7956 while ((m = mono_class_get_methods (klass, &iter))) {
7957 buffer_add_methodid (buf, domain, m);
7960 g_assert (i == nmethods);
7963 case CMD_TYPE_GET_FIELDS: {
7966 gpointer iter = NULL;
7969 nfields = mono_class_num_fields (klass);
7971 buffer_add_int (buf, nfields);
7973 while ((f = mono_class_get_fields (klass, &iter))) {
7974 buffer_add_fieldid (buf, domain, f);
7975 buffer_add_string (buf, f->name);
7976 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7977 buffer_add_int (buf, f->type->attrs);
7980 g_assert (i == nfields);
7983 case CMD_TYPE_GET_PROPERTIES: {
7986 gpointer iter = NULL;
7989 nprops = mono_class_num_properties (klass);
7991 buffer_add_int (buf, nprops);
7993 while ((p = mono_class_get_properties (klass, &iter))) {
7994 buffer_add_propertyid (buf, domain, p);
7995 buffer_add_string (buf, p->name);
7996 buffer_add_methodid (buf, domain, p->get);
7997 buffer_add_methodid (buf, domain, p->set);
7998 buffer_add_int (buf, p->attrs);
8001 g_assert (i == nprops);
8004 case CMD_TYPE_GET_CATTRS: {
8005 MonoClass *attr_klass;
8006 MonoCustomAttrInfo *cinfo;
8008 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8009 /* attr_klass can be NULL */
8013 cinfo = mono_custom_attrs_from_class (klass);
8015 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8020 case CMD_TYPE_GET_FIELD_CATTRS: {
8021 MonoClass *attr_klass;
8022 MonoCustomAttrInfo *cinfo;
8023 MonoClassField *field;
8025 field = decode_fieldid (p, &p, end, NULL, &err);
8028 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8032 cinfo = mono_custom_attrs_from_field (klass, field);
8034 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8039 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8040 MonoClass *attr_klass;
8041 MonoCustomAttrInfo *cinfo;
8044 prop = decode_propertyid (p, &p, end, NULL, &err);
8047 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8051 cinfo = mono_custom_attrs_from_property (klass, prop);
8053 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8058 case CMD_TYPE_GET_VALUES:
8059 case CMD_TYPE_GET_VALUES_2: {
8066 MonoThread *thread_obj;
8067 MonoInternalThread *thread = NULL;
8068 guint32 special_static_type;
8070 if (command == CMD_TYPE_GET_VALUES_2) {
8071 int objid = decode_objid (p, &p, end);
8074 err = get_object (objid, (MonoObject**)&thread_obj);
8078 thread = THREAD_TO_INTERNAL (thread_obj);
8081 len = decode_int (p, &p, end);
8082 for (i = 0; i < len; ++i) {
8083 f = decode_fieldid (p, &p, end, NULL, &err);
8087 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8088 return ERR_INVALID_FIELDID;
8089 special_static_type = mono_class_field_get_special_static_type (f);
8090 if (special_static_type != SPECIAL_STATIC_NONE) {
8091 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8092 return ERR_INVALID_FIELDID;
8095 /* Check that the field belongs to the object */
8097 for (k = klass; k; k = k->parent) {
8098 if (k == f->parent) {
8104 return ERR_INVALID_FIELDID;
8106 vtable = mono_class_vtable (domain, f->parent);
8107 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8108 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8109 buffer_add_value (buf, f->type, val, domain);
8114 case CMD_TYPE_SET_VALUES: {
8122 len = decode_int (p, &p, end);
8123 for (i = 0; i < len; ++i) {
8124 f = decode_fieldid (p, &p, end, NULL, &err);
8128 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8129 return ERR_INVALID_FIELDID;
8130 if (mono_class_field_is_special_static (f))
8131 return ERR_INVALID_FIELDID;
8133 /* Check that the field belongs to the object */
8135 for (k = klass; k; k = k->parent) {
8136 if (k == f->parent) {
8142 return ERR_INVALID_FIELDID;
8144 // FIXME: Check for literal/const
8146 vtable = mono_class_vtable (domain, f->parent);
8147 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8148 err = decode_value (f->type, domain, val, p, &p, end);
8153 if (MONO_TYPE_IS_REFERENCE (f->type))
8154 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8156 mono_field_static_set_value (vtable, f, val);
8161 case CMD_TYPE_GET_OBJECT: {
8162 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8163 buffer_add_objid (buf, o);
8166 case CMD_TYPE_GET_SOURCE_FILES:
8167 case CMD_TYPE_GET_SOURCE_FILES_2: {
8168 char *source_file, *base;
8172 files = get_source_files_for_type (klass);
8174 buffer_add_int (buf, files->len);
8175 for (i = 0; i < files->len; ++i) {
8176 source_file = g_ptr_array_index (files, i);
8177 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8178 buffer_add_string (buf, source_file);
8180 base = dbg_path_get_basename (source_file);
8181 buffer_add_string (buf, base);
8184 g_free (source_file);
8186 g_ptr_array_free (files, TRUE);
8189 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8190 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8194 if (mono_class_is_assignable_from (klass, oklass))
8195 buffer_add_byte (buf, 1);
8197 buffer_add_byte (buf, 0);
8200 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8201 char *name = decode_string (p, &p, end);
8202 int i, flags = decode_int (p, &p, end);
8203 MonoException *ex = NULL;
8204 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8207 return ERR_LOADER_ERROR;
8208 buffer_add_int (buf, array->len);
8209 for (i = 0; i < array->len; ++i) {
8210 MonoMethod *method = g_ptr_array_index (array, i);
8211 buffer_add_methodid (buf, domain, method);
8214 g_ptr_array_free (array, TRUE);
8218 case CMD_TYPE_GET_INTERFACES: {
8220 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8222 MonoClass *tclass, *iface;
8223 GHashTableIter iter;
8227 for (parent = tclass; parent; parent = parent->parent) {
8228 mono_class_setup_interfaces (parent, &error);
8229 if (!mono_error_ok (&error))
8230 return ERR_LOADER_ERROR;
8231 collect_interfaces (parent, iface_hash, &error);
8232 if (!mono_error_ok (&error))
8233 return ERR_LOADER_ERROR;
8236 buffer_add_int (buf, g_hash_table_size (iface_hash));
8238 g_hash_table_iter_init (&iter, iface_hash);
8239 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8240 buffer_add_typeid (buf, domain, iface);
8241 g_hash_table_destroy (iface_hash);
8244 case CMD_TYPE_GET_INTERFACE_MAP: {
8245 int tindex, ioffset;
8246 gboolean variance_used;
8248 int len, nmethods, i;
8252 len = decode_int (p, &p, end);
8253 mono_class_setup_vtable (klass);
8255 for (tindex = 0; tindex < len; ++tindex) {
8256 iclass = decode_typeid (p, &p, end, NULL, &err);
8260 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8262 return ERR_INVALID_ARGUMENT;
8264 nmethods = mono_class_num_methods (iclass);
8265 buffer_add_int (buf, nmethods);
8268 while ((method = mono_class_get_methods (iclass, &iter))) {
8269 buffer_add_methodid (buf, domain, method);
8271 for (i = 0; i < nmethods; ++i)
8272 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8276 case CMD_TYPE_IS_INITIALIZED: {
8277 MonoVTable *vtable = mono_class_vtable (domain, klass);
8280 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8282 buffer_add_int (buf, 0);
8285 case CMD_TYPE_CREATE_INSTANCE: {
8288 obj = mono_object_new (domain, klass);
8289 buffer_add_objid (buf, obj);
8293 return ERR_NOT_IMPLEMENTED;
8300 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8303 MonoDomain *old_domain;
8307 klass = decode_typeid (p, &p, end, &domain, &err);
8311 old_domain = mono_domain_get ();
8313 mono_domain_set (domain, TRUE);
8315 err = type_commands_internal (command, klass, domain, p, end, buf);
8317 mono_domain_set (old_domain, TRUE);
8323 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8325 MonoMethodHeader *header;
8329 case CMD_METHOD_GET_NAME: {
8330 buffer_add_string (buf, method->name);
8333 case CMD_METHOD_GET_DECLARING_TYPE: {
8334 buffer_add_typeid (buf, domain, method->klass);
8337 case CMD_METHOD_GET_DEBUG_INFO: {
8338 MonoDebugMethodInfo *minfo;
8340 int i, j, n_il_offsets;
8342 GPtrArray *source_file_list;
8343 MonoSymSeqPoint *sym_seq_points;
8345 header = mono_method_get_header (method);
8347 buffer_add_int (buf, 0);
8348 buffer_add_string (buf, "");
8349 buffer_add_int (buf, 0);
8353 minfo = mono_debug_lookup_method (method);
8355 buffer_add_int (buf, header->code_size);
8356 buffer_add_string (buf, "");
8357 buffer_add_int (buf, 0);
8358 mono_metadata_free_mh (header);
8362 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8363 buffer_add_int (buf, header->code_size);
8364 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8365 buffer_add_int (buf, source_file_list->len);
8366 for (i = 0; i < source_file_list->len; ++i) {
8367 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8368 buffer_add_string (buf, sinfo->source_file);
8369 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8370 for (j = 0; j < 16; ++j)
8371 buffer_add_byte (buf, sinfo->hash [j]);
8375 buffer_add_string (buf, source_file);
8377 buffer_add_int (buf, n_il_offsets);
8378 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8379 for (i = 0; i < n_il_offsets; ++i) {
8380 MonoSymSeqPoint *sp = &sym_seq_points [i];
8381 const char *srcfile = "";
8383 if (source_files [i] != -1) {
8384 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8385 srcfile = sinfo->source_file;
8387 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);
8388 buffer_add_int (buf, sp->il_offset);
8389 buffer_add_int (buf, sp->line);
8390 if (CHECK_PROTOCOL_VERSION (2, 13))
8391 buffer_add_int (buf, source_files [i]);
8392 if (CHECK_PROTOCOL_VERSION (2, 19))
8393 buffer_add_int (buf, sp->column);
8394 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8395 buffer_add_int (buf, sp->end_line);
8396 buffer_add_int (buf, sp->end_column);
8399 g_free (source_file);
8400 g_free (source_files);
8401 g_free (sym_seq_points);
8402 g_ptr_array_free (source_file_list, TRUE);
8403 mono_metadata_free_mh (header);
8406 case CMD_METHOD_GET_PARAM_INFO: {
8407 MonoMethodSignature *sig = mono_method_signature (method);
8411 /* FIXME: mono_class_from_mono_type () and byrefs */
8413 /* FIXME: Use a smaller encoding */
8414 buffer_add_int (buf, sig->call_convention);
8415 buffer_add_int (buf, sig->param_count);
8416 buffer_add_int (buf, sig->generic_param_count);
8417 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8418 for (i = 0; i < sig->param_count; ++i) {
8420 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8423 /* Emit parameter names */
8424 names = g_new (char *, sig->param_count);
8425 mono_method_get_param_names (method, (const char **) names);
8426 for (i = 0; i < sig->param_count; ++i)
8427 buffer_add_string (buf, names [i]);
8432 case CMD_METHOD_GET_LOCALS_INFO: {
8434 MonoDebugLocalsInfo *locals;
8435 int *locals_map = NULL;
8437 header = mono_method_get_header (method);
8439 return ERR_INVALID_ARGUMENT;
8441 locals = mono_debug_lookup_locals (method);
8443 buffer_add_int (buf, header->num_locals);
8445 for (i = 0; i < header->num_locals; ++i) {
8446 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8449 for (i = 0; i < header->num_locals; ++i) {
8451 sprintf (lname, "V_%d", i);
8452 buffer_add_string (buf, lname);
8455 for (i = 0; i < header->num_locals; ++i) {
8456 buffer_add_int (buf, 0);
8457 buffer_add_int (buf, header->code_size);
8460 num_locals = locals->num_locals;
8461 buffer_add_int (buf, num_locals);
8464 for (i = 0; i < num_locals; ++i) {
8465 g_assert (locals->locals [i].index < header->num_locals);
8466 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8469 for (i = 0; i < num_locals; ++i)
8470 buffer_add_string (buf, locals->locals [i].name);
8472 for (i = 0; i < num_locals; ++i) {
8473 if (locals->locals [i].block) {
8474 buffer_add_int (buf, locals->locals [i].block->start_offset);
8475 buffer_add_int (buf, locals->locals [i].block->end_offset);
8477 buffer_add_int (buf, 0);
8478 buffer_add_int (buf, header->code_size);
8482 mono_metadata_free_mh (header);
8485 mono_debug_free_locals (locals);
8486 g_free (locals_map);
8490 case CMD_METHOD_GET_INFO:
8491 buffer_add_int (buf, method->flags);
8492 buffer_add_int (buf, method->iflags);
8493 buffer_add_int (buf, method->token);
8494 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8496 if (method->is_generic)
8498 if (mono_method_signature (method)->generic_param_count)
8500 buffer_add_byte (buf, attrs);
8501 if (method->is_generic || method->is_inflated) {
8504 if (method->is_generic) {
8507 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8509 result = imethod->declaring;
8510 if (imethod->context.class_inst) {
8511 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8512 /*Generic methods gets the context of the GTD.*/
8513 if (mono_class_get_context (klass)) {
8515 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8516 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8521 buffer_add_methodid (buf, domain, result);
8523 buffer_add_id (buf, 0);
8525 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8526 if (mono_method_signature (method)->generic_param_count) {
8529 if (method->is_inflated) {
8530 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8532 count = inst->type_argc;
8533 buffer_add_int (buf, count);
8535 for (i = 0; i < count; i++)
8536 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8538 buffer_add_int (buf, 0);
8540 } else if (method->is_generic) {
8541 MonoGenericContainer *container = mono_method_get_generic_container (method);
8543 count = mono_method_signature (method)->generic_param_count;
8544 buffer_add_int (buf, count);
8545 for (i = 0; i < count; i++) {
8546 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8547 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8548 buffer_add_typeid (buf, domain, pklass);
8551 buffer_add_int (buf, 0);
8554 buffer_add_int (buf, 0);
8559 case CMD_METHOD_GET_BODY: {
8562 header = mono_method_get_header (method);
8564 buffer_add_int (buf, 0);
8566 if (CHECK_PROTOCOL_VERSION (2, 18))
8567 buffer_add_int (buf, 0);
8569 buffer_add_int (buf, header->code_size);
8570 for (i = 0; i < header->code_size; ++i)
8571 buffer_add_byte (buf, header->code [i]);
8573 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8574 buffer_add_int (buf, header->num_clauses);
8575 for (i = 0; i < header->num_clauses; ++i) {
8576 MonoExceptionClause *clause = &header->clauses [i];
8578 buffer_add_int (buf, clause->flags);
8579 buffer_add_int (buf, clause->try_offset);
8580 buffer_add_int (buf, clause->try_len);
8581 buffer_add_int (buf, clause->handler_offset);
8582 buffer_add_int (buf, clause->handler_len);
8583 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8584 buffer_add_typeid (buf, domain, clause->data.catch_class);
8585 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8586 buffer_add_int (buf, clause->data.filter_offset);
8590 mono_metadata_free_mh (header);
8595 case CMD_METHOD_RESOLVE_TOKEN: {
8596 guint32 token = decode_int (p, &p, end);
8599 switch (mono_metadata_token_code (token)) {
8600 case MONO_TOKEN_STRING: {
8604 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8607 s2 = mono_string_to_utf8 (s);
8609 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8610 buffer_add_string (buf, s2);
8616 MonoClass *handle_class;
8618 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8619 val = mono_method_get_wrapper_data (method, token);
8620 handle_class = mono_method_get_wrapper_data (method, token + 1);
8622 if (handle_class == NULL) {
8623 // Can't figure out the token type
8624 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8629 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8631 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8634 if (handle_class == mono_defaults.typehandle_class) {
8635 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8636 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8637 buffer_add_typeid (buf, domain, (MonoClass *) val);
8639 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8640 } else if (handle_class == mono_defaults.fieldhandle_class) {
8641 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8642 buffer_add_fieldid (buf, domain, val);
8643 } else if (handle_class == mono_defaults.methodhandle_class) {
8644 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8645 buffer_add_methodid (buf, domain, val);
8646 } else if (handle_class == mono_defaults.string_class) {
8649 s = mono_string_to_utf8 (val);
8650 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8651 buffer_add_string (buf, s);
8654 g_assert_not_reached ();
8661 case CMD_METHOD_GET_CATTRS: {
8662 MonoClass *attr_klass;
8663 MonoCustomAttrInfo *cinfo;
8665 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8666 /* attr_klass can be NULL */
8670 cinfo = mono_custom_attrs_from_method (method);
8672 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8677 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8679 MonoType **type_argv;
8683 MonoGenericInst *ginst;
8684 MonoGenericContext tmp_context;
8685 MonoMethod *inflated;
8687 type_argc = decode_int (p, &p, end);
8688 type_argv = g_new0 (MonoType*, type_argc);
8689 for (i = 0; i < type_argc; ++i) {
8690 klass = decode_typeid (p, &p, end, &d, &err);
8697 return ERR_INVALID_ARGUMENT;
8699 type_argv [i] = &klass->byval_arg;
8701 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8703 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8704 tmp_context.method_inst = ginst;
8706 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8707 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8708 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8709 return ERR_INVALID_ARGUMENT;
8710 buffer_add_methodid (buf, domain, inflated);
8714 return ERR_NOT_IMPLEMENTED;
8721 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8724 MonoDomain *old_domain;
8728 method = decode_methodid (p, &p, end, &domain, &err);
8732 old_domain = mono_domain_get ();
8734 mono_domain_set (domain, TRUE);
8736 err = method_commands_internal (command, method, domain, p, end, buf);
8738 mono_domain_set (old_domain, TRUE);
8744 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8746 int objid = decode_objid (p, &p, end);
8748 MonoThread *thread_obj;
8749 MonoInternalThread *thread;
8751 err = get_object (objid, (MonoObject**)&thread_obj);
8755 thread = THREAD_TO_INTERNAL (thread_obj);
8758 case CMD_THREAD_GET_NAME: {
8760 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8763 buffer_add_int (buf, 0);
8768 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8770 buffer_add_int (buf, len);
8771 buffer_add_data (buf, (guint8*)name, len);
8776 case CMD_THREAD_GET_FRAME_INFO: {
8777 DebuggerTlsData *tls;
8778 int i, start_frame, length;
8780 // Wait for suspending if it already started
8781 // FIXME: Races with suspend_count
8782 while (!is_suspended ()) {
8784 wait_for_suspend ();
8788 wait_for_suspend ();
8789 if (!is_suspended ())
8790 return ERR_NOT_SUSPENDED;
8793 start_frame = decode_int (p, &p, end);
8794 length = decode_int (p, &p, end);
8796 if (start_frame != 0 || length != -1)
8797 return ERR_NOT_IMPLEMENTED;
8799 mono_loader_lock ();
8800 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8801 mono_loader_unlock ();
8804 compute_frame_info (thread, tls);
8806 buffer_add_int (buf, tls->frame_count);
8807 for (i = 0; i < tls->frame_count; ++i) {
8808 buffer_add_int (buf, tls->frames [i]->id);
8809 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8810 buffer_add_int (buf, tls->frames [i]->il_offset);
8812 * Instead of passing the frame type directly to the client, we associate
8813 * it with the previous frame using a set of flags. This avoids lots of
8814 * conditional code in the client, since a frame whose type isn't
8815 * FRAME_TYPE_MANAGED has no method, location, etc.
8817 buffer_add_byte (buf, tls->frames [i]->flags);
8822 case CMD_THREAD_GET_STATE:
8823 buffer_add_int (buf, thread->state);
8825 case CMD_THREAD_GET_INFO:
8826 buffer_add_byte (buf, thread->threadpool_thread);
8828 case CMD_THREAD_GET_ID:
8829 buffer_add_long (buf, (guint64)(gsize)thread);
8831 case CMD_THREAD_GET_TID:
8832 buffer_add_long (buf, (guint64)thread->tid);
8834 case CMD_THREAD_SET_IP: {
8835 DebuggerTlsData *tls;
8838 MonoSeqPointInfo *seq_points;
8843 method = decode_methodid (p, &p, end, &domain, &err);
8846 il_offset = decode_long (p, &p, end);
8848 while (!is_suspended ()) {
8850 wait_for_suspend ();
8853 mono_loader_lock ();
8854 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8855 mono_loader_unlock ();
8858 compute_frame_info (thread, tls);
8859 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8860 return ERR_INVALID_ARGUMENT;
8862 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
8864 g_assert (seq_points);
8867 return ERR_INVALID_ARGUMENT;
8869 // FIXME: Check that the ip change is safe
8871 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);
8872 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8876 return ERR_NOT_IMPLEMENTED;
8883 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8887 MonoThread *thread_obj;
8888 MonoInternalThread *thread;
8889 int pos, i, len, frame_idx;
8890 DebuggerTlsData *tls;
8892 MonoDebugMethodJitInfo *jit;
8893 MonoMethodSignature *sig;
8895 MonoMethodHeader *header;
8897 objid = decode_objid (p, &p, end);
8898 err = get_object (objid, (MonoObject**)&thread_obj);
8902 thread = THREAD_TO_INTERNAL (thread_obj);
8904 id = decode_id (p, &p, end);
8906 mono_loader_lock ();
8907 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8908 mono_loader_unlock ();
8911 for (i = 0; i < tls->frame_count; ++i) {
8912 if (tls->frames [i]->id == id)
8915 if (i == tls->frame_count)
8916 return ERR_INVALID_FRAMEID;
8919 frame = tls->frames [frame_idx];
8921 /* This is supported for frames without has_ctx etc. set */
8922 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
8923 if (CHECK_PROTOCOL_VERSION (2, 38))
8924 buffer_add_domainid (buf, frame->domain);
8928 if (!frame->has_ctx)
8929 return ERR_ABSENT_INFORMATION;
8932 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8933 if (!frame->jit && frame->api_method->is_inflated)
8934 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8938 /* This could happen for aot images with no jit debug info */
8939 s = mono_method_full_name (frame->api_method, TRUE);
8940 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
8942 return ERR_ABSENT_INFORMATION;
8947 sig = mono_method_signature (frame->actual_method);
8949 if (!mono_get_seq_points (frame->domain, frame->actual_method))
8951 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8953 return ERR_ABSENT_INFORMATION;
8956 case CMD_STACK_FRAME_GET_VALUES: {
8957 len = decode_int (p, &p, end);
8958 header = mono_method_get_header (frame->actual_method);
8960 for (i = 0; i < len; ++i) {
8961 pos = decode_int (p, &p, end);
8966 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
8968 g_assert (pos >= 0 && pos < jit->num_params);
8970 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8972 MonoDebugLocalsInfo *locals;
8974 locals = mono_debug_lookup_locals (frame->method);
8976 g_assert (pos < locals->num_locals);
8977 pos = locals->locals [pos].index;
8978 mono_debug_free_locals (locals);
8980 g_assert (pos >= 0 && pos < jit->num_locals);
8982 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
8984 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8987 mono_metadata_free_mh (header);
8990 case CMD_STACK_FRAME_GET_THIS: {
8991 if (frame->api_method->klass->valuetype) {
8992 if (!sig->hasthis) {
8993 MonoObject *p = NULL;
8994 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8996 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8999 if (!sig->hasthis) {
9000 MonoObject *p = NULL;
9001 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9003 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9008 case CMD_STACK_FRAME_SET_VALUES: {
9011 MonoDebugVarInfo *var;
9013 len = decode_int (p, &p, end);
9014 header = mono_method_get_header (frame->actual_method);
9016 for (i = 0; i < len; ++i) {
9017 pos = decode_int (p, &p, end);
9022 g_assert (pos >= 0 && pos < jit->num_params);
9024 t = sig->params [pos];
9025 var = &jit->params [pos];
9027 MonoDebugLocalsInfo *locals;
9029 locals = mono_debug_lookup_locals (frame->method);
9031 g_assert (pos < locals->num_locals);
9032 pos = locals->locals [pos].index;
9033 mono_debug_free_locals (locals);
9035 g_assert (pos >= 0 && pos < jit->num_locals);
9037 t = header->locals [pos];
9038 var = &jit->locals [pos];
9041 if (MONO_TYPE_IS_REFERENCE (t))
9042 val_buf = g_alloca (sizeof (MonoObject*));
9044 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9045 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9049 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9051 mono_metadata_free_mh (header);
9054 case CMD_STACK_FRAME_GET_DOMAIN: {
9055 if (CHECK_PROTOCOL_VERSION (2, 38))
9056 buffer_add_domainid (buf, frame->domain);
9060 return ERR_NOT_IMPLEMENTED;
9067 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9070 int objid, err, index, len, i, esize;
9073 objid = decode_objid (p, &p, end);
9074 err = get_object (objid, (MonoObject**)&arr);
9079 case CMD_ARRAY_REF_GET_LENGTH:
9080 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9082 buffer_add_int (buf, arr->max_length);
9083 buffer_add_int (buf, 0);
9085 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9086 buffer_add_int (buf, arr->bounds [i].length);
9087 buffer_add_int (buf, arr->bounds [i].lower_bound);
9091 case CMD_ARRAY_REF_GET_VALUES:
9092 index = decode_int (p, &p, end);
9093 len = decode_int (p, &p, end);
9095 g_assert (index >= 0 && len >= 0);
9096 // Reordered to avoid integer overflow
9097 g_assert (!(index > arr->max_length - len));
9099 esize = mono_array_element_size (arr->obj.vtable->klass);
9100 for (i = index; i < index + len; ++i) {
9101 elem = (gpointer*)((char*)arr->vector + (i * esize));
9102 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9105 case CMD_ARRAY_REF_SET_VALUES:
9106 index = decode_int (p, &p, end);
9107 len = decode_int (p, &p, end);
9109 g_assert (index >= 0 && len >= 0);
9110 // Reordered to avoid integer overflow
9111 g_assert (!(index > arr->max_length - len));
9113 esize = mono_array_element_size (arr->obj.vtable->klass);
9114 for (i = index; i < index + len; ++i) {
9115 elem = (gpointer*)((char*)arr->vector + (i * esize));
9117 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9121 return ERR_NOT_IMPLEMENTED;
9128 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9133 int i, index, length;
9135 gboolean use_utf16 = FALSE;
9137 objid = decode_objid (p, &p, end);
9138 err = get_object (objid, (MonoObject**)&str);
9143 case CMD_STRING_REF_GET_VALUE:
9144 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9145 for (i = 0; i < mono_string_length (str); ++i)
9146 if (mono_string_chars (str)[i] == 0)
9148 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9151 buffer_add_int (buf, mono_string_length (str) * 2);
9152 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9154 s = mono_string_to_utf8 (str);
9155 buffer_add_string (buf, s);
9159 case CMD_STRING_REF_GET_LENGTH:
9160 buffer_add_long (buf, mono_string_length (str));
9162 case CMD_STRING_REF_GET_CHARS:
9163 index = decode_long (p, &p, end);
9164 length = decode_long (p, &p, end);
9165 if (index > mono_string_length (str) - length)
9166 return ERR_INVALID_ARGUMENT;
9167 c = mono_string_chars (str) + index;
9168 for (i = 0; i < length; ++i)
9169 buffer_add_short (buf, c [i]);
9172 return ERR_NOT_IMPLEMENTED;
9179 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9188 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9189 objid = decode_objid (p, &p, end);
9190 err = get_object (objid, &obj);
9192 buffer_add_int (buf, 1);
9194 buffer_add_int (buf, 0);
9198 objid = decode_objid (p, &p, end);
9199 err = get_object (objid, &obj);
9203 MonoClass *obj_type;
9205 obj_type = obj->vtable->klass;
9206 if (mono_class_is_transparent_proxy (obj_type))
9207 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9209 g_assert (obj_type);
9212 case CMD_OBJECT_REF_GET_TYPE:
9213 /* This handles transparent proxies too */
9214 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9216 case CMD_OBJECT_REF_GET_VALUES:
9217 len = decode_int (p, &p, end);
9219 for (i = 0; i < len; ++i) {
9220 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9224 /* Check that the field belongs to the object */
9226 for (k = obj_type; k; k = k->parent) {
9227 if (k == f->parent) {
9233 return ERR_INVALID_FIELDID;
9235 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9239 if (mono_class_field_is_special_static (f))
9240 return ERR_INVALID_FIELDID;
9242 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9243 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9244 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9245 mono_field_static_get_value (vtable, f, val);
9246 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9249 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9253 case CMD_OBJECT_REF_SET_VALUES:
9254 len = decode_int (p, &p, end);
9256 for (i = 0; i < len; ++i) {
9257 f = decode_fieldid (p, &p, end, NULL, &err);
9261 /* Check that the field belongs to the object */
9263 for (k = obj_type; k; k = k->parent) {
9264 if (k == f->parent) {
9270 return ERR_INVALID_FIELDID;
9272 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9276 if (mono_class_field_is_special_static (f))
9277 return ERR_INVALID_FIELDID;
9279 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9280 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9282 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9283 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9288 mono_field_static_set_value (vtable, f, val);
9291 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9297 case CMD_OBJECT_REF_GET_ADDRESS:
9298 buffer_add_long (buf, (gssize)obj);
9300 case CMD_OBJECT_REF_GET_DOMAIN:
9301 buffer_add_domainid (buf, obj->vtable->domain);
9303 case CMD_OBJECT_REF_GET_INFO:
9304 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9305 buffer_add_domainid (buf, obj->vtable->domain);
9308 return ERR_NOT_IMPLEMENTED;
9315 command_set_to_string (CommandSet command_set)
9317 switch (command_set) {
9320 case CMD_SET_OBJECT_REF:
9321 return "OBJECT_REF";
9322 case CMD_SET_STRING_REF:
9323 return "STRING_REF";
9324 case CMD_SET_THREAD:
9326 case CMD_SET_ARRAY_REF:
9328 case CMD_SET_EVENT_REQUEST:
9329 return "EVENT_REQUEST";
9330 case CMD_SET_STACK_FRAME:
9331 return "STACK_FRAME";
9332 case CMD_SET_APPDOMAIN:
9334 case CMD_SET_ASSEMBLY:
9336 case CMD_SET_METHOD:
9340 case CMD_SET_MODULE:
9351 static const char* vm_cmds_str [] = {
9359 "SET_PROTOCOL_VERSION",
9362 "GET_TYPES_FOR_SOURCE_FILE",
9367 static const char* thread_cmds_str[] = {
9377 static const char* event_cmds_str[] = {
9380 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9383 static const char* appdomain_cmds_str[] = {
9385 "GET_FRIENDLY_NAME",
9387 "GET_ENTRY_ASSEMBLY",
9390 "CREATE_BOXED_VALUE"
9393 static const char* assembly_cmds_str[] = {
9396 "GET_MANIFEST_MODULE",
9402 static const char* module_cmds_str[] = {
9406 static const char* field_cmds_str[] = {
9410 static const char* method_cmds_str[] = {
9412 "GET_DECLARING_TYPE",
9420 "MAKE_GENERIC_METHOD"
9423 static const char* type_cmds_str[] = {
9431 "IS_ASSIGNABLE_FROM",
9435 "GET_PROPERTY_CATTRS",
9436 "GET_SOURCE_FILES_2",
9438 "GET_METHODS_BY_NAME_FLAGS",
9440 "GET_INTERFACE_MAP",
9444 static const char* stack_frame_cmds_str[] = {
9451 static const char* array_cmds_str[] = {
9457 static const char* string_cmds_str[] = {
9463 static const char* object_cmds_str[] = {
9474 cmd_to_string (CommandSet set, int command)
9482 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9484 case CMD_SET_OBJECT_REF:
9485 cmds = object_cmds_str;
9486 cmds_len = G_N_ELEMENTS (object_cmds_str);
9488 case CMD_SET_STRING_REF:
9489 cmds = string_cmds_str;
9490 cmds_len = G_N_ELEMENTS (string_cmds_str);
9492 case CMD_SET_THREAD:
9493 cmds = thread_cmds_str;
9494 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9496 case CMD_SET_ARRAY_REF:
9497 cmds = array_cmds_str;
9498 cmds_len = G_N_ELEMENTS (array_cmds_str);
9500 case CMD_SET_EVENT_REQUEST:
9501 cmds = event_cmds_str;
9502 cmds_len = G_N_ELEMENTS (event_cmds_str);
9504 case CMD_SET_STACK_FRAME:
9505 cmds = stack_frame_cmds_str;
9506 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9508 case CMD_SET_APPDOMAIN:
9509 cmds = appdomain_cmds_str;
9510 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9512 case CMD_SET_ASSEMBLY:
9513 cmds = assembly_cmds_str;
9514 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9516 case CMD_SET_METHOD:
9517 cmds = method_cmds_str;
9518 cmds_len = G_N_ELEMENTS (method_cmds_str);
9521 cmds = type_cmds_str;
9522 cmds_len = G_N_ELEMENTS (type_cmds_str);
9524 case CMD_SET_MODULE:
9525 cmds = module_cmds_str;
9526 cmds_len = G_N_ELEMENTS (module_cmds_str);
9529 cmds = field_cmds_str;
9530 cmds_len = G_N_ELEMENTS (field_cmds_str);
9533 cmds = event_cmds_str;
9534 cmds_len = G_N_ELEMENTS (event_cmds_str);
9539 if (command > 0 && command <= cmds_len)
9540 return cmds [command - 1];
9546 wait_for_attach (void)
9548 #ifndef DISABLE_SOCKET_TRANSPORT
9549 if (listen_fd == -1) {
9550 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9554 /* Block and wait for client connection */
9555 MONO_PREPARE_BLOCKING;
9556 conn_fd = socket_transport_accept (listen_fd);
9557 MONO_FINISH_BLOCKING;
9559 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9560 if (conn_fd == -1) {
9561 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9565 g_assert_not_reached ();
9569 disconnected = !transport_handshake ();
9571 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9581 * This thread handles communication with the debugger client using a JDWP
9584 static guint32 WINAPI
9585 debugger_thread (void *arg)
9587 int res, len, id, flags, command_set = 0, command = 0;
9588 guint8 header [HEADER_LENGTH];
9589 guint8 *data, *p, *end;
9593 gboolean attach_failed = FALSE;
9595 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer)mono_native_thread_id_get ());
9597 debugger_thread_id = mono_native_thread_id_get ();
9599 mono_jit_thread_attach (mono_get_root_domain ());
9601 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9603 mono_set_is_debugger_attached (TRUE);
9605 if (agent_config.defer) {
9606 if (!wait_for_attach ()) {
9607 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9608 attach_failed = TRUE; // Don't abort process when we can't listen
9610 /* Send start event to client */
9611 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9615 while (!attach_failed) {
9616 MONO_PREPARE_BLOCKING;
9617 res = transport_recv (header, HEADER_LENGTH);
9618 MONO_FINISH_BLOCKING;
9620 /* This will break if the socket is closed during shutdown too */
9621 if (res != HEADER_LENGTH) {
9622 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9627 end = header + HEADER_LENGTH;
9629 len = decode_int (p, &p, end);
9630 id = decode_int (p, &p, end);
9631 flags = decode_byte (p, &p, end);
9632 command_set = decode_byte (p, &p, end);
9633 command = decode_byte (p, &p, end);
9635 g_assert (flags == 0);
9638 const char *cmd_str;
9641 cmd_str = cmd_to_string (command_set, command);
9643 sprintf (cmd_num, "%d", command);
9647 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);
9650 data = g_malloc (len - HEADER_LENGTH);
9651 if (len - HEADER_LENGTH > 0)
9653 MONO_PREPARE_BLOCKING;
9654 res = transport_recv (data, len - HEADER_LENGTH);
9655 MONO_FINISH_BLOCKING;
9656 if (res != len - HEADER_LENGTH) {
9657 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9663 end = data + (len - HEADER_LENGTH);
9665 buffer_init (&buf, 128);
9670 /* Process the request */
9671 switch (command_set) {
9673 err = vm_commands (command, id, p, end, &buf);
9674 if (!err && command == CMD_VM_INVOKE_METHOD)
9675 /* Sent after the invoke is complete */
9678 case CMD_SET_EVENT_REQUEST:
9679 err = event_commands (command, p, end, &buf);
9681 case CMD_SET_APPDOMAIN:
9682 err = domain_commands (command, p, end, &buf);
9684 case CMD_SET_ASSEMBLY:
9685 err = assembly_commands (command, p, end, &buf);
9687 case CMD_SET_MODULE:
9688 err = module_commands (command, p, end, &buf);
9691 err = field_commands (command, p, end, &buf);
9694 err = type_commands (command, p, end, &buf);
9696 case CMD_SET_METHOD:
9697 err = method_commands (command, p, end, &buf);
9699 case CMD_SET_THREAD:
9700 err = thread_commands (command, p, end, &buf);
9702 case CMD_SET_STACK_FRAME:
9703 err = frame_commands (command, p, end, &buf);
9705 case CMD_SET_ARRAY_REF:
9706 err = array_commands (command, p, end, &buf);
9708 case CMD_SET_STRING_REF:
9709 err = string_commands (command, p, end, &buf);
9711 case CMD_SET_OBJECT_REF:
9712 err = object_commands (command, p, end, &buf);
9715 err = ERR_NOT_IMPLEMENTED;
9718 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9719 buffer_replies = TRUE;
9723 if (buffer_replies) {
9724 buffer_reply_packet (id, err, &buf);
9726 send_reply_packet (id, err, &buf);
9727 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9731 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9732 send_buffered_reply_packets ();
9733 buffer_replies = FALSE;
9739 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9743 mono_set_is_debugger_attached (FALSE);
9746 mono_mutex_lock (&debugger_thread_exited_mutex);
9747 debugger_thread_exited = TRUE;
9748 mono_cond_signal (&debugger_thread_exited_cond);
9749 mono_mutex_unlock (&debugger_thread_exited_mutex);
9750 MONO_FINISH_TRY_BLOCKING;
9752 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9754 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9755 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9756 start_debugger_thread ();
9762 #else /* DISABLE_DEBUGGER_AGENT */
9765 mono_debugger_agent_parse_options (char *options)
9767 g_error ("This runtime is configured with the debugger agent disabled.");
9771 mono_debugger_agent_init (void)
9776 mono_debugger_agent_breakpoint_hit (void *sigctx)
9781 mono_debugger_agent_single_step_event (void *sigctx)
9786 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9791 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9792 MonoContext *catch_ctx)
9797 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9802 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9807 mono_debugger_agent_user_break (void)
9813 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9818 mono_debugger_agent_debug_log_is_enabled (void)
9824 mono_debugger_agent_unhandled_exception (MonoException *exc)
9826 g_assert_not_reached ();
9830 debugger_agent_single_step_from_context (MonoContext *ctx)
9832 g_assert_not_reached ();
9836 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9838 g_assert_not_reached ();