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>
43 #ifdef HAVE_UCONTEXT_H
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
62 #ifdef PLATFORM_ANDROID
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/utils/mono-semaphore.h>
76 #include <mono/utils/mono-error-internals.h>
77 #include <mono/utils/mono-stack-unwinding.h>
78 #include <mono/utils/mono-time.h>
79 #include "debugger-agent.h"
82 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
83 #define DISABLE_DEBUGGER_AGENT 1
86 #ifdef DISABLE_SOFT_DEBUG
87 #define DISABLE_DEBUGGER_AGENT 1
91 #include <mono/utils/mono-threads.h>
94 #ifndef DISABLE_DEBUGGER_AGENT
96 #include <mono/io-layer/mono-mutex.h>
98 /* Definitions to make backporting to 2.6 easier */
99 //#define MonoInternalThread MonoThread
100 //#define mono_thread_internal_current mono_thread_current
101 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
123 guint32 il_offset, native_offset;
127 * If method is gshared, this is the actual instance, otherwise this is equal to
130 MonoMethod *actual_method;
132 MonoDebugMethodJitInfo *jit;
134 mgreg_t *reg_locations [MONO_MAX_IREGS];
136 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
137 * the frame can become invalid.
142 typedef struct _InvokeData InvokeData;
150 /* This is the context which needs to be restored after the invoke */
154 * If this is set, invoke this method with the arguments given by ARGS.
158 guint32 suspend_count;
160 InvokeData *last_invoke;
164 MonoThreadUnwindState context;
166 gpointer resume_event;
167 /* This is computed on demand when it is requested using the wire protocol */
168 /* It is freed up when the thread is resumed */
172 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
175 gboolean frames_up_to_date;
177 * Points to data about a pending invoke which needs to be executed after the thread
180 InvokeData *pending_invoke;
182 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
187 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
188 * within a finite amount of time.
192 * Set to TRUE if this thread is suspended in suspend_current ().
194 gboolean really_suspended;
195 /* Used to pass the context to the breakpoint/single step handler */
196 MonoContext handler_ctx;
197 /* Whenever thread_stop () was called for this thread */
200 /* Number of thread interruptions not yet processed */
201 gint32 interrupt_count;
203 /* Whenever to disable breakpoints (used during invokes) */
204 gboolean disable_breakpoints;
207 * Number of times this thread has been resumed using resume_thread ().
209 guint32 resume_count;
211 MonoInternalThread *thread;
214 * Information about the frame which transitioned to native code for running
217 StackFrameInfo async_last_frame;
220 * The context where the stack walk can be started for running threads.
222 MonoThreadUnwindState async_state;
225 * The context used for filter clauses
227 MonoThreadUnwindState filter_state;
230 * The callee address of the last mono_runtime_invoke call
232 gpointer invoke_addr;
234 gboolean abort_requested;
237 * The current mono_runtime_invoke invocation.
242 * The context where single stepping should resume while the thread is suspended because
243 * of an EXCEPTION event.
245 MonoContext catch_ctx;
247 gboolean has_catch_ctx;
250 * The context which needs to be restored after handling a single step/breakpoint
251 * event. This is the same as the ctx at step/breakpoint site, but includes changes
252 * to caller saved registers done by set_var ().
254 MonoContext restore_ctx;
259 void (*connect) (const char *address);
260 void (*close1) (void);
261 void (*close2) (void);
262 gboolean (*send) (void *buf, int len);
263 int (*recv) (void *buf, int len);
267 * Wire Protocol definitions
270 #define HEADER_LENGTH 11
272 #define MAJOR_VERSION 2
273 #define MINOR_VERSION 17
277 CMD_SET_OBJECT_REF = 9,
278 CMD_SET_STRING_REF = 10,
280 CMD_SET_ARRAY_REF = 13,
281 CMD_SET_EVENT_REQUEST = 15,
282 CMD_SET_STACK_FRAME = 16,
283 CMD_SET_APPDOMAIN = 20,
284 CMD_SET_ASSEMBLY = 21,
292 EVENT_KIND_VM_START = 0,
293 EVENT_KIND_VM_DEATH = 1,
294 EVENT_KIND_THREAD_START = 2,
295 EVENT_KIND_THREAD_DEATH = 3,
296 EVENT_KIND_APPDOMAIN_CREATE = 4,
297 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
298 EVENT_KIND_METHOD_ENTRY = 6,
299 EVENT_KIND_METHOD_EXIT = 7,
300 EVENT_KIND_ASSEMBLY_LOAD = 8,
301 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
302 EVENT_KIND_BREAKPOINT = 10,
303 EVENT_KIND_STEP = 11,
304 EVENT_KIND_TYPE_LOAD = 12,
305 EVENT_KIND_EXCEPTION = 13,
306 EVENT_KIND_KEEPALIVE = 14,
307 EVENT_KIND_USER_BREAK = 15,
308 EVENT_KIND_USER_LOG = 16
312 SUSPEND_POLICY_NONE = 0,
313 SUSPEND_POLICY_EVENT_THREAD = 1,
314 SUSPEND_POLICY_ALL = 2
319 ERR_INVALID_OBJECT = 20,
320 ERR_INVALID_FIELDID = 25,
321 ERR_INVALID_FRAMEID = 30,
322 ERR_NOT_IMPLEMENTED = 100,
323 ERR_NOT_SUSPENDED = 101,
324 ERR_INVALID_ARGUMENT = 102,
326 ERR_NO_INVOCATION = 104,
327 ERR_ABSENT_INFORMATION = 105,
328 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
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
355 STEP_FILTER_NONE = 0,
356 STEP_FILTER_STATIC_CTOR = 1
360 TOKEN_TYPE_STRING = 0,
362 TOKEN_TYPE_FIELD = 2,
363 TOKEN_TYPE_METHOD = 3,
364 TOKEN_TYPE_UNKNOWN = 4
368 VALUE_TYPE_ID_NULL = 0xf0,
369 VALUE_TYPE_ID_TYPE = 0xf1
373 FRAME_FLAG_DEBUGGER_INVOKE = 1,
374 FRAME_FLAG_NATIVE_TRANSITION = 2
378 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
379 INVOKE_FLAG_SINGLE_THREADED = 2
383 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
384 } BindingFlagsExtensions;
388 CMD_VM_ALL_THREADS = 2,
393 CMD_VM_INVOKE_METHOD = 7,
394 CMD_VM_SET_PROTOCOL_VERSION = 8,
395 CMD_VM_ABORT_INVOKE = 9,
396 CMD_VM_SET_KEEPALIVE = 10,
397 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
398 CMD_VM_GET_TYPES = 12
402 CMD_THREAD_GET_FRAME_INFO = 1,
403 CMD_THREAD_GET_NAME = 2,
404 CMD_THREAD_GET_STATE = 3,
405 CMD_THREAD_GET_INFO = 4,
406 CMD_THREAD_GET_ID = 5,
407 CMD_THREAD_GET_TID = 6
411 CMD_EVENT_REQUEST_SET = 1,
412 CMD_EVENT_REQUEST_CLEAR = 2,
413 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
421 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
422 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
423 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
424 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
425 CMD_APPDOMAIN_CREATE_STRING = 5,
426 CMD_APPDOMAIN_GET_CORLIB = 6,
427 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
431 CMD_ASSEMBLY_GET_LOCATION = 1,
432 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
433 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
434 CMD_ASSEMBLY_GET_OBJECT = 4,
435 CMD_ASSEMBLY_GET_TYPE = 5,
436 CMD_ASSEMBLY_GET_NAME = 6
440 CMD_MODULE_GET_INFO = 1,
444 CMD_METHOD_GET_NAME = 1,
445 CMD_METHOD_GET_DECLARING_TYPE = 2,
446 CMD_METHOD_GET_DEBUG_INFO = 3,
447 CMD_METHOD_GET_PARAM_INFO = 4,
448 CMD_METHOD_GET_LOCALS_INFO = 5,
449 CMD_METHOD_GET_INFO = 6,
450 CMD_METHOD_GET_BODY = 7,
451 CMD_METHOD_RESOLVE_TOKEN = 8,
455 CMD_TYPE_GET_INFO = 1,
456 CMD_TYPE_GET_METHODS = 2,
457 CMD_TYPE_GET_FIELDS = 3,
458 CMD_TYPE_GET_VALUES = 4,
459 CMD_TYPE_GET_OBJECT = 5,
460 CMD_TYPE_GET_SOURCE_FILES = 6,
461 CMD_TYPE_SET_VALUES = 7,
462 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
463 CMD_TYPE_GET_PROPERTIES = 9,
464 CMD_TYPE_GET_CATTRS = 10,
465 CMD_TYPE_GET_FIELD_CATTRS = 11,
466 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
467 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
468 CMD_TYPE_GET_VALUES_2 = 14,
469 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
470 CMD_TYPE_GET_INTERFACES = 16,
471 CMD_TYPE_GET_INTERFACE_MAP = 17,
475 CMD_STACK_FRAME_GET_VALUES = 1,
476 CMD_STACK_FRAME_GET_THIS = 2,
477 CMD_STACK_FRAME_SET_VALUES = 3
481 CMD_ARRAY_REF_GET_LENGTH = 1,
482 CMD_ARRAY_REF_GET_VALUES = 2,
483 CMD_ARRAY_REF_SET_VALUES = 3,
487 CMD_STRING_REF_GET_VALUE = 1,
488 CMD_STRING_REF_GET_LENGTH = 2,
489 CMD_STRING_REF_GET_CHARS = 3
493 CMD_OBJECT_REF_GET_TYPE = 1,
494 CMD_OBJECT_REF_GET_VALUES = 2,
495 CMD_OBJECT_REF_IS_COLLECTED = 3,
496 CMD_OBJECT_REF_GET_ADDRESS = 4,
497 CMD_OBJECT_REF_GET_DOMAIN = 5,
498 CMD_OBJECT_REF_SET_VALUES = 6,
499 CMD_OBJECT_REF_GET_INFO = 7,
505 int count; /* For kind == MOD_KIND_COUNT */
506 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
507 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
508 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
509 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
510 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
511 StepFilter filter; /* For kind == MOD_KIND_STEP */
513 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
522 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
526 * Describes a single step request.
530 MonoInternalThread *thread;
536 MonoMethod *last_method;
538 /* Whenever single stepping is performed using start/stop_single_stepping () */
540 /* The list of breakpoints used to implement step-over */
545 * Contains additional information for an event
548 /* For EVENT_KIND_EXCEPTION */
550 MonoContext catch_ctx;
552 /* For EVENT_KIND_USER_LOG */
554 char *category, *message;
555 /* For EVENT_KIND_TYPE_LOAD */
559 /* Dummy structure used for the profiler callbacks */
564 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
567 #define get_last_sock_error() WSAGetLastError()
568 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
569 #define MONO_EINTR WSAEINTR
571 #define get_last_sock_error() errno
572 #define MONO_EWOULDBLOCK EWOULDBLOCK
573 #define MONO_EINTR EINTR
576 #define CHECK_PROTOCOL_VERSION(major,minor) \
577 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
583 static AgentConfig agent_config;
586 * Whenever the agent is fully initialized.
587 * When using the onuncaught or onthrow options, only some parts of the agent are
588 * initialized on startup, and the full initialization which includes connection
589 * establishment and the startup of the agent thread is only done in response to
592 static gint32 inited;
594 #ifndef DISABLE_SOCKET_TRANSPORT
596 static int listen_fd;
599 static int packet_id = 0;
601 static int objref_id = 0;
603 static int event_request_id = 0;
605 static int frame_id = 0;
607 static GPtrArray *event_requests;
609 static MonoNativeTlsKey debugger_tls_id;
611 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
613 /* Maps MonoInternalThread -> DebuggerTlsData */
614 static MonoGHashTable *thread_to_tls;
616 /* Maps tid -> MonoInternalThread */
617 static MonoGHashTable *tid_to_thread;
619 /* Maps tid -> MonoThread (not MonoInternalThread) */
620 static MonoGHashTable *tid_to_thread_obj;
622 static gsize debugger_thread_id;
624 static HANDLE debugger_thread_handle;
626 static int log_level;
628 static gboolean embedding;
630 static FILE *log_file;
632 /* Assemblies whose assembly load event has no been sent yet */
633 static GPtrArray *pending_assembly_loads;
635 /* Whenever the debugger thread has exited */
636 static gboolean debugger_thread_exited;
638 /* Cond variable used to wait for debugger_thread_exited becoming true */
639 static mono_cond_t debugger_thread_exited_cond;
641 /* Mutex for the cond var above */
642 static mono_mutex_t debugger_thread_exited_mutex;
644 static DebuggerProfiler debugger_profiler;
646 /* The single step request instance */
647 static SingleStepReq *ss_req = NULL;
648 static gpointer ss_invoke_addr = NULL;
650 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
651 /* Number of single stepping operations in progress */
655 /* The protocol version of the client */
656 static int major_version, minor_version;
658 /* Whenever the variables above are set by the client */
659 static gboolean protocol_version_set;
661 /* A hash table containing all active domains */
662 static GHashTable *domains;
664 static void transport_init (void);
665 static void transport_connect (const char *address);
666 static gboolean transport_handshake (void);
667 static void register_transport (DebuggerTransport *trans);
669 static guint32 WINAPI debugger_thread (void *arg);
671 static void runtime_initialized (MonoProfiler *prof);
673 static void runtime_shutdown (MonoProfiler *prof);
675 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
677 static void thread_end (MonoProfiler *prof, uintptr_t tid);
679 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
681 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
683 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
685 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
687 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
689 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
691 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
693 static void emit_assembly_load (gpointer assembly, gpointer user_data);
695 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
697 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
699 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
701 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
703 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
705 static void start_single_stepping (void);
707 static void stop_single_stepping (void);
709 static void suspend_current (void);
711 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
713 static void clear_types_for_assembly (MonoAssembly *assembly);
715 static void clear_breakpoints_for_domain (MonoDomain *domain);
717 static void process_profiler_event (EventKind event, gpointer arg);
719 /* Submodule init/cleanup */
720 static void breakpoints_init (void);
721 static void breakpoints_cleanup (void);
723 static void objrefs_init (void);
724 static void objrefs_cleanup (void);
726 static void ids_init (void);
727 static void ids_cleanup (void);
729 static void suspend_init (void);
731 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
732 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
733 static void ss_destroy (SingleStepReq *req);
735 static void start_debugger_thread (void);
736 static void stop_debugger_thread (void);
738 static void finish_agent_init (gboolean on_startup);
740 static void process_profiler_event (EventKind event, gpointer arg);
742 #ifndef DISABLE_SOCKET_TRANSPORT
744 register_socket_transport (void);
748 parse_address (char *address, char **host, int *port)
750 char *pos = strchr (address, ':');
752 if (pos == NULL || pos == address)
755 *host = g_malloc (pos - address + 1);
756 strncpy (*host, address, pos - address);
757 (*host) [pos - address] = '\0';
759 *port = atoi (pos + 1);
767 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
768 fprintf (stderr, "Available options:\n");
769 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
770 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
771 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
772 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
773 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
774 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
775 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
776 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
777 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
781 parse_flag (const char *option, char *flag)
783 if (!strcmp (flag, "y"))
785 else if (!strcmp (flag, "n"))
788 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
795 mono_debugger_agent_parse_options (char *options)
802 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
803 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
807 extra = getenv ("MONO_SDB_ENV_OPTIONS");
809 options = g_strdup_printf ("%s,%s", options, extra);
811 agent_config.enabled = TRUE;
812 agent_config.suspend = TRUE;
813 agent_config.server = FALSE;
814 agent_config.defer = FALSE;
815 agent_config.address = NULL;
817 args = g_strsplit (options, ",", -1);
818 for (ptr = args; ptr && *ptr; ptr ++) {
821 if (strncmp (arg, "transport=", 10) == 0) {
822 agent_config.transport = g_strdup (arg + 10);
823 } else if (strncmp (arg, "address=", 8) == 0) {
824 agent_config.address = g_strdup (arg + 8);
825 } else if (strncmp (arg, "loglevel=", 9) == 0) {
826 agent_config.log_level = atoi (arg + 9);
827 } else if (strncmp (arg, "logfile=", 8) == 0) {
828 agent_config.log_file = g_strdup (arg + 8);
829 } else if (strncmp (arg, "suspend=", 8) == 0) {
830 agent_config.suspend = parse_flag ("suspend", arg + 8);
831 } else if (strncmp (arg, "server=", 7) == 0) {
832 agent_config.server = parse_flag ("server", arg + 7);
833 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
834 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
835 } else if (strncmp (arg, "onthrow=", 8) == 0) {
836 /* We support multiple onthrow= options */
837 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
838 } else if (strncmp (arg, "onthrow", 7) == 0) {
839 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
840 } else if (strncmp (arg, "help", 4) == 0) {
843 } else if (strncmp (arg, "timeout=", 8) == 0) {
844 agent_config.timeout = atoi (arg + 8);
845 } else if (strncmp (arg, "launch=", 7) == 0) {
846 agent_config.launch = g_strdup (arg + 7);
847 } else if (strncmp (arg, "embedding=", 10) == 0) {
848 agent_config.embedding = atoi (arg + 10) == 1;
849 } else if (strncmp (arg, "keepalive=", 10) == 0) {
850 agent_config.keepalive = atoi (arg + 10);
857 if (agent_config.server && !agent_config.suspend) {
858 /* Waiting for deferred attachment */
859 agent_config.defer = TRUE;
860 if (agent_config.address == NULL) {
861 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
865 if (agent_config.transport == NULL) {
866 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
870 if (agent_config.address == NULL && !agent_config.server) {
871 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
876 if (!strcmp (agent_config.transport, "dt_socket")) {
877 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
878 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
885 mono_debugger_agent_init (void)
887 if (!agent_config.enabled)
892 /* Need to know whenever a thread has acquired the loader mutex */
893 mono_loader_lock_track_ownership (TRUE);
895 event_requests = g_ptr_array_new ();
897 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
898 mono_cond_init (&debugger_thread_exited_cond, NULL);
900 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
901 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
902 mono_profiler_install_runtime_initialized (runtime_initialized);
903 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
904 mono_profiler_install_thread (thread_startup, thread_end);
905 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
906 mono_profiler_install_jit_end (jit_end);
907 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
909 mono_native_tls_alloc (&debugger_tls_id, NULL);
911 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
912 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
914 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
915 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
917 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
918 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
920 pending_assembly_loads = g_ptr_array_new ();
921 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
923 log_level = agent_config.log_level;
925 embedding = agent_config.embedding;
928 if (agent_config.log_file) {
929 log_file = fopen (agent_config.log_file, "w+");
931 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
943 mini_get_debug_options ()->gen_seq_points = TRUE;
945 * This is needed because currently we don't handle liveness info.
947 mini_get_debug_options ()->mdb_optimizations = TRUE;
949 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
950 /* This is needed because we can't set local variables in registers yet */
951 mono_disable_optimizations (MONO_OPT_LINEARS);
955 * The stack walk done from thread_interrupt () needs to be signal safe, but it
956 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
957 * safe (#3411). So load AOT info eagerly when the debugger is running as a
960 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
962 if (!agent_config.onuncaught && !agent_config.onthrow)
963 finish_agent_init (TRUE);
965 /* FIXME: Is this still needed ? */
966 #if defined(__MACH__)
967 mono_thread_info_disable_new_interrupt (TRUE);
974 * Finish the initialization of the agent. This involves connecting the transport
975 * and starting the agent thread. This is either done at startup, or
976 * in response to some event like an unhandled exception.
979 finish_agent_init (gboolean on_startup)
983 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
986 if (agent_config.launch) {
989 // FIXME: Generated address
990 // FIXME: Races with transport_connect ()
992 argv [0] = agent_config.launch;
993 argv [1] = agent_config.transport;
994 argv [2] = agent_config.address;
997 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
999 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1004 transport_connect (agent_config.address);
1007 /* Do some which is usually done after sending the VMStart () event */
1008 vm_start_event_sent = TRUE;
1009 start_debugger_thread ();
1014 mono_debugger_agent_cleanup (void)
1019 stop_debugger_thread ();
1021 breakpoints_cleanup ();
1025 mono_mutex_destroy (&debugger_thread_exited_mutex);
1026 mono_cond_destroy (&debugger_thread_exited_cond);
1033 #ifndef DISABLE_SOCKET_TRANSPORT
1038 * recv() + handle incomplete reads and EINTR
1041 socket_transport_recv (void *buf, int len)
1050 res = recv (fd, (char *) buf + total, len - total, flags);
1053 if (agent_config.keepalive && res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1054 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1057 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1062 #define HAVE_GETADDRINFO 1
1066 set_keepalive (void)
1071 if (!agent_config.keepalive)
1074 tv.tv_sec = agent_config.keepalive / 1000;
1075 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1077 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1078 g_assert (result >= 0);
1082 socket_transport_accept (int socket_fd)
1084 conn_fd = accept (socket_fd, NULL, NULL);
1085 if (conn_fd == -1) {
1086 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1088 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1095 socket_transport_send (void *data, int len)
1100 res = send (conn_fd, data, len, 0);
1101 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1109 * socket_transport_connect:
1111 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1114 socket_transport_connect (const char *address)
1116 #ifdef HAVE_GETADDRINFO
1117 struct addrinfo hints;
1118 struct addrinfo *result, *rp;
1120 struct hostent *result;
1122 int sfd = -1, s, res;
1123 char port_string [128];
1127 if (agent_config.address) {
1128 res = parse_address (agent_config.address, &host, &port);
1129 g_assert (res == 0);
1139 sprintf (port_string, "%d", port);
1141 mono_network_init ();
1143 /* Obtain address(es) matching host/port */
1144 #ifdef HAVE_GETADDRINFO
1145 memset (&hints, 0, sizeof (struct addrinfo));
1146 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1147 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1149 hints.ai_protocol = 0; /* Any protocol */
1151 s = getaddrinfo (host, port_string, &hints, &result);
1153 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1157 /* The PS3 doesn't even have _r or hstrerror () */
1158 result = gethostbyname (host);
1160 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1165 if (agent_config.server) {
1166 #ifdef HAVE_GETADDRINFO
1167 /* Wait for a connection */
1169 struct sockaddr_in addr;
1172 /* No address, generate one */
1173 sfd = socket (AF_INET, SOCK_STREAM, 0);
1176 /* This will bind the socket to a random port */
1177 res = listen (sfd, 16);
1179 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1184 addrlen = sizeof (addr);
1185 memset (&addr, 0, sizeof (addr));
1186 res = getsockname (sfd, &addr, &addrlen);
1187 g_assert (res == 0);
1189 host = (char*)"127.0.0.1";
1190 port = ntohs (addr.sin_port);
1192 /* Emit the address to stdout */
1193 /* FIXME: Should print another interface, not localhost */
1194 printf ("%s:%d\n", host, port);
1196 /* Listen on the provided address */
1197 for (rp = result; rp != NULL; rp = rp->ai_next) {
1200 sfd = socket (rp->ai_family, rp->ai_socktype,
1205 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1208 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1212 res = listen (sfd, 16);
1221 * this function is not present on win2000 which we still support, and the
1222 * workaround described here:
1223 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1224 * only works with MSVC.
1226 #ifdef HAVE_GETADDRINFO
1227 freeaddrinfo (result);
1232 if (agent_config.defer)
1235 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1237 if (agent_config.timeout) {
1242 tv.tv_usec = agent_config.timeout * 1000;
1244 FD_SET (sfd, &readfds);
1245 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1247 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1252 conn_fd = socket_transport_accept (sfd);
1256 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1259 #endif /* HAVE_GETADDRINFO */
1261 /* Connect to the specified address */
1262 #ifdef HAVE_GETADDRINFO
1263 /* FIXME: Respect the timeout */
1264 for (rp = result; rp != NULL; rp = rp->ai_next) {
1265 sfd = socket (rp->ai_family, rp->ai_socktype,
1270 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1271 break; /* Success */
1277 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1281 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1283 g_assert_not_reached ();
1284 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1286 g_assert_not_reached ();
1292 /* See the comment above */
1293 #ifdef HAVE_GETADDRINFO
1294 freeaddrinfo (result);
1299 disconnected = !transport_handshake ();
1305 socket_transport_close1 (void)
1307 /* This will interrupt the agent thread */
1308 /* Close the read part only so it can still send back replies */
1309 /* Also shut down the connection listener so that we can exit normally */
1311 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1312 shutdown (conn_fd, SD_BOTH);
1313 shutdown (listen_fd, SD_BOTH);
1314 closesocket (listen_fd);
1316 shutdown (conn_fd, SHUT_RD);
1317 shutdown (listen_fd, SHUT_RDWR);
1323 socket_transport_close2 (void)
1326 shutdown (conn_fd, SD_BOTH);
1328 shutdown (conn_fd, SHUT_RDWR);
1333 register_socket_transport (void)
1335 DebuggerTransport trans;
1337 trans.name = "dt_socket";
1338 trans.connect = socket_transport_connect;
1339 trans.close1 = socket_transport_close1;
1340 trans.close2 = socket_transport_close2;
1341 trans.send = socket_transport_send;
1342 trans.recv = socket_transport_recv;
1344 register_transport (&trans);
1347 #endif /* DISABLE_SOCKET_TRANSPORT */
1353 #define MAX_TRANSPORTS 16
1355 static DebuggerTransport *transport;
1357 static DebuggerTransport transports [MAX_TRANSPORTS];
1358 static int ntransports;
1361 register_transport (DebuggerTransport *trans)
1363 g_assert (ntransports < MAX_TRANSPORTS);
1365 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1370 transport_init (void)
1374 #ifndef DISABLE_SOCKET_TRANSPORT
1375 register_socket_transport ();
1378 for (i = 0; i < ntransports; ++i) {
1379 if (!strcmp (agent_config.transport, transports [i].name))
1382 if (i == ntransports) {
1383 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1384 for (i = 0; i < ntransports; ++i)
1385 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1386 fprintf (stderr, "\n");
1389 transport = &transports [i];
1393 transport_connect (const char *address)
1395 transport->connect (address);
1399 transport_close1 (void)
1401 transport->close1 ();
1405 transport_close2 (void)
1407 transport->close2 ();
1411 transport_send (void *buf, int len)
1413 return transport->send (buf, len);
1417 transport_recv (void *buf, int len)
1419 return transport->recv (buf, len);
1423 transport_handshake (void)
1425 char handshake_msg [128];
1429 /* Write handshake message */
1430 sprintf (handshake_msg, "DWP-Handshake");
1432 res = transport_send (handshake_msg, strlen (handshake_msg));
1433 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1434 g_assert (res != -1);
1437 res = transport_recv (buf, strlen (handshake_msg));
1438 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1439 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1444 * To support older clients, the client sends its protocol version after connecting
1445 * using a command. Until that is received, default to our protocol version.
1447 major_version = MAJOR_VERSION;
1448 minor_version = MINOR_VERSION;
1449 protocol_version_set = FALSE;
1451 #ifndef DISABLE_SOCKET_TRANSPORT
1452 // FIXME: Move this somewhere else
1454 * Set TCP_NODELAY on the socket so the client receives events/command
1455 * results immediately.
1459 int result = setsockopt (conn_fd,
1464 g_assert (result >= 0);
1474 stop_debugger_thread (void)
1479 transport_close1 ();
1482 * Wait for the thread to exit.
1484 * If we continue with the shutdown without waiting for it, then the client might
1485 * not receive an answer to its last command like a resume.
1486 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1489 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1490 if (GetCurrentThreadId () != debugger_thread_id) {
1492 mono_mutex_lock (&debugger_thread_exited_mutex);
1493 if (!debugger_thread_exited) {
1495 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1496 mono_mutex_unlock (&debugger_thread_exited_mutex);
1498 mono_mutex_lock (&debugger_thread_exited_mutex);
1501 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1504 mono_mutex_unlock (&debugger_thread_exited_mutex);
1505 } while (!debugger_thread_exited);
1508 transport_close2 ();
1512 start_debugger_thread (void)
1516 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1517 g_assert (debugger_thread_handle);
1521 * Functions to decode protocol data
1525 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1528 g_assert (*endbuf <= limit);
1533 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1536 g_assert (*endbuf <= limit);
1538 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1541 static inline gint64
1542 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1544 guint32 high = decode_int (buf, &buf, limit);
1545 guint32 low = decode_int (buf, &buf, limit);
1549 return ((((guint64)high) << 32) | ((guint64)low));
1553 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1555 return decode_int (buf, endbuf, limit);
1559 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1561 int len = decode_int (buf, &buf, limit);
1569 s = g_malloc (len + 1);
1572 memcpy (s, buf, len);
1581 * Functions to encode protocol data
1585 guint8 *buf, *p, *end;
1589 buffer_init (Buffer *buf, int size)
1591 buf->buf = g_malloc (size);
1593 buf->end = buf->buf + size;
1597 buffer_make_room (Buffer *buf, int size)
1599 if (buf->end - buf->p < size) {
1600 int new_size = buf->end - buf->buf + size + 32;
1601 guint8 *p = g_realloc (buf->buf, new_size);
1602 size = buf->p - buf->buf;
1605 buf->end = buf->buf + new_size;
1610 buffer_add_byte (Buffer *buf, guint8 val)
1612 buffer_make_room (buf, 1);
1618 buffer_add_short (Buffer *buf, guint32 val)
1620 buffer_make_room (buf, 2);
1621 buf->p [0] = (val >> 8) & 0xff;
1622 buf->p [1] = (val >> 0) & 0xff;
1627 buffer_add_int (Buffer *buf, guint32 val)
1629 buffer_make_room (buf, 4);
1630 buf->p [0] = (val >> 24) & 0xff;
1631 buf->p [1] = (val >> 16) & 0xff;
1632 buf->p [2] = (val >> 8) & 0xff;
1633 buf->p [3] = (val >> 0) & 0xff;
1638 buffer_add_long (Buffer *buf, guint64 l)
1640 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1641 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1645 buffer_add_id (Buffer *buf, int id)
1647 buffer_add_int (buf, (guint64)id);
1651 buffer_add_data (Buffer *buf, guint8 *data, int len)
1653 buffer_make_room (buf, len);
1654 memcpy (buf->p, data, len);
1659 buffer_add_string (Buffer *buf, const char *str)
1664 buffer_add_int (buf, 0);
1667 buffer_add_int (buf, len);
1668 buffer_add_data (buf, (guint8*)str, len);
1673 buffer_free (Buffer *buf)
1679 send_packet (int command_set, int command, Buffer *data)
1685 id = InterlockedIncrement (&packet_id);
1687 len = data->p - data->buf + 11;
1688 buffer_init (&buf, len);
1689 buffer_add_int (&buf, len);
1690 buffer_add_int (&buf, id);
1691 buffer_add_byte (&buf, 0); /* flags */
1692 buffer_add_byte (&buf, command_set);
1693 buffer_add_byte (&buf, command);
1694 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1696 res = transport_send (buf.buf, len);
1704 send_reply_packet (int id, int error, Buffer *data)
1710 len = data->p - data->buf + 11;
1711 buffer_init (&buf, len);
1712 buffer_add_int (&buf, len);
1713 buffer_add_int (&buf, id);
1714 buffer_add_byte (&buf, 0x80); /* flags */
1715 buffer_add_byte (&buf, (error >> 8) & 0xff);
1716 buffer_add_byte (&buf, error);
1717 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1719 res = transport_send (buf.buf, len);
1731 * Represents an object accessible by the debugger client.
1734 /* Unique id used in the wire protocol to refer to objects */
1737 * A weakref gc handle pointing to the object. The gc handle is used to
1738 * detect if the object was garbage collected.
1743 /* Maps objid -> ObjRef */
1744 static GHashTable *objrefs;
1747 free_objref (gpointer value)
1751 mono_gchandle_free (o->handle);
1759 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1763 objrefs_cleanup (void)
1765 g_hash_table_destroy (objrefs);
1769 static GHashTable *obj_to_objref;
1772 * Return an ObjRef for OBJ.
1775 get_objref (MonoObject *obj)
1778 GSList *reflist = NULL, *l;
1784 mono_loader_lock ();
1787 obj_to_objref = g_hash_table_new (NULL, NULL);
1789 /* FIXME: The tables can grow indefinitely */
1791 if (mono_gc_is_moving ()) {
1793 * Objects can move, so use a hash table mapping hash codes to lists of
1794 * ObjRef structures.
1796 hash = mono_object_hash (obj);
1798 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1799 for (l = reflist; l; l = l->next) {
1801 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1802 mono_loader_unlock ();
1807 /* Use a hash table with masked pointers to internalize object references */
1808 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1809 /* ref might refer to a different object with the same addr which was GCd */
1810 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1811 mono_loader_unlock ();
1816 ref = g_new0 (ObjRef, 1);
1817 ref->id = InterlockedIncrement (&objref_id);
1818 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1820 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1822 if (mono_gc_is_moving ()) {
1823 reflist = g_slist_append (reflist, ref);
1824 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1826 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1829 mono_loader_unlock ();
1835 get_objid (MonoObject *obj)
1837 return get_objref (obj)->id;
1841 * Set OBJ to the object identified by OBJID.
1842 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1846 get_object_allow_null (int objid, MonoObject **obj)
1856 return ERR_INVALID_OBJECT;
1858 mono_loader_lock ();
1860 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1863 *obj = mono_gchandle_get_target (ref->handle);
1864 mono_loader_unlock ();
1866 return ERR_INVALID_OBJECT;
1869 mono_loader_unlock ();
1870 return ERR_INVALID_OBJECT;
1875 get_object (int objid, MonoObject **obj)
1877 int err = get_object_allow_null (objid, obj);
1882 return ERR_INVALID_OBJECT;
1887 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1889 return decode_id (buf, endbuf, limit);
1893 buffer_add_objid (Buffer *buf, MonoObject *o)
1895 buffer_add_id (buf, get_objid (o));
1914 * Represents a runtime structure accessible to the debugger client
1917 /* Unique id used in the wire protocol */
1919 /* Domain of the runtime structure, NULL if the domain was unloaded */
1926 MonoAssembly *assembly;
1927 MonoClassField *field;
1929 MonoProperty *property;
1934 /* Maps runtime structure -> Id */
1935 GHashTable *val_to_id [ID_NUM];
1936 /* Classes whose class load event has been sent */
1937 GHashTable *loaded_classes;
1938 /* Maps MonoClass->GPtrArray of file names */
1939 GHashTable *source_files;
1940 /* Maps source file basename -> GSList of classes */
1941 GHashTable *source_file_to_class;
1942 /* Same with ignore-case */
1943 GHashTable *source_file_to_class_ignorecase;
1947 static GPtrArray *ids [ID_NUM];
1954 for (i = 0; i < ID_NUM; ++i)
1955 ids [i] = g_ptr_array_new ();
1963 for (i = 0; i < ID_NUM; ++i) {
1965 for (j = 0; j < ids [i]->len; ++j)
1966 g_free (g_ptr_array_index (ids [i], j));
1967 g_ptr_array_free (ids [i], TRUE);
1974 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1976 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1978 GHashTableIter iter;
1979 GPtrArray *file_names;
1984 for (i = 0; i < ID_NUM; ++i)
1985 if (info->val_to_id [i])
1986 g_hash_table_destroy (info->val_to_id [i]);
1987 g_hash_table_destroy (info->loaded_classes);
1989 g_hash_table_iter_init (&iter, info->source_files);
1990 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
1991 for (i = 0; i < file_names->len; ++i)
1992 g_free (g_ptr_array_index (file_names, i));
1993 g_ptr_array_free (file_names, TRUE);
1996 g_hash_table_iter_init (&iter, info->source_file_to_class);
1997 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2002 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2003 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2011 domain_jit_info (domain)->agent_info = NULL;
2013 /* Clear ids referencing structures in the domain */
2014 for (i = 0; i < ID_NUM; ++i) {
2016 for (j = 0; j < ids [i]->len; ++j) {
2017 Id *id = g_ptr_array_index (ids [i], j);
2018 if (id->domain == domain)
2024 mono_loader_lock ();
2025 g_hash_table_remove (domains, domain);
2026 mono_loader_unlock ();
2029 static AgentDomainInfo*
2030 get_agent_domain_info (MonoDomain *domain)
2032 AgentDomainInfo *info = NULL;
2034 mono_domain_lock (domain);
2036 info = domain_jit_info (domain)->agent_info;
2038 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2039 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2040 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2041 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2042 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2045 mono_domain_unlock (domain);
2051 get_id (MonoDomain *domain, IdType type, gpointer val)
2054 AgentDomainInfo *info;
2059 mono_loader_lock ();
2061 mono_domain_lock (domain);
2063 info = get_agent_domain_info (domain);
2065 if (info->val_to_id [type] == NULL)
2066 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2068 id = g_hash_table_lookup (info->val_to_id [type], val);
2070 mono_domain_unlock (domain);
2071 mono_loader_unlock ();
2075 id = g_new0 (Id, 1);
2077 id->id = ids [type]->len + 1;
2078 id->domain = domain;
2081 g_hash_table_insert (info->val_to_id [type], val, id);
2083 mono_domain_unlock (domain);
2085 g_ptr_array_add (ids [type], id);
2087 mono_loader_unlock ();
2092 static inline gpointer
2093 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2097 int id = decode_id (buf, endbuf, limit);
2106 // FIXME: error handling
2107 mono_loader_lock ();
2108 g_assert (id > 0 && id <= ids [type]->len);
2110 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2111 mono_loader_unlock ();
2113 if (res->domain == NULL) {
2114 *err = ERR_UNLOADED;
2119 *domain = res->domain;
2121 return res->data.val;
2125 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2127 buffer_add_id (buf, get_id (domain, type, val));
2130 static inline MonoClass*
2131 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2133 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2136 static inline MonoAssembly*
2137 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2139 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2142 static inline MonoImage*
2143 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2145 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2148 static inline MonoMethod*
2149 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2151 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2154 static inline MonoClassField*
2155 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2157 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2160 static inline MonoDomain*
2161 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2163 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2166 static inline MonoProperty*
2167 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2169 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2173 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2175 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2179 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2181 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2185 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2187 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2191 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2193 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2197 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2199 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2203 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2205 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2209 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2211 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2214 static void invoke_method (void);
2221 * save_thread_context:
2223 * Set CTX as the current threads context which is used for computing stack traces.
2224 * This function is signal-safe.
2227 save_thread_context (MonoContext *ctx)
2229 DebuggerTlsData *tls;
2231 tls = mono_native_tls_get_value (debugger_tls_id);
2235 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2237 mono_thread_state_init_from_current (&tls->context);
2240 /* The number of times the runtime is suspended */
2241 static gint32 suspend_count;
2243 /* Number of threads suspended */
2245 * If this is equal to the size of thread_to_tls, the runtime is considered
2248 static gint32 threads_suspend_count;
2250 static mono_mutex_t suspend_mutex;
2252 /* Cond variable used to wait for suspend_count becoming 0 */
2253 static mono_cond_t suspend_cond;
2255 /* Semaphore used to wait for a thread becoming suspended */
2256 static MonoSemType suspend_sem;
2261 mono_mutex_init (&suspend_mutex, NULL);
2262 mono_cond_init (&suspend_cond, NULL);
2263 MONO_SEM_INIT (&suspend_sem, 0);
2268 StackFrameInfo last_frame;
2269 gboolean last_frame_set;
2272 } GetLastFrameUserData;
2275 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2277 GetLastFrameUserData *data = user_data;
2279 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2282 if (!data->last_frame_set) {
2283 /* Store the last frame */
2284 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2285 data->last_frame_set = TRUE;
2288 /* Store the context/lmf for the frame above the last frame */
2289 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2290 data->lmf = info->lmf;
2299 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2300 * INFO is set, process the thread described by INFO.
2301 * This should be signal safe.
2304 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2308 MonoNativeThreadId tid;
2311 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2312 * guarantee the signal handler will be called that many times. Instead of tracking
2313 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2314 * has been requested that hasn't been handled yet, otherwise we can have threads
2315 * refuse to die when VM_EXIT is called
2317 #if defined(__APPLE__)
2318 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2322 * We use interrupt_count to determine whenever this interrupt should be processed
2323 * by us or the normal interrupt processing code in the signal handler.
2324 * There is no race here with notify_thread (), since the signal is sent after
2325 * incrementing interrupt_count.
2327 if (tls->interrupt_count == 0)
2330 InterlockedDecrement (&tls->interrupt_count);
2334 ip = mono_arch_ip_from_context (sigctx);
2336 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2341 tid = mono_thread_info_get_tid (info);
2343 tid = GetCurrentThreadId ();
2345 // FIXME: Races when the thread leaves managed code before hitting a single step
2349 /* Running managed code, will be suspended by the single step code */
2350 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2354 * Running native code, will be suspended when it returns to/enters
2355 * managed code. Treat it as already suspended.
2356 * This might interrupt the code in process_single_step_inner (), we use the
2357 * tls->suspending flag to avoid races when that happens.
2359 if (!tls->suspended && !tls->suspending) {
2361 GetLastFrameUserData data;
2363 // FIXME: printf is not signal safe, but this is only used during
2364 // debugger debugging
2366 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2367 //save_thread_context (&ctx);
2370 /* Already terminated */
2373 tls->context.valid = FALSE;
2376 * We are in a difficult position: we want to be able to provide stack
2377 * traces for this thread, but we can't use the current ctx+lmf, since
2378 * the thread is still running, so it might return to managed code,
2379 * making these invalid.
2380 * So we start a stack walk and save the first frame, along with the
2381 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2382 * suspended when it returns to managed code, so the parent's ctx should
2385 data.last_frame_set = FALSE;
2387 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2389 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2390 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2391 * since we are not in a JITted method.
2393 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2395 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2397 if (data.last_frame_set) {
2398 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2399 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2401 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2404 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2405 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2406 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2408 /* No managed frames */
2409 tls->async_state.valid = FALSE;
2411 mono_memory_barrier ();
2413 tls->suspended = TRUE;
2414 MONO_SEM_POST (&suspend_sem);
2421 * mono_debugger_agent_thread_interrupt:
2423 * Called by the abort signal handler.
2424 * Should be signal safe.
2427 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2429 DebuggerTlsData *tls;
2434 tls = mono_native_tls_get_value (debugger_tls_id);
2438 return thread_interrupt (tls, NULL, sigctx, ji);
2442 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2445 mono_debugger_agent_thread_interrupt (NULL, NULL);
2447 #endif /* HOST_WIN32 */
2450 * reset_native_thread_suspend_state:
2452 * Reset the suspended flag on native threads
2455 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2457 DebuggerTlsData *tls = value;
2459 if (!tls->really_suspended && tls->suspended)
2460 tls->suspended = FALSE;
2466 * Notify a thread that it needs to suspend.
2469 notify_thread (gpointer key, gpointer value, gpointer user_data)
2471 MonoInternalThread *thread = key;
2472 DebuggerTlsData *tls = value;
2473 gsize tid = thread->tid;
2476 if (GetCurrentThreadId () == tid || tls->terminated)
2479 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2482 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2483 * guarantee the signal handler will be called that many times. Instead of tracking
2484 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2485 * has been requested that hasn't been handled yet, otherwise we can have threads
2486 * refuse to die when VM_EXIT is called
2488 #if defined(__APPLE__)
2489 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2493 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2494 * of things like breaking waits etc. which we don't want.
2496 InterlockedIncrement (&tls->interrupt_count);
2499 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2501 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2503 if (mono_thread_info_new_interrupt_enabled ()) {
2504 MonoThreadInfo *info;
2507 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2510 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2512 thread_interrupt (tls, info, NULL, ji);
2514 mono_thread_info_resume (mono_thread_info_get_tid (info));
2516 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2519 * Attached thread which died without detaching.
2521 tls->terminated = TRUE;
2527 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2529 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2532 if (mono_loader_lock_is_owned_by_self ()) {
2534 * Shortcut for the check in suspend_current (). This speeds up processing
2535 * when executing long running code inside the loader lock, i.e. assembly load
2541 if (debugger_thread_id == GetCurrentThreadId ())
2544 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2545 if (suspend_count - tls->resume_count > 0)
2546 tls->suspending = TRUE;
2548 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2550 if (suspend_count - tls->resume_count == 0) {
2552 * We are executing a single threaded invoke but the single step for
2553 * suspending is still active.
2554 * FIXME: This slows down single threaded invokes.
2556 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2560 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2562 /* Can't suspend in these methods */
2563 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2566 save_thread_context (ctx);
2574 * Increase the suspend count of the VM. While the suspend count is greater
2575 * than 0, runtime threads are suspended at certain points during execution.
2580 mono_loader_lock ();
2582 mono_mutex_lock (&suspend_mutex);
2586 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2588 if (suspend_count == 1) {
2589 // FIXME: Is it safe to call this inside the lock ?
2590 start_single_stepping ();
2591 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2594 mono_mutex_unlock (&suspend_mutex);
2596 mono_loader_unlock ();
2602 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2610 g_assert (debugger_thread_id == GetCurrentThreadId ());
2612 mono_loader_lock ();
2614 mono_mutex_lock (&suspend_mutex);
2616 g_assert (suspend_count > 0);
2619 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2621 if (suspend_count == 0) {
2622 // FIXME: Is it safe to call this inside the lock ?
2623 stop_single_stepping ();
2624 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2627 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2628 err = mono_cond_broadcast (&suspend_cond);
2629 g_assert (err == 0);
2631 mono_mutex_unlock (&suspend_mutex);
2632 //g_assert (err == 0);
2634 mono_loader_unlock ();
2640 * Resume just one thread.
2643 resume_thread (MonoInternalThread *thread)
2646 DebuggerTlsData *tls;
2648 g_assert (debugger_thread_id == GetCurrentThreadId ());
2650 mono_loader_lock ();
2652 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2655 mono_mutex_lock (&suspend_mutex);
2657 g_assert (suspend_count > 0);
2659 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2661 tls->resume_count += suspend_count;
2664 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2665 * but only the one whose resume_count field is > 0 will be resumed.
2667 err = mono_cond_broadcast (&suspend_cond);
2668 g_assert (err == 0);
2670 mono_mutex_unlock (&suspend_mutex);
2671 //g_assert (err == 0);
2673 mono_loader_unlock ();
2677 invalidate_frames (DebuggerTlsData *tls)
2682 tls = mono_native_tls_get_value (debugger_tls_id);
2685 for (i = 0; i < tls->frame_count; ++i) {
2686 if (tls->frames [i]->jit)
2687 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2688 g_free (tls->frames [i]);
2690 g_free (tls->frames);
2691 tls->frame_count = 0;
2698 * Suspend the current thread until the runtime is resumed. If the thread has a
2699 * pending invoke, then the invoke is executed before this function returns.
2702 suspend_current (void)
2705 DebuggerTlsData *tls;
2707 g_assert (debugger_thread_id != GetCurrentThreadId ());
2709 if (mono_loader_lock_is_owned_by_self ()) {
2711 * If we own the loader mutex, can't suspend until we release it, since the
2712 * whole runtime can deadlock otherwise.
2717 tls = mono_native_tls_get_value (debugger_tls_id);
2720 mono_mutex_lock (&suspend_mutex);
2722 tls->suspending = FALSE;
2723 tls->really_suspended = TRUE;
2725 if (!tls->suspended) {
2726 tls->suspended = TRUE;
2727 MONO_SEM_POST (&suspend_sem);
2730 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2732 while (suspend_count - tls->resume_count > 0) {
2734 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2736 mono_mutex_unlock (&suspend_mutex);
2738 mono_mutex_lock (&suspend_mutex);
2744 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2745 g_assert (err == 0);
2749 tls->suspended = FALSE;
2750 tls->really_suspended = FALSE;
2752 threads_suspend_count --;
2754 mono_mutex_unlock (&suspend_mutex);
2756 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2758 if (tls->pending_invoke) {
2759 /* Save the original context */
2760 tls->pending_invoke->has_ctx = TRUE;
2761 tls->pending_invoke->ctx = tls->context.ctx;
2766 /* The frame info becomes invalid after a resume */
2767 tls->context.valid = FALSE;
2768 tls->async_state.valid = FALSE;
2769 invalidate_frames (NULL);
2773 count_thread (gpointer key, gpointer value, gpointer user_data)
2775 DebuggerTlsData *tls = value;
2777 if (!tls->suspended && !tls->terminated)
2778 *(int*)user_data = *(int*)user_data + 1;
2782 count_threads_to_wait_for (void)
2786 mono_loader_lock ();
2787 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2788 mono_loader_unlock ();
2796 * Wait until the runtime is completely suspended.
2799 wait_for_suspend (void)
2801 int nthreads, nwait, err;
2802 gboolean waited = FALSE;
2804 // FIXME: Threads starting/stopping ?
2805 mono_loader_lock ();
2806 nthreads = mono_g_hash_table_size (thread_to_tls);
2807 mono_loader_unlock ();
2810 nwait = count_threads_to_wait_for ();
2812 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2813 err = MONO_SEM_WAIT (&suspend_sem);
2814 g_assert (err == 0);
2822 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2828 * Return whenever the runtime is suspended.
2833 return count_threads_to_wait_for () == 0;
2836 static MonoSeqPointInfo*
2837 get_seq_points (MonoDomain *domain, MonoMethod *method)
2839 MonoSeqPointInfo *seq_points;
2841 mono_domain_lock (domain);
2842 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2843 if (!seq_points && method->is_inflated) {
2844 /* generic sharing + aot */
2845 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2847 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2849 mono_domain_unlock (domain);
2854 static MonoSeqPointInfo*
2855 find_seq_points (MonoDomain *domain, MonoMethod *method)
2857 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2860 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2861 g_assert (seq_points);
2867 * find_next_seq_point_for_native_offset:
2869 * Find the first sequence point after NATIVE_OFFSET.
2872 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2874 MonoSeqPointInfo *seq_points;
2877 seq_points = find_seq_points (domain, method);
2881 for (i = 0; i < seq_points->len; ++i) {
2882 if (seq_points->seq_points [i].native_offset >= native_offset)
2883 return &seq_points->seq_points [i];
2890 * find_prev_seq_point_for_native_offset:
2892 * Find the first sequence point before NATIVE_OFFSET.
2895 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2897 MonoSeqPointInfo *seq_points;
2900 seq_points = find_seq_points (domain, method);
2904 for (i = seq_points->len - 1; i >= 0; --i) {
2905 if (seq_points->seq_points [i].native_offset <= native_offset)
2906 return &seq_points->seq_points [i];
2915 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2916 * should be the location of a sequence point.
2918 static G_GNUC_UNUSED SeqPoint*
2919 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2921 MonoSeqPointInfo *seq_points;
2926 seq_points = get_seq_points (domain, method);
2931 for (i = 0; i < seq_points->len; ++i) {
2932 if (seq_points->seq_points [i].il_offset == il_offset)
2933 return &seq_points->seq_points [i];
2940 DebuggerTlsData *tls;
2942 } ComputeFramesUserData;
2945 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2947 ComputeFramesUserData *ud = user_data;
2949 MonoMethod *method, *actual_method;
2953 if (info->type != FRAME_TYPE_MANAGED) {
2954 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2955 /* Mark the last frame as an invoke frame */
2957 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2963 method = info->ji->method;
2965 method = info->method;
2966 actual_method = info->actual_method;
2971 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
2974 if (info->il_offset == -1) {
2975 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
2976 if (ud->frames == NULL) {
2977 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
2979 info->il_offset = sp->il_offset;
2981 if (info->il_offset == -1)
2982 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2985 DEBUG (1, fprintf (log_file, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed));
2987 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2988 if (!CHECK_PROTOCOL_VERSION (2, 17))
2989 /* Older clients can't handle this flag */
2991 method = mono_marshal_method_from_wrapper (method);
2994 actual_method = method;
2995 flags |= FRAME_FLAG_NATIVE_TRANSITION;
2998 frame = g_new0 (StackFrame, 1);
2999 frame->method = method;
3000 frame->actual_method = actual_method;
3001 frame->il_offset = info->il_offset;
3002 frame->native_offset = info->native_offset;
3003 frame->flags = flags;
3004 if (info->reg_locations)
3005 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3008 frame->has_ctx = TRUE;
3010 frame->domain = info->domain;
3012 ud->frames = g_slist_append (ud->frames, frame);
3018 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3020 ComputeFramesUserData *ud = user_data;
3023 * 'tls->filter_ctx' is the location of the throw site.
3025 * mono_walk_stack() will never actually hit the throw site, but unwind
3026 * directly from the filter to the call site; we abort stack unwinding here
3027 * once this happens and resume from the throw site.
3030 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3033 return process_frame (info, ctx, user_data);
3037 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3039 ComputeFramesUserData user_data;
3041 int i, findex, new_frame_count;
3042 StackFrame **new_frames, *f;
3043 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3045 // FIXME: Locking on tls
3046 if (tls->frames && tls->frames_up_to_date)
3049 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3051 user_data.tls = tls;
3052 user_data.frames = NULL;
3053 if (tls->terminated) {
3054 tls->frame_count = 0;
3056 } if (!tls->really_suspended && tls->async_state.valid) {
3057 /* Have to use the state saved by the signal handler */
3058 process_frame (&tls->async_last_frame, NULL, &user_data);
3059 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3060 } else if (tls->filter_state.valid) {
3062 * We are inside an exception filter.
3064 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3066 if (tls->context.valid)
3067 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3069 * After that, we resume unwinding from the location where the exception has been thrown.
3071 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3072 } else if (tls->context.valid) {
3073 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3076 tls->frame_count = 0;
3080 new_frame_count = g_slist_length (user_data.frames);
3081 new_frames = g_new0 (StackFrame*, new_frame_count);
3083 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3087 * Reuse the id for already existing stack frames, so invokes don't invalidate
3088 * the still valid stack frames.
3090 for (i = 0; i < tls->frame_count; ++i) {
3091 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3092 f->id = tls->frames [i]->id;
3097 if (i >= tls->frame_count)
3098 f->id = InterlockedIncrement (&frame_id);
3100 new_frames [findex ++] = f;
3103 g_slist_free (user_data.frames);
3105 invalidate_frames (tls);
3107 tls->frames = new_frames;
3108 tls->frame_count = new_frame_count;
3109 tls->frames_up_to_date = TRUE;
3113 * GHFunc to emit an appdomain creation event
3114 * @param key Don't care
3115 * @param value A loaded appdomain
3116 * @param user_data Don't care
3119 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3121 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3122 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3126 * GHFunc to emit a thread start event
3127 * @param key A thread id
3128 * @param value A thread object
3129 * @param user_data Don't care
3132 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3134 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3135 process_profiler_event (EVENT_KIND_THREAD_START, value);
3139 * GFunc to emit an assembly load event
3140 * @param value A loaded assembly
3141 * @param user_data Don't care
3144 emit_assembly_load (gpointer value, gpointer user_data)
3146 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3150 * GFunc to emit a type load event
3151 * @param value A loaded type
3152 * @param user_data Don't care
3155 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3157 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3161 strdup_tolower (char *s)
3166 for (p = s2; *p; ++p)
3176 * create_event_list:
3178 * Return a list of event request ids matching EVENT, starting from REQS, which
3179 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3181 * We return request ids, instead of requests, to simplify threading, since
3182 * requests could be deleted anytime when the loader lock is not held.
3183 * LOCKING: Assumes the loader lock is held.
3186 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3189 GSList *events = NULL;
3191 *suspend_policy = SUSPEND_POLICY_NONE;
3194 reqs = event_requests;
3199 for (i = 0; i < reqs->len; ++i) {
3200 EventRequest *req = g_ptr_array_index (reqs, i);
3201 if (req->event_kind == event) {
3202 gboolean filtered = FALSE;
3205 for (j = 0; j < req->nmodifiers; ++j) {
3206 Modifier *mod = &req->modifiers [j];
3208 if (mod->kind == MOD_KIND_COUNT) {
3210 if (mod->data.count > 0) {
3211 if (mod->data.count > 0) {
3213 if (mod->data.count == 0)
3217 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3218 if (mod->data.thread != mono_thread_internal_current ())
3220 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3221 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3223 if (ei->caught && !mod->caught)
3225 if (!ei->caught && !mod->uncaught)
3227 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3229 gboolean found = FALSE;
3230 MonoAssembly **assemblies = mod->data.assemblies;
3233 for (k = 0; assemblies [k]; ++k)
3234 if (assemblies [k] == ji->method->klass->image->assembly)
3239 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3240 gpointer iter = NULL;
3242 MonoDebugSourceInfo *sinfo;
3243 char *source_file, *s;
3244 gboolean found = FALSE;
3246 GPtrArray *source_file_list;
3248 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3249 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3252 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL);
3253 for (i = 0; i < source_file_list->len; ++i) {
3254 sinfo = g_ptr_array_index (source_file_list, i);
3256 * Do a case-insesitive match by converting the file name to
3259 s = strdup_tolower (sinfo->source_file);
3260 if (g_hash_table_lookup (mod->data.source_files, s))
3264 g_ptr_array_free (source_file_list, TRUE);
3269 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3272 s = mono_type_full_name (&ei->klass->byval_arg);
3273 if (!g_hash_table_lookup (mod->data.type_names, s))
3276 } else if (mod->kind == MOD_KIND_STEP) {
3277 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3278 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3279 !strcmp (ji->method->name, ".cctor"))
3285 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3286 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3291 /* Send a VM START/DEATH event by default */
3292 if (event == EVENT_KIND_VM_START)
3293 events = g_slist_append (events, GINT_TO_POINTER (0));
3294 if (event == EVENT_KIND_VM_DEATH)
3295 events = g_slist_append (events, GINT_TO_POINTER (0));
3300 static G_GNUC_UNUSED const char*
3301 event_to_string (EventKind event)
3304 case EVENT_KIND_VM_START: return "VM_START";
3305 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3306 case EVENT_KIND_THREAD_START: return "THREAD_START";
3307 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3308 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3309 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3310 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3311 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3312 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3313 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3314 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3315 case EVENT_KIND_STEP: return "STEP";
3316 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3317 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3318 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3319 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3320 case EVENT_KIND_USER_LOG: return "USER_LOG";
3322 g_assert_not_reached ();
3329 * Send an event to the client, suspending the vm if needed.
3330 * LOCKING: Since this can suspend the calling thread, no locks should be held
3332 * The EVENTS list is freed by this function.
3335 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3339 MonoDomain *domain = mono_domain_get ();
3340 MonoThread *thread = NULL;
3341 gboolean send_success = FALSE;
3346 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3350 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3351 // FIXME: We miss those events
3352 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3356 if (vm_death_event_sent) {
3357 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3361 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3362 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3367 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3371 if (event == EVENT_KIND_KEEPALIVE)
3372 suspend_policy = SUSPEND_POLICY_NONE;
3377 if (agent_config.defer) {
3378 /* Make sure the thread id is always set when doing deferred debugging */
3379 if (debugger_thread_id == GetCurrentThreadId ()) {
3380 /* Don't suspend on events from the debugger thread */
3381 suspend_policy = SUSPEND_POLICY_NONE;
3382 thread = mono_thread_get_main ();
3384 else thread = mono_thread_current ();
3386 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3387 // FIXME: Send these with a NULL thread, don't suspend the current thread
3392 nevents = g_slist_length (events);
3393 buffer_init (&buf, 128);
3394 buffer_add_byte (&buf, suspend_policy);
3395 buffer_add_int (&buf, nevents);
3397 for (l = events; l; l = l->next) {
3398 buffer_add_byte (&buf, event); // event kind
3399 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3404 thread = mono_thread_current ();
3406 if (event == EVENT_KIND_VM_START && arg != NULL)
3409 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3412 case EVENT_KIND_THREAD_START:
3413 case EVENT_KIND_THREAD_DEATH:
3415 case EVENT_KIND_APPDOMAIN_CREATE:
3416 case EVENT_KIND_APPDOMAIN_UNLOAD:
3417 buffer_add_domainid (&buf, arg);
3419 case EVENT_KIND_METHOD_ENTRY:
3420 case EVENT_KIND_METHOD_EXIT:
3421 buffer_add_methodid (&buf, domain, arg);
3423 case EVENT_KIND_ASSEMBLY_LOAD:
3424 case EVENT_KIND_ASSEMBLY_UNLOAD:
3425 buffer_add_assemblyid (&buf, domain, arg);
3427 case EVENT_KIND_TYPE_LOAD:
3428 buffer_add_typeid (&buf, domain, arg);
3430 case EVENT_KIND_BREAKPOINT:
3431 case EVENT_KIND_STEP:
3432 buffer_add_methodid (&buf, domain, arg);
3433 buffer_add_long (&buf, il_offset);
3435 case EVENT_KIND_VM_START:
3436 buffer_add_domainid (&buf, mono_get_root_domain ());
3438 case EVENT_KIND_VM_DEATH:
3440 case EVENT_KIND_EXCEPTION: {
3441 EventInfo *ei = arg;
3442 buffer_add_objid (&buf, ei->exc);
3445 case EVENT_KIND_USER_BREAK:
3447 case EVENT_KIND_USER_LOG: {
3448 EventInfo *ei = arg;
3449 buffer_add_int (&buf, ei->level);
3450 buffer_add_string (&buf, ei->category ? ei->category : "");
3451 buffer_add_string (&buf, ei->message ? ei->message : "");
3454 case EVENT_KIND_KEEPALIVE:
3455 suspend_policy = SUSPEND_POLICY_NONE;
3458 g_assert_not_reached ();
3462 if (event == EVENT_KIND_VM_START) {
3463 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3464 if (!agent_config.defer)
3465 start_debugger_thread ();
3468 if (event == EVENT_KIND_VM_DEATH) {
3469 vm_death_event_sent = TRUE;
3470 suspend_policy = SUSPEND_POLICY_NONE;
3473 if (mono_runtime_is_shutting_down ())
3474 suspend_policy = SUSPEND_POLICY_NONE;
3476 if (suspend_policy != SUSPEND_POLICY_NONE) {
3478 * Save the thread context and start suspending before sending the packet,
3479 * since we could be receiving the resume request before send_packet ()
3482 save_thread_context (ctx);
3486 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3490 g_slist_free (events);
3493 if (!send_success) {
3494 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3498 if (event == EVENT_KIND_VM_START) {
3499 vm_start_event_sent = TRUE;
3502 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3504 switch (suspend_policy) {
3505 case SUSPEND_POLICY_NONE:
3507 case SUSPEND_POLICY_ALL:
3510 case SUSPEND_POLICY_EVENT_THREAD:
3514 g_assert_not_reached ();
3519 process_profiler_event (EventKind event, gpointer arg)
3523 EventInfo ei, *ei_arg = NULL;
3525 if (event == EVENT_KIND_TYPE_LOAD) {
3530 mono_loader_lock ();
3531 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3532 mono_loader_unlock ();
3534 process_event (event, arg, 0, NULL, events, suspend_policy);
3538 runtime_initialized (MonoProfiler *prof)
3540 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3541 if (agent_config.defer)
3542 start_debugger_thread ();
3546 runtime_shutdown (MonoProfiler *prof)
3548 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3550 mono_debugger_agent_cleanup ();
3554 thread_startup (MonoProfiler *prof, uintptr_t tid)
3556 MonoInternalThread *thread = mono_thread_internal_current ();
3557 MonoInternalThread *old_thread;
3558 DebuggerTlsData *tls;
3560 if (tid == debugger_thread_id)
3563 g_assert (thread->tid == tid);
3565 mono_loader_lock ();
3566 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3567 mono_loader_unlock ();
3569 if (thread == old_thread) {
3571 * For some reason, thread_startup () might be called for the same thread
3572 * multiple times (attach ?).
3574 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3578 * thread_end () might not be called for some threads, and the tid could
3581 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3582 mono_loader_lock ();
3583 mono_g_hash_table_remove (thread_to_tls, old_thread);
3584 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3585 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3586 mono_loader_unlock ();
3590 tls = mono_native_tls_get_value (debugger_tls_id);
3592 // FIXME: Free this somewhere
3593 tls = g_new0 (DebuggerTlsData, 1);
3594 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3595 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3596 tls->thread = thread;
3597 mono_native_tls_set_value (debugger_tls_id, tls);
3599 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3601 mono_loader_lock ();
3602 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3603 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3604 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3605 mono_loader_unlock ();
3607 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3610 * suspend_vm () could have missed this thread, so wait for a resume.
3616 thread_end (MonoProfiler *prof, uintptr_t tid)
3618 MonoInternalThread *thread;
3619 DebuggerTlsData *tls = NULL;
3621 mono_loader_lock ();
3622 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3624 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3625 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3626 tls->terminated = TRUE;
3627 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3628 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3629 MONO_GC_UNREGISTER_ROOT (tls->thread);
3632 mono_loader_unlock ();
3634 /* We might be called for threads started before we registered the start callback */
3636 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3637 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3642 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3644 mono_loader_lock ();
3645 g_hash_table_insert (domains, domain, domain);
3646 mono_loader_unlock ();
3648 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3652 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3654 clear_breakpoints_for_domain (domain);
3656 mono_loader_lock ();
3657 /* Invalidate each thread's frame stack */
3658 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3659 mono_loader_unlock ();
3661 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3665 * invalidate_each_thread:
3667 * A GHFunc to invalidate frames.
3668 * value must be a DebuggerTlsData*
3671 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3673 invalidate_frames (value);
3677 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3679 /* Sent later in jit_end () */
3680 mono_loader_lock ();
3681 g_ptr_array_add (pending_assembly_loads, assembly);
3682 mono_loader_unlock ();
3686 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3688 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3690 clear_event_requests_for_assembly (assembly);
3691 clear_types_for_assembly (assembly);
3695 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3697 #if defined(HOST_WIN32) && !defined(__GNUC__)
3698 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3700 gpointer stackptr = __builtin_frame_address (1);
3702 MonoInternalThread *thread = mono_thread_internal_current ();
3703 DebuggerTlsData *tls;
3705 mono_loader_lock ();
3707 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3708 /* Could be the debugger thread with assembly/type load hooks */
3710 tls->invoke_addr = stackptr;
3712 mono_loader_unlock ();
3716 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3719 #if defined(HOST_WIN32) && !defined(__GNUC__)
3720 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3722 gpointer stackptr = __builtin_frame_address (1);
3725 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3729 * We need to stop single stepping when exiting a runtime invoke, since if it is
3730 * a step out, it may return to native code, and thus never end.
3732 mono_loader_lock ();
3733 ss_invoke_addr = NULL;
3735 for (i = 0; i < event_requests->len; ++i) {
3736 EventRequest *req = g_ptr_array_index (event_requests, i);
3738 if (req->event_kind == EVENT_KIND_STEP) {
3739 ss_destroy (req->info);
3740 g_ptr_array_remove_index_fast (event_requests, i);
3745 mono_loader_unlock ();
3749 send_type_load (MonoClass *klass)
3751 gboolean type_load = FALSE;
3752 MonoDomain *domain = mono_domain_get ();
3753 AgentDomainInfo *info = NULL;
3755 mono_loader_lock ();
3756 mono_domain_lock (domain);
3758 info = get_agent_domain_info (domain);
3760 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3762 g_hash_table_insert (info->loaded_classes, klass, klass);
3765 mono_domain_unlock (domain);
3766 mono_loader_unlock ();
3768 emit_type_load (klass, klass, NULL);
3772 * Emit load events for all types currently loaded in the domain.
3773 * Takes the loader and domain locks.
3774 * user_data is unused.
3777 send_types_for_domain (MonoDomain *domain, void *user_data)
3779 AgentDomainInfo *info = NULL;
3781 mono_loader_lock ();
3782 mono_domain_lock (domain);
3783 info = get_agent_domain_info (domain);
3785 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3786 mono_domain_unlock (domain);
3787 mono_loader_unlock ();
3791 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3794 * We emit type load events when the first method of the type is JITted,
3795 * since the class load profiler callbacks might be called with the
3796 * loader lock held. They could also occur in the debugger thread.
3797 * Same for assembly load events.
3800 MonoAssembly *assembly = NULL;
3802 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3803 mono_loader_lock ();
3804 if (pending_assembly_loads->len > 0) {
3805 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3806 g_ptr_array_remove_index (pending_assembly_loads, 0);
3808 mono_loader_unlock ();
3811 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3817 send_type_load (method->klass);
3820 add_pending_breakpoints (method, jinfo);
3824 * BREAKPOINTS/SINGLE STEPPING
3828 * Contains information about an inserted breakpoint.
3831 long il_offset, native_offset;
3836 } BreakpointInstance;
3839 * Contains generic information about a breakpoint.
3843 * The method where the breakpoint is placed. Can be NULL in which case it
3844 * is inserted into every method. This is used to implement method entry/
3845 * exit events. Can be a generic method definition, in which case the
3846 * breakpoint is inserted into every instance.
3852 * A list of BreakpointInstance structures describing where the breakpoint
3853 * was inserted. There could be more than one because of
3854 * generics/appdomains/method entry/exit.
3856 GPtrArray *children;
3859 /* List of breakpoints */
3860 static GPtrArray *breakpoints;
3861 /* Maps breakpoint locations to the number of breakpoints at that location */
3862 static GHashTable *bp_locs;
3865 breakpoints_init (void)
3867 breakpoints = g_ptr_array_new ();
3868 bp_locs = g_hash_table_new (NULL, NULL);
3872 * insert_breakpoint:
3874 * Insert the breakpoint described by BP into the method described by
3878 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3881 BreakpointInstance *inst;
3882 SeqPoint *sp = NULL;
3885 mono_error_init (error);
3887 for (i = 0; i < seq_points->len; ++i) {
3888 sp = &seq_points->seq_points [i];
3890 if (sp->il_offset == bp->il_offset)
3894 if (i == seq_points->len) {
3896 * The set of IL offsets with seq points doesn't completely match the
3897 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3899 for (i = 0; i < seq_points->len; ++i) {
3900 sp = &seq_points->seq_points [i];
3902 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3907 if (i == seq_points->len) {
3908 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (ji->method, TRUE), bp->il_offset, seq_points->len);
3910 for (i = 0; i < seq_points->len; ++i)
3911 printf ("%d\n", seq_points->seq_points [i].il_offset);
3914 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3923 inst = g_new0 (BreakpointInstance, 1);
3925 inst->native_offset = sp->native_offset;
3926 inst->ip = (guint8*)ji->code_start + sp->native_offset;
3928 inst->domain = domain;
3930 mono_loader_lock ();
3932 g_ptr_array_add (bp->children, inst);
3934 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3935 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3936 mono_loader_unlock ();
3939 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3940 mono_arch_set_breakpoint (ji, inst->ip);
3946 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
3950 remove_breakpoint (BreakpointInstance *inst)
3952 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3954 MonoJitInfo *ji = inst->ji;
3955 guint8 *ip = inst->ip;
3957 mono_loader_lock ();
3958 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3959 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3960 mono_loader_unlock ();
3962 g_assert (count > 0);
3965 mono_arch_clear_breakpoint (ji, ip);
3972 static inline gboolean
3973 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3979 if (method == bp->method)
3981 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
3984 if (bp->method->is_inflated && method->is_inflated) {
3985 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
3986 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3988 /* Open generic methods should match closed generic methods of the same class */
3989 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
3990 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
3991 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
3993 /* FIXME: Handle !mvar */
3994 if (t1->type != MONO_TYPE_MVAR)
4005 * add_pending_breakpoints:
4007 * Insert pending breakpoints into the newly JITted method METHOD.
4010 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4013 MonoSeqPointInfo *seq_points;
4019 domain = mono_domain_get ();
4021 mono_loader_lock ();
4023 for (i = 0; i < breakpoints->len; ++i) {
4024 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4025 gboolean found = FALSE;
4027 if (!bp_matches_method (bp, method))
4030 for (j = 0; j < bp->children->len; ++j) {
4031 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4038 mono_domain_lock (domain);
4039 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4040 if (!seq_points && ji->method->is_inflated)
4041 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4042 mono_domain_unlock (domain);
4044 /* Could be AOT code */
4046 g_assert (seq_points);
4048 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4052 mono_loader_unlock ();
4056 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4062 mono_error_init (error);
4064 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4066 /* Might be AOTed code */
4067 code = mono_aot_get_method (domain, method);
4069 ji = mono_jit_info_table_find (domain, code);
4074 insert_breakpoint (seq_points, domain, ji, bp, error);
4078 clear_breakpoint (MonoBreakpoint *bp);
4083 * Set a breakpoint at IL_OFFSET in METHOD.
4084 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4085 * METHOD can also be a generic method definition, in which case a breakpoint
4086 * is placed in all instances of the method.
4087 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4090 static MonoBreakpoint*
4091 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4094 GHashTableIter iter, iter2;
4097 MonoSeqPointInfo *seq_points;
4100 mono_error_init (error);
4103 // - suspend/resume the vm to prevent code patching problems
4104 // - multiple breakpoints on the same location
4105 // - dynamic methods
4108 bp = g_new0 (MonoBreakpoint, 1);
4109 bp->method = method;
4110 bp->il_offset = il_offset;
4112 bp->children = g_ptr_array_new ();
4114 DEBUG(1, fprintf (log_file, "[dbg] Setting %sbreakpoint at %s:0x%x.\n", (req->event_kind == EVENT_KIND_STEP) ? "single step " : "", method ? mono_method_full_name (method, TRUE) : "<all>", (int)il_offset));
4116 mono_loader_lock ();
4118 g_hash_table_iter_init (&iter, domains);
4119 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4120 mono_domain_lock (domain);
4122 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4123 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4124 if (bp_matches_method (bp, m))
4125 set_bp_in_method (domain, m, seq_points, bp, error);
4128 mono_domain_unlock (domain);
4131 mono_loader_unlock ();
4133 mono_loader_lock ();
4134 g_ptr_array_add (breakpoints, bp);
4135 mono_loader_unlock ();
4137 if (error && !mono_error_ok (error)) {
4138 clear_breakpoint (bp);
4146 clear_breakpoint (MonoBreakpoint *bp)
4150 // FIXME: locking, races
4151 for (i = 0; i < bp->children->len; ++i) {
4152 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4154 remove_breakpoint (inst);
4159 mono_loader_lock ();
4160 g_ptr_array_remove (breakpoints, bp);
4161 mono_loader_unlock ();
4163 g_ptr_array_free (bp->children, TRUE);
4168 breakpoints_cleanup (void)
4172 mono_loader_lock ();
4174 while (i < event_requests->len) {
4175 EventRequest *req = g_ptr_array_index (event_requests, i);
4177 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4178 clear_breakpoint (req->info);
4179 g_ptr_array_remove_index_fast (event_requests, i);
4186 for (i = 0; i < breakpoints->len; ++i)
4187 g_free (g_ptr_array_index (breakpoints, i));
4189 g_ptr_array_free (breakpoints, TRUE);
4190 g_hash_table_destroy (bp_locs);
4195 mono_loader_unlock ();
4199 * clear_breakpoints_for_domain:
4201 * Clear breakpoint instances which reference DOMAIN.
4204 clear_breakpoints_for_domain (MonoDomain *domain)
4208 /* This could be called after shutdown */
4212 mono_loader_lock ();
4213 for (i = 0; i < breakpoints->len; ++i) {
4214 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4217 while (j < bp->children->len) {
4218 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4220 if (inst->domain == domain) {
4221 remove_breakpoint (inst);
4225 g_ptr_array_remove_index_fast (bp->children, j);
4231 mono_loader_unlock ();
4235 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4237 return bp->method && bp->method->klass->image->assembly == assembly;
4241 process_breakpoint_inner (DebuggerTlsData *tls)
4245 int i, j, suspend_policy;
4246 guint32 native_offset;
4248 BreakpointInstance *inst;
4249 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4250 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4251 EventKind kind = EVENT_KIND_BREAKPOINT;
4252 MonoContext *ctx = &tls->restore_ctx;
4253 MonoSeqPointInfo *info;
4256 // FIXME: Speed this up
4258 ip = MONO_CONTEXT_GET_IP (ctx);
4259 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4261 g_assert (ji->method);
4263 /* Compute the native offset of the breakpoint from the ip */
4264 native_offset = ip - (guint8*)ji->code_start;
4267 * Skip the instruction causing the breakpoint signal.
4269 mono_arch_skip_breakpoint (ctx, ji);
4271 if (ji->method->wrapper_type || tls->disable_breakpoints)
4274 bp_reqs = g_ptr_array_new ();
4275 ss_reqs = g_ptr_array_new ();
4276 ss_reqs_orig = g_ptr_array_new ();
4278 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
4280 mono_loader_lock ();
4283 * The ip points to the instruction causing the breakpoint event, which is after
4284 * the offset recorded in the seq point map, so find the prev seq point before ip.
4286 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4289 for (i = 0; i < breakpoints->len; ++i) {
4290 bp = g_ptr_array_index (breakpoints, i);
4295 for (j = 0; j < bp->children->len; ++j) {
4296 inst = g_ptr_array_index (bp->children, j);
4297 if (inst->ji == ji && inst->sp == sp) {
4298 if (bp->req->event_kind == EVENT_KIND_STEP) {
4299 g_ptr_array_add (ss_reqs_orig, bp->req);
4301 g_ptr_array_add (bp_reqs, bp->req);
4306 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4307 /* Maybe a method entry/exit event */
4308 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4309 kind = EVENT_KIND_METHOD_ENTRY;
4310 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4311 kind = EVENT_KIND_METHOD_EXIT;
4314 /* Process single step requests */
4315 for (i = 0; i < ss_reqs_orig->len; ++i) {
4316 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4317 SingleStepReq *ss_req = req->info;
4318 gboolean hit = TRUE;
4320 if (ss_req->size == STEP_SIZE_LINE) {
4321 /* Have to check whenever a different source line was reached */
4322 MonoDebugMethodInfo *minfo;
4323 MonoDebugSourceLocation *loc = NULL;
4325 minfo = mono_debug_lookup_method (ji->method);
4328 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4330 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
4331 /* Have to continue single stepping */
4335 ss_req->last_method = ji->method;
4336 ss_req->last_line = loc->row;
4337 mono_debug_free_source_location (loc);
4342 g_ptr_array_add (ss_reqs, req);
4344 /* Start single stepping again from the current sequence point */
4345 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4348 if (ss_reqs->len > 0)
4349 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4350 if (bp_reqs->len > 0)
4351 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4352 if (kind != EVENT_KIND_BREAKPOINT)
4353 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4355 mono_loader_unlock ();
4357 g_ptr_array_free (bp_reqs, TRUE);
4358 g_ptr_array_free (ss_reqs, TRUE);
4361 * FIXME: The first event will suspend, so the second will only be sent after the
4365 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4367 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4368 if (enter_leave_events)
4369 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4372 /* Process a breakpoint/single step event after resuming from a signal handler */
4374 process_signal_event (void (*func) (DebuggerTlsData*))
4376 DebuggerTlsData *tls;
4377 MonoContext orig_restore_ctx, ctx;
4378 static void (*restore_context) (void *);
4380 if (!restore_context)
4381 restore_context = mono_get_restore_context ();
4383 tls = mono_native_tls_get_value (debugger_tls_id);
4384 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4385 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4386 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4390 /* This is called when resuming from a signal handler, so it shouldn't return */
4391 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4392 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4393 restore_context (&ctx);
4394 g_assert_not_reached ();
4398 process_breakpoint (void)
4400 process_signal_event (process_breakpoint_inner);
4404 resume_from_signal_handler (void *sigctx, void *func)
4406 DebuggerTlsData *tls;
4409 /* Save the original context in TLS */
4410 // FIXME: This might not work on an altstack ?
4411 tls = mono_native_tls_get_value (debugger_tls_id);
4414 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4415 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4416 // clob:c could be added to op_seq_point.
4418 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4419 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4420 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4421 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4423 MONO_CONTEXT_SET_IP (&ctx, func);
4425 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4427 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4428 mono_ppc_set_func_into_sigctx (sigctx, func);
4433 mono_debugger_agent_breakpoint_hit (void *sigctx)
4436 * We are called from a signal handler, and running code there causes all kinds of
4437 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4438 * So set up the signal context to return to the real breakpoint handler function.
4441 resume_from_signal_handler (sigctx, process_breakpoint);
4445 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4447 if (frame->managed) {
4448 *(MonoContext*)data = *ctx;
4457 * Called by System.Diagnostics.Debugger:Break ().
4460 mono_debugger_agent_user_break (void)
4462 if (agent_config.enabled) {
4467 /* Obtain a context */
4468 MONO_CONTEXT_SET_IP (&ctx, NULL);
4469 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4470 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4472 mono_loader_lock ();
4473 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4474 mono_loader_unlock ();
4476 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4483 ss_depth_to_string (StepDepth depth)
4486 case STEP_DEPTH_OVER:
4488 case STEP_DEPTH_OUT:
4490 case STEP_DEPTH_INTO:
4493 g_assert_not_reached ();
4499 process_single_step_inner (DebuggerTlsData *tls)
4504 int il_offset, suspend_policy;
4507 MonoContext *ctx = &tls->restore_ctx;
4509 MonoSeqPointInfo *info;
4511 ip = MONO_CONTEXT_GET_IP (ctx);
4513 /* Skip the instruction causing the single step */
4514 mono_arch_skip_single_step (ctx);
4516 if (suspend_count > 0) {
4517 process_suspend (tls, ctx);
4522 // FIXME: A suspend race
4525 if (mono_thread_internal_current () != ss_req->thread)
4528 if (log_level > 0) {
4529 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4531 DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_depth_to_string (ss_req->depth), mono_method_full_name (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4534 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4536 g_assert (ji->method);
4538 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4543 * Stopping in memset makes half-initialized vtypes visible.
4544 * Stopping in memcpy makes half-copied vtypes visible.
4546 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4550 * The ip points to the instruction causing the single step event, which is before
4551 * the offset recorded in the seq point map, so find the next seq point after ip.
4553 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4556 il_offset = sp->il_offset;
4558 // FIXME: No tests fail if this is disabled
4560 if (ss_req->size == STEP_SIZE_LINE) {
4564 /* Step until a different source line is reached */
4565 MonoDebugMethodInfo *minfo;
4567 minfo = mono_debug_lookup_method (ji->method);
4570 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4572 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4573 mono_debug_free_source_location (loc);
4578 * Step until we reach a location with line number info,
4579 * otherwise the client can't show a location.
4580 * This can happen for example with statics initialized inline
4581 * outside of a cctor.
4586 ss_req->last_method = ji->method;
4587 ss_req->last_line = loc->row;
4588 mono_debug_free_source_location (loc);
4594 /* Start single stepping again from the current sequence point */
4595 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4597 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4598 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4599 !strcmp (ji->method->name, ".cctor"))
4602 // FIXME: Has to lock earlier
4604 reqs = g_ptr_array_new ();
4606 mono_loader_lock ();
4608 g_ptr_array_add (reqs, ss_req->req);
4610 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4612 g_ptr_array_free (reqs, TRUE);
4614 mono_loader_unlock ();
4616 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4620 process_single_step (void)
4622 process_signal_event (process_single_step_inner);
4626 * mono_debugger_agent_single_step_event:
4628 * Called from a signal handler to handle a single step event.
4631 mono_debugger_agent_single_step_event (void *sigctx)
4633 /* Resume to process_single_step through the signal context */
4635 // FIXME: Since step out/over is implemented using step in, the step in case should
4636 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4639 if (GetCurrentThreadId () == debugger_thread_id) {
4641 * This could happen despite our best effors when the runtime calls
4642 * assembly/type resolve hooks.
4643 * FIXME: Breakpoints too.
4647 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4648 mono_arch_skip_single_step (&ctx);
4649 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4653 resume_from_signal_handler (sigctx, process_single_step);
4657 debugger_agent_single_step_from_context (MonoContext *ctx)
4659 DebuggerTlsData *tls;
4660 MonoContext orig_restore_ctx;
4662 tls = mono_native_tls_get_value (debugger_tls_id);
4665 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4666 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4667 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4669 process_single_step_inner (tls);
4671 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4672 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4676 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4678 DebuggerTlsData *tls;
4679 MonoContext orig_restore_ctx;
4681 tls = mono_native_tls_get_value (debugger_tls_id);
4683 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4684 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4686 process_breakpoint_inner (tls);
4688 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4689 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4693 * start_single_stepping:
4695 * Turn on single stepping. Can be called multiple times, for example,
4696 * by a single step event request + a suspend.
4699 start_single_stepping (void)
4701 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4702 int val = InterlockedIncrement (&ss_count);
4705 mono_arch_start_single_stepping ();
4707 if (ss_req != NULL && ss_invoke_addr == NULL) {
4708 DebuggerTlsData *tls;
4710 mono_loader_lock ();
4712 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4713 ss_invoke_addr = tls->invoke_addr;
4715 mono_loader_unlock ();
4718 g_assert_not_reached ();
4723 stop_single_stepping (void)
4725 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4726 int val = InterlockedDecrement (&ss_count);
4729 mono_arch_stop_single_stepping ();
4731 g_assert_not_reached ();
4738 * Stop the single stepping operation given by SS_REQ.
4741 ss_stop (SingleStepReq *ss_req)
4746 for (l = ss_req->bps; l; l = l->next) {
4747 clear_breakpoint (l->data);
4749 g_slist_free (ss_req->bps);
4753 if (ss_req->global) {
4754 stop_single_stepping ();
4755 ss_req->global = FALSE;
4762 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4763 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4764 * belong to the same thread as CTX.
4767 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4772 gboolean enable_global = FALSE;
4774 /* Stop the previous operation */
4778 * Implement single stepping using breakpoints if possible.
4780 if (step_to_catch) {
4781 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4782 ss_req->bps = g_slist_append (ss_req->bps, bp);
4786 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT) && ctx) {
4787 /* Need parent frames */
4788 if (!tls->context.valid)
4789 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4790 compute_frame_info (tls->thread, tls);
4794 * Find the first sequence point in the current or in a previous frame which
4795 * is not the last in its method.
4797 if (ss_req->depth == STEP_DEPTH_OUT) {
4798 /* Ignore seq points in current method */
4799 while (frame_index < tls->frame_count) {
4800 StackFrame *frame = tls->frames [frame_index];
4802 method = frame->method;
4803 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4805 if (sp && sp->next_len != 0)
4809 while (sp && sp->next_len == 0) {
4811 if (frame_index < tls->frame_count) {
4812 StackFrame *frame = tls->frames [frame_index];
4814 method = frame->method;
4815 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4821 if (sp && sp->next_len > 0) {
4822 for (i = 0; i < sp->next_len; ++i) {
4823 next_sp = &info->seq_points [sp->next [i]];
4825 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4826 ss_req->bps = g_slist_append (ss_req->bps, bp);
4830 if (ss_req->depth == STEP_DEPTH_INTO) {
4831 /* Enable global stepping so we stop at method entry too */
4832 enable_global = TRUE;
4836 * The ctx/frame info computed above will become invalid when we continue.
4838 tls->context.valid = FALSE;
4839 tls->async_state.valid = FALSE;
4840 invalidate_frames (tls);
4843 if (enable_global) {
4844 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4845 ss_req->global = TRUE;
4846 start_single_stepping ();
4847 } else if (!ss_req->bps) {
4848 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4849 ss_req->global = TRUE;
4850 start_single_stepping ();
4852 ss_req->global = FALSE;
4857 * Start single stepping of thread THREAD
4860 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4862 DebuggerTlsData *tls;
4863 MonoSeqPointInfo *info = NULL;
4864 SeqPoint *sp = NULL;
4865 MonoMethod *method = NULL;
4866 MonoDebugMethodInfo *minfo;
4867 gboolean step_to_catch = FALSE;
4869 if (suspend_count == 0)
4870 return ERR_NOT_SUSPENDED;
4872 wait_for_suspend ();
4874 // FIXME: Multiple requests
4876 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4877 return ERR_NOT_IMPLEMENTED;
4880 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4882 ss_req = g_new0 (SingleStepReq, 1);
4884 ss_req->thread = thread;
4885 ss_req->size = size;
4886 ss_req->depth = depth;
4889 mono_loader_lock ();
4890 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4891 mono_loader_unlock ();
4893 g_assert (tls->context.valid);
4894 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4896 if (tls->has_catch_ctx) {
4898 StackFrameInfo frame;
4899 MonoContext new_ctx;
4900 MonoLMF *lmf = NULL;
4903 * We are stopped at a throw site. Stepping should go to the catch site.
4906 /* Find the the jit info for the catch context */
4907 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4909 g_assert (frame.type == FRAME_TYPE_MANAGED);
4912 * Find the seq point corresponding to the landing site ip, which is the first seq
4915 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4918 method = frame.method;
4920 step_to_catch = TRUE;
4921 /* This make sure the seq point is not skipped by process_single_step () */
4922 ss_req->last_sp = NULL;
4925 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4928 /* Compute the initial line info */
4929 compute_frame_info (thread, tls);
4931 if (tls->frame_count) {
4932 frame = tls->frames [0];
4934 ss_req->last_method = frame->method;
4935 ss_req->last_line = -1;
4937 minfo = mono_debug_lookup_method (frame->method);
4938 if (minfo && frame->il_offset != -1) {
4939 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4942 ss_req->last_line = loc->row;
4949 if (!step_to_catch) {
4952 compute_frame_info (thread, tls);
4954 if (tls->frame_count) {
4955 frame = tls->frames [0];
4957 if (!method && frame->il_offset != -1) {
4958 /* FIXME: Sort the table and use a binary search */
4959 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4961 method = frame->method;
4966 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
4972 ss_destroy (SingleStepReq *req)
4975 g_assert (ss_req == req);
4984 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
4987 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
4993 if (!agent_config.enabled)
4996 mono_loader_lock ();
4997 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
4998 mono_loader_unlock ();
5001 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5002 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5004 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5006 g_free (ei.category);
5007 g_free (ei.message);
5011 mono_debugger_agent_debug_log_is_enabled (void)
5013 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5014 return agent_config.enabled;
5018 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5019 MonoContext *catch_ctx)
5025 DebuggerTlsData *tls = NULL;
5027 if (thread_to_tls != NULL) {
5028 MonoInternalThread *thread = mono_thread_internal_current ();
5030 mono_loader_lock ();
5031 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5032 mono_loader_unlock ();
5034 if (tls && tls->abort_requested)
5036 if (tls && tls->disable_breakpoints)
5040 memset (&ei, 0, sizeof (EventInfo));
5042 /* Just-In-Time debugging */
5044 if (agent_config.onuncaught && !inited) {
5045 finish_agent_init (FALSE);
5048 * Send an unsolicited EXCEPTION event with a dummy request id.
5050 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5051 ei.exc = (MonoObject*)exc;
5052 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5055 } else if (agent_config.onthrow && !inited) {
5057 gboolean found = FALSE;
5059 for (l = agent_config.onthrow; l; l = l->next) {
5060 char *ex_type = l->data;
5061 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5063 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5070 finish_agent_init (FALSE);
5073 * Send an unsolicited EXCEPTION event with a dummy request id.
5075 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5076 ei.exc = (MonoObject*)exc;
5077 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5085 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5087 ei.exc = (MonoObject*)exc;
5088 ei.caught = catch_ctx != NULL;
5090 mono_loader_lock ();
5091 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5092 mono_loader_unlock ();
5094 if (tls && catch_ctx) {
5095 tls->catch_ctx = *catch_ctx;
5096 tls->has_catch_ctx = TRUE;
5099 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5102 tls->has_catch_ctx = FALSE;
5106 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5108 DebuggerTlsData *tls;
5113 tls = mono_native_tls_get_value (debugger_tls_id);
5118 * We're about to invoke an exception filter during the first pass of exception handling.
5120 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5121 * 'orig_ctx' is the context where the exception has been thrown.
5124 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5126 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5127 * the call site (line 37) and then continue to Main(), but it would never
5128 * include the throw site (line 32).
5130 * Since exception filters are invoked during the first pass of exception handling,
5131 * the stack frames of the throw site are still intact, so we should include them
5134 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5136 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5137 * but report the location of the 'throw' to the user.
5141 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5145 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5147 DebuggerTlsData *tls;
5152 tls = mono_native_tls_get_value (debugger_tls_id);
5156 tls->filter_state.valid = FALSE;
5160 * buffer_add_value_full:
5162 * Add the encoding of the value at ADDR described by T to the buffer.
5163 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5167 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5173 g_assert (*(void**)addr);
5174 addr = *(void**)addr;
5179 case MONO_TYPE_BOOLEAN:
5182 case MONO_TYPE_CHAR:
5202 case MONO_TYPE_VOID:
5203 buffer_add_byte (buf, t->type);
5205 case MONO_TYPE_BOOLEAN:
5208 buffer_add_byte (buf, t->type);
5209 buffer_add_int (buf, *(gint8*)addr);
5211 case MONO_TYPE_CHAR:
5214 buffer_add_byte (buf, t->type);
5215 buffer_add_int (buf, *(gint16*)addr);
5220 buffer_add_byte (buf, t->type);
5221 buffer_add_int (buf, *(gint32*)addr);
5226 buffer_add_byte (buf, t->type);
5227 buffer_add_long (buf, *(gint64*)addr);
5231 /* Treat it as a vtype */
5233 case MONO_TYPE_PTR: {
5234 gssize val = *(gssize*)addr;
5236 buffer_add_byte (buf, t->type);
5237 buffer_add_long (buf, val);
5241 case MONO_TYPE_STRING:
5242 case MONO_TYPE_SZARRAY:
5243 case MONO_TYPE_OBJECT:
5244 case MONO_TYPE_CLASS:
5245 case MONO_TYPE_ARRAY:
5246 obj = *(MonoObject**)addr;
5249 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5251 if (obj->vtable->klass->valuetype) {
5252 t = &obj->vtable->klass->byval_arg;
5253 addr = mono_object_unbox (obj);
5255 } else if (obj->vtable->klass->rank) {
5256 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5257 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5258 buffer_add_byte (buf, MONO_TYPE_CLASS);
5260 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5262 buffer_add_objid (buf, obj);
5266 case MONO_TYPE_VALUETYPE: {
5270 MonoClass *klass = mono_class_from_mono_type (t);
5272 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5273 buffer_add_byte (buf, klass->enumtype);
5274 buffer_add_typeid (buf, domain, klass);
5278 while ((f = mono_class_get_fields (klass, &iter))) {
5279 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5281 if (mono_field_is_deleted (f))
5285 buffer_add_int (buf, nfields);
5288 while ((f = mono_class_get_fields (klass, &iter))) {
5289 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5291 if (mono_field_is_deleted (f))
5293 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5297 case MONO_TYPE_GENERICINST:
5298 if (mono_type_generic_inst_is_valuetype (t)) {
5310 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5312 buffer_add_value_full (buf, t, addr, domain, FALSE);
5316 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5319 int type = decode_byte (buf, &buf, limit);
5321 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5322 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5323 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5324 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5325 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5326 char *name = mono_type_full_name (t);
5327 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5329 return ERR_INVALID_ARGUMENT;
5333 case MONO_TYPE_BOOLEAN:
5334 *(guint8*)addr = decode_int (buf, &buf, limit);
5336 case MONO_TYPE_CHAR:
5337 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5340 *(gint8*)addr = decode_int (buf, &buf, limit);
5343 *(guint8*)addr = decode_int (buf, &buf, limit);
5346 *(gint16*)addr = decode_int (buf, &buf, limit);
5349 *(guint16*)addr = decode_int (buf, &buf, limit);
5352 *(gint32*)addr = decode_int (buf, &buf, limit);
5355 *(guint32*)addr = decode_int (buf, &buf, limit);
5358 *(gint64*)addr = decode_long (buf, &buf, limit);
5361 *(guint64*)addr = decode_long (buf, &buf, limit);
5364 *(guint32*)addr = decode_int (buf, &buf, limit);
5367 *(guint64*)addr = decode_long (buf, &buf, limit);
5370 /* We send these as I8, so we get them back as such */
5371 g_assert (type == MONO_TYPE_I8);
5372 *(gssize*)addr = decode_long (buf, &buf, limit);
5374 case MONO_TYPE_GENERICINST:
5375 if (MONO_TYPE_ISSTRUCT (t)) {
5376 /* The client sends these as a valuetype */
5384 /* We send these as vtypes, so we get them back as such */
5385 g_assert (type == MONO_TYPE_VALUETYPE);
5388 case MONO_TYPE_VALUETYPE: {
5389 gboolean is_enum = decode_byte (buf, &buf, limit);
5393 gpointer iter = NULL;
5396 /* Enums are sent as a normal vtype */
5398 return ERR_NOT_IMPLEMENTED;
5399 klass = decode_typeid (buf, &buf, limit, &d, &err);
5403 if (klass != mono_class_from_mono_type (t))
5404 return ERR_INVALID_ARGUMENT;
5406 nfields = decode_int (buf, &buf, limit);
5407 while ((f = mono_class_get_fields (klass, &iter))) {
5408 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5410 if (mono_field_is_deleted (f))
5412 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5417 g_assert (nfields == 0);
5422 if (MONO_TYPE_IS_REFERENCE (t)) {
5423 if (type == MONO_TYPE_OBJECT) {
5424 int objid = decode_objid (buf, &buf, limit);
5428 err = get_object (objid, (MonoObject**)&obj);
5432 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
5433 return ERR_INVALID_ARGUMENT;
5434 if (obj && obj->vtable->domain != domain)
5435 return ERR_INVALID_ARGUMENT;
5437 mono_gc_wbarrier_generic_store (addr, obj);
5438 } else if (type == VALUE_TYPE_ID_NULL) {
5439 *(MonoObject**)addr = NULL;
5441 return ERR_INVALID_ARGUMENT;
5455 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5462 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5463 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5466 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5467 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5469 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5471 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5472 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5473 addr += (gint32)var->offset;
5475 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5477 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5479 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5483 g_assert_not_reached ();
5488 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5494 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5495 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5497 if (MONO_TYPE_IS_REFERENCE (t))
5498 size = sizeof (gpointer);
5500 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5503 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5504 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5506 gboolean is_signed = FALSE;
5508 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5513 v = is_signed ? *(gint8*)val : *(guint8*)val;
5516 v = is_signed ? *(gint16*)val : *(guint16*)val;
5519 v = is_signed ? *(gint32*)val : *(guint32*)val;
5522 v = is_signed ? *(gint64*)val : *(guint64*)val;
5525 g_assert_not_reached ();
5528 /* Set value on the stack or in the return ctx */
5529 if (reg_locations [reg]) {
5530 /* Saved on the stack */
5531 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5532 *(reg_locations [reg]) = v;
5535 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5536 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5539 // FIXME: Move these to mono-context.h/c.
5540 mono_arch_context_set_int_reg (ctx, reg, v);
5542 // FIXME: Can't set registers, so we disable linears
5547 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5548 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5549 addr += (gint32)var->offset;
5551 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5553 // FIXME: Write barriers
5554 memcpy (addr, val, size);
5556 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5560 g_assert_not_reached ();
5565 clear_event_request (int req_id, int etype)
5569 mono_loader_lock ();
5570 for (i = 0; i < event_requests->len; ++i) {
5571 EventRequest *req = g_ptr_array_index (event_requests, i);
5573 if (req->id == req_id && req->event_kind == etype) {
5574 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5575 clear_breakpoint (req->info);
5576 if (req->event_kind == EVENT_KIND_STEP)
5577 ss_destroy (req->info);
5578 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5579 clear_breakpoint (req->info);
5580 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5581 clear_breakpoint (req->info);
5582 g_ptr_array_remove_index_fast (event_requests, i);
5587 mono_loader_unlock ();
5591 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5593 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5594 return breakpoint_matches_assembly (req->info, assembly);
5598 for (i = 0; i < req->nmodifiers; ++i) {
5599 Modifier *m = &req->modifiers [i];
5601 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5603 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5604 for (j = 0; m->data.assemblies [j]; ++j)
5605 if (m->data.assemblies [j] == assembly)
5615 * clear_event_requests_for_assembly:
5617 * Clear all events requests which reference ASSEMBLY.
5620 clear_event_requests_for_assembly (MonoAssembly *assembly)
5625 mono_loader_lock ();
5629 for (i = 0; i < event_requests->len; ++i) {
5630 EventRequest *req = g_ptr_array_index (event_requests, i);
5632 if (event_req_matches_assembly (req, assembly)) {
5633 clear_event_request (req->id, req->event_kind);
5639 mono_loader_unlock ();
5643 * type_comes_from_assembly:
5645 * GHRFunc that returns TRUE if klass comes from assembly
5648 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5650 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5654 * clear_types_for_assembly:
5656 * Clears types from loaded_classes for a given assembly
5659 clear_types_for_assembly (MonoAssembly *assembly)
5661 MonoDomain *domain = mono_domain_get ();
5662 AgentDomainInfo *info = NULL;
5664 mono_loader_lock ();
5665 info = get_agent_domain_info (domain);
5666 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5667 mono_loader_unlock ();
5671 add_thread (gpointer key, gpointer value, gpointer user_data)
5673 MonoInternalThread *thread = value;
5674 Buffer *buf = user_data;
5676 buffer_add_objid (buf, (MonoObject*)thread);
5680 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5682 guint8 *p = invoke->p;
5683 guint8 *end = invoke->endp;
5686 MonoMethodSignature *sig;
5689 MonoObject *this, *res, *exc;
5692 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5695 MonoStopwatch watch;
5697 if (invoke->method) {
5699 * Invoke this method directly, currently only Environment.Exit () is supported.
5702 DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this ? this->vtable->klass->name : "<null>"));
5703 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5704 g_assert_not_reached ();
5707 m = decode_methodid (p, &p, end, &domain, &err);
5710 sig = mono_method_signature (m);
5712 if (m->klass->valuetype)
5713 this_buf = g_alloca (mono_class_instance_size (m->klass));
5715 this_buf = g_alloca (sizeof (MonoObject*));
5716 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5717 /* Should be null */
5718 int type = decode_byte (p, &p, end);
5719 if (type != VALUE_TYPE_ID_NULL)
5720 return ERR_INVALID_ARGUMENT;
5721 memset (this_buf, 0, mono_class_instance_size (m->klass));
5723 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5728 if (!m->klass->valuetype)
5729 this = *(MonoObject**)this_buf;
5733 DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this ? this->vtable->klass->name : "<null>"));
5735 if (this && this->vtable->domain != domain)
5738 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5739 if (!strcmp (m->name, ".ctor")) {
5740 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5741 return ERR_INVALID_ARGUMENT;
5743 this = mono_object_new (domain, m->klass);
5745 return ERR_INVALID_ARGUMENT;
5749 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5750 return ERR_INVALID_ARGUMENT;
5752 nargs = decode_int (p, &p, end);
5753 if (nargs != sig->param_count)
5754 return ERR_INVALID_ARGUMENT;
5755 /* Use alloca to get gc tracking */
5756 arg_buf = g_alloca (nargs * sizeof (gpointer));
5757 memset (arg_buf, 0, nargs * sizeof (gpointer));
5758 args = g_alloca (nargs * sizeof (gpointer));
5759 for (i = 0; i < nargs; ++i) {
5760 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5761 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5765 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5768 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5769 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5772 args [i] = arg_buf [i];
5779 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5780 tls->disable_breakpoints = TRUE;
5782 tls->disable_breakpoints = FALSE;
5785 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5787 /* FIXME: Move this to arch specific code */
5788 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5789 if (invoke->has_ctx) {
5792 lmf_addr = mono_get_lmf_addr ();
5795 memset (&ext, 0, sizeof (ext));
5797 ext.lmf.previous_lmf = *(lmf_addr);
5798 /* Mark that this is a MonoLMFExt */
5799 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5800 ext.lmf.rsp = (gssize)&ext;
5801 #elif defined(TARGET_X86)
5802 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5803 /* Mark that this is a MonoLMFExt */
5804 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5805 ext.lmf.ebp = (gssize)&ext;
5806 #elif defined(TARGET_ARM)
5807 ext.lmf.previous_lmf = *(lmf_addr);
5808 /* Mark that this is a MonoLMFExt */
5809 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5810 ext.lmf.sp = (gssize)&ext;
5811 #elif defined(TARGET_POWERPC)
5812 ext.lmf.previous_lmf = *(lmf_addr);
5813 /* Mark that this is a MonoLMFExt */
5814 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5815 ext.lmf.ebp = (gssize)&ext;
5816 #elif defined(TARGET_S390X)
5817 ext.lmf.previous_lmf = *(lmf_addr);
5818 /* Mark that this is a MonoLMFExt */
5819 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5820 ext.lmf.ebp = (gssize)&ext;
5821 #elif defined(TARGET_MIPS)
5822 ext.lmf.previous_lmf = *(lmf_addr);
5823 /* Mark that this is a MonoLMFExt */
5824 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5825 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5827 g_assert_not_reached ();
5830 ext.debugger_invoke = TRUE;
5831 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5833 mono_set_lmf ((MonoLMF*)&ext);
5837 mono_stopwatch_start (&watch);
5838 if (m->klass->valuetype)
5839 res = mono_runtime_invoke (m, this_buf, args, &exc);
5841 res = mono_runtime_invoke (m, this, args, &exc);
5842 mono_stopwatch_stop (&watch);
5843 DEBUG (1, fprintf (log_file, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer)GetCurrentThreadId (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch)));
5845 buffer_add_byte (buf, 0);
5846 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5848 buffer_add_byte (buf, 1);
5849 if (sig->ret->type == MONO_TYPE_VOID) {
5850 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5851 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5854 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5855 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5856 buffer_add_value (buf, sig->ret, &res, domain);
5857 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5858 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5860 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &res, domain);
5862 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5865 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5872 tls->disable_breakpoints = FALSE;
5874 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5875 if (invoke->has_ctx)
5876 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5879 // FIXME: byref arguments
5887 * Invoke the method given by tls->pending_invoke in the current thread.
5890 invoke_method (void)
5892 DebuggerTlsData *tls;
5897 static void (*restore_context) (void *);
5898 MonoContext restore_ctx;
5900 if (!restore_context)
5901 restore_context = mono_get_restore_context ();
5903 tls = mono_native_tls_get_value (debugger_tls_id);
5907 * Store the `InvokeData *' in `tls->invoke' until we're done with
5908 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5911 mono_loader_lock ();
5913 invoke = tls->pending_invoke;
5915 tls->pending_invoke = NULL;
5917 invoke->last_invoke = tls->invoke;
5918 tls->invoke = invoke;
5920 mono_loader_unlock ();
5922 tls->frames_up_to_date = FALSE;
5926 buffer_init (&buf, 128);
5928 err = do_invoke_method (tls, &buf, invoke);
5930 /* Start suspending before sending the reply */
5931 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5934 send_reply_packet (id, err, &buf);
5938 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5940 if (invoke->has_ctx)
5941 save_thread_context (&restore_ctx);
5943 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5944 g_assert (tls->resume_count);
5945 tls->resume_count -= invoke->suspend_count;
5948 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5951 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5953 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5954 * after the mono_runtime_invoke() already returned, but it doesn't matter
5955 * because we reset the abort here.
5958 mono_loader_lock ();
5960 if (tls->abort_requested)
5961 mono_thread_internal_reset_abort (tls->thread);
5963 tls->invoke = tls->invoke->last_invoke;
5964 tls->abort_requested = FALSE;
5966 mono_loader_unlock ();
5975 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5977 MonoThread *thread = value;
5978 DebuggerTlsData *tls;
5981 mono_loader_lock ();
5982 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5984 res = tls->really_suspended;
5985 mono_loader_unlock ();
5991 get_source_files_for_type (MonoClass *klass)
5993 gpointer iter = NULL;
5995 MonoDebugSourceInfo *sinfo;
5999 files = g_ptr_array_new ();
6001 while ((method = mono_class_get_methods (klass, &iter))) {
6002 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6003 GPtrArray *source_file_list;
6006 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL);
6007 for (j = 0; j < source_file_list->len; ++j) {
6008 sinfo = g_ptr_array_index (source_file_list, j);
6009 for (i = 0; i < files->len; ++i)
6010 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6012 if (i == files->len)
6013 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6015 g_ptr_array_free (source_file_list, TRUE);
6023 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6026 case CMD_VM_VERSION: {
6027 char *build_info, *version;
6029 build_info = mono_get_runtime_build_info ();
6030 version = g_strdup_printf ("mono %s", build_info);
6032 buffer_add_string (buf, version); /* vm version */
6033 buffer_add_int (buf, MAJOR_VERSION);
6034 buffer_add_int (buf, MINOR_VERSION);
6035 g_free (build_info);
6039 case CMD_VM_SET_PROTOCOL_VERSION: {
6040 major_version = decode_int (p, &p, end);
6041 minor_version = decode_int (p, &p, end);
6042 protocol_version_set = TRUE;
6043 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6046 case CMD_VM_ALL_THREADS: {
6048 mono_loader_lock ();
6049 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6050 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6051 mono_loader_unlock ();
6054 case CMD_VM_SUSPEND:
6056 wait_for_suspend ();
6059 if (suspend_count == 0)
6060 return ERR_NOT_SUSPENDED;
6063 case CMD_VM_DISPOSE:
6064 /* Clear all event requests */
6065 mono_loader_lock ();
6066 while (event_requests->len > 0) {
6067 EventRequest *req = g_ptr_array_index (event_requests, 0);
6069 clear_event_request (req->id, req->event_kind);
6071 mono_loader_unlock ();
6073 while (suspend_count > 0)
6075 disconnected = TRUE;
6076 vm_start_event_sent = FALSE;
6079 MonoInternalThread *thread;
6080 DebuggerTlsData *tls;
6081 MonoClass *env_class;
6082 MonoMethod *exit_method = NULL;
6086 exit_code = decode_int (p, &p, end);
6088 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6090 /* Have to send a reply before exiting */
6091 send_reply_packet (id, 0, buf);
6093 /* Clear all event requests */
6094 mono_loader_lock ();
6095 while (event_requests->len > 0) {
6096 EventRequest *req = g_ptr_array_index (event_requests, 0);
6098 clear_event_request (req->id, req->event_kind);
6100 mono_loader_unlock ();
6103 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6104 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6105 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6106 * better than doing the shutdown ourselves, since it avoids various races.
6110 wait_for_suspend ();
6112 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6114 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6116 mono_loader_lock ();
6117 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6118 mono_loader_unlock ();
6120 if (thread && exit_method) {
6121 mono_loader_lock ();
6122 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6123 mono_loader_unlock ();
6125 args = g_new0 (gpointer, 1);
6126 args [0] = g_malloc (sizeof (int));
6127 *(int*)(args [0]) = exit_code;
6129 tls->pending_invoke = g_new0 (InvokeData, 1);
6130 tls->pending_invoke->method = exit_method;
6131 tls->pending_invoke->args = args;
6133 while (suspend_count > 0)
6137 * No thread found, do it ourselves.
6138 * FIXME: This can race with normal shutdown etc.
6140 while (suspend_count > 0)
6143 mono_runtime_set_shutting_down ();
6145 mono_threads_set_shutting_down ();
6147 /* Suspend all managed threads since the runtime is going away */
6148 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6149 mono_thread_suspend_all_other_threads ();
6150 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6151 mono_runtime_quit ();
6152 transport_close2 ();
6153 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6159 case CMD_VM_INVOKE_METHOD: {
6160 int objid = decode_objid (p, &p, end);
6162 DebuggerTlsData *tls;
6165 err = get_object (objid, (MonoObject**)&thread);
6169 flags = decode_int (p, &p, end);
6171 // Wait for suspending if it already started
6173 wait_for_suspend ();
6174 if (!is_suspended ())
6175 return ERR_NOT_SUSPENDED;
6177 mono_loader_lock ();
6178 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6179 mono_loader_unlock ();
6182 if (!tls->really_suspended)
6183 /* The thread is still running native code, can't do invokes */
6184 return ERR_NOT_SUSPENDED;
6187 * Store the invoke data into tls, the thread will execute it after it is
6190 if (tls->pending_invoke)
6192 tls->pending_invoke = g_new0 (InvokeData, 1);
6193 tls->pending_invoke->id = id;
6194 tls->pending_invoke->flags = flags;
6195 tls->pending_invoke->p = g_malloc (end - p);
6196 memcpy (tls->pending_invoke->p, p, end - p);
6197 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6198 tls->pending_invoke->suspend_count = suspend_count;
6200 if (flags & INVOKE_FLAG_SINGLE_THREADED)
6201 resume_thread (THREAD_TO_INTERNAL (thread));
6206 case CMD_VM_ABORT_INVOKE: {
6207 int objid = decode_objid (p, &p, end);
6209 DebuggerTlsData *tls;
6212 err = get_object (objid, (MonoObject**)&thread);
6216 invoke_id = decode_int (p, &p, end);
6218 mono_loader_lock ();
6219 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6222 if (tls->abort_requested) {
6223 mono_loader_unlock ();
6228 * Check whether we're still inside the mono_runtime_invoke() and that it's
6229 * actually the correct invocation.
6231 * Careful, we do not stop the thread that's doing the invocation, so we can't
6232 * inspect its stack. However, invoke_method() also acquires the loader lock
6233 * when it's done, so we're safe here.
6237 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6238 mono_loader_unlock ();
6239 return ERR_NO_INVOCATION;
6242 tls->abort_requested = TRUE;
6244 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6245 mono_loader_unlock ();
6249 case CMD_VM_SET_KEEPALIVE: {
6250 int timeout = decode_int (p, &p, end);
6251 agent_config.keepalive = timeout;
6253 #ifndef DISABLE_SOCKET_TRANSPORT
6260 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6261 GHashTableIter iter, kiter;
6266 char *fname, *basename;
6267 gboolean ignore_case;
6268 GSList *class_list, *l;
6269 GPtrArray *res_classes, *res_domains;
6271 fname = decode_string (p, &p, end);
6272 ignore_case = decode_byte (p, &p, end);
6274 basename = g_path_get_basename (fname);
6276 res_classes = g_ptr_array_new ();
6277 res_domains = g_ptr_array_new ();
6279 mono_loader_lock ();
6280 g_hash_table_iter_init (&iter, domains);
6281 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6282 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6284 /* Update 'source_file_to_class' cache */
6285 g_hash_table_iter_init (&kiter, info->loaded_classes);
6286 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6287 if (!g_hash_table_lookup (info->source_files, klass)) {
6288 files = get_source_files_for_type (klass);
6289 g_hash_table_insert (info->source_files, klass, files);
6291 for (i = 0; i < files->len; ++i) {
6292 char *s = g_ptr_array_index (files, i);
6293 char *s2 = g_path_get_basename (s);
6296 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6298 class_list = g_slist_prepend (class_list, klass);
6299 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6301 class_list = g_slist_prepend (class_list, klass);
6302 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6305 /* The _ignorecase hash contains the lowercase path */
6306 s3 = strdup_tolower (s2);
6307 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6309 class_list = g_slist_prepend (class_list, klass);
6310 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6312 class_list = g_slist_prepend (class_list, klass);
6313 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6325 s = strdup_tolower (basename);
6326 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6329 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6332 for (l = class_list; l; l = l->next) {
6335 g_ptr_array_add (res_classes, klass);
6336 g_ptr_array_add (res_domains, domain);
6339 mono_loader_unlock ();
6344 buffer_add_int (buf, res_classes->len);
6345 for (i = 0; i < res_classes->len; ++i)
6346 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6347 g_ptr_array_free (res_classes, TRUE);
6348 g_ptr_array_free (res_domains, TRUE);
6351 case CMD_VM_GET_TYPES: {
6352 GHashTableIter iter;
6356 gboolean ignore_case;
6357 GPtrArray *res_classes, *res_domains;
6358 MonoTypeNameParse info;
6360 name = decode_string (p, &p, end);
6361 ignore_case = decode_byte (p, &p, end);
6363 if (!mono_reflection_parse_type (name, &info)) {
6365 mono_reflection_free_type_info (&info);
6366 return ERR_INVALID_ARGUMENT;
6369 res_classes = g_ptr_array_new ();
6370 res_domains = g_ptr_array_new ();
6372 mono_loader_lock ();
6373 g_hash_table_iter_init (&iter, domains);
6374 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6376 gboolean type_resolve;
6380 mono_domain_assemblies_lock (domain);
6381 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6385 type_resolve = TRUE;
6386 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6388 g_ptr_array_add (res_classes, mono_type_get_class (t));
6389 g_ptr_array_add (res_domains, domain);
6393 mono_domain_assemblies_unlock (domain);
6395 mono_loader_unlock ();
6398 mono_reflection_free_type_info (&info);
6400 buffer_add_int (buf, res_classes->len);
6401 for (i = 0; i < res_classes->len; ++i)
6402 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6403 g_ptr_array_free (res_classes, TRUE);
6404 g_ptr_array_free (res_domains, TRUE);
6409 return ERR_NOT_IMPLEMENTED;
6416 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6422 case CMD_EVENT_REQUEST_SET: {
6424 int i, event_kind, suspend_policy, nmodifiers, mod;
6427 MonoThread *step_thread;
6428 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6432 event_kind = decode_byte (p, &p, end);
6433 suspend_policy = decode_byte (p, &p, end);
6434 nmodifiers = decode_byte (p, &p, end);
6436 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6437 req->id = InterlockedIncrement (&event_request_id);
6438 req->event_kind = event_kind;
6439 req->suspend_policy = suspend_policy;
6440 req->nmodifiers = nmodifiers;
6443 for (i = 0; i < nmodifiers; ++i) {
6444 mod = decode_byte (p, &p, end);
6446 req->modifiers [i].kind = mod;
6447 if (mod == MOD_KIND_COUNT) {
6448 req->modifiers [i].data.count = decode_int (p, &p, end);
6449 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6450 method = decode_methodid (p, &p, end, &domain, &err);
6453 location = decode_long (p, &p, end);
6454 } else if (mod == MOD_KIND_STEP) {
6455 step_thread_id = decode_id (p, &p, end);
6456 size = decode_int (p, &p, end);
6457 depth = decode_int (p, &p, end);
6458 if (CHECK_PROTOCOL_VERSION (2, 16))
6459 filter = decode_int (p, &p, end);
6460 req->modifiers [i].data.filter = filter;
6461 } else if (mod == MOD_KIND_THREAD_ONLY) {
6462 int id = decode_id (p, &p, end);
6464 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6469 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6470 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6474 req->modifiers [i].caught = decode_byte (p, &p, end);
6475 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6476 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : ""));
6478 req->modifiers [i].data.exc_class = exc_class;
6480 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6482 return ERR_INVALID_ARGUMENT;
6485 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6486 int n = decode_int (p, &p, end);
6489 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6490 for (j = 0; j < n; ++j) {
6491 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6493 g_free (req->modifiers [i].data.assemblies);
6497 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6498 int n = decode_int (p, &p, end);
6501 modifier = &req->modifiers [i];
6502 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6503 for (j = 0; j < n; ++j) {
6504 char *s = decode_string (p, &p, end);
6508 s2 = strdup_tolower (s);
6509 g_hash_table_insert (modifier->data.source_files, s2, s2);
6513 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6514 int n = decode_int (p, &p, end);
6517 modifier = &req->modifiers [i];
6518 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6519 for (j = 0; j < n; ++j) {
6520 char *s = decode_string (p, &p, end);
6523 g_hash_table_insert (modifier->data.type_names, s, s);
6527 return ERR_NOT_IMPLEMENTED;
6531 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6534 req->info = set_breakpoint (method, location, req, &error);
6535 if (!mono_error_ok (&error)) {
6537 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6538 mono_error_cleanup (&error);
6539 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6541 } else if (req->event_kind == EVENT_KIND_STEP) {
6542 g_assert (step_thread_id);
6544 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6550 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6555 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6556 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6557 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6558 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6559 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6560 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6562 if (req->nmodifiers) {
6564 return ERR_NOT_IMPLEMENTED;
6568 mono_loader_lock ();
6569 g_ptr_array_add (event_requests, req);
6571 if (agent_config.defer) {
6572 /* Transmit cached data to the client on receipt of the event request */
6573 switch (req->event_kind) {
6574 case EVENT_KIND_APPDOMAIN_CREATE:
6575 /* Emit load events for currently loaded domains */
6576 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6578 case EVENT_KIND_ASSEMBLY_LOAD:
6579 /* Emit load events for currently loaded assemblies */
6580 mono_assembly_foreach (emit_assembly_load, NULL);
6582 case EVENT_KIND_THREAD_START:
6583 /* Emit start events for currently started threads */
6584 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6586 case EVENT_KIND_TYPE_LOAD:
6587 /* Emit type load events for currently loaded types */
6588 mono_domain_foreach (send_types_for_domain, NULL);
6594 mono_loader_unlock ();
6596 buffer_add_int (buf, req->id);
6599 case CMD_EVENT_REQUEST_CLEAR: {
6600 int etype = decode_byte (p, &p, end);
6601 int req_id = decode_int (p, &p, end);
6603 // FIXME: Make a faster mapping from req_id to request
6604 mono_loader_lock ();
6605 clear_event_request (req_id, etype);
6606 mono_loader_unlock ();
6609 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6612 mono_loader_lock ();
6614 while (i < event_requests->len) {
6615 EventRequest *req = g_ptr_array_index (event_requests, i);
6617 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6618 clear_breakpoint (req->info);
6620 g_ptr_array_remove_index_fast (event_requests, i);
6626 mono_loader_unlock ();
6630 return ERR_NOT_IMPLEMENTED;
6637 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6643 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6644 buffer_add_domainid (buf, mono_get_root_domain ());
6647 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6648 domain = decode_domainid (p, &p, end, NULL, &err);
6651 buffer_add_string (buf, domain->friendly_name);
6654 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6659 domain = decode_domainid (p, &p, end, NULL, &err);
6662 mono_loader_lock ();
6664 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6667 buffer_add_int (buf, count);
6668 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6670 buffer_add_assemblyid (buf, domain, ass);
6672 mono_loader_unlock ();
6675 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6676 domain = decode_domainid (p, &p, end, NULL, &err);
6680 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6683 case CMD_APPDOMAIN_GET_CORLIB: {
6684 domain = decode_domainid (p, &p, end, NULL, &err);
6688 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6691 case CMD_APPDOMAIN_CREATE_STRING: {
6695 domain = decode_domainid (p, &p, end, NULL, &err);
6698 s = decode_string (p, &p, end);
6700 o = mono_string_new (domain, s);
6701 buffer_add_objid (buf, (MonoObject*)o);
6704 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6706 MonoDomain *domain2;
6709 domain = decode_domainid (p, &p, end, NULL, &err);
6712 klass = decode_typeid (p, &p, end, &domain2, &err);
6717 g_assert (domain == domain2);
6719 o = mono_object_new (domain, klass);
6721 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6725 buffer_add_objid (buf, o);
6729 return ERR_NOT_IMPLEMENTED;
6736 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6742 ass = decode_assemblyid (p, &p, end, &domain, &err);
6747 case CMD_ASSEMBLY_GET_LOCATION: {
6748 buffer_add_string (buf, mono_image_get_filename (ass->image));
6751 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6755 if (ass->image->dynamic) {
6756 buffer_add_id (buf, 0);
6758 token = mono_image_get_entry_point (ass->image);
6760 buffer_add_id (buf, 0);
6762 m = mono_get_method (ass->image, token, NULL);
6763 buffer_add_methodid (buf, domain, m);
6768 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6769 buffer_add_moduleid (buf, domain, ass->image);
6772 case CMD_ASSEMBLY_GET_OBJECT: {
6773 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
6774 buffer_add_objid (buf, o);
6777 case CMD_ASSEMBLY_GET_TYPE: {
6778 char *s = decode_string (p, &p, end);
6779 gboolean ignorecase = decode_byte (p, &p, end);
6780 MonoTypeNameParse info;
6782 gboolean type_resolve, res;
6783 MonoDomain *d = mono_domain_get ();
6785 /* This is needed to be able to find referenced assemblies */
6786 res = mono_domain_set (domain, FALSE);
6789 if (!mono_reflection_parse_type (s, &info)) {
6792 if (info.assembly.name)
6794 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6796 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6797 mono_reflection_free_type_info (&info);
6800 mono_domain_set (d, TRUE);
6804 case CMD_ASSEMBLY_GET_NAME: {
6806 MonoAssembly *mass = ass;
6808 name = g_strdup_printf (
6809 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6811 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6812 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6813 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6814 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6816 buffer_add_string (buf, name);
6821 return ERR_NOT_IMPLEMENTED;
6828 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6834 case CMD_MODULE_GET_INFO: {
6835 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
6838 basename = g_path_get_basename (image->name);
6839 buffer_add_string (buf, basename); // name
6840 buffer_add_string (buf, image->module_name); // scopename
6841 buffer_add_string (buf, image->name); // fqname
6842 buffer_add_string (buf, mono_image_get_guid (image)); // guid
6843 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
6848 return ERR_NOT_IMPLEMENTED;
6855 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6857 if (val && val->vtable->klass == mono_defaults.monotype_class) {
6858 /* Special case these so the client doesn't have to handle Type objects */
6860 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6861 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
6862 } else if (MONO_TYPE_IS_REFERENCE (t))
6863 buffer_add_value (buf, t, &val, domain);
6865 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6869 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6875 buffer_add_int (buf, 0);
6879 for (i = 0; i < cinfo->num_attrs; ++i) {
6880 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6883 buffer_add_int (buf, nattrs);
6885 for (i = 0; i < cinfo->num_attrs; ++i) {
6886 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6887 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6888 MonoArray *typed_args, *named_args;
6890 CattrNamedArg *arginfo;
6892 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6894 buffer_add_methodid (buf, domain, attr->ctor);
6898 buffer_add_int (buf, mono_array_length (typed_args));
6899 for (j = 0; j < mono_array_length (typed_args); ++j) {
6900 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6902 t = mono_method_signature (attr->ctor)->params [j];
6904 buffer_add_cattr_arg (buf, t, domain, val);
6907 buffer_add_int (buf, 0);
6912 buffer_add_int (buf, mono_array_length (named_args));
6914 for (j = 0; j < mono_array_length (named_args); ++j) {
6915 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
6917 if (arginfo [j].prop) {
6918 buffer_add_byte (buf, 0x54);
6919 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6920 } else if (arginfo [j].field) {
6921 buffer_add_byte (buf, 0x53);
6922 buffer_add_fieldid (buf, domain, arginfo [j].field);
6924 g_assert_not_reached ();
6927 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6930 buffer_add_int (buf, 0);
6936 /* FIXME: Code duplication with icall.c */
6938 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
6943 mono_class_setup_interfaces (klass, error);
6944 if (!mono_error_ok (error))
6947 for (i = 0; i < klass->interface_count; i++) {
6948 ic = klass->interfaces [i];
6949 g_hash_table_insert (ifaces, ic, ic);
6951 collect_interfaces (ic, ifaces, error);
6952 if (!mono_error_ok (error))
6958 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6968 case CMD_TYPE_GET_INFO: {
6969 buffer_add_string (buf, klass->name_space);
6970 buffer_add_string (buf, klass->name);
6972 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
6973 buffer_add_string (buf, name);
6975 buffer_add_assemblyid (buf, domain, klass->image->assembly);
6976 buffer_add_moduleid (buf, domain, klass->image);
6977 buffer_add_typeid (buf, domain, klass->parent);
6978 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
6979 buffer_add_typeid (buf, domain, klass->element_class);
6981 buffer_add_id (buf, 0);
6982 buffer_add_int (buf, klass->type_token);
6983 buffer_add_byte (buf, klass->rank);
6984 buffer_add_int (buf, klass->flags);
6986 type = &klass->byval_arg;
6987 // FIXME: Can't decide whenever a class represents a byref type
6990 if (type->type == MONO_TYPE_PTR)
6992 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
6994 if (type->type == MONO_TYPE_VALUETYPE)
6996 if (klass->enumtype)
6998 if (klass->generic_container)
7000 if (klass->generic_container || klass->generic_class)
7002 buffer_add_byte (buf, b);
7005 while ((nested = mono_class_get_nested_types (klass, &iter)))
7007 buffer_add_int (buf, nnested);
7009 while ((nested = mono_class_get_nested_types (klass, &iter)))
7010 buffer_add_typeid (buf, domain, nested);
7011 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7012 if (klass->generic_container)
7013 buffer_add_typeid (buf, domain, klass);
7014 else if (klass->generic_class)
7015 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7017 buffer_add_id (buf, 0);
7019 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7022 if (klass->generic_class) {
7023 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7025 count = inst->type_argc;
7026 buffer_add_int (buf, count);
7027 for (i = 0; i < count; i++)
7028 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7029 } else if (klass->generic_container) {
7030 MonoGenericContainer *container = klass->generic_container;
7033 count = container->type_argc;
7034 buffer_add_int (buf, count);
7035 for (i = 0; i < count; i++) {
7036 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7037 buffer_add_typeid (buf, domain, pklass);
7040 buffer_add_int (buf, 0);
7045 case CMD_TYPE_GET_METHODS: {
7048 gpointer iter = NULL;
7051 mono_class_setup_methods (klass);
7053 nmethods = mono_class_num_methods (klass);
7055 buffer_add_int (buf, nmethods);
7057 while ((m = mono_class_get_methods (klass, &iter))) {
7058 buffer_add_methodid (buf, domain, m);
7061 g_assert (i == nmethods);
7064 case CMD_TYPE_GET_FIELDS: {
7067 gpointer iter = NULL;
7070 nfields = mono_class_num_fields (klass);
7072 buffer_add_int (buf, nfields);
7074 while ((f = mono_class_get_fields (klass, &iter))) {
7075 buffer_add_fieldid (buf, domain, f);
7076 buffer_add_string (buf, f->name);
7077 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7078 buffer_add_int (buf, f->type->attrs);
7081 g_assert (i == nfields);
7084 case CMD_TYPE_GET_PROPERTIES: {
7087 gpointer iter = NULL;
7090 nprops = mono_class_num_properties (klass);
7092 buffer_add_int (buf, nprops);
7094 while ((p = mono_class_get_properties (klass, &iter))) {
7095 buffer_add_propertyid (buf, domain, p);
7096 buffer_add_string (buf, p->name);
7097 buffer_add_methodid (buf, domain, p->get);
7098 buffer_add_methodid (buf, domain, p->set);
7099 buffer_add_int (buf, p->attrs);
7102 g_assert (i == nprops);
7105 case CMD_TYPE_GET_CATTRS: {
7106 MonoClass *attr_klass;
7107 MonoCustomAttrInfo *cinfo;
7109 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7110 /* attr_klass can be NULL */
7114 cinfo = mono_custom_attrs_from_class (klass);
7116 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7119 case CMD_TYPE_GET_FIELD_CATTRS: {
7120 MonoClass *attr_klass;
7121 MonoCustomAttrInfo *cinfo;
7122 MonoClassField *field;
7124 field = decode_fieldid (p, &p, end, NULL, &err);
7127 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7131 cinfo = mono_custom_attrs_from_field (klass, field);
7133 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7136 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7137 MonoClass *attr_klass;
7138 MonoCustomAttrInfo *cinfo;
7141 prop = decode_propertyid (p, &p, end, NULL, &err);
7144 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7148 cinfo = mono_custom_attrs_from_property (klass, prop);
7150 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7153 case CMD_TYPE_GET_VALUES:
7154 case CMD_TYPE_GET_VALUES_2: {
7161 MonoThread *thread_obj;
7162 MonoInternalThread *thread = NULL;
7163 guint32 special_static_type;
7165 if (command == CMD_TYPE_GET_VALUES_2) {
7166 int objid = decode_objid (p, &p, end);
7169 err = get_object (objid, (MonoObject**)&thread_obj);
7173 thread = THREAD_TO_INTERNAL (thread_obj);
7176 len = decode_int (p, &p, end);
7177 for (i = 0; i < len; ++i) {
7178 f = decode_fieldid (p, &p, end, NULL, &err);
7182 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7183 return ERR_INVALID_FIELDID;
7184 special_static_type = mono_class_field_get_special_static_type (f);
7185 if (special_static_type != SPECIAL_STATIC_NONE) {
7186 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7187 return ERR_INVALID_FIELDID;
7190 /* Check that the field belongs to the object */
7192 for (k = klass; k; k = k->parent) {
7193 if (k == f->parent) {
7199 return ERR_INVALID_FIELDID;
7201 vtable = mono_class_vtable (domain, f->parent);
7202 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7203 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7204 buffer_add_value (buf, f->type, val, domain);
7209 case CMD_TYPE_SET_VALUES: {
7217 len = decode_int (p, &p, end);
7218 for (i = 0; i < len; ++i) {
7219 f = decode_fieldid (p, &p, end, NULL, &err);
7223 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7224 return ERR_INVALID_FIELDID;
7225 if (mono_class_field_is_special_static (f))
7226 return ERR_INVALID_FIELDID;
7228 /* Check that the field belongs to the object */
7230 for (k = klass; k; k = k->parent) {
7231 if (k == f->parent) {
7237 return ERR_INVALID_FIELDID;
7239 // FIXME: Check for literal/const
7241 vtable = mono_class_vtable (domain, f->parent);
7242 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7243 err = decode_value (f->type, domain, val, p, &p, end);
7248 if (MONO_TYPE_IS_REFERENCE (f->type))
7249 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7251 mono_field_static_set_value (vtable, f, val);
7256 case CMD_TYPE_GET_OBJECT: {
7257 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
7258 buffer_add_objid (buf, o);
7261 case CMD_TYPE_GET_SOURCE_FILES:
7262 case CMD_TYPE_GET_SOURCE_FILES_2: {
7263 char *source_file, *base;
7267 files = get_source_files_for_type (klass);
7269 buffer_add_int (buf, files->len);
7270 for (i = 0; i < files->len; ++i) {
7271 source_file = g_ptr_array_index (files, i);
7272 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7273 buffer_add_string (buf, source_file);
7275 base = g_path_get_basename (source_file);
7276 buffer_add_string (buf, base);
7279 g_free (source_file);
7281 g_ptr_array_free (files, TRUE);
7284 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7285 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7289 if (mono_class_is_assignable_from (klass, oklass))
7290 buffer_add_byte (buf, 1);
7292 buffer_add_byte (buf, 0);
7295 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7296 char *name = decode_string (p, &p, end);
7297 int i, flags = decode_int (p, &p, end);
7298 MonoException *ex = NULL;
7299 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7302 return ERR_LOADER_ERROR;
7303 buffer_add_int (buf, array->len);
7304 for (i = 0; i < array->len; ++i) {
7305 MonoMethod *method = g_ptr_array_index (array, i);
7306 buffer_add_methodid (buf, domain, method);
7309 g_ptr_array_free (array, TRUE);
7313 case CMD_TYPE_GET_INTERFACES: {
7315 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7317 MonoClass *tclass, *iface;
7318 GHashTableIter iter;
7322 for (parent = tclass; parent; parent = parent->parent) {
7323 mono_class_setup_interfaces (parent, &error);
7324 if (!mono_error_ok (&error))
7325 return ERR_LOADER_ERROR;
7326 collect_interfaces (parent, iface_hash, &error);
7327 if (!mono_error_ok (&error))
7328 return ERR_LOADER_ERROR;
7331 buffer_add_int (buf, g_hash_table_size (iface_hash));
7333 g_hash_table_iter_init (&iter, iface_hash);
7334 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7335 buffer_add_typeid (buf, domain, iface);
7336 g_hash_table_destroy (iface_hash);
7339 case CMD_TYPE_GET_INTERFACE_MAP: {
7340 int tindex, ioffset;
7341 gboolean variance_used;
7343 int len, nmethods, i;
7347 len = decode_int (p, &p, end);
7348 mono_class_setup_vtable (klass);
7350 for (tindex = 0; tindex < len; ++tindex) {
7351 iclass = decode_typeid (p, &p, end, NULL, &err);
7355 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7357 return ERR_INVALID_ARGUMENT;
7359 nmethods = mono_class_num_methods (iclass);
7360 buffer_add_int (buf, nmethods);
7363 while ((method = mono_class_get_methods (iclass, &iter))) {
7364 buffer_add_methodid (buf, domain, method);
7366 for (i = 0; i < nmethods; ++i)
7367 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7372 return ERR_NOT_IMPLEMENTED;
7379 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7382 MonoDomain *old_domain;
7386 klass = decode_typeid (p, &p, end, &domain, &err);
7390 old_domain = mono_domain_get ();
7392 mono_domain_set (domain, TRUE);
7394 err = type_commands_internal (command, klass, domain, p, end, buf);
7396 mono_domain_set (old_domain, TRUE);
7402 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7404 MonoMethodHeader *header;
7407 case CMD_METHOD_GET_NAME: {
7408 buffer_add_string (buf, method->name);
7411 case CMD_METHOD_GET_DECLARING_TYPE: {
7412 buffer_add_typeid (buf, domain, method->klass);
7415 case CMD_METHOD_GET_DEBUG_INFO: {
7416 MonoDebugMethodInfo *minfo;
7418 int i, j, n_il_offsets;
7422 GPtrArray *source_file_list;
7424 header = mono_method_get_header (method);
7426 buffer_add_int (buf, 0);
7427 buffer_add_string (buf, "");
7428 buffer_add_int (buf, 0);
7432 minfo = mono_debug_lookup_method (method);
7434 buffer_add_int (buf, header->code_size);
7435 buffer_add_string (buf, "");
7436 buffer_add_int (buf, 0);
7437 mono_metadata_free_mh (header);
7441 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &source_files);
7442 buffer_add_int (buf, header->code_size);
7443 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7444 buffer_add_int (buf, source_file_list->len);
7445 for (i = 0; i < source_file_list->len; ++i) {
7446 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7447 buffer_add_string (buf, sinfo->source_file);
7448 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7449 for (j = 0; j < 16; ++j)
7450 buffer_add_byte (buf, sinfo->hash [j]);
7454 buffer_add_string (buf, source_file);
7456 buffer_add_int (buf, n_il_offsets);
7457 DEBUG (10, printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7458 for (i = 0; i < n_il_offsets; ++i) {
7459 const char *srcfile = "";
7461 if (source_files [i] != -1) {
7462 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7463 srcfile = sinfo->source_file;
7465 DEBUG (10, printf ("IL%x -> %s:%d\n", il_offsets [i], srcfile, line_numbers [i]));
7466 buffer_add_int (buf, il_offsets [i]);
7467 buffer_add_int (buf, line_numbers [i]);
7468 if (CHECK_PROTOCOL_VERSION (2, 13))
7469 buffer_add_int (buf, source_files [i]);
7471 g_free (source_file);
7472 g_free (il_offsets);
7473 g_free (line_numbers);
7474 g_free (source_files);
7475 g_ptr_array_free (source_file_list, TRUE);
7476 mono_metadata_free_mh (header);
7479 case CMD_METHOD_GET_PARAM_INFO: {
7480 MonoMethodSignature *sig = mono_method_signature (method);
7484 /* FIXME: mono_class_from_mono_type () and byrefs */
7486 /* FIXME: Use a smaller encoding */
7487 buffer_add_int (buf, sig->call_convention);
7488 buffer_add_int (buf, sig->param_count);
7489 buffer_add_int (buf, sig->generic_param_count);
7490 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7491 for (i = 0; i < sig->param_count; ++i) {
7493 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7496 /* Emit parameter names */
7497 names = g_new (char *, sig->param_count);
7498 mono_method_get_param_names (method, (const char **) names);
7499 for (i = 0; i < sig->param_count; ++i)
7500 buffer_add_string (buf, names [i]);
7505 case CMD_METHOD_GET_LOCALS_INFO: {
7506 int i, j, num_locals;
7507 MonoDebugLocalsInfo *locals;
7509 header = mono_method_get_header (method);
7511 return ERR_INVALID_ARGUMENT;
7513 buffer_add_int (buf, header->num_locals);
7516 for (i = 0; i < header->num_locals; ++i)
7517 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7520 locals = mono_debug_lookup_locals (method);
7522 num_locals = locals->num_locals;
7525 for (i = 0; i < header->num_locals; ++i) {
7526 for (j = 0; j < num_locals; ++j)
7527 if (locals->locals [j].index == i)
7530 buffer_add_string (buf, locals->locals [j].name);
7532 buffer_add_string (buf, "");
7536 for (i = 0; i < header->num_locals; ++i) {
7537 for (j = 0; j < num_locals; ++j)
7538 if (locals->locals [j].index == i)
7540 if (j < num_locals && locals->locals [j].block) {
7541 buffer_add_int (buf, locals->locals [j].block->start_offset);
7542 buffer_add_int (buf, locals->locals [j].block->end_offset);
7544 buffer_add_int (buf, 0);
7545 buffer_add_int (buf, header->code_size);
7548 mono_metadata_free_mh (header);
7551 mono_debug_symfile_free_locals (locals);
7555 case CMD_METHOD_GET_INFO:
7556 buffer_add_int (buf, method->flags);
7557 buffer_add_int (buf, method->iflags);
7558 buffer_add_int (buf, method->token);
7559 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7561 if (method->is_generic)
7563 if (mono_method_signature (method)->generic_param_count)
7565 buffer_add_byte (buf, attrs);
7566 if (method->is_generic || method->is_inflated) {
7569 if (method->is_generic) {
7572 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7574 result = imethod->declaring;
7575 if (imethod->context.class_inst) {
7576 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7577 /*Generic methods gets the context of the GTD.*/
7578 if (mono_class_get_context (klass))
7579 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7583 buffer_add_methodid (buf, domain, result);
7585 buffer_add_id (buf, 0);
7587 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7588 if (mono_method_signature (method)->generic_param_count) {
7591 if (method->is_inflated) {
7592 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7594 count = inst->type_argc;
7595 buffer_add_int (buf, count);
7597 for (i = 0; i < count; i++)
7598 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7600 buffer_add_int (buf, 0);
7602 } else if (method->is_generic) {
7603 MonoGenericContainer *container = mono_method_get_generic_container (method);
7605 count = mono_method_signature (method)->generic_param_count;
7606 buffer_add_int (buf, count);
7607 for (i = 0; i < count; i++) {
7608 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7609 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7610 buffer_add_typeid (buf, domain, pklass);
7613 buffer_add_int (buf, 0);
7616 buffer_add_int (buf, 0);
7621 case CMD_METHOD_GET_BODY: {
7624 header = mono_method_get_header (method);
7626 buffer_add_int (buf, 0);
7628 buffer_add_int (buf, header->code_size);
7629 for (i = 0; i < header->code_size; ++i)
7630 buffer_add_byte (buf, header->code [i]);
7632 mono_metadata_free_mh (header);
7635 case CMD_METHOD_RESOLVE_TOKEN: {
7636 guint32 token = decode_int (p, &p, end);
7639 switch (mono_metadata_token_code (token)) {
7640 case MONO_TOKEN_STRING: {
7644 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7647 s2 = mono_string_to_utf8 (s);
7649 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7650 buffer_add_string (buf, s2);
7656 MonoClass *handle_class;
7658 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7659 val = mono_method_get_wrapper_data (method, token);
7660 handle_class = mono_method_get_wrapper_data (method, token + 1);
7662 if (handle_class == NULL) {
7663 // Can't figure out the token type
7664 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7668 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7672 if (handle_class == mono_defaults.typehandle_class) {
7673 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7674 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7675 buffer_add_typeid (buf, domain, (MonoClass *) val);
7677 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7678 } else if (handle_class == mono_defaults.fieldhandle_class) {
7679 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7680 buffer_add_fieldid (buf, domain, val);
7681 } else if (handle_class == mono_defaults.methodhandle_class) {
7682 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7683 buffer_add_methodid (buf, domain, val);
7684 } else if (handle_class == mono_defaults.string_class) {
7687 s = mono_string_to_utf8 (val);
7688 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7689 buffer_add_string (buf, s);
7692 g_assert_not_reached ();
7700 return ERR_NOT_IMPLEMENTED;
7707 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7710 MonoDomain *old_domain;
7714 method = decode_methodid (p, &p, end, &domain, &err);
7718 old_domain = mono_domain_get ();
7720 mono_domain_set (domain, TRUE);
7722 err = method_commands_internal (command, method, domain, p, end, buf);
7724 mono_domain_set (old_domain, TRUE);
7730 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7732 int objid = decode_objid (p, &p, end);
7734 MonoThread *thread_obj;
7735 MonoInternalThread *thread;
7737 err = get_object (objid, (MonoObject**)&thread_obj);
7741 thread = THREAD_TO_INTERNAL (thread_obj);
7744 case CMD_THREAD_GET_NAME: {
7746 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7749 buffer_add_int (buf, 0);
7754 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7756 buffer_add_int (buf, len);
7757 buffer_add_data (buf, (guint8*)name, len);
7762 case CMD_THREAD_GET_FRAME_INFO: {
7763 DebuggerTlsData *tls;
7764 int i, start_frame, length;
7766 // Wait for suspending if it already started
7767 // FIXME: Races with suspend_count
7768 while (!is_suspended ()) {
7770 wait_for_suspend ();
7774 wait_for_suspend ();
7775 if (!is_suspended ())
7776 return ERR_NOT_SUSPENDED;
7779 start_frame = decode_int (p, &p, end);
7780 length = decode_int (p, &p, end);
7782 if (start_frame != 0 || length != -1)
7783 return ERR_NOT_IMPLEMENTED;
7785 mono_loader_lock ();
7786 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7787 mono_loader_unlock ();
7790 compute_frame_info (thread, tls);
7792 buffer_add_int (buf, tls->frame_count);
7793 for (i = 0; i < tls->frame_count; ++i) {
7794 buffer_add_int (buf, tls->frames [i]->id);
7795 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
7796 buffer_add_int (buf, tls->frames [i]->il_offset);
7798 * Instead of passing the frame type directly to the client, we associate
7799 * it with the previous frame using a set of flags. This avoids lots of
7800 * conditional code in the client, since a frame whose type isn't
7801 * FRAME_TYPE_MANAGED has no method, location, etc.
7803 buffer_add_byte (buf, tls->frames [i]->flags);
7808 case CMD_THREAD_GET_STATE:
7809 buffer_add_int (buf, thread->state);
7811 case CMD_THREAD_GET_INFO:
7812 buffer_add_byte (buf, thread->threadpool_thread);
7814 case CMD_THREAD_GET_ID:
7815 buffer_add_long (buf, (guint64)(gsize)thread);
7817 case CMD_THREAD_GET_TID:
7818 buffer_add_long (buf, (guint64)thread->tid);
7821 return ERR_NOT_IMPLEMENTED;
7828 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7832 MonoThread *thread_obj;
7833 MonoInternalThread *thread;
7834 int pos, i, len, frame_idx;
7835 DebuggerTlsData *tls;
7837 MonoDebugMethodJitInfo *jit;
7838 MonoDebugVarInfo *var;
7839 MonoMethodSignature *sig;
7841 MonoMethodHeader *header;
7843 objid = decode_objid (p, &p, end);
7844 err = get_object (objid, (MonoObject**)&thread_obj);
7848 thread = THREAD_TO_INTERNAL (thread_obj);
7850 id = decode_id (p, &p, end);
7852 mono_loader_lock ();
7853 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7854 mono_loader_unlock ();
7857 for (i = 0; i < tls->frame_count; ++i) {
7858 if (tls->frames [i]->id == id)
7861 if (i == tls->frame_count)
7862 return ERR_INVALID_FRAMEID;
7865 frame = tls->frames [frame_idx];
7867 if (!frame->has_ctx)
7869 return ERR_INVALID_FRAMEID;
7872 frame->jit = mono_debug_find_method (frame->method, frame->domain);
7873 if (!frame->jit && frame->method->is_inflated)
7874 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->method), frame->domain);
7878 /* This could happen for aot images with no jit debug info */
7879 s = mono_method_full_name (frame->method, TRUE);
7880 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
7882 return ERR_ABSENT_INFORMATION;
7887 sig = mono_method_signature (frame->actual_method);
7889 if (!get_seq_points (frame->domain, frame->actual_method))
7891 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
7893 return ERR_ABSENT_INFORMATION;
7896 case CMD_STACK_FRAME_GET_VALUES: {
7897 len = decode_int (p, &p, end);
7898 header = mono_method_get_header (frame->actual_method);
7900 for (i = 0; i < len; ++i) {
7901 pos = decode_int (p, &p, end);
7906 g_assert (pos >= 0 && pos < jit->num_params);
7908 var = &jit->params [pos];
7910 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
7912 g_assert (pos >= 0 && pos < jit->num_locals);
7914 var = &jit->locals [pos];
7916 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
7919 mono_metadata_free_mh (header);
7922 case CMD_STACK_FRAME_GET_THIS: {
7923 if (frame->method->klass->valuetype) {
7924 if (!sig->hasthis) {
7925 MonoObject *p = NULL;
7926 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
7928 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7931 if (!sig->hasthis) {
7932 MonoObject *p = NULL;
7933 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
7935 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7940 case CMD_STACK_FRAME_SET_VALUES: {
7943 MonoDebugVarInfo *var;
7945 len = decode_int (p, &p, end);
7946 header = mono_method_get_header (frame->actual_method);
7948 for (i = 0; i < len; ++i) {
7949 pos = decode_int (p, &p, end);
7954 g_assert (pos >= 0 && pos < jit->num_params);
7956 t = sig->params [pos];
7957 var = &jit->params [pos];
7959 g_assert (pos >= 0 && pos < jit->num_locals);
7961 t = header->locals [pos];
7962 var = &jit->locals [pos];
7965 if (MONO_TYPE_IS_REFERENCE (t))
7966 val_buf = g_alloca (sizeof (MonoObject*));
7968 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
7969 err = decode_value (t, frame->domain, val_buf, p, &p, end);
7973 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
7975 mono_metadata_free_mh (header);
7979 return ERR_NOT_IMPLEMENTED;
7986 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7989 int objid, err, index, len, i, esize;
7992 objid = decode_objid (p, &p, end);
7993 err = get_object (objid, (MonoObject**)&arr);
7998 case CMD_ARRAY_REF_GET_LENGTH:
7999 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8001 buffer_add_int (buf, arr->max_length);
8002 buffer_add_int (buf, 0);
8004 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8005 buffer_add_int (buf, arr->bounds [i].length);
8006 buffer_add_int (buf, arr->bounds [i].lower_bound);
8010 case CMD_ARRAY_REF_GET_VALUES:
8011 index = decode_int (p, &p, end);
8012 len = decode_int (p, &p, end);
8014 g_assert (index >= 0 && len >= 0);
8015 // Reordered to avoid integer overflow
8016 g_assert (!(index > arr->max_length - len));
8018 esize = mono_array_element_size (arr->obj.vtable->klass);
8019 for (i = index; i < index + len; ++i) {
8020 elem = (gpointer*)((char*)arr->vector + (i * esize));
8021 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8024 case CMD_ARRAY_REF_SET_VALUES:
8025 index = decode_int (p, &p, end);
8026 len = decode_int (p, &p, end);
8028 g_assert (index >= 0 && len >= 0);
8029 // Reordered to avoid integer overflow
8030 g_assert (!(index > arr->max_length - len));
8032 esize = mono_array_element_size (arr->obj.vtable->klass);
8033 for (i = index; i < index + len; ++i) {
8034 elem = (gpointer*)((char*)arr->vector + (i * esize));
8036 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8040 return ERR_NOT_IMPLEMENTED;
8047 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8052 int i, index, length;
8055 objid = decode_objid (p, &p, end);
8056 err = get_object (objid, (MonoObject**)&str);
8061 case CMD_STRING_REF_GET_VALUE:
8062 s = mono_string_to_utf8 (str);
8063 buffer_add_string (buf, s);
8066 case CMD_STRING_REF_GET_LENGTH:
8067 buffer_add_long (buf, mono_string_length (str));
8069 case CMD_STRING_REF_GET_CHARS:
8070 index = decode_long (p, &p, end);
8071 length = decode_long (p, &p, end);
8072 if (index > mono_string_length (str) - length)
8073 return ERR_INVALID_ARGUMENT;
8074 c = mono_string_chars (str) + index;
8075 for (i = 0; i < length; ++i)
8076 buffer_add_short (buf, c [i]);
8079 return ERR_NOT_IMPLEMENTED;
8086 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8095 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8096 objid = decode_objid (p, &p, end);
8097 err = get_object (objid, &obj);
8099 buffer_add_int (buf, 1);
8101 buffer_add_int (buf, 0);
8105 objid = decode_objid (p, &p, end);
8106 err = get_object (objid, &obj);
8111 case CMD_OBJECT_REF_GET_TYPE:
8112 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8114 case CMD_OBJECT_REF_GET_VALUES:
8115 len = decode_int (p, &p, end);
8117 for (i = 0; i < len; ++i) {
8118 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8122 /* Check that the field belongs to the object */
8124 for (k = obj->vtable->klass; k; k = k->parent) {
8125 if (k == f->parent) {
8131 return ERR_INVALID_FIELDID;
8133 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8137 if (mono_class_field_is_special_static (f))
8138 return ERR_INVALID_FIELDID;
8140 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8141 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8142 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8143 mono_field_static_get_value (vtable, f, val);
8144 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8147 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8151 case CMD_OBJECT_REF_SET_VALUES:
8152 len = decode_int (p, &p, end);
8154 for (i = 0; i < len; ++i) {
8155 f = decode_fieldid (p, &p, end, NULL, &err);
8159 /* Check that the field belongs to the object */
8161 for (k = obj->vtable->klass; k; k = k->parent) {
8162 if (k == f->parent) {
8168 return ERR_INVALID_FIELDID;
8170 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8174 if (mono_class_field_is_special_static (f))
8175 return ERR_INVALID_FIELDID;
8177 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8178 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8180 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8181 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8186 mono_field_static_set_value (vtable, f, val);
8189 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8195 case CMD_OBJECT_REF_GET_ADDRESS:
8196 buffer_add_long (buf, (gssize)obj);
8198 case CMD_OBJECT_REF_GET_DOMAIN:
8199 buffer_add_domainid (buf, obj->vtable->domain);
8201 case CMD_OBJECT_REF_GET_INFO:
8202 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8203 buffer_add_domainid (buf, obj->vtable->domain);
8206 return ERR_NOT_IMPLEMENTED;
8213 command_set_to_string (CommandSet command_set)
8215 switch (command_set) {
8218 case CMD_SET_OBJECT_REF:
8219 return "OBJECT_REF";
8220 case CMD_SET_STRING_REF:
8221 return "STRING_REF";
8222 case CMD_SET_THREAD:
8224 case CMD_SET_ARRAY_REF:
8226 case CMD_SET_EVENT_REQUEST:
8227 return "EVENT_REQUEST";
8228 case CMD_SET_STACK_FRAME:
8229 return "STACK_FRAME";
8230 case CMD_SET_APPDOMAIN:
8232 case CMD_SET_ASSEMBLY:
8234 case CMD_SET_METHOD:
8238 case CMD_SET_MODULE:
8248 cmd_to_string (CommandSet set, int command)
8253 case CMD_VM_VERSION:
8255 case CMD_VM_ALL_THREADS:
8256 return "ALL_THREADS";
8257 case CMD_VM_SUSPEND:
8263 case CMD_VM_DISPOSE:
8265 case CMD_VM_INVOKE_METHOD:
8266 return "INVOKE_METHOD";
8267 case CMD_VM_SET_PROTOCOL_VERSION:
8268 return "SET_PROTOCOL_VERSION";
8269 case CMD_VM_ABORT_INVOKE:
8270 return "ABORT_INVOKE";
8283 wait_for_attach (void)
8285 #ifndef DISABLE_SOCKET_TRANSPORT
8286 if (listen_fd == -1) {
8287 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8291 /* Block and wait for client connection */
8292 conn_fd = socket_transport_accept (listen_fd);
8293 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8294 if (conn_fd == -1) {
8295 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8299 g_assert_not_reached ();
8303 disconnected = !transport_handshake ();
8305 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8315 * This thread handles communication with the debugger client using a JDWP
8318 static guint32 WINAPI
8319 debugger_thread (void *arg)
8321 int res, len, id, flags, command_set = 0, command = 0;
8322 guint8 header [HEADER_LENGTH];
8323 guint8 *data, *p, *end;
8327 gboolean attach_failed = FALSE;
8329 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8331 debugger_thread_id = GetCurrentThreadId ();
8333 mono_jit_thread_attach (mono_get_root_domain ());
8335 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8337 mono_set_is_debugger_attached (TRUE);
8339 if (agent_config.defer) {
8340 if (!wait_for_attach ()) {
8341 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8342 attach_failed = TRUE; // Don't abort process when we can't listen
8344 /* Send start event to client */
8345 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8349 while (!attach_failed) {
8350 res = transport_recv (header, HEADER_LENGTH);
8352 /* This will break if the socket is closed during shutdown too */
8353 if (res != HEADER_LENGTH)
8357 end = header + HEADER_LENGTH;
8359 len = decode_int (p, &p, end);
8360 id = decode_int (p, &p, end);
8361 flags = decode_byte (p, &p, end);
8362 command_set = decode_byte (p, &p, end);
8363 command = decode_byte (p, &p, end);
8365 g_assert (flags == 0);
8368 const char *cmd_str;
8371 cmd_str = cmd_to_string (command_set, command);
8373 sprintf (cmd_num, "%d", command);
8377 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8380 data = g_malloc (len - HEADER_LENGTH);
8381 if (len - HEADER_LENGTH > 0)
8383 res = transport_recv (data, len - HEADER_LENGTH);
8384 if (res != len - HEADER_LENGTH)
8389 end = data + (len - HEADER_LENGTH);
8391 buffer_init (&buf, 128);
8396 /* Process the request */
8397 switch (command_set) {
8399 err = vm_commands (command, id, p, end, &buf);
8400 if (!err && command == CMD_VM_INVOKE_METHOD)
8401 /* Sent after the invoke is complete */
8404 case CMD_SET_EVENT_REQUEST:
8405 err = event_commands (command, p, end, &buf);
8407 case CMD_SET_APPDOMAIN:
8408 err = domain_commands (command, p, end, &buf);
8410 case CMD_SET_ASSEMBLY:
8411 err = assembly_commands (command, p, end, &buf);
8413 case CMD_SET_MODULE:
8414 err = module_commands (command, p, end, &buf);
8417 err = type_commands (command, p, end, &buf);
8419 case CMD_SET_METHOD:
8420 err = method_commands (command, p, end, &buf);
8422 case CMD_SET_THREAD:
8423 err = thread_commands (command, p, end, &buf);
8425 case CMD_SET_STACK_FRAME:
8426 err = frame_commands (command, p, end, &buf);
8428 case CMD_SET_ARRAY_REF:
8429 err = array_commands (command, p, end, &buf);
8431 case CMD_SET_STRING_REF:
8432 err = string_commands (command, p, end, &buf);
8434 case CMD_SET_OBJECT_REF:
8435 err = object_commands (command, p, end, &buf);
8438 err = ERR_NOT_IMPLEMENTED;
8442 send_reply_packet (id, err, &buf);
8447 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8451 mono_set_is_debugger_attached (FALSE);
8453 mono_mutex_lock (&debugger_thread_exited_mutex);
8454 debugger_thread_exited = TRUE;
8455 mono_cond_signal (&debugger_thread_exited_cond);
8456 mono_mutex_unlock (&debugger_thread_exited_mutex);
8458 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8460 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8461 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8462 start_debugger_thread ();
8468 #else /* DISABLE_DEBUGGER_AGENT */
8471 mono_debugger_agent_parse_options (char *options)
8473 g_error ("This runtime is configured with the debugger agent disabled.");
8477 mono_debugger_agent_init (void)
8482 mono_debugger_agent_breakpoint_hit (void *sigctx)
8487 mono_debugger_agent_single_step_event (void *sigctx)
8492 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8497 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8503 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8504 MonoContext *catch_ctx)
8509 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8514 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8519 mono_debugger_agent_user_break (void)
8525 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8530 mono_debugger_agent_debug_log_is_enabled (void)