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 + (getpid () % 1000));
865 //agent_config.log_level = 0;
867 if (agent_config.transport == NULL) {
868 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
872 if (agent_config.address == NULL && !agent_config.server) {
873 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
878 if (!strcmp (agent_config.transport, "dt_socket")) {
879 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
880 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
887 mono_debugger_agent_init (void)
889 if (!agent_config.enabled)
894 /* Need to know whenever a thread has acquired the loader mutex */
895 mono_loader_lock_track_ownership (TRUE);
897 event_requests = g_ptr_array_new ();
899 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
900 mono_cond_init (&debugger_thread_exited_cond, NULL);
902 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
903 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
904 mono_profiler_install_runtime_initialized (runtime_initialized);
905 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
906 mono_profiler_install_thread (thread_startup, thread_end);
907 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
908 mono_profiler_install_jit_end (jit_end);
909 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
911 mono_native_tls_alloc (&debugger_tls_id, NULL);
913 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
914 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
916 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
917 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
919 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
920 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
922 pending_assembly_loads = g_ptr_array_new ();
923 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
925 log_level = agent_config.log_level;
927 embedding = agent_config.embedding;
930 if (agent_config.log_file) {
931 log_file = fopen (agent_config.log_file, "w+");
933 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
945 mini_get_debug_options ()->gen_seq_points = TRUE;
947 * This is needed because currently we don't handle liveness info.
949 mini_get_debug_options ()->mdb_optimizations = TRUE;
951 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
952 /* This is needed because we can't set local variables in registers yet */
953 mono_disable_optimizations (MONO_OPT_LINEARS);
957 * The stack walk done from thread_interrupt () needs to be signal safe, but it
958 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
959 * safe (#3411). So load AOT info eagerly when the debugger is running as a
962 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
964 if (!agent_config.onuncaught && !agent_config.onthrow)
965 finish_agent_init (TRUE);
967 /* FIXME: Is this still needed ? */
968 #if defined(__MACH__)
969 mono_thread_info_disable_new_interrupt (TRUE);
976 * Finish the initialization of the agent. This involves connecting the transport
977 * and starting the agent thread. This is either done at startup, or
978 * in response to some event like an unhandled exception.
981 finish_agent_init (gboolean on_startup)
985 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
988 if (agent_config.launch) {
991 // FIXME: Generated address
992 // FIXME: Races with transport_connect ()
994 argv [0] = agent_config.launch;
995 argv [1] = agent_config.transport;
996 argv [2] = agent_config.address;
999 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1001 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1006 transport_connect (agent_config.address);
1009 /* Do some which is usually done after sending the VMStart () event */
1010 vm_start_event_sent = TRUE;
1011 start_debugger_thread ();
1016 mono_debugger_agent_cleanup (void)
1021 stop_debugger_thread ();
1023 breakpoints_cleanup ();
1027 mono_mutex_destroy (&debugger_thread_exited_mutex);
1028 mono_cond_destroy (&debugger_thread_exited_cond);
1035 #ifndef DISABLE_SOCKET_TRANSPORT
1040 * recv() + handle incomplete reads and EINTR
1043 socket_transport_recv (void *buf, int len)
1052 res = recv (fd, (char *) buf + total, len - total, flags);
1055 if (agent_config.keepalive && res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1056 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1059 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1064 #define HAVE_GETADDRINFO 1
1068 set_keepalive (void)
1073 if (!agent_config.keepalive)
1076 tv.tv_sec = agent_config.keepalive / 1000;
1077 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1079 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1080 g_assert (result >= 0);
1084 socket_transport_accept (int socket_fd)
1086 conn_fd = accept (socket_fd, NULL, NULL);
1087 if (conn_fd == -1) {
1088 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1090 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1097 socket_transport_send (void *data, int len)
1102 res = send (conn_fd, data, len, 0);
1103 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1111 * socket_transport_connect:
1113 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1116 socket_transport_connect (const char *address)
1118 #ifdef HAVE_GETADDRINFO
1119 struct addrinfo hints;
1120 struct addrinfo *result, *rp;
1122 struct hostent *result;
1124 int sfd = -1, s, res;
1125 char port_string [128];
1129 if (agent_config.address) {
1130 res = parse_address (agent_config.address, &host, &port);
1131 g_assert (res == 0);
1141 sprintf (port_string, "%d", port);
1143 mono_network_init ();
1145 /* Obtain address(es) matching host/port */
1146 #ifdef HAVE_GETADDRINFO
1147 memset (&hints, 0, sizeof (struct addrinfo));
1148 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1149 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1151 hints.ai_protocol = 0; /* Any protocol */
1153 s = getaddrinfo (host, port_string, &hints, &result);
1155 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1159 /* The PS3 doesn't even have _r or hstrerror () */
1160 result = gethostbyname (host);
1162 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1167 if (agent_config.server) {
1168 #ifdef HAVE_GETADDRINFO
1169 /* Wait for a connection */
1171 struct sockaddr_in addr;
1174 /* No address, generate one */
1175 sfd = socket (AF_INET, SOCK_STREAM, 0);
1178 /* This will bind the socket to a random port */
1179 res = listen (sfd, 16);
1181 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1186 addrlen = sizeof (addr);
1187 memset (&addr, 0, sizeof (addr));
1188 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1189 g_assert (res == 0);
1191 host = (char*)"127.0.0.1";
1192 port = ntohs (addr.sin_port);
1194 /* Emit the address to stdout */
1195 /* FIXME: Should print another interface, not localhost */
1196 printf ("%s:%d\n", host, port);
1198 /* Listen on the provided address */
1199 for (rp = result; rp != NULL; rp = rp->ai_next) {
1202 sfd = socket (rp->ai_family, rp->ai_socktype,
1207 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1210 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1214 res = listen (sfd, 16);
1223 * this function is not present on win2000 which we still support, and the
1224 * workaround described here:
1225 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1226 * only works with MSVC.
1228 #ifdef HAVE_GETADDRINFO
1229 freeaddrinfo (result);
1234 if (agent_config.defer)
1237 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1239 if (agent_config.timeout) {
1244 tv.tv_usec = agent_config.timeout * 1000;
1246 FD_SET (sfd, &readfds);
1247 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1249 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1254 conn_fd = socket_transport_accept (sfd);
1258 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1261 #endif /* HAVE_GETADDRINFO */
1263 /* Connect to the specified address */
1264 #ifdef HAVE_GETADDRINFO
1265 /* FIXME: Respect the timeout */
1266 for (rp = result; rp != NULL; rp = rp->ai_next) {
1267 sfd = socket (rp->ai_family, rp->ai_socktype,
1272 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1273 break; /* Success */
1279 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1283 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1285 g_assert_not_reached ();
1286 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1288 g_assert_not_reached ();
1294 /* See the comment above */
1295 #ifdef HAVE_GETADDRINFO
1296 freeaddrinfo (result);
1301 disconnected = !transport_handshake ();
1307 socket_transport_close1 (void)
1309 /* This will interrupt the agent thread */
1310 /* Close the read part only so it can still send back replies */
1311 /* Also shut down the connection listener so that we can exit normally */
1313 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1314 shutdown (conn_fd, SD_BOTH);
1315 shutdown (listen_fd, SD_BOTH);
1316 closesocket (listen_fd);
1318 shutdown (conn_fd, SHUT_RD);
1319 shutdown (listen_fd, SHUT_RDWR);
1325 socket_transport_close2 (void)
1328 shutdown (conn_fd, SD_BOTH);
1330 shutdown (conn_fd, SHUT_RDWR);
1335 register_socket_transport (void)
1337 DebuggerTransport trans;
1339 trans.name = "dt_socket";
1340 trans.connect = socket_transport_connect;
1341 trans.close1 = socket_transport_close1;
1342 trans.close2 = socket_transport_close2;
1343 trans.send = socket_transport_send;
1344 trans.recv = socket_transport_recv;
1346 register_transport (&trans);
1349 #endif /* DISABLE_SOCKET_TRANSPORT */
1355 #define MAX_TRANSPORTS 16
1357 static DebuggerTransport *transport;
1359 static DebuggerTransport transports [MAX_TRANSPORTS];
1360 static int ntransports;
1363 register_transport (DebuggerTransport *trans)
1365 g_assert (ntransports < MAX_TRANSPORTS);
1367 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1372 transport_init (void)
1376 #ifndef DISABLE_SOCKET_TRANSPORT
1377 register_socket_transport ();
1380 for (i = 0; i < ntransports; ++i) {
1381 if (!strcmp (agent_config.transport, transports [i].name))
1384 if (i == ntransports) {
1385 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1386 for (i = 0; i < ntransports; ++i)
1387 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1388 fprintf (stderr, "\n");
1391 transport = &transports [i];
1395 transport_connect (const char *address)
1397 transport->connect (address);
1401 transport_close1 (void)
1403 transport->close1 ();
1407 transport_close2 (void)
1409 transport->close2 ();
1413 transport_send (void *buf, int len)
1415 return transport->send (buf, len);
1419 transport_recv (void *buf, int len)
1421 return transport->recv (buf, len);
1425 transport_handshake (void)
1427 char handshake_msg [128];
1431 /* Write handshake message */
1432 sprintf (handshake_msg, "DWP-Handshake");
1434 res = transport_send (handshake_msg, strlen (handshake_msg));
1435 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1436 g_assert (res != -1);
1439 res = transport_recv (buf, strlen (handshake_msg));
1440 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1441 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1446 * To support older clients, the client sends its protocol version after connecting
1447 * using a command. Until that is received, default to our protocol version.
1449 major_version = MAJOR_VERSION;
1450 minor_version = MINOR_VERSION;
1451 protocol_version_set = FALSE;
1453 #ifndef DISABLE_SOCKET_TRANSPORT
1454 // FIXME: Move this somewhere else
1456 * Set TCP_NODELAY on the socket so the client receives events/command
1457 * results immediately.
1461 int result = setsockopt (conn_fd,
1466 g_assert (result >= 0);
1476 stop_debugger_thread (void)
1481 transport_close1 ();
1484 * Wait for the thread to exit.
1486 * If we continue with the shutdown without waiting for it, then the client might
1487 * not receive an answer to its last command like a resume.
1488 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1491 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1492 if (GetCurrentThreadId () != debugger_thread_id) {
1494 mono_mutex_lock (&debugger_thread_exited_mutex);
1495 if (!debugger_thread_exited) {
1497 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1498 mono_mutex_unlock (&debugger_thread_exited_mutex);
1500 mono_mutex_lock (&debugger_thread_exited_mutex);
1503 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1506 mono_mutex_unlock (&debugger_thread_exited_mutex);
1507 } while (!debugger_thread_exited);
1510 transport_close2 ();
1514 start_debugger_thread (void)
1518 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1519 g_assert (debugger_thread_handle);
1523 * Functions to decode protocol data
1527 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1530 g_assert (*endbuf <= limit);
1535 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1538 g_assert (*endbuf <= limit);
1540 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1543 static inline gint64
1544 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1546 guint32 high = decode_int (buf, &buf, limit);
1547 guint32 low = decode_int (buf, &buf, limit);
1551 return ((((guint64)high) << 32) | ((guint64)low));
1555 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1557 return decode_int (buf, endbuf, limit);
1561 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1563 int len = decode_int (buf, &buf, limit);
1571 s = g_malloc (len + 1);
1574 memcpy (s, buf, len);
1583 * Functions to encode protocol data
1587 guint8 *buf, *p, *end;
1591 buffer_init (Buffer *buf, int size)
1593 buf->buf = g_malloc (size);
1595 buf->end = buf->buf + size;
1599 buffer_make_room (Buffer *buf, int size)
1601 if (buf->end - buf->p < size) {
1602 int new_size = buf->end - buf->buf + size + 32;
1603 guint8 *p = g_realloc (buf->buf, new_size);
1604 size = buf->p - buf->buf;
1607 buf->end = buf->buf + new_size;
1612 buffer_add_byte (Buffer *buf, guint8 val)
1614 buffer_make_room (buf, 1);
1620 buffer_add_short (Buffer *buf, guint32 val)
1622 buffer_make_room (buf, 2);
1623 buf->p [0] = (val >> 8) & 0xff;
1624 buf->p [1] = (val >> 0) & 0xff;
1629 buffer_add_int (Buffer *buf, guint32 val)
1631 buffer_make_room (buf, 4);
1632 buf->p [0] = (val >> 24) & 0xff;
1633 buf->p [1] = (val >> 16) & 0xff;
1634 buf->p [2] = (val >> 8) & 0xff;
1635 buf->p [3] = (val >> 0) & 0xff;
1640 buffer_add_long (Buffer *buf, guint64 l)
1642 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1643 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1647 buffer_add_id (Buffer *buf, int id)
1649 buffer_add_int (buf, (guint64)id);
1653 buffer_add_data (Buffer *buf, guint8 *data, int len)
1655 buffer_make_room (buf, len);
1656 memcpy (buf->p, data, len);
1661 buffer_add_string (Buffer *buf, const char *str)
1666 buffer_add_int (buf, 0);
1669 buffer_add_int (buf, len);
1670 buffer_add_data (buf, (guint8*)str, len);
1675 buffer_free (Buffer *buf)
1681 send_packet (int command_set, int command, Buffer *data)
1687 id = InterlockedIncrement (&packet_id);
1689 len = data->p - data->buf + 11;
1690 buffer_init (&buf, len);
1691 buffer_add_int (&buf, len);
1692 buffer_add_int (&buf, id);
1693 buffer_add_byte (&buf, 0); /* flags */
1694 buffer_add_byte (&buf, command_set);
1695 buffer_add_byte (&buf, command);
1696 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1698 res = transport_send (buf.buf, len);
1706 send_reply_packet (int id, int error, Buffer *data)
1712 len = data->p - data->buf + 11;
1713 buffer_init (&buf, len);
1714 buffer_add_int (&buf, len);
1715 buffer_add_int (&buf, id);
1716 buffer_add_byte (&buf, 0x80); /* flags */
1717 buffer_add_byte (&buf, (error >> 8) & 0xff);
1718 buffer_add_byte (&buf, error);
1719 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1721 res = transport_send (buf.buf, len);
1733 * Represents an object accessible by the debugger client.
1736 /* Unique id used in the wire protocol to refer to objects */
1739 * A weakref gc handle pointing to the object. The gc handle is used to
1740 * detect if the object was garbage collected.
1745 /* Maps objid -> ObjRef */
1746 static GHashTable *objrefs;
1749 free_objref (gpointer value)
1753 mono_gchandle_free (o->handle);
1761 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1765 objrefs_cleanup (void)
1767 g_hash_table_destroy (objrefs);
1771 static GHashTable *obj_to_objref;
1774 * Return an ObjRef for OBJ.
1777 get_objref (MonoObject *obj)
1780 GSList *reflist = NULL, *l;
1786 mono_loader_lock ();
1789 obj_to_objref = g_hash_table_new (NULL, NULL);
1791 /* FIXME: The tables can grow indefinitely */
1793 if (mono_gc_is_moving ()) {
1795 * Objects can move, so use a hash table mapping hash codes to lists of
1796 * ObjRef structures.
1798 hash = mono_object_hash (obj);
1800 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1801 for (l = reflist; l; l = l->next) {
1803 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1804 mono_loader_unlock ();
1809 /* Use a hash table with masked pointers to internalize object references */
1810 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1811 /* ref might refer to a different object with the same addr which was GCd */
1812 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1813 mono_loader_unlock ();
1818 ref = g_new0 (ObjRef, 1);
1819 ref->id = InterlockedIncrement (&objref_id);
1820 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1822 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1824 if (mono_gc_is_moving ()) {
1825 reflist = g_slist_append (reflist, ref);
1826 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1828 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1831 mono_loader_unlock ();
1837 get_objid (MonoObject *obj)
1839 return get_objref (obj)->id;
1843 * Set OBJ to the object identified by OBJID.
1844 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1848 get_object_allow_null (int objid, MonoObject **obj)
1858 return ERR_INVALID_OBJECT;
1860 mono_loader_lock ();
1862 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1865 *obj = mono_gchandle_get_target (ref->handle);
1866 mono_loader_unlock ();
1868 return ERR_INVALID_OBJECT;
1871 mono_loader_unlock ();
1872 return ERR_INVALID_OBJECT;
1877 get_object (int objid, MonoObject **obj)
1879 int err = get_object_allow_null (objid, obj);
1884 return ERR_INVALID_OBJECT;
1889 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1891 return decode_id (buf, endbuf, limit);
1895 buffer_add_objid (Buffer *buf, MonoObject *o)
1897 buffer_add_id (buf, get_objid (o));
1916 * Represents a runtime structure accessible to the debugger client
1919 /* Unique id used in the wire protocol */
1921 /* Domain of the runtime structure, NULL if the domain was unloaded */
1928 MonoAssembly *assembly;
1929 MonoClassField *field;
1931 MonoProperty *property;
1936 /* Maps runtime structure -> Id */
1937 GHashTable *val_to_id [ID_NUM];
1938 /* Classes whose class load event has been sent */
1939 GHashTable *loaded_classes;
1940 /* Maps MonoClass->GPtrArray of file names */
1941 GHashTable *source_files;
1942 /* Maps source file basename -> GSList of classes */
1943 GHashTable *source_file_to_class;
1944 /* Same with ignore-case */
1945 GHashTable *source_file_to_class_ignorecase;
1949 static GPtrArray *ids [ID_NUM];
1956 for (i = 0; i < ID_NUM; ++i)
1957 ids [i] = g_ptr_array_new ();
1965 for (i = 0; i < ID_NUM; ++i) {
1967 for (j = 0; j < ids [i]->len; ++j)
1968 g_free (g_ptr_array_index (ids [i], j));
1969 g_ptr_array_free (ids [i], TRUE);
1976 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1978 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1980 GHashTableIter iter;
1981 GPtrArray *file_names;
1986 for (i = 0; i < ID_NUM; ++i)
1987 if (info->val_to_id [i])
1988 g_hash_table_destroy (info->val_to_id [i]);
1989 g_hash_table_destroy (info->loaded_classes);
1991 g_hash_table_iter_init (&iter, info->source_files);
1992 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
1993 for (i = 0; i < file_names->len; ++i)
1994 g_free (g_ptr_array_index (file_names, i));
1995 g_ptr_array_free (file_names, TRUE);
1998 g_hash_table_iter_init (&iter, info->source_file_to_class);
1999 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2004 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2005 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2013 domain_jit_info (domain)->agent_info = NULL;
2015 /* Clear ids referencing structures in the domain */
2016 for (i = 0; i < ID_NUM; ++i) {
2018 for (j = 0; j < ids [i]->len; ++j) {
2019 Id *id = g_ptr_array_index (ids [i], j);
2020 if (id->domain == domain)
2026 mono_loader_lock ();
2027 g_hash_table_remove (domains, domain);
2028 mono_loader_unlock ();
2031 static AgentDomainInfo*
2032 get_agent_domain_info (MonoDomain *domain)
2034 AgentDomainInfo *info = NULL;
2036 mono_domain_lock (domain);
2038 info = domain_jit_info (domain)->agent_info;
2040 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2041 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2042 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2043 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2044 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2047 mono_domain_unlock (domain);
2053 get_id (MonoDomain *domain, IdType type, gpointer val)
2056 AgentDomainInfo *info;
2061 mono_loader_lock ();
2063 mono_domain_lock (domain);
2065 info = get_agent_domain_info (domain);
2067 if (info->val_to_id [type] == NULL)
2068 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2070 id = g_hash_table_lookup (info->val_to_id [type], val);
2072 mono_domain_unlock (domain);
2073 mono_loader_unlock ();
2077 id = g_new0 (Id, 1);
2079 id->id = ids [type]->len + 1;
2080 id->domain = domain;
2083 g_hash_table_insert (info->val_to_id [type], val, id);
2085 mono_domain_unlock (domain);
2087 g_ptr_array_add (ids [type], id);
2089 mono_loader_unlock ();
2094 static inline gpointer
2095 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2099 int id = decode_id (buf, endbuf, limit);
2108 // FIXME: error handling
2109 mono_loader_lock ();
2110 g_assert (id > 0 && id <= ids [type]->len);
2112 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2113 mono_loader_unlock ();
2115 if (res->domain == NULL) {
2116 *err = ERR_UNLOADED;
2121 *domain = res->domain;
2123 return res->data.val;
2127 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2129 buffer_add_id (buf, get_id (domain, type, val));
2132 static inline MonoClass*
2133 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2135 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2138 static inline MonoAssembly*
2139 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2141 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2144 static inline MonoImage*
2145 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2147 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2150 static inline MonoMethod*
2151 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2153 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2156 static inline MonoClassField*
2157 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2159 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2162 static inline MonoDomain*
2163 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2165 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2168 static inline MonoProperty*
2169 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2171 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2175 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2177 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2181 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2183 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2187 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2189 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2193 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2195 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2199 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2201 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2205 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2207 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2211 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2213 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2216 static void invoke_method (void);
2223 * save_thread_context:
2225 * Set CTX as the current threads context which is used for computing stack traces.
2226 * This function is signal-safe.
2229 save_thread_context (MonoContext *ctx)
2231 DebuggerTlsData *tls;
2233 tls = mono_native_tls_get_value (debugger_tls_id);
2237 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2239 mono_thread_state_init_from_current (&tls->context);
2242 /* The number of times the runtime is suspended */
2243 static gint32 suspend_count;
2245 /* Number of threads suspended */
2247 * If this is equal to the size of thread_to_tls, the runtime is considered
2250 static gint32 threads_suspend_count;
2252 static mono_mutex_t suspend_mutex;
2254 /* Cond variable used to wait for suspend_count becoming 0 */
2255 static mono_cond_t suspend_cond;
2257 /* Semaphore used to wait for a thread becoming suspended */
2258 static MonoSemType suspend_sem;
2263 mono_mutex_init (&suspend_mutex, NULL);
2264 mono_cond_init (&suspend_cond, NULL);
2265 MONO_SEM_INIT (&suspend_sem, 0);
2270 StackFrameInfo last_frame;
2271 gboolean last_frame_set;
2274 } GetLastFrameUserData;
2277 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2279 GetLastFrameUserData *data = user_data;
2281 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2284 if (!data->last_frame_set) {
2285 /* Store the last frame */
2286 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2287 data->last_frame_set = TRUE;
2290 /* Store the context/lmf for the frame above the last frame */
2291 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2292 data->lmf = info->lmf;
2301 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2302 * INFO is set, process the thread described by INFO.
2303 * This should be signal safe.
2306 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2310 MonoNativeThreadId tid;
2313 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2314 * guarantee the signal handler will be called that many times. Instead of tracking
2315 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2316 * has been requested that hasn't been handled yet, otherwise we can have threads
2317 * refuse to die when VM_EXIT is called
2319 #if defined(__APPLE__)
2320 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2324 * We use interrupt_count to determine whenever this interrupt should be processed
2325 * by us or the normal interrupt processing code in the signal handler.
2326 * There is no race here with notify_thread (), since the signal is sent after
2327 * incrementing interrupt_count.
2329 if (tls->interrupt_count == 0)
2332 InterlockedDecrement (&tls->interrupt_count);
2336 ip = mono_arch_ip_from_context (sigctx);
2338 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2343 tid = mono_thread_info_get_tid (info);
2345 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2347 // FIXME: Races when the thread leaves managed code before hitting a single step
2351 /* Running managed code, will be suspended by the single step code */
2352 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2356 * Running native code, will be suspended when it returns to/enters
2357 * managed code. Treat it as already suspended.
2358 * This might interrupt the code in process_single_step_inner (), we use the
2359 * tls->suspending flag to avoid races when that happens.
2361 if (!tls->suspended && !tls->suspending) {
2363 GetLastFrameUserData data;
2365 // FIXME: printf is not signal safe, but this is only used during
2366 // debugger debugging
2368 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2369 //save_thread_context (&ctx);
2372 /* Already terminated */
2375 tls->context.valid = FALSE;
2378 * We are in a difficult position: we want to be able to provide stack
2379 * traces for this thread, but we can't use the current ctx+lmf, since
2380 * the thread is still running, so it might return to managed code,
2381 * making these invalid.
2382 * So we start a stack walk and save the first frame, along with the
2383 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2384 * suspended when it returns to managed code, so the parent's ctx should
2387 data.last_frame_set = FALSE;
2389 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2391 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2392 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2393 * since we are not in a JITted method.
2395 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2397 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2399 if (data.last_frame_set) {
2400 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2401 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2403 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2406 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2407 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2408 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2410 /* No managed frames */
2411 tls->async_state.valid = FALSE;
2413 mono_memory_barrier ();
2415 tls->suspended = TRUE;
2416 MONO_SEM_POST (&suspend_sem);
2423 * mono_debugger_agent_thread_interrupt:
2425 * Called by the abort signal handler.
2426 * Should be signal safe.
2429 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2431 DebuggerTlsData *tls;
2436 tls = mono_native_tls_get_value (debugger_tls_id);
2440 return thread_interrupt (tls, NULL, sigctx, ji);
2444 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2447 mono_debugger_agent_thread_interrupt (NULL, NULL);
2449 #endif /* HOST_WIN32 */
2452 * reset_native_thread_suspend_state:
2454 * Reset the suspended flag on native threads
2457 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2459 DebuggerTlsData *tls = value;
2461 if (!tls->really_suspended && tls->suspended)
2462 tls->suspended = FALSE;
2468 * Notify a thread that it needs to suspend.
2471 notify_thread (gpointer key, gpointer value, gpointer user_data)
2473 MonoInternalThread *thread = key;
2474 DebuggerTlsData *tls = value;
2475 gsize tid = thread->tid;
2478 if (GetCurrentThreadId () == tid || tls->terminated)
2481 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2484 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2485 * guarantee the signal handler will be called that many times. Instead of tracking
2486 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2487 * has been requested that hasn't been handled yet, otherwise we can have threads
2488 * refuse to die when VM_EXIT is called
2490 #if defined(__APPLE__)
2491 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2495 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2496 * of things like breaking waits etc. which we don't want.
2498 InterlockedIncrement (&tls->interrupt_count);
2501 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2503 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2505 if (mono_thread_info_new_interrupt_enabled ()) {
2506 MonoThreadInfo *info;
2509 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2512 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2514 thread_interrupt (tls, info, NULL, ji);
2516 mono_thread_info_resume (mono_thread_info_get_tid (info));
2518 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2521 * Attached thread which died without detaching.
2523 tls->terminated = TRUE;
2529 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2531 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2534 if (mono_loader_lock_is_owned_by_self ()) {
2536 * Shortcut for the check in suspend_current (). This speeds up processing
2537 * when executing long running code inside the loader lock, i.e. assembly load
2543 if (debugger_thread_id == GetCurrentThreadId ())
2546 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2547 if (suspend_count - tls->resume_count > 0)
2548 tls->suspending = TRUE;
2550 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2552 if (suspend_count - tls->resume_count == 0) {
2554 * We are executing a single threaded invoke but the single step for
2555 * suspending is still active.
2556 * FIXME: This slows down single threaded invokes.
2558 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2562 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2564 /* Can't suspend in these methods */
2565 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2568 save_thread_context (ctx);
2576 * Increase the suspend count of the VM. While the suspend count is greater
2577 * than 0, runtime threads are suspended at certain points during execution.
2582 mono_loader_lock ();
2584 mono_mutex_lock (&suspend_mutex);
2588 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2590 if (suspend_count == 1) {
2591 // FIXME: Is it safe to call this inside the lock ?
2592 start_single_stepping ();
2593 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2596 mono_mutex_unlock (&suspend_mutex);
2598 mono_loader_unlock ();
2604 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2612 g_assert (debugger_thread_id == GetCurrentThreadId ());
2614 mono_loader_lock ();
2616 mono_mutex_lock (&suspend_mutex);
2618 g_assert (suspend_count > 0);
2621 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2623 if (suspend_count == 0) {
2624 // FIXME: Is it safe to call this inside the lock ?
2625 stop_single_stepping ();
2626 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2629 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2630 err = mono_cond_broadcast (&suspend_cond);
2631 g_assert (err == 0);
2633 mono_mutex_unlock (&suspend_mutex);
2634 //g_assert (err == 0);
2636 mono_loader_unlock ();
2642 * Resume just one thread.
2645 resume_thread (MonoInternalThread *thread)
2648 DebuggerTlsData *tls;
2650 g_assert (debugger_thread_id == GetCurrentThreadId ());
2652 mono_loader_lock ();
2654 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2657 mono_mutex_lock (&suspend_mutex);
2659 g_assert (suspend_count > 0);
2661 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2663 tls->resume_count += suspend_count;
2666 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2667 * but only the one whose resume_count field is > 0 will be resumed.
2669 err = mono_cond_broadcast (&suspend_cond);
2670 g_assert (err == 0);
2672 mono_mutex_unlock (&suspend_mutex);
2673 //g_assert (err == 0);
2675 mono_loader_unlock ();
2679 invalidate_frames (DebuggerTlsData *tls)
2684 tls = mono_native_tls_get_value (debugger_tls_id);
2687 for (i = 0; i < tls->frame_count; ++i) {
2688 if (tls->frames [i]->jit)
2689 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2690 g_free (tls->frames [i]);
2692 g_free (tls->frames);
2693 tls->frame_count = 0;
2700 * Suspend the current thread until the runtime is resumed. If the thread has a
2701 * pending invoke, then the invoke is executed before this function returns.
2704 suspend_current (void)
2707 DebuggerTlsData *tls;
2709 g_assert (debugger_thread_id != GetCurrentThreadId ());
2711 if (mono_loader_lock_is_owned_by_self ()) {
2713 * If we own the loader mutex, can't suspend until we release it, since the
2714 * whole runtime can deadlock otherwise.
2719 tls = mono_native_tls_get_value (debugger_tls_id);
2722 mono_mutex_lock (&suspend_mutex);
2724 tls->suspending = FALSE;
2725 tls->really_suspended = TRUE;
2727 if (!tls->suspended) {
2728 tls->suspended = TRUE;
2729 MONO_SEM_POST (&suspend_sem);
2732 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2734 while (suspend_count - tls->resume_count > 0) {
2736 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2738 mono_mutex_unlock (&suspend_mutex);
2740 mono_mutex_lock (&suspend_mutex);
2746 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2747 g_assert (err == 0);
2751 tls->suspended = FALSE;
2752 tls->really_suspended = FALSE;
2754 threads_suspend_count --;
2756 mono_mutex_unlock (&suspend_mutex);
2758 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2760 if (tls->pending_invoke) {
2761 /* Save the original context */
2762 tls->pending_invoke->has_ctx = TRUE;
2763 tls->pending_invoke->ctx = tls->context.ctx;
2768 /* The frame info becomes invalid after a resume */
2769 tls->context.valid = FALSE;
2770 tls->async_state.valid = FALSE;
2771 invalidate_frames (NULL);
2775 count_thread (gpointer key, gpointer value, gpointer user_data)
2777 DebuggerTlsData *tls = value;
2779 if (!tls->suspended && !tls->terminated)
2780 *(int*)user_data = *(int*)user_data + 1;
2784 count_threads_to_wait_for (void)
2788 mono_loader_lock ();
2789 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2790 mono_loader_unlock ();
2798 * Wait until the runtime is completely suspended.
2801 wait_for_suspend (void)
2803 int nthreads, nwait, err;
2804 gboolean waited = FALSE;
2806 // FIXME: Threads starting/stopping ?
2807 mono_loader_lock ();
2808 nthreads = mono_g_hash_table_size (thread_to_tls);
2809 mono_loader_unlock ();
2812 nwait = count_threads_to_wait_for ();
2814 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2815 err = MONO_SEM_WAIT (&suspend_sem);
2816 g_assert (err == 0);
2824 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2830 * Return whenever the runtime is suspended.
2835 return count_threads_to_wait_for () == 0;
2838 static MonoSeqPointInfo*
2839 get_seq_points (MonoDomain *domain, MonoMethod *method)
2841 MonoSeqPointInfo *seq_points;
2843 mono_domain_lock (domain);
2844 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2845 if (!seq_points && method->is_inflated) {
2846 /* generic sharing + aot */
2847 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2849 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2851 mono_domain_unlock (domain);
2856 static MonoSeqPointInfo*
2857 find_seq_points (MonoDomain *domain, MonoMethod *method)
2859 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2862 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2863 g_assert (seq_points);
2869 * find_next_seq_point_for_native_offset:
2871 * Find the first sequence point after NATIVE_OFFSET.
2874 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2876 MonoSeqPointInfo *seq_points;
2879 seq_points = find_seq_points (domain, method);
2883 for (i = 0; i < seq_points->len; ++i) {
2884 if (seq_points->seq_points [i].native_offset >= native_offset)
2885 return &seq_points->seq_points [i];
2892 * find_prev_seq_point_for_native_offset:
2894 * Find the first sequence point before NATIVE_OFFSET.
2897 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2899 MonoSeqPointInfo *seq_points;
2902 seq_points = find_seq_points (domain, method);
2906 for (i = seq_points->len - 1; i >= 0; --i) {
2907 if (seq_points->seq_points [i].native_offset <= native_offset)
2908 return &seq_points->seq_points [i];
2917 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2918 * should be the location of a sequence point.
2920 static G_GNUC_UNUSED SeqPoint*
2921 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2923 MonoSeqPointInfo *seq_points;
2928 seq_points = get_seq_points (domain, method);
2933 for (i = 0; i < seq_points->len; ++i) {
2934 if (seq_points->seq_points [i].il_offset == il_offset)
2935 return &seq_points->seq_points [i];
2942 DebuggerTlsData *tls;
2944 } ComputeFramesUserData;
2947 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2949 ComputeFramesUserData *ud = user_data;
2951 MonoMethod *method, *actual_method;
2955 if (info->type != FRAME_TYPE_MANAGED) {
2956 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2957 /* Mark the last frame as an invoke frame */
2959 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2965 method = info->ji->method;
2967 method = info->method;
2968 actual_method = info->actual_method;
2973 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
2976 if (info->il_offset == -1) {
2977 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
2978 if (ud->frames == NULL) {
2979 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
2981 info->il_offset = sp->il_offset;
2983 if (info->il_offset == -1)
2984 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2987 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));
2989 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2990 if (!CHECK_PROTOCOL_VERSION (2, 17))
2991 /* Older clients can't handle this flag */
2993 method = mono_marshal_method_from_wrapper (method);
2996 actual_method = method;
2997 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3000 frame = g_new0 (StackFrame, 1);
3001 frame->method = method;
3002 frame->actual_method = actual_method;
3003 frame->il_offset = info->il_offset;
3004 frame->native_offset = info->native_offset;
3005 frame->flags = flags;
3006 if (info->reg_locations)
3007 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3010 frame->has_ctx = TRUE;
3012 frame->domain = info->domain;
3014 ud->frames = g_slist_append (ud->frames, frame);
3020 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3022 ComputeFramesUserData *ud = user_data;
3025 * 'tls->filter_ctx' is the location of the throw site.
3027 * mono_walk_stack() will never actually hit the throw site, but unwind
3028 * directly from the filter to the call site; we abort stack unwinding here
3029 * once this happens and resume from the throw site.
3032 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3035 return process_frame (info, ctx, user_data);
3039 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3041 ComputeFramesUserData user_data;
3043 int i, findex, new_frame_count;
3044 StackFrame **new_frames, *f;
3045 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3047 // FIXME: Locking on tls
3048 if (tls->frames && tls->frames_up_to_date)
3051 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3053 user_data.tls = tls;
3054 user_data.frames = NULL;
3055 if (tls->terminated) {
3056 tls->frame_count = 0;
3058 } if (!tls->really_suspended && tls->async_state.valid) {
3059 /* Have to use the state saved by the signal handler */
3060 process_frame (&tls->async_last_frame, NULL, &user_data);
3061 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3062 } else if (tls->filter_state.valid) {
3064 * We are inside an exception filter.
3066 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3068 if (tls->context.valid)
3069 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3071 * After that, we resume unwinding from the location where the exception has been thrown.
3073 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3074 } else if (tls->context.valid) {
3075 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3078 tls->frame_count = 0;
3082 new_frame_count = g_slist_length (user_data.frames);
3083 new_frames = g_new0 (StackFrame*, new_frame_count);
3085 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3089 * Reuse the id for already existing stack frames, so invokes don't invalidate
3090 * the still valid stack frames.
3092 for (i = 0; i < tls->frame_count; ++i) {
3093 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3094 f->id = tls->frames [i]->id;
3099 if (i >= tls->frame_count)
3100 f->id = InterlockedIncrement (&frame_id);
3102 new_frames [findex ++] = f;
3105 g_slist_free (user_data.frames);
3107 invalidate_frames (tls);
3109 tls->frames = new_frames;
3110 tls->frame_count = new_frame_count;
3111 tls->frames_up_to_date = TRUE;
3115 * GHFunc to emit an appdomain creation event
3116 * @param key Don't care
3117 * @param value A loaded appdomain
3118 * @param user_data Don't care
3121 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3123 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3124 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3128 * GHFunc to emit a thread start event
3129 * @param key A thread id
3130 * @param value A thread object
3131 * @param user_data Don't care
3134 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3136 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3137 process_profiler_event (EVENT_KIND_THREAD_START, value);
3141 * GFunc to emit an assembly load event
3142 * @param value A loaded assembly
3143 * @param user_data Don't care
3146 emit_assembly_load (gpointer value, gpointer user_data)
3148 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3152 * GFunc to emit a type load event
3153 * @param value A loaded type
3154 * @param user_data Don't care
3157 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3159 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3163 strdup_tolower (char *s)
3168 for (p = s2; *p; ++p)
3178 * create_event_list:
3180 * Return a list of event request ids matching EVENT, starting from REQS, which
3181 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3183 * We return request ids, instead of requests, to simplify threading, since
3184 * requests could be deleted anytime when the loader lock is not held.
3185 * LOCKING: Assumes the loader lock is held.
3188 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3191 GSList *events = NULL;
3193 *suspend_policy = SUSPEND_POLICY_NONE;
3196 reqs = event_requests;
3201 for (i = 0; i < reqs->len; ++i) {
3202 EventRequest *req = g_ptr_array_index (reqs, i);
3203 if (req->event_kind == event) {
3204 gboolean filtered = FALSE;
3207 for (j = 0; j < req->nmodifiers; ++j) {
3208 Modifier *mod = &req->modifiers [j];
3210 if (mod->kind == MOD_KIND_COUNT) {
3212 if (mod->data.count > 0) {
3213 if (mod->data.count > 0) {
3215 if (mod->data.count == 0)
3219 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3220 if (mod->data.thread != mono_thread_internal_current ())
3222 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3223 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3225 if (ei->caught && !mod->caught)
3227 if (!ei->caught && !mod->uncaught)
3229 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3231 gboolean found = FALSE;
3232 MonoAssembly **assemblies = mod->data.assemblies;
3235 for (k = 0; assemblies [k]; ++k)
3236 if (assemblies [k] == ji->method->klass->image->assembly)
3241 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3242 gpointer iter = NULL;
3244 MonoDebugSourceInfo *sinfo;
3245 char *source_file, *s;
3246 gboolean found = FALSE;
3248 GPtrArray *source_file_list;
3250 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3251 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3254 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL);
3255 for (i = 0; i < source_file_list->len; ++i) {
3256 sinfo = g_ptr_array_index (source_file_list, i);
3258 * Do a case-insesitive match by converting the file name to
3261 s = strdup_tolower (sinfo->source_file);
3262 if (g_hash_table_lookup (mod->data.source_files, s))
3266 g_ptr_array_free (source_file_list, TRUE);
3271 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3274 s = mono_type_full_name (&ei->klass->byval_arg);
3275 if (!g_hash_table_lookup (mod->data.type_names, s))
3278 } else if (mod->kind == MOD_KIND_STEP) {
3279 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3280 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3281 !strcmp (ji->method->name, ".cctor"))
3287 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3288 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3293 /* Send a VM START/DEATH event by default */
3294 if (event == EVENT_KIND_VM_START)
3295 events = g_slist_append (events, GINT_TO_POINTER (0));
3296 if (event == EVENT_KIND_VM_DEATH)
3297 events = g_slist_append (events, GINT_TO_POINTER (0));
3302 static G_GNUC_UNUSED const char*
3303 event_to_string (EventKind event)
3306 case EVENT_KIND_VM_START: return "VM_START";
3307 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3308 case EVENT_KIND_THREAD_START: return "THREAD_START";
3309 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3310 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3311 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3312 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3313 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3314 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3315 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3316 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3317 case EVENT_KIND_STEP: return "STEP";
3318 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3319 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3320 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3321 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3322 case EVENT_KIND_USER_LOG: return "USER_LOG";
3324 g_assert_not_reached ();
3331 * Send an event to the client, suspending the vm if needed.
3332 * LOCKING: Since this can suspend the calling thread, no locks should be held
3334 * The EVENTS list is freed by this function.
3337 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3341 MonoDomain *domain = mono_domain_get ();
3342 MonoThread *thread = NULL;
3343 gboolean send_success = FALSE;
3348 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3352 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3353 // FIXME: We miss those events
3354 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3358 if (vm_death_event_sent) {
3359 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3363 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3364 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3369 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3373 if (event == EVENT_KIND_KEEPALIVE)
3374 suspend_policy = SUSPEND_POLICY_NONE;
3379 if (agent_config.defer) {
3380 /* Make sure the thread id is always set when doing deferred debugging */
3381 if (debugger_thread_id == GetCurrentThreadId ()) {
3382 /* Don't suspend on events from the debugger thread */
3383 suspend_policy = SUSPEND_POLICY_NONE;
3384 thread = mono_thread_get_main ();
3386 else thread = mono_thread_current ();
3388 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3389 // FIXME: Send these with a NULL thread, don't suspend the current thread
3394 nevents = g_slist_length (events);
3395 buffer_init (&buf, 128);
3396 buffer_add_byte (&buf, suspend_policy);
3397 buffer_add_int (&buf, nevents);
3399 for (l = events; l; l = l->next) {
3400 buffer_add_byte (&buf, event); // event kind
3401 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3406 thread = mono_thread_current ();
3408 if (event == EVENT_KIND_VM_START && arg != NULL)
3411 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3414 case EVENT_KIND_THREAD_START:
3415 case EVENT_KIND_THREAD_DEATH:
3417 case EVENT_KIND_APPDOMAIN_CREATE:
3418 case EVENT_KIND_APPDOMAIN_UNLOAD:
3419 buffer_add_domainid (&buf, arg);
3421 case EVENT_KIND_METHOD_ENTRY:
3422 case EVENT_KIND_METHOD_EXIT:
3423 buffer_add_methodid (&buf, domain, arg);
3425 case EVENT_KIND_ASSEMBLY_LOAD:
3426 case EVENT_KIND_ASSEMBLY_UNLOAD:
3427 buffer_add_assemblyid (&buf, domain, arg);
3429 case EVENT_KIND_TYPE_LOAD:
3430 buffer_add_typeid (&buf, domain, arg);
3432 case EVENT_KIND_BREAKPOINT:
3433 case EVENT_KIND_STEP:
3434 buffer_add_methodid (&buf, domain, arg);
3435 buffer_add_long (&buf, il_offset);
3437 case EVENT_KIND_VM_START:
3438 buffer_add_domainid (&buf, mono_get_root_domain ());
3440 case EVENT_KIND_VM_DEATH:
3442 case EVENT_KIND_EXCEPTION: {
3443 EventInfo *ei = arg;
3444 buffer_add_objid (&buf, ei->exc);
3447 case EVENT_KIND_USER_BREAK:
3449 case EVENT_KIND_USER_LOG: {
3450 EventInfo *ei = arg;
3451 buffer_add_int (&buf, ei->level);
3452 buffer_add_string (&buf, ei->category ? ei->category : "");
3453 buffer_add_string (&buf, ei->message ? ei->message : "");
3456 case EVENT_KIND_KEEPALIVE:
3457 suspend_policy = SUSPEND_POLICY_NONE;
3460 g_assert_not_reached ();
3464 if (event == EVENT_KIND_VM_START) {
3465 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3466 if (!agent_config.defer)
3467 start_debugger_thread ();
3470 if (event == EVENT_KIND_VM_DEATH) {
3471 vm_death_event_sent = TRUE;
3472 suspend_policy = SUSPEND_POLICY_NONE;
3475 if (mono_runtime_is_shutting_down ())
3476 suspend_policy = SUSPEND_POLICY_NONE;
3478 if (suspend_policy != SUSPEND_POLICY_NONE) {
3480 * Save the thread context and start suspending before sending the packet,
3481 * since we could be receiving the resume request before send_packet ()
3484 save_thread_context (ctx);
3488 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3492 g_slist_free (events);
3495 if (!send_success) {
3496 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3500 if (event == EVENT_KIND_VM_START) {
3501 vm_start_event_sent = TRUE;
3504 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3506 switch (suspend_policy) {
3507 case SUSPEND_POLICY_NONE:
3509 case SUSPEND_POLICY_ALL:
3512 case SUSPEND_POLICY_EVENT_THREAD:
3516 g_assert_not_reached ();
3521 process_profiler_event (EventKind event, gpointer arg)
3525 EventInfo ei, *ei_arg = NULL;
3527 if (event == EVENT_KIND_TYPE_LOAD) {
3532 mono_loader_lock ();
3533 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3534 mono_loader_unlock ();
3536 process_event (event, arg, 0, NULL, events, suspend_policy);
3540 runtime_initialized (MonoProfiler *prof)
3542 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3543 if (agent_config.defer)
3544 start_debugger_thread ();
3548 runtime_shutdown (MonoProfiler *prof)
3550 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3552 mono_debugger_agent_cleanup ();
3556 thread_startup (MonoProfiler *prof, uintptr_t tid)
3558 MonoInternalThread *thread = mono_thread_internal_current ();
3559 MonoInternalThread *old_thread;
3560 DebuggerTlsData *tls;
3562 if (tid == debugger_thread_id)
3565 g_assert (thread->tid == tid);
3567 mono_loader_lock ();
3568 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3569 mono_loader_unlock ();
3571 if (thread == old_thread) {
3573 * For some reason, thread_startup () might be called for the same thread
3574 * multiple times (attach ?).
3576 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3580 * thread_end () might not be called for some threads, and the tid could
3583 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3584 mono_loader_lock ();
3585 mono_g_hash_table_remove (thread_to_tls, old_thread);
3586 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3587 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3588 mono_loader_unlock ();
3592 tls = mono_native_tls_get_value (debugger_tls_id);
3594 // FIXME: Free this somewhere
3595 tls = g_new0 (DebuggerTlsData, 1);
3596 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3597 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3598 tls->thread = thread;
3599 mono_native_tls_set_value (debugger_tls_id, tls);
3601 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3603 mono_loader_lock ();
3604 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3605 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3606 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3607 mono_loader_unlock ();
3609 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3612 * suspend_vm () could have missed this thread, so wait for a resume.
3618 thread_end (MonoProfiler *prof, uintptr_t tid)
3620 MonoInternalThread *thread;
3621 DebuggerTlsData *tls = NULL;
3623 mono_loader_lock ();
3624 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3626 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3627 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3629 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3630 tls->terminated = TRUE;
3631 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3632 MONO_GC_UNREGISTER_ROOT (tls->thread);
3636 mono_loader_unlock ();
3638 /* We might be called for threads started before we registered the start callback */
3640 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3641 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3646 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3648 mono_loader_lock ();
3649 g_hash_table_insert (domains, domain, domain);
3650 mono_loader_unlock ();
3652 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3656 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3658 clear_breakpoints_for_domain (domain);
3660 mono_loader_lock ();
3661 /* Invalidate each thread's frame stack */
3662 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3663 mono_loader_unlock ();
3665 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3669 * invalidate_each_thread:
3671 * A GHFunc to invalidate frames.
3672 * value must be a DebuggerTlsData*
3675 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3677 invalidate_frames (value);
3681 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3683 /* Sent later in jit_end () */
3684 mono_loader_lock ();
3685 g_ptr_array_add (pending_assembly_loads, assembly);
3686 mono_loader_unlock ();
3690 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3692 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3694 clear_event_requests_for_assembly (assembly);
3695 clear_types_for_assembly (assembly);
3699 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3701 #if defined(HOST_WIN32) && !defined(__GNUC__)
3702 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3704 gpointer stackptr = __builtin_frame_address (1);
3706 MonoInternalThread *thread = mono_thread_internal_current ();
3707 DebuggerTlsData *tls;
3709 mono_loader_lock ();
3711 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3712 /* Could be the debugger thread with assembly/type load hooks */
3714 tls->invoke_addr = stackptr;
3716 mono_loader_unlock ();
3720 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3723 #if defined(HOST_WIN32) && !defined(__GNUC__)
3724 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3726 gpointer stackptr = __builtin_frame_address (1);
3729 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3733 * We need to stop single stepping when exiting a runtime invoke, since if it is
3734 * a step out, it may return to native code, and thus never end.
3736 mono_loader_lock ();
3737 ss_invoke_addr = NULL;
3739 for (i = 0; i < event_requests->len; ++i) {
3740 EventRequest *req = g_ptr_array_index (event_requests, i);
3742 if (req->event_kind == EVENT_KIND_STEP) {
3743 ss_destroy (req->info);
3744 g_ptr_array_remove_index_fast (event_requests, i);
3749 mono_loader_unlock ();
3753 send_type_load (MonoClass *klass)
3755 gboolean type_load = FALSE;
3756 MonoDomain *domain = mono_domain_get ();
3757 AgentDomainInfo *info = NULL;
3759 mono_loader_lock ();
3760 mono_domain_lock (domain);
3762 info = get_agent_domain_info (domain);
3764 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3766 g_hash_table_insert (info->loaded_classes, klass, klass);
3769 mono_domain_unlock (domain);
3770 mono_loader_unlock ();
3772 emit_type_load (klass, klass, NULL);
3776 * Emit load events for all types currently loaded in the domain.
3777 * Takes the loader and domain locks.
3778 * user_data is unused.
3781 send_types_for_domain (MonoDomain *domain, void *user_data)
3783 AgentDomainInfo *info = NULL;
3785 mono_loader_lock ();
3786 mono_domain_lock (domain);
3787 info = get_agent_domain_info (domain);
3789 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3790 mono_domain_unlock (domain);
3791 mono_loader_unlock ();
3795 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3798 * We emit type load events when the first method of the type is JITted,
3799 * since the class load profiler callbacks might be called with the
3800 * loader lock held. They could also occur in the debugger thread.
3801 * Same for assembly load events.
3804 MonoAssembly *assembly = NULL;
3806 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3807 mono_loader_lock ();
3808 if (pending_assembly_loads->len > 0) {
3809 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3810 g_ptr_array_remove_index (pending_assembly_loads, 0);
3812 mono_loader_unlock ();
3815 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3821 send_type_load (method->klass);
3824 add_pending_breakpoints (method, jinfo);
3828 * BREAKPOINTS/SINGLE STEPPING
3832 * Contains information about an inserted breakpoint.
3835 long il_offset, native_offset;
3840 } BreakpointInstance;
3843 * Contains generic information about a breakpoint.
3847 * The method where the breakpoint is placed. Can be NULL in which case it
3848 * is inserted into every method. This is used to implement method entry/
3849 * exit events. Can be a generic method definition, in which case the
3850 * breakpoint is inserted into every instance.
3856 * A list of BreakpointInstance structures describing where the breakpoint
3857 * was inserted. There could be more than one because of
3858 * generics/appdomains/method entry/exit.
3860 GPtrArray *children;
3863 /* List of breakpoints */
3864 static GPtrArray *breakpoints;
3865 /* Maps breakpoint locations to the number of breakpoints at that location */
3866 static GHashTable *bp_locs;
3869 breakpoints_init (void)
3871 breakpoints = g_ptr_array_new ();
3872 bp_locs = g_hash_table_new (NULL, NULL);
3876 * insert_breakpoint:
3878 * Insert the breakpoint described by BP into the method described by
3882 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3885 BreakpointInstance *inst;
3886 SeqPoint *sp = NULL;
3889 mono_error_init (error);
3891 for (i = 0; i < seq_points->len; ++i) {
3892 sp = &seq_points->seq_points [i];
3894 if (sp->il_offset == bp->il_offset)
3898 if (i == seq_points->len) {
3900 * The set of IL offsets with seq points doesn't completely match the
3901 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3903 for (i = 0; i < seq_points->len; ++i) {
3904 sp = &seq_points->seq_points [i];
3906 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3911 if (i == seq_points->len) {
3912 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);
3914 for (i = 0; i < seq_points->len; ++i)
3915 printf ("%d\n", seq_points->seq_points [i].il_offset);
3918 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3927 inst = g_new0 (BreakpointInstance, 1);
3929 inst->native_offset = sp->native_offset;
3930 inst->ip = (guint8*)ji->code_start + sp->native_offset;
3932 inst->domain = domain;
3934 mono_loader_lock ();
3936 g_ptr_array_add (bp->children, inst);
3938 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3939 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3940 mono_loader_unlock ();
3943 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3944 mono_arch_set_breakpoint (ji, inst->ip);
3950 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
3954 remove_breakpoint (BreakpointInstance *inst)
3956 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3958 MonoJitInfo *ji = inst->ji;
3959 guint8 *ip = inst->ip;
3961 mono_loader_lock ();
3962 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3963 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3964 mono_loader_unlock ();
3966 g_assert (count > 0);
3969 mono_arch_clear_breakpoint (ji, ip);
3976 static inline gboolean
3977 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3983 if (method == bp->method)
3985 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
3988 if (bp->method->is_inflated && method->is_inflated) {
3989 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
3990 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3992 /* Open generic methods should match closed generic methods of the same class */
3993 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
3994 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
3995 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
3997 /* FIXME: Handle !mvar */
3998 if (t1->type != MONO_TYPE_MVAR)
4009 * add_pending_breakpoints:
4011 * Insert pending breakpoints into the newly JITted method METHOD.
4014 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4017 MonoSeqPointInfo *seq_points;
4023 domain = mono_domain_get ();
4025 mono_loader_lock ();
4027 for (i = 0; i < breakpoints->len; ++i) {
4028 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4029 gboolean found = FALSE;
4031 if (!bp_matches_method (bp, method))
4034 for (j = 0; j < bp->children->len; ++j) {
4035 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4042 mono_domain_lock (domain);
4043 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4044 if (!seq_points && ji->method->is_inflated)
4045 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4046 mono_domain_unlock (domain);
4048 /* Could be AOT code */
4050 g_assert (seq_points);
4052 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4056 mono_loader_unlock ();
4060 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4066 mono_error_init (error);
4068 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4070 /* Might be AOTed code */
4071 code = mono_aot_get_method (domain, method);
4073 ji = mono_jit_info_table_find (domain, code);
4078 insert_breakpoint (seq_points, domain, ji, bp, error);
4082 clear_breakpoint (MonoBreakpoint *bp);
4087 * Set a breakpoint at IL_OFFSET in METHOD.
4088 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4089 * METHOD can also be a generic method definition, in which case a breakpoint
4090 * is placed in all instances of the method.
4091 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4094 static MonoBreakpoint*
4095 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4098 GHashTableIter iter, iter2;
4101 MonoSeqPointInfo *seq_points;
4104 mono_error_init (error);
4107 // - suspend/resume the vm to prevent code patching problems
4108 // - multiple breakpoints on the same location
4109 // - dynamic methods
4112 bp = g_new0 (MonoBreakpoint, 1);
4113 bp->method = method;
4114 bp->il_offset = il_offset;
4116 bp->children = g_ptr_array_new ();
4118 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));
4120 mono_loader_lock ();
4122 g_hash_table_iter_init (&iter, domains);
4123 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4124 mono_domain_lock (domain);
4126 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4127 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4128 if (bp_matches_method (bp, m))
4129 set_bp_in_method (domain, m, seq_points, bp, error);
4132 mono_domain_unlock (domain);
4135 mono_loader_unlock ();
4137 mono_loader_lock ();
4138 g_ptr_array_add (breakpoints, bp);
4139 mono_loader_unlock ();
4141 if (error && !mono_error_ok (error)) {
4142 clear_breakpoint (bp);
4150 clear_breakpoint (MonoBreakpoint *bp)
4154 // FIXME: locking, races
4155 for (i = 0; i < bp->children->len; ++i) {
4156 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4158 remove_breakpoint (inst);
4163 mono_loader_lock ();
4164 g_ptr_array_remove (breakpoints, bp);
4165 mono_loader_unlock ();
4167 g_ptr_array_free (bp->children, TRUE);
4172 breakpoints_cleanup (void)
4176 mono_loader_lock ();
4178 while (i < event_requests->len) {
4179 EventRequest *req = g_ptr_array_index (event_requests, i);
4181 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4182 clear_breakpoint (req->info);
4183 g_ptr_array_remove_index_fast (event_requests, i);
4190 for (i = 0; i < breakpoints->len; ++i)
4191 g_free (g_ptr_array_index (breakpoints, i));
4193 g_ptr_array_free (breakpoints, TRUE);
4194 g_hash_table_destroy (bp_locs);
4199 mono_loader_unlock ();
4203 * clear_breakpoints_for_domain:
4205 * Clear breakpoint instances which reference DOMAIN.
4208 clear_breakpoints_for_domain (MonoDomain *domain)
4212 /* This could be called after shutdown */
4216 mono_loader_lock ();
4217 for (i = 0; i < breakpoints->len; ++i) {
4218 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4221 while (j < bp->children->len) {
4222 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4224 if (inst->domain == domain) {
4225 remove_breakpoint (inst);
4229 g_ptr_array_remove_index_fast (bp->children, j);
4235 mono_loader_unlock ();
4239 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4241 return bp->method && bp->method->klass->image->assembly == assembly;
4245 process_breakpoint_inner (DebuggerTlsData *tls)
4249 int i, j, suspend_policy;
4250 guint32 native_offset;
4252 BreakpointInstance *inst;
4253 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4254 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4255 EventKind kind = EVENT_KIND_BREAKPOINT;
4256 MonoContext *ctx = &tls->restore_ctx;
4257 MonoSeqPointInfo *info;
4260 // FIXME: Speed this up
4262 ip = MONO_CONTEXT_GET_IP (ctx);
4263 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4265 g_assert (ji->method);
4267 /* Compute the native offset of the breakpoint from the ip */
4268 native_offset = ip - (guint8*)ji->code_start;
4271 * Skip the instruction causing the breakpoint signal.
4273 mono_arch_skip_breakpoint (ctx, ji);
4275 if (ji->method->wrapper_type || tls->disable_breakpoints)
4278 bp_reqs = g_ptr_array_new ();
4279 ss_reqs = g_ptr_array_new ();
4280 ss_reqs_orig = g_ptr_array_new ();
4282 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, ip, native_offset));
4284 mono_loader_lock ();
4287 * The ip points to the instruction causing the breakpoint event, which is after
4288 * the offset recorded in the seq point map, so find the prev seq point before ip.
4290 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4293 for (i = 0; i < breakpoints->len; ++i) {
4294 bp = g_ptr_array_index (breakpoints, i);
4299 for (j = 0; j < bp->children->len; ++j) {
4300 inst = g_ptr_array_index (bp->children, j);
4301 if (inst->ji == ji && inst->sp == sp) {
4302 if (bp->req->event_kind == EVENT_KIND_STEP) {
4303 g_ptr_array_add (ss_reqs_orig, bp->req);
4305 g_ptr_array_add (bp_reqs, bp->req);
4310 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4311 /* Maybe a method entry/exit event */
4312 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4313 kind = EVENT_KIND_METHOD_ENTRY;
4314 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4315 kind = EVENT_KIND_METHOD_EXIT;
4318 /* Process single step requests */
4319 for (i = 0; i < ss_reqs_orig->len; ++i) {
4320 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4321 SingleStepReq *ss_req = req->info;
4322 gboolean hit = TRUE;
4324 if (ss_req->size == STEP_SIZE_LINE) {
4325 /* Have to check whenever a different source line was reached */
4326 MonoDebugMethodInfo *minfo;
4327 MonoDebugSourceLocation *loc = NULL;
4329 minfo = mono_debug_lookup_method (ji->method);
4332 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4334 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
4335 /* Have to continue single stepping */
4339 ss_req->last_method = ji->method;
4340 ss_req->last_line = loc->row;
4341 mono_debug_free_source_location (loc);
4346 g_ptr_array_add (ss_reqs, req);
4348 /* Start single stepping again from the current sequence point */
4349 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4352 if (ss_reqs->len > 0)
4353 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4354 if (bp_reqs->len > 0)
4355 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4356 if (kind != EVENT_KIND_BREAKPOINT)
4357 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4359 mono_loader_unlock ();
4361 g_ptr_array_free (bp_reqs, TRUE);
4362 g_ptr_array_free (ss_reqs, TRUE);
4365 * FIXME: The first event will suspend, so the second will only be sent after the
4369 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4371 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4372 if (enter_leave_events)
4373 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4376 /* Process a breakpoint/single step event after resuming from a signal handler */
4378 process_signal_event (void (*func) (DebuggerTlsData*))
4380 DebuggerTlsData *tls;
4381 MonoContext orig_restore_ctx, ctx;
4382 static void (*restore_context) (void *);
4384 if (!restore_context)
4385 restore_context = mono_get_restore_context ();
4387 tls = mono_native_tls_get_value (debugger_tls_id);
4388 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4389 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4390 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4394 /* This is called when resuming from a signal handler, so it shouldn't return */
4395 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4396 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4397 restore_context (&ctx);
4398 g_assert_not_reached ();
4402 process_breakpoint (void)
4404 process_signal_event (process_breakpoint_inner);
4408 resume_from_signal_handler (void *sigctx, void *func)
4410 DebuggerTlsData *tls;
4413 /* Save the original context in TLS */
4414 // FIXME: This might not work on an altstack ?
4415 tls = mono_native_tls_get_value (debugger_tls_id);
4418 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4419 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4420 // clob:c could be added to op_seq_point.
4422 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4423 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4424 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4425 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4427 MONO_CONTEXT_SET_IP (&ctx, func);
4429 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4431 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4432 mono_ppc_set_func_into_sigctx (sigctx, func);
4437 mono_debugger_agent_breakpoint_hit (void *sigctx)
4440 * We are called from a signal handler, and running code there causes all kinds of
4441 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4442 * So set up the signal context to return to the real breakpoint handler function.
4445 resume_from_signal_handler (sigctx, process_breakpoint);
4449 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4451 if (frame->managed) {
4452 *(MonoContext*)data = *ctx;
4461 * Called by System.Diagnostics.Debugger:Break ().
4464 mono_debugger_agent_user_break (void)
4466 if (agent_config.enabled) {
4471 /* Obtain a context */
4472 MONO_CONTEXT_SET_IP (&ctx, NULL);
4473 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4474 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4476 mono_loader_lock ();
4477 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4478 mono_loader_unlock ();
4480 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4487 ss_depth_to_string (StepDepth depth)
4490 case STEP_DEPTH_OVER:
4492 case STEP_DEPTH_OUT:
4494 case STEP_DEPTH_INTO:
4497 g_assert_not_reached ();
4503 process_single_step_inner (DebuggerTlsData *tls)
4508 int il_offset, suspend_policy;
4511 MonoContext *ctx = &tls->restore_ctx;
4513 MonoSeqPointInfo *info;
4515 ip = MONO_CONTEXT_GET_IP (ctx);
4517 /* Skip the instruction causing the single step */
4518 mono_arch_skip_single_step (ctx);
4520 if (suspend_count > 0) {
4521 process_suspend (tls, ctx);
4526 // FIXME: A suspend race
4529 if (mono_thread_internal_current () != ss_req->thread)
4532 if (log_level > 0) {
4533 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4535 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));
4538 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4540 g_assert (ji->method);
4542 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4547 * Stopping in memset makes half-initialized vtypes visible.
4548 * Stopping in memcpy makes half-copied vtypes visible.
4550 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4554 * The ip points to the instruction causing the single step event, which is before
4555 * the offset recorded in the seq point map, so find the next seq point after ip.
4557 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4560 il_offset = sp->il_offset;
4562 // FIXME: No tests fail if this is disabled
4564 if (ss_req->size == STEP_SIZE_LINE) {
4568 /* Step until a different source line is reached */
4569 MonoDebugMethodInfo *minfo;
4571 minfo = mono_debug_lookup_method (ji->method);
4574 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4576 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4577 mono_debug_free_source_location (loc);
4582 * Step until we reach a location with line number info,
4583 * otherwise the client can't show a location.
4584 * This can happen for example with statics initialized inline
4585 * outside of a cctor.
4590 ss_req->last_method = ji->method;
4591 ss_req->last_line = loc->row;
4592 mono_debug_free_source_location (loc);
4598 /* Start single stepping again from the current sequence point */
4599 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4601 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4602 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4603 !strcmp (ji->method->name, ".cctor"))
4606 // FIXME: Has to lock earlier
4608 reqs = g_ptr_array_new ();
4610 mono_loader_lock ();
4612 g_ptr_array_add (reqs, ss_req->req);
4614 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4616 g_ptr_array_free (reqs, TRUE);
4618 mono_loader_unlock ();
4620 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4624 process_single_step (void)
4626 process_signal_event (process_single_step_inner);
4630 * mono_debugger_agent_single_step_event:
4632 * Called from a signal handler to handle a single step event.
4635 mono_debugger_agent_single_step_event (void *sigctx)
4637 /* Resume to process_single_step through the signal context */
4639 // FIXME: Since step out/over is implemented using step in, the step in case should
4640 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4643 if (GetCurrentThreadId () == debugger_thread_id) {
4645 * This could happen despite our best effors when the runtime calls
4646 * assembly/type resolve hooks.
4647 * FIXME: Breakpoints too.
4651 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4652 mono_arch_skip_single_step (&ctx);
4653 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4657 resume_from_signal_handler (sigctx, process_single_step);
4661 debugger_agent_single_step_from_context (MonoContext *ctx)
4663 DebuggerTlsData *tls;
4664 MonoContext orig_restore_ctx;
4666 tls = mono_native_tls_get_value (debugger_tls_id);
4669 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4670 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4671 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4673 process_single_step_inner (tls);
4675 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4676 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4680 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4682 DebuggerTlsData *tls;
4683 MonoContext orig_restore_ctx;
4685 tls = mono_native_tls_get_value (debugger_tls_id);
4687 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4688 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4690 process_breakpoint_inner (tls);
4692 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4693 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4697 * start_single_stepping:
4699 * Turn on single stepping. Can be called multiple times, for example,
4700 * by a single step event request + a suspend.
4703 start_single_stepping (void)
4705 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4706 int val = InterlockedIncrement (&ss_count);
4709 mono_arch_start_single_stepping ();
4711 if (ss_req != NULL && ss_invoke_addr == NULL) {
4712 DebuggerTlsData *tls;
4714 mono_loader_lock ();
4716 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4717 ss_invoke_addr = tls->invoke_addr;
4719 mono_loader_unlock ();
4722 g_assert_not_reached ();
4727 stop_single_stepping (void)
4729 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4730 int val = InterlockedDecrement (&ss_count);
4733 mono_arch_stop_single_stepping ();
4735 g_assert_not_reached ();
4742 * Stop the single stepping operation given by SS_REQ.
4745 ss_stop (SingleStepReq *ss_req)
4750 for (l = ss_req->bps; l; l = l->next) {
4751 clear_breakpoint (l->data);
4753 g_slist_free (ss_req->bps);
4757 if (ss_req->global) {
4758 stop_single_stepping ();
4759 ss_req->global = FALSE;
4766 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4767 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4768 * belong to the same thread as CTX.
4771 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4776 gboolean enable_global = FALSE;
4778 /* Stop the previous operation */
4782 * Implement single stepping using breakpoints if possible.
4784 if (step_to_catch) {
4785 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4786 ss_req->bps = g_slist_append (ss_req->bps, bp);
4790 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT) && ctx) {
4791 /* Need parent frames */
4792 if (!tls->context.valid)
4793 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4794 compute_frame_info (tls->thread, tls);
4798 * Find the first sequence point in the current or in a previous frame which
4799 * is not the last in its method.
4801 if (ss_req->depth == STEP_DEPTH_OUT) {
4802 /* Ignore seq points in current method */
4803 while (frame_index < tls->frame_count) {
4804 StackFrame *frame = tls->frames [frame_index];
4806 method = frame->method;
4807 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4809 if (sp && sp->next_len != 0)
4813 while (sp && sp->next_len == 0) {
4815 if (frame_index < tls->frame_count) {
4816 StackFrame *frame = tls->frames [frame_index];
4818 method = frame->method;
4819 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4825 if (sp && sp->next_len > 0) {
4826 for (i = 0; i < sp->next_len; ++i) {
4827 next_sp = &info->seq_points [sp->next [i]];
4829 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4830 ss_req->bps = g_slist_append (ss_req->bps, bp);
4834 if (ss_req->depth == STEP_DEPTH_INTO) {
4835 /* Enable global stepping so we stop at method entry too */
4836 enable_global = TRUE;
4840 * The ctx/frame info computed above will become invalid when we continue.
4842 tls->context.valid = FALSE;
4843 tls->async_state.valid = FALSE;
4844 invalidate_frames (tls);
4847 if (enable_global) {
4848 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4849 ss_req->global = TRUE;
4850 start_single_stepping ();
4851 } else if (!ss_req->bps) {
4852 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4853 ss_req->global = TRUE;
4854 start_single_stepping ();
4856 ss_req->global = FALSE;
4861 * Start single stepping of thread THREAD
4864 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4866 DebuggerTlsData *tls;
4867 MonoSeqPointInfo *info = NULL;
4868 SeqPoint *sp = NULL;
4869 MonoMethod *method = NULL;
4870 MonoDebugMethodInfo *minfo;
4871 gboolean step_to_catch = FALSE;
4873 if (suspend_count == 0)
4874 return ERR_NOT_SUSPENDED;
4876 wait_for_suspend ();
4878 // FIXME: Multiple requests
4880 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4881 return ERR_NOT_IMPLEMENTED;
4884 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4886 ss_req = g_new0 (SingleStepReq, 1);
4888 ss_req->thread = thread;
4889 ss_req->size = size;
4890 ss_req->depth = depth;
4893 mono_loader_lock ();
4894 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4895 mono_loader_unlock ();
4897 g_assert (tls->context.valid);
4898 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4900 if (tls->has_catch_ctx) {
4902 StackFrameInfo frame;
4903 MonoContext new_ctx;
4904 MonoLMF *lmf = NULL;
4907 * We are stopped at a throw site. Stepping should go to the catch site.
4910 /* Find the the jit info for the catch context */
4911 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4913 g_assert (frame.type == FRAME_TYPE_MANAGED);
4916 * Find the seq point corresponding to the landing site ip, which is the first seq
4919 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4922 method = frame.method;
4924 step_to_catch = TRUE;
4925 /* This make sure the seq point is not skipped by process_single_step () */
4926 ss_req->last_sp = NULL;
4929 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4932 /* Compute the initial line info */
4933 compute_frame_info (thread, tls);
4935 if (tls->frame_count) {
4936 frame = tls->frames [0];
4938 ss_req->last_method = frame->method;
4939 ss_req->last_line = -1;
4941 minfo = mono_debug_lookup_method (frame->method);
4942 if (minfo && frame->il_offset != -1) {
4943 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4946 ss_req->last_line = loc->row;
4953 if (!step_to_catch) {
4956 compute_frame_info (thread, tls);
4958 if (tls->frame_count) {
4959 frame = tls->frames [0];
4961 if (!method && frame->il_offset != -1) {
4962 /* FIXME: Sort the table and use a binary search */
4963 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4965 method = frame->method;
4970 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
4976 ss_destroy (SingleStepReq *req)
4979 g_assert (ss_req == req);
4988 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
4991 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
4997 if (!agent_config.enabled)
5000 mono_loader_lock ();
5001 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5002 mono_loader_unlock ();
5005 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5006 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5008 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5010 g_free (ei.category);
5011 g_free (ei.message);
5015 mono_debugger_agent_debug_log_is_enabled (void)
5017 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5018 return agent_config.enabled;
5022 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5023 MonoContext *catch_ctx)
5029 DebuggerTlsData *tls = NULL;
5031 if (thread_to_tls != NULL) {
5032 MonoInternalThread *thread = mono_thread_internal_current ();
5034 mono_loader_lock ();
5035 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5036 mono_loader_unlock ();
5038 if (tls && tls->abort_requested)
5040 if (tls && tls->disable_breakpoints)
5044 memset (&ei, 0, sizeof (EventInfo));
5046 /* Just-In-Time debugging */
5048 if (agent_config.onuncaught && !inited) {
5049 finish_agent_init (FALSE);
5052 * Send an unsolicited EXCEPTION event with a dummy request id.
5054 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5055 ei.exc = (MonoObject*)exc;
5056 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5059 } else if (agent_config.onthrow && !inited) {
5061 gboolean found = FALSE;
5063 for (l = agent_config.onthrow; l; l = l->next) {
5064 char *ex_type = l->data;
5065 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5067 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5074 finish_agent_init (FALSE);
5077 * Send an unsolicited EXCEPTION event with a dummy request id.
5079 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5080 ei.exc = (MonoObject*)exc;
5081 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5089 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5091 ei.exc = (MonoObject*)exc;
5092 ei.caught = catch_ctx != NULL;
5094 mono_loader_lock ();
5095 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5096 mono_loader_unlock ();
5098 if (tls && catch_ctx) {
5099 tls->catch_ctx = *catch_ctx;
5100 tls->has_catch_ctx = TRUE;
5103 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5106 tls->has_catch_ctx = FALSE;
5110 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5112 DebuggerTlsData *tls;
5117 tls = mono_native_tls_get_value (debugger_tls_id);
5122 * We're about to invoke an exception filter during the first pass of exception handling.
5124 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5125 * 'orig_ctx' is the context where the exception has been thrown.
5128 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5130 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5131 * the call site (line 37) and then continue to Main(), but it would never
5132 * include the throw site (line 32).
5134 * Since exception filters are invoked during the first pass of exception handling,
5135 * the stack frames of the throw site are still intact, so we should include them
5138 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5140 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5141 * but report the location of the 'throw' to the user.
5145 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5149 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5151 DebuggerTlsData *tls;
5156 tls = mono_native_tls_get_value (debugger_tls_id);
5160 tls->filter_state.valid = FALSE;
5164 * buffer_add_value_full:
5166 * Add the encoding of the value at ADDR described by T to the buffer.
5167 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5171 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5177 g_assert (*(void**)addr);
5178 addr = *(void**)addr;
5183 case MONO_TYPE_BOOLEAN:
5186 case MONO_TYPE_CHAR:
5206 case MONO_TYPE_VOID:
5207 buffer_add_byte (buf, t->type);
5209 case MONO_TYPE_BOOLEAN:
5212 buffer_add_byte (buf, t->type);
5213 buffer_add_int (buf, *(gint8*)addr);
5215 case MONO_TYPE_CHAR:
5218 buffer_add_byte (buf, t->type);
5219 buffer_add_int (buf, *(gint16*)addr);
5224 buffer_add_byte (buf, t->type);
5225 buffer_add_int (buf, *(gint32*)addr);
5230 buffer_add_byte (buf, t->type);
5231 buffer_add_long (buf, *(gint64*)addr);
5235 /* Treat it as a vtype */
5237 case MONO_TYPE_PTR: {
5238 gssize val = *(gssize*)addr;
5240 buffer_add_byte (buf, t->type);
5241 buffer_add_long (buf, val);
5245 case MONO_TYPE_STRING:
5246 case MONO_TYPE_SZARRAY:
5247 case MONO_TYPE_OBJECT:
5248 case MONO_TYPE_CLASS:
5249 case MONO_TYPE_ARRAY:
5250 obj = *(MonoObject**)addr;
5253 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5255 if (obj->vtable->klass->valuetype) {
5256 t = &obj->vtable->klass->byval_arg;
5257 addr = mono_object_unbox (obj);
5259 } else if (obj->vtable->klass->rank) {
5260 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5261 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5262 buffer_add_byte (buf, MONO_TYPE_CLASS);
5264 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5266 buffer_add_objid (buf, obj);
5270 case MONO_TYPE_VALUETYPE: {
5274 MonoClass *klass = mono_class_from_mono_type (t);
5276 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5277 buffer_add_byte (buf, klass->enumtype);
5278 buffer_add_typeid (buf, domain, klass);
5282 while ((f = mono_class_get_fields (klass, &iter))) {
5283 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5285 if (mono_field_is_deleted (f))
5289 buffer_add_int (buf, nfields);
5292 while ((f = mono_class_get_fields (klass, &iter))) {
5293 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5295 if (mono_field_is_deleted (f))
5297 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5301 case MONO_TYPE_GENERICINST:
5302 if (mono_type_generic_inst_is_valuetype (t)) {
5314 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5316 buffer_add_value_full (buf, t, addr, domain, FALSE);
5320 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5323 int type = decode_byte (buf, &buf, limit);
5325 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5326 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5327 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5328 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5329 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5330 char *name = mono_type_full_name (t);
5331 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5333 return ERR_INVALID_ARGUMENT;
5337 case MONO_TYPE_BOOLEAN:
5338 *(guint8*)addr = decode_int (buf, &buf, limit);
5340 case MONO_TYPE_CHAR:
5341 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5344 *(gint8*)addr = decode_int (buf, &buf, limit);
5347 *(guint8*)addr = decode_int (buf, &buf, limit);
5350 *(gint16*)addr = decode_int (buf, &buf, limit);
5353 *(guint16*)addr = decode_int (buf, &buf, limit);
5356 *(gint32*)addr = decode_int (buf, &buf, limit);
5359 *(guint32*)addr = decode_int (buf, &buf, limit);
5362 *(gint64*)addr = decode_long (buf, &buf, limit);
5365 *(guint64*)addr = decode_long (buf, &buf, limit);
5368 *(guint32*)addr = decode_int (buf, &buf, limit);
5371 *(guint64*)addr = decode_long (buf, &buf, limit);
5374 /* We send these as I8, so we get them back as such */
5375 g_assert (type == MONO_TYPE_I8);
5376 *(gssize*)addr = decode_long (buf, &buf, limit);
5378 case MONO_TYPE_GENERICINST:
5379 if (MONO_TYPE_ISSTRUCT (t)) {
5380 /* The client sends these as a valuetype */
5388 /* We send these as vtypes, so we get them back as such */
5389 g_assert (type == MONO_TYPE_VALUETYPE);
5392 case MONO_TYPE_VALUETYPE: {
5393 gboolean is_enum = decode_byte (buf, &buf, limit);
5397 gpointer iter = NULL;
5400 /* Enums are sent as a normal vtype */
5402 return ERR_NOT_IMPLEMENTED;
5403 klass = decode_typeid (buf, &buf, limit, &d, &err);
5407 if (klass != mono_class_from_mono_type (t))
5408 return ERR_INVALID_ARGUMENT;
5410 nfields = decode_int (buf, &buf, limit);
5411 while ((f = mono_class_get_fields (klass, &iter))) {
5412 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5414 if (mono_field_is_deleted (f))
5416 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5421 g_assert (nfields == 0);
5426 if (MONO_TYPE_IS_REFERENCE (t)) {
5427 if (type == MONO_TYPE_OBJECT) {
5428 int objid = decode_objid (buf, &buf, limit);
5432 err = get_object (objid, (MonoObject**)&obj);
5436 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
5437 return ERR_INVALID_ARGUMENT;
5438 if (obj && obj->vtable->domain != domain)
5439 return ERR_INVALID_ARGUMENT;
5441 mono_gc_wbarrier_generic_store (addr, obj);
5442 } else if (type == VALUE_TYPE_ID_NULL) {
5443 *(MonoObject**)addr = NULL;
5445 return ERR_INVALID_ARGUMENT;
5459 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5466 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5467 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5470 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5471 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5473 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5475 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5476 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5477 addr += (gint32)var->offset;
5479 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5481 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5483 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5487 g_assert_not_reached ();
5492 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5498 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5499 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5501 if (MONO_TYPE_IS_REFERENCE (t))
5502 size = sizeof (gpointer);
5504 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5507 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5508 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5510 gboolean is_signed = FALSE;
5512 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5517 v = is_signed ? *(gint8*)val : *(guint8*)val;
5520 v = is_signed ? *(gint16*)val : *(guint16*)val;
5523 v = is_signed ? *(gint32*)val : *(guint32*)val;
5526 v = is_signed ? *(gint64*)val : *(guint64*)val;
5529 g_assert_not_reached ();
5535 /* Set value on the stack or in the return ctx */
5536 if (reg_locations [reg]) {
5537 /* Saved on the stack */
5538 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5539 *(reg_locations [reg]) = v;
5542 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5543 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5546 // FIXME: Move these to mono-context.h/c.
5547 mono_arch_context_set_int_reg (ctx, reg, v);
5549 // FIXME: Can't set registers, so we disable linears
5554 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5555 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5556 addr += (gint32)var->offset;
5558 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5561 addr = *(guint8**)addr;
5567 // FIXME: Write barriers
5568 memcpy (addr, val, size);
5570 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5574 g_assert_not_reached ();
5579 clear_event_request (int req_id, int etype)
5583 mono_loader_lock ();
5584 for (i = 0; i < event_requests->len; ++i) {
5585 EventRequest *req = g_ptr_array_index (event_requests, i);
5587 if (req->id == req_id && req->event_kind == etype) {
5588 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5589 clear_breakpoint (req->info);
5590 if (req->event_kind == EVENT_KIND_STEP)
5591 ss_destroy (req->info);
5592 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5593 clear_breakpoint (req->info);
5594 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5595 clear_breakpoint (req->info);
5596 g_ptr_array_remove_index_fast (event_requests, i);
5601 mono_loader_unlock ();
5605 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5607 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5608 return breakpoint_matches_assembly (req->info, assembly);
5612 for (i = 0; i < req->nmodifiers; ++i) {
5613 Modifier *m = &req->modifiers [i];
5615 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5617 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5618 for (j = 0; m->data.assemblies [j]; ++j)
5619 if (m->data.assemblies [j] == assembly)
5629 * clear_event_requests_for_assembly:
5631 * Clear all events requests which reference ASSEMBLY.
5634 clear_event_requests_for_assembly (MonoAssembly *assembly)
5639 mono_loader_lock ();
5643 for (i = 0; i < event_requests->len; ++i) {
5644 EventRequest *req = g_ptr_array_index (event_requests, i);
5646 if (event_req_matches_assembly (req, assembly)) {
5647 clear_event_request (req->id, req->event_kind);
5653 mono_loader_unlock ();
5657 * type_comes_from_assembly:
5659 * GHRFunc that returns TRUE if klass comes from assembly
5662 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5664 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5668 * clear_types_for_assembly:
5670 * Clears types from loaded_classes for a given assembly
5673 clear_types_for_assembly (MonoAssembly *assembly)
5675 MonoDomain *domain = mono_domain_get ();
5676 AgentDomainInfo *info = NULL;
5678 mono_loader_lock ();
5679 info = get_agent_domain_info (domain);
5680 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5681 mono_loader_unlock ();
5685 add_thread (gpointer key, gpointer value, gpointer user_data)
5687 MonoInternalThread *thread = value;
5688 Buffer *buf = user_data;
5690 buffer_add_objid (buf, (MonoObject*)thread);
5694 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5696 guint8 *p = invoke->p;
5697 guint8 *end = invoke->endp;
5700 MonoMethodSignature *sig;
5703 MonoObject *this, *res, *exc;
5706 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5709 MonoStopwatch watch;
5711 if (invoke->method) {
5713 * Invoke this method directly, currently only Environment.Exit () is supported.
5716 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>"));
5717 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5718 g_assert_not_reached ();
5721 m = decode_methodid (p, &p, end, &domain, &err);
5724 sig = mono_method_signature (m);
5726 if (m->klass->valuetype)
5727 this_buf = g_alloca (mono_class_instance_size (m->klass));
5729 this_buf = g_alloca (sizeof (MonoObject*));
5730 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5731 /* Should be null */
5732 int type = decode_byte (p, &p, end);
5733 if (type != VALUE_TYPE_ID_NULL)
5734 return ERR_INVALID_ARGUMENT;
5735 memset (this_buf, 0, mono_class_instance_size (m->klass));
5737 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5742 if (!m->klass->valuetype)
5743 this = *(MonoObject**)this_buf;
5747 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>"));
5749 if (this && this->vtable->domain != domain)
5752 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5753 if (!strcmp (m->name, ".ctor")) {
5754 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5755 return ERR_INVALID_ARGUMENT;
5757 this = mono_object_new (domain, m->klass);
5759 return ERR_INVALID_ARGUMENT;
5763 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5764 return ERR_INVALID_ARGUMENT;
5766 nargs = decode_int (p, &p, end);
5767 if (nargs != sig->param_count)
5768 return ERR_INVALID_ARGUMENT;
5769 /* Use alloca to get gc tracking */
5770 arg_buf = g_alloca (nargs * sizeof (gpointer));
5771 memset (arg_buf, 0, nargs * sizeof (gpointer));
5772 args = g_alloca (nargs * sizeof (gpointer));
5773 for (i = 0; i < nargs; ++i) {
5774 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5775 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5779 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5782 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5783 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5786 args [i] = arg_buf [i];
5793 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5794 tls->disable_breakpoints = TRUE;
5796 tls->disable_breakpoints = FALSE;
5799 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5801 /* FIXME: Move this to arch specific code */
5802 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5803 if (invoke->has_ctx) {
5806 lmf_addr = mono_get_lmf_addr ();
5809 memset (&ext, 0, sizeof (ext));
5811 ext.lmf.previous_lmf = *(lmf_addr);
5812 /* Mark that this is a MonoLMFExt */
5813 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5814 ext.lmf.rsp = (gssize)&ext;
5815 #elif defined(TARGET_X86)
5816 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5817 /* Mark that this is a MonoLMFExt */
5818 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5819 ext.lmf.ebp = (gssize)&ext;
5820 #elif defined(TARGET_ARM)
5821 ext.lmf.previous_lmf = *(lmf_addr);
5822 /* Mark that this is a MonoLMFExt */
5823 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5824 ext.lmf.sp = (gssize)&ext;
5825 #elif defined(TARGET_POWERPC)
5826 ext.lmf.previous_lmf = *(lmf_addr);
5827 /* Mark that this is a MonoLMFExt */
5828 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5829 ext.lmf.ebp = (gssize)&ext;
5830 #elif defined(TARGET_S390X)
5831 ext.lmf.previous_lmf = *(lmf_addr);
5832 /* Mark that this is a MonoLMFExt */
5833 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5834 ext.lmf.ebp = (gssize)&ext;
5835 #elif defined(TARGET_MIPS)
5836 ext.lmf.previous_lmf = *(lmf_addr);
5837 /* Mark that this is a MonoLMFExt */
5838 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5839 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5841 g_assert_not_reached ();
5844 ext.debugger_invoke = TRUE;
5845 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5847 mono_set_lmf ((MonoLMF*)&ext);
5851 mono_stopwatch_start (&watch);
5852 if (m->klass->valuetype)
5853 res = mono_runtime_invoke (m, this_buf, args, &exc);
5855 res = mono_runtime_invoke (m, this, args, &exc);
5856 mono_stopwatch_stop (&watch);
5857 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)));
5859 buffer_add_byte (buf, 0);
5860 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5862 buffer_add_byte (buf, 1);
5863 if (sig->ret->type == MONO_TYPE_VOID) {
5864 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5865 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5868 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5869 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5870 buffer_add_value (buf, sig->ret, &res, domain);
5871 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
5872 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5874 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &res, domain);
5876 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5879 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5886 tls->disable_breakpoints = FALSE;
5888 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5889 if (invoke->has_ctx)
5890 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5893 // FIXME: byref arguments
5901 * Invoke the method given by tls->pending_invoke in the current thread.
5904 invoke_method (void)
5906 DebuggerTlsData *tls;
5911 static void (*restore_context) (void *);
5912 MonoContext restore_ctx;
5914 if (!restore_context)
5915 restore_context = mono_get_restore_context ();
5917 tls = mono_native_tls_get_value (debugger_tls_id);
5921 * Store the `InvokeData *' in `tls->invoke' until we're done with
5922 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5925 mono_loader_lock ();
5927 invoke = tls->pending_invoke;
5929 tls->pending_invoke = NULL;
5931 invoke->last_invoke = tls->invoke;
5932 tls->invoke = invoke;
5934 mono_loader_unlock ();
5936 tls->frames_up_to_date = FALSE;
5940 buffer_init (&buf, 128);
5942 err = do_invoke_method (tls, &buf, invoke);
5944 /* Start suspending before sending the reply */
5945 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
5946 for (i = 0; i < invoke->suspend_count; ++i)
5950 send_reply_packet (id, err, &buf);
5954 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5956 if (invoke->has_ctx)
5957 save_thread_context (&restore_ctx);
5959 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5960 g_assert (tls->resume_count);
5961 tls->resume_count -= invoke->suspend_count;
5964 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5967 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5969 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5970 * after the mono_runtime_invoke() already returned, but it doesn't matter
5971 * because we reset the abort here.
5974 mono_loader_lock ();
5976 if (tls->abort_requested)
5977 mono_thread_internal_reset_abort (tls->thread);
5979 tls->invoke = tls->invoke->last_invoke;
5980 tls->abort_requested = FALSE;
5982 mono_loader_unlock ();
5991 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5993 MonoThread *thread = value;
5994 DebuggerTlsData *tls;
5997 mono_loader_lock ();
5998 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6000 res = tls->really_suspended;
6001 mono_loader_unlock ();
6007 get_source_files_for_type (MonoClass *klass)
6009 gpointer iter = NULL;
6011 MonoDebugSourceInfo *sinfo;
6015 files = g_ptr_array_new ();
6017 while ((method = mono_class_get_methods (klass, &iter))) {
6018 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6019 GPtrArray *source_file_list;
6022 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL);
6023 for (j = 0; j < source_file_list->len; ++j) {
6024 sinfo = g_ptr_array_index (source_file_list, j);
6025 for (i = 0; i < files->len; ++i)
6026 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6028 if (i == files->len)
6029 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6031 g_ptr_array_free (source_file_list, TRUE);
6039 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6042 case CMD_VM_VERSION: {
6043 char *build_info, *version;
6045 build_info = mono_get_runtime_build_info ();
6046 version = g_strdup_printf ("mono %s", build_info);
6048 buffer_add_string (buf, version); /* vm version */
6049 buffer_add_int (buf, MAJOR_VERSION);
6050 buffer_add_int (buf, MINOR_VERSION);
6051 g_free (build_info);
6055 case CMD_VM_SET_PROTOCOL_VERSION: {
6056 major_version = decode_int (p, &p, end);
6057 minor_version = decode_int (p, &p, end);
6058 protocol_version_set = TRUE;
6059 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6062 case CMD_VM_ALL_THREADS: {
6064 mono_loader_lock ();
6065 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6066 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6067 mono_loader_unlock ();
6070 case CMD_VM_SUSPEND:
6072 wait_for_suspend ();
6075 if (suspend_count == 0)
6076 return ERR_NOT_SUSPENDED;
6079 case CMD_VM_DISPOSE:
6080 /* Clear all event requests */
6081 mono_loader_lock ();
6082 while (event_requests->len > 0) {
6083 EventRequest *req = g_ptr_array_index (event_requests, 0);
6085 clear_event_request (req->id, req->event_kind);
6087 mono_loader_unlock ();
6089 while (suspend_count > 0)
6091 disconnected = TRUE;
6092 vm_start_event_sent = FALSE;
6095 MonoInternalThread *thread;
6096 DebuggerTlsData *tls;
6097 MonoClass *env_class;
6098 MonoMethod *exit_method = NULL;
6102 exit_code = decode_int (p, &p, end);
6104 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6106 /* Have to send a reply before exiting */
6107 send_reply_packet (id, 0, buf);
6109 /* Clear all event requests */
6110 mono_loader_lock ();
6111 while (event_requests->len > 0) {
6112 EventRequest *req = g_ptr_array_index (event_requests, 0);
6114 clear_event_request (req->id, req->event_kind);
6116 mono_loader_unlock ();
6119 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6120 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6121 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6122 * better than doing the shutdown ourselves, since it avoids various races.
6126 wait_for_suspend ();
6128 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6130 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6132 mono_loader_lock ();
6133 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6134 mono_loader_unlock ();
6136 if (thread && exit_method) {
6137 mono_loader_lock ();
6138 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6139 mono_loader_unlock ();
6141 args = g_new0 (gpointer, 1);
6142 args [0] = g_malloc (sizeof (int));
6143 *(int*)(args [0]) = exit_code;
6145 tls->pending_invoke = g_new0 (InvokeData, 1);
6146 tls->pending_invoke->method = exit_method;
6147 tls->pending_invoke->args = args;
6149 while (suspend_count > 0)
6153 * No thread found, do it ourselves.
6154 * FIXME: This can race with normal shutdown etc.
6156 while (suspend_count > 0)
6159 mono_runtime_set_shutting_down ();
6161 mono_threads_set_shutting_down ();
6163 /* Suspend all managed threads since the runtime is going away */
6164 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6165 mono_thread_suspend_all_other_threads ();
6166 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6167 mono_runtime_quit ();
6168 transport_close2 ();
6169 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6175 case CMD_VM_INVOKE_METHOD: {
6176 int objid = decode_objid (p, &p, end);
6178 DebuggerTlsData *tls;
6179 int i, count, err, flags;
6181 err = get_object (objid, (MonoObject**)&thread);
6185 flags = decode_int (p, &p, end);
6187 // Wait for suspending if it already started
6189 wait_for_suspend ();
6190 if (!is_suspended ())
6191 return ERR_NOT_SUSPENDED;
6193 mono_loader_lock ();
6194 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6195 mono_loader_unlock ();
6198 if (!tls->really_suspended)
6199 /* The thread is still running native code, can't do invokes */
6200 return ERR_NOT_SUSPENDED;
6203 * Store the invoke data into tls, the thread will execute it after it is
6206 if (tls->pending_invoke)
6207 return ERR_NOT_SUSPENDED;
6208 tls->pending_invoke = g_new0 (InvokeData, 1);
6209 tls->pending_invoke->id = id;
6210 tls->pending_invoke->flags = flags;
6211 tls->pending_invoke->p = g_malloc (end - p);
6212 memcpy (tls->pending_invoke->p, p, end - p);
6213 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6214 tls->pending_invoke->suspend_count = suspend_count;
6216 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6217 resume_thread (THREAD_TO_INTERNAL (thread));
6220 count = suspend_count;
6221 for (i = 0; i < count; ++i)
6226 case CMD_VM_ABORT_INVOKE: {
6227 int objid = decode_objid (p, &p, end);
6229 DebuggerTlsData *tls;
6232 err = get_object (objid, (MonoObject**)&thread);
6236 invoke_id = decode_int (p, &p, end);
6238 mono_loader_lock ();
6239 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6242 if (tls->abort_requested) {
6243 mono_loader_unlock ();
6248 * Check whether we're still inside the mono_runtime_invoke() and that it's
6249 * actually the correct invocation.
6251 * Careful, we do not stop the thread that's doing the invocation, so we can't
6252 * inspect its stack. However, invoke_method() also acquires the loader lock
6253 * when it's done, so we're safe here.
6257 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6258 mono_loader_unlock ();
6259 return ERR_NO_INVOCATION;
6262 tls->abort_requested = TRUE;
6264 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6265 mono_loader_unlock ();
6269 case CMD_VM_SET_KEEPALIVE: {
6270 int timeout = decode_int (p, &p, end);
6271 agent_config.keepalive = timeout;
6273 #ifndef DISABLE_SOCKET_TRANSPORT
6280 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6281 GHashTableIter iter, kiter;
6286 char *fname, *basename;
6287 gboolean ignore_case;
6288 GSList *class_list, *l;
6289 GPtrArray *res_classes, *res_domains;
6291 fname = decode_string (p, &p, end);
6292 ignore_case = decode_byte (p, &p, end);
6294 basename = g_path_get_basename (fname);
6296 res_classes = g_ptr_array_new ();
6297 res_domains = g_ptr_array_new ();
6299 mono_loader_lock ();
6300 g_hash_table_iter_init (&iter, domains);
6301 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6302 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6304 /* Update 'source_file_to_class' cache */
6305 g_hash_table_iter_init (&kiter, info->loaded_classes);
6306 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6307 if (!g_hash_table_lookup (info->source_files, klass)) {
6308 files = get_source_files_for_type (klass);
6309 g_hash_table_insert (info->source_files, klass, files);
6311 for (i = 0; i < files->len; ++i) {
6312 char *s = g_ptr_array_index (files, i);
6313 char *s2 = g_path_get_basename (s);
6316 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6318 class_list = g_slist_prepend (class_list, klass);
6319 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6321 class_list = g_slist_prepend (class_list, klass);
6322 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6325 /* The _ignorecase hash contains the lowercase path */
6326 s3 = strdup_tolower (s2);
6327 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6329 class_list = g_slist_prepend (class_list, klass);
6330 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6332 class_list = g_slist_prepend (class_list, klass);
6333 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6345 s = strdup_tolower (basename);
6346 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6349 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6352 for (l = class_list; l; l = l->next) {
6355 g_ptr_array_add (res_classes, klass);
6356 g_ptr_array_add (res_domains, domain);
6359 mono_loader_unlock ();
6364 buffer_add_int (buf, res_classes->len);
6365 for (i = 0; i < res_classes->len; ++i)
6366 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6367 g_ptr_array_free (res_classes, TRUE);
6368 g_ptr_array_free (res_domains, TRUE);
6371 case CMD_VM_GET_TYPES: {
6372 GHashTableIter iter;
6376 gboolean ignore_case;
6377 GPtrArray *res_classes, *res_domains;
6378 MonoTypeNameParse info;
6380 name = decode_string (p, &p, end);
6381 ignore_case = decode_byte (p, &p, end);
6383 if (!mono_reflection_parse_type (name, &info)) {
6385 mono_reflection_free_type_info (&info);
6386 return ERR_INVALID_ARGUMENT;
6389 res_classes = g_ptr_array_new ();
6390 res_domains = g_ptr_array_new ();
6392 mono_loader_lock ();
6393 g_hash_table_iter_init (&iter, domains);
6394 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6396 gboolean type_resolve;
6400 mono_domain_assemblies_lock (domain);
6401 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6405 type_resolve = TRUE;
6406 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6408 g_ptr_array_add (res_classes, mono_type_get_class (t));
6409 g_ptr_array_add (res_domains, domain);
6413 mono_domain_assemblies_unlock (domain);
6415 mono_loader_unlock ();
6418 mono_reflection_free_type_info (&info);
6420 buffer_add_int (buf, res_classes->len);
6421 for (i = 0; i < res_classes->len; ++i)
6422 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6423 g_ptr_array_free (res_classes, TRUE);
6424 g_ptr_array_free (res_domains, TRUE);
6429 return ERR_NOT_IMPLEMENTED;
6436 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6442 case CMD_EVENT_REQUEST_SET: {
6444 int i, event_kind, suspend_policy, nmodifiers, mod;
6447 MonoThread *step_thread;
6448 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6452 event_kind = decode_byte (p, &p, end);
6453 suspend_policy = decode_byte (p, &p, end);
6454 nmodifiers = decode_byte (p, &p, end);
6456 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6457 req->id = InterlockedIncrement (&event_request_id);
6458 req->event_kind = event_kind;
6459 req->suspend_policy = suspend_policy;
6460 req->nmodifiers = nmodifiers;
6463 for (i = 0; i < nmodifiers; ++i) {
6464 mod = decode_byte (p, &p, end);
6466 req->modifiers [i].kind = mod;
6467 if (mod == MOD_KIND_COUNT) {
6468 req->modifiers [i].data.count = decode_int (p, &p, end);
6469 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6470 method = decode_methodid (p, &p, end, &domain, &err);
6473 location = decode_long (p, &p, end);
6474 } else if (mod == MOD_KIND_STEP) {
6475 step_thread_id = decode_id (p, &p, end);
6476 size = decode_int (p, &p, end);
6477 depth = decode_int (p, &p, end);
6478 if (CHECK_PROTOCOL_VERSION (2, 16))
6479 filter = decode_int (p, &p, end);
6480 req->modifiers [i].data.filter = filter;
6481 } else if (mod == MOD_KIND_THREAD_ONLY) {
6482 int id = decode_id (p, &p, end);
6484 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6489 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6490 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6494 req->modifiers [i].caught = decode_byte (p, &p, end);
6495 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6496 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" : ""));
6498 req->modifiers [i].data.exc_class = exc_class;
6500 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6502 return ERR_INVALID_ARGUMENT;
6505 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6506 int n = decode_int (p, &p, end);
6509 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6510 for (j = 0; j < n; ++j) {
6511 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6513 g_free (req->modifiers [i].data.assemblies);
6517 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6518 int n = decode_int (p, &p, end);
6521 modifier = &req->modifiers [i];
6522 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6523 for (j = 0; j < n; ++j) {
6524 char *s = decode_string (p, &p, end);
6528 s2 = strdup_tolower (s);
6529 g_hash_table_insert (modifier->data.source_files, s2, s2);
6533 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6534 int n = decode_int (p, &p, end);
6537 modifier = &req->modifiers [i];
6538 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6539 for (j = 0; j < n; ++j) {
6540 char *s = decode_string (p, &p, end);
6543 g_hash_table_insert (modifier->data.type_names, s, s);
6547 return ERR_NOT_IMPLEMENTED;
6551 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6554 req->info = set_breakpoint (method, location, req, &error);
6555 if (!mono_error_ok (&error)) {
6557 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6558 mono_error_cleanup (&error);
6559 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6561 } else if (req->event_kind == EVENT_KIND_STEP) {
6562 g_assert (step_thread_id);
6564 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6570 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6575 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6576 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6577 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6578 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6579 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6580 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6582 if (req->nmodifiers) {
6584 return ERR_NOT_IMPLEMENTED;
6588 mono_loader_lock ();
6589 g_ptr_array_add (event_requests, req);
6591 if (agent_config.defer) {
6592 /* Transmit cached data to the client on receipt of the event request */
6593 switch (req->event_kind) {
6594 case EVENT_KIND_APPDOMAIN_CREATE:
6595 /* Emit load events for currently loaded domains */
6596 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6598 case EVENT_KIND_ASSEMBLY_LOAD:
6599 /* Emit load events for currently loaded assemblies */
6600 mono_assembly_foreach (emit_assembly_load, NULL);
6602 case EVENT_KIND_THREAD_START:
6603 /* Emit start events for currently started threads */
6604 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6606 case EVENT_KIND_TYPE_LOAD:
6607 /* Emit type load events for currently loaded types */
6608 mono_domain_foreach (send_types_for_domain, NULL);
6614 mono_loader_unlock ();
6616 buffer_add_int (buf, req->id);
6619 case CMD_EVENT_REQUEST_CLEAR: {
6620 int etype = decode_byte (p, &p, end);
6621 int req_id = decode_int (p, &p, end);
6623 // FIXME: Make a faster mapping from req_id to request
6624 mono_loader_lock ();
6625 clear_event_request (req_id, etype);
6626 mono_loader_unlock ();
6629 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6632 mono_loader_lock ();
6634 while (i < event_requests->len) {
6635 EventRequest *req = g_ptr_array_index (event_requests, i);
6637 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6638 clear_breakpoint (req->info);
6640 g_ptr_array_remove_index_fast (event_requests, i);
6646 mono_loader_unlock ();
6650 return ERR_NOT_IMPLEMENTED;
6657 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6663 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6664 buffer_add_domainid (buf, mono_get_root_domain ());
6667 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6668 domain = decode_domainid (p, &p, end, NULL, &err);
6671 buffer_add_string (buf, domain->friendly_name);
6674 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6679 domain = decode_domainid (p, &p, end, NULL, &err);
6682 mono_loader_lock ();
6684 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6687 buffer_add_int (buf, count);
6688 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6690 buffer_add_assemblyid (buf, domain, ass);
6692 mono_loader_unlock ();
6695 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6696 domain = decode_domainid (p, &p, end, NULL, &err);
6700 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6703 case CMD_APPDOMAIN_GET_CORLIB: {
6704 domain = decode_domainid (p, &p, end, NULL, &err);
6708 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6711 case CMD_APPDOMAIN_CREATE_STRING: {
6715 domain = decode_domainid (p, &p, end, NULL, &err);
6718 s = decode_string (p, &p, end);
6720 o = mono_string_new (domain, s);
6721 buffer_add_objid (buf, (MonoObject*)o);
6724 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6726 MonoDomain *domain2;
6729 domain = decode_domainid (p, &p, end, NULL, &err);
6732 klass = decode_typeid (p, &p, end, &domain2, &err);
6737 g_assert (domain == domain2);
6739 o = mono_object_new (domain, klass);
6741 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6745 buffer_add_objid (buf, o);
6749 return ERR_NOT_IMPLEMENTED;
6756 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6762 ass = decode_assemblyid (p, &p, end, &domain, &err);
6767 case CMD_ASSEMBLY_GET_LOCATION: {
6768 buffer_add_string (buf, mono_image_get_filename (ass->image));
6771 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6775 if (ass->image->dynamic) {
6776 buffer_add_id (buf, 0);
6778 token = mono_image_get_entry_point (ass->image);
6780 buffer_add_id (buf, 0);
6782 m = mono_get_method (ass->image, token, NULL);
6783 buffer_add_methodid (buf, domain, m);
6788 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6789 buffer_add_moduleid (buf, domain, ass->image);
6792 case CMD_ASSEMBLY_GET_OBJECT: {
6793 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
6794 buffer_add_objid (buf, o);
6797 case CMD_ASSEMBLY_GET_TYPE: {
6798 char *s = decode_string (p, &p, end);
6799 gboolean ignorecase = decode_byte (p, &p, end);
6800 MonoTypeNameParse info;
6802 gboolean type_resolve, res;
6803 MonoDomain *d = mono_domain_get ();
6805 /* This is needed to be able to find referenced assemblies */
6806 res = mono_domain_set (domain, FALSE);
6809 if (!mono_reflection_parse_type (s, &info)) {
6812 if (info.assembly.name)
6814 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6816 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6817 mono_reflection_free_type_info (&info);
6820 mono_domain_set (d, TRUE);
6824 case CMD_ASSEMBLY_GET_NAME: {
6826 MonoAssembly *mass = ass;
6828 name = g_strdup_printf (
6829 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6831 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6832 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6833 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6834 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6836 buffer_add_string (buf, name);
6841 return ERR_NOT_IMPLEMENTED;
6848 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6854 case CMD_MODULE_GET_INFO: {
6855 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
6858 basename = g_path_get_basename (image->name);
6859 buffer_add_string (buf, basename); // name
6860 buffer_add_string (buf, image->module_name); // scopename
6861 buffer_add_string (buf, image->name); // fqname
6862 buffer_add_string (buf, mono_image_get_guid (image)); // guid
6863 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
6868 return ERR_NOT_IMPLEMENTED;
6875 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6877 if (val && val->vtable->klass == mono_defaults.monotype_class) {
6878 /* Special case these so the client doesn't have to handle Type objects */
6880 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6881 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
6882 } else if (MONO_TYPE_IS_REFERENCE (t))
6883 buffer_add_value (buf, t, &val, domain);
6885 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6889 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6895 buffer_add_int (buf, 0);
6899 for (i = 0; i < cinfo->num_attrs; ++i) {
6900 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6903 buffer_add_int (buf, nattrs);
6905 for (i = 0; i < cinfo->num_attrs; ++i) {
6906 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6907 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6908 MonoArray *typed_args, *named_args;
6910 CattrNamedArg *arginfo;
6912 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6914 buffer_add_methodid (buf, domain, attr->ctor);
6918 buffer_add_int (buf, mono_array_length (typed_args));
6919 for (j = 0; j < mono_array_length (typed_args); ++j) {
6920 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6922 t = mono_method_signature (attr->ctor)->params [j];
6924 buffer_add_cattr_arg (buf, t, domain, val);
6927 buffer_add_int (buf, 0);
6932 buffer_add_int (buf, mono_array_length (named_args));
6934 for (j = 0; j < mono_array_length (named_args); ++j) {
6935 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
6937 if (arginfo [j].prop) {
6938 buffer_add_byte (buf, 0x54);
6939 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6940 } else if (arginfo [j].field) {
6941 buffer_add_byte (buf, 0x53);
6942 buffer_add_fieldid (buf, domain, arginfo [j].field);
6944 g_assert_not_reached ();
6947 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6950 buffer_add_int (buf, 0);
6956 /* FIXME: Code duplication with icall.c */
6958 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
6963 mono_class_setup_interfaces (klass, error);
6964 if (!mono_error_ok (error))
6967 for (i = 0; i < klass->interface_count; i++) {
6968 ic = klass->interfaces [i];
6969 g_hash_table_insert (ifaces, ic, ic);
6971 collect_interfaces (ic, ifaces, error);
6972 if (!mono_error_ok (error))
6978 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6988 case CMD_TYPE_GET_INFO: {
6989 buffer_add_string (buf, klass->name_space);
6990 buffer_add_string (buf, klass->name);
6992 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
6993 buffer_add_string (buf, name);
6995 buffer_add_assemblyid (buf, domain, klass->image->assembly);
6996 buffer_add_moduleid (buf, domain, klass->image);
6997 buffer_add_typeid (buf, domain, klass->parent);
6998 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
6999 buffer_add_typeid (buf, domain, klass->element_class);
7001 buffer_add_id (buf, 0);
7002 buffer_add_int (buf, klass->type_token);
7003 buffer_add_byte (buf, klass->rank);
7004 buffer_add_int (buf, klass->flags);
7006 type = &klass->byval_arg;
7007 // FIXME: Can't decide whenever a class represents a byref type
7010 if (type->type == MONO_TYPE_PTR)
7012 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7014 if (type->type == MONO_TYPE_VALUETYPE)
7016 if (klass->enumtype)
7018 if (klass->generic_container)
7020 if (klass->generic_container || klass->generic_class)
7022 buffer_add_byte (buf, b);
7025 while ((nested = mono_class_get_nested_types (klass, &iter)))
7027 buffer_add_int (buf, nnested);
7029 while ((nested = mono_class_get_nested_types (klass, &iter)))
7030 buffer_add_typeid (buf, domain, nested);
7031 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7032 if (klass->generic_container)
7033 buffer_add_typeid (buf, domain, klass);
7034 else if (klass->generic_class)
7035 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7037 buffer_add_id (buf, 0);
7039 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7042 if (klass->generic_class) {
7043 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7045 count = inst->type_argc;
7046 buffer_add_int (buf, count);
7047 for (i = 0; i < count; i++)
7048 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7049 } else if (klass->generic_container) {
7050 MonoGenericContainer *container = klass->generic_container;
7053 count = container->type_argc;
7054 buffer_add_int (buf, count);
7055 for (i = 0; i < count; i++) {
7056 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7057 buffer_add_typeid (buf, domain, pklass);
7060 buffer_add_int (buf, 0);
7065 case CMD_TYPE_GET_METHODS: {
7068 gpointer iter = NULL;
7071 mono_class_setup_methods (klass);
7073 nmethods = mono_class_num_methods (klass);
7075 buffer_add_int (buf, nmethods);
7077 while ((m = mono_class_get_methods (klass, &iter))) {
7078 buffer_add_methodid (buf, domain, m);
7081 g_assert (i == nmethods);
7084 case CMD_TYPE_GET_FIELDS: {
7087 gpointer iter = NULL;
7090 nfields = mono_class_num_fields (klass);
7092 buffer_add_int (buf, nfields);
7094 while ((f = mono_class_get_fields (klass, &iter))) {
7095 buffer_add_fieldid (buf, domain, f);
7096 buffer_add_string (buf, f->name);
7097 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7098 buffer_add_int (buf, f->type->attrs);
7101 g_assert (i == nfields);
7104 case CMD_TYPE_GET_PROPERTIES: {
7107 gpointer iter = NULL;
7110 nprops = mono_class_num_properties (klass);
7112 buffer_add_int (buf, nprops);
7114 while ((p = mono_class_get_properties (klass, &iter))) {
7115 buffer_add_propertyid (buf, domain, p);
7116 buffer_add_string (buf, p->name);
7117 buffer_add_methodid (buf, domain, p->get);
7118 buffer_add_methodid (buf, domain, p->set);
7119 buffer_add_int (buf, p->attrs);
7122 g_assert (i == nprops);
7125 case CMD_TYPE_GET_CATTRS: {
7126 MonoClass *attr_klass;
7127 MonoCustomAttrInfo *cinfo;
7129 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7130 /* attr_klass can be NULL */
7134 cinfo = mono_custom_attrs_from_class (klass);
7136 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7139 case CMD_TYPE_GET_FIELD_CATTRS: {
7140 MonoClass *attr_klass;
7141 MonoCustomAttrInfo *cinfo;
7142 MonoClassField *field;
7144 field = decode_fieldid (p, &p, end, NULL, &err);
7147 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7151 cinfo = mono_custom_attrs_from_field (klass, field);
7153 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7156 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7157 MonoClass *attr_klass;
7158 MonoCustomAttrInfo *cinfo;
7161 prop = decode_propertyid (p, &p, end, NULL, &err);
7164 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7168 cinfo = mono_custom_attrs_from_property (klass, prop);
7170 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7173 case CMD_TYPE_GET_VALUES:
7174 case CMD_TYPE_GET_VALUES_2: {
7181 MonoThread *thread_obj;
7182 MonoInternalThread *thread = NULL;
7183 guint32 special_static_type;
7185 if (command == CMD_TYPE_GET_VALUES_2) {
7186 int objid = decode_objid (p, &p, end);
7189 err = get_object (objid, (MonoObject**)&thread_obj);
7193 thread = THREAD_TO_INTERNAL (thread_obj);
7196 len = decode_int (p, &p, end);
7197 for (i = 0; i < len; ++i) {
7198 f = decode_fieldid (p, &p, end, NULL, &err);
7202 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7203 return ERR_INVALID_FIELDID;
7204 special_static_type = mono_class_field_get_special_static_type (f);
7205 if (special_static_type != SPECIAL_STATIC_NONE) {
7206 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7207 return ERR_INVALID_FIELDID;
7210 /* Check that the field belongs to the object */
7212 for (k = klass; k; k = k->parent) {
7213 if (k == f->parent) {
7219 return ERR_INVALID_FIELDID;
7221 vtable = mono_class_vtable (domain, f->parent);
7222 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7223 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7224 buffer_add_value (buf, f->type, val, domain);
7229 case CMD_TYPE_SET_VALUES: {
7237 len = decode_int (p, &p, end);
7238 for (i = 0; i < len; ++i) {
7239 f = decode_fieldid (p, &p, end, NULL, &err);
7243 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7244 return ERR_INVALID_FIELDID;
7245 if (mono_class_field_is_special_static (f))
7246 return ERR_INVALID_FIELDID;
7248 /* Check that the field belongs to the object */
7250 for (k = klass; k; k = k->parent) {
7251 if (k == f->parent) {
7257 return ERR_INVALID_FIELDID;
7259 // FIXME: Check for literal/const
7261 vtable = mono_class_vtable (domain, f->parent);
7262 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7263 err = decode_value (f->type, domain, val, p, &p, end);
7268 if (MONO_TYPE_IS_REFERENCE (f->type))
7269 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7271 mono_field_static_set_value (vtable, f, val);
7276 case CMD_TYPE_GET_OBJECT: {
7277 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7278 buffer_add_objid (buf, o);
7281 case CMD_TYPE_GET_SOURCE_FILES:
7282 case CMD_TYPE_GET_SOURCE_FILES_2: {
7283 char *source_file, *base;
7287 files = get_source_files_for_type (klass);
7289 buffer_add_int (buf, files->len);
7290 for (i = 0; i < files->len; ++i) {
7291 source_file = g_ptr_array_index (files, i);
7292 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7293 buffer_add_string (buf, source_file);
7295 base = g_path_get_basename (source_file);
7296 buffer_add_string (buf, base);
7299 g_free (source_file);
7301 g_ptr_array_free (files, TRUE);
7304 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7305 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7309 if (mono_class_is_assignable_from (klass, oklass))
7310 buffer_add_byte (buf, 1);
7312 buffer_add_byte (buf, 0);
7315 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7316 char *name = decode_string (p, &p, end);
7317 int i, flags = decode_int (p, &p, end);
7318 MonoException *ex = NULL;
7319 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7322 return ERR_LOADER_ERROR;
7323 buffer_add_int (buf, array->len);
7324 for (i = 0; i < array->len; ++i) {
7325 MonoMethod *method = g_ptr_array_index (array, i);
7326 buffer_add_methodid (buf, domain, method);
7329 g_ptr_array_free (array, TRUE);
7333 case CMD_TYPE_GET_INTERFACES: {
7335 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7337 MonoClass *tclass, *iface;
7338 GHashTableIter iter;
7342 for (parent = tclass; parent; parent = parent->parent) {
7343 mono_class_setup_interfaces (parent, &error);
7344 if (!mono_error_ok (&error))
7345 return ERR_LOADER_ERROR;
7346 collect_interfaces (parent, iface_hash, &error);
7347 if (!mono_error_ok (&error))
7348 return ERR_LOADER_ERROR;
7351 buffer_add_int (buf, g_hash_table_size (iface_hash));
7353 g_hash_table_iter_init (&iter, iface_hash);
7354 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7355 buffer_add_typeid (buf, domain, iface);
7356 g_hash_table_destroy (iface_hash);
7359 case CMD_TYPE_GET_INTERFACE_MAP: {
7360 int tindex, ioffset;
7361 gboolean variance_used;
7363 int len, nmethods, i;
7367 len = decode_int (p, &p, end);
7368 mono_class_setup_vtable (klass);
7370 for (tindex = 0; tindex < len; ++tindex) {
7371 iclass = decode_typeid (p, &p, end, NULL, &err);
7375 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7377 return ERR_INVALID_ARGUMENT;
7379 nmethods = mono_class_num_methods (iclass);
7380 buffer_add_int (buf, nmethods);
7383 while ((method = mono_class_get_methods (iclass, &iter))) {
7384 buffer_add_methodid (buf, domain, method);
7386 for (i = 0; i < nmethods; ++i)
7387 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7392 return ERR_NOT_IMPLEMENTED;
7399 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7402 MonoDomain *old_domain;
7406 klass = decode_typeid (p, &p, end, &domain, &err);
7410 old_domain = mono_domain_get ();
7412 mono_domain_set (domain, TRUE);
7414 err = type_commands_internal (command, klass, domain, p, end, buf);
7416 mono_domain_set (old_domain, TRUE);
7422 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7424 MonoMethodHeader *header;
7427 case CMD_METHOD_GET_NAME: {
7428 buffer_add_string (buf, method->name);
7431 case CMD_METHOD_GET_DECLARING_TYPE: {
7432 buffer_add_typeid (buf, domain, method->klass);
7435 case CMD_METHOD_GET_DEBUG_INFO: {
7436 MonoDebugMethodInfo *minfo;
7438 int i, j, n_il_offsets;
7442 GPtrArray *source_file_list;
7444 header = mono_method_get_header (method);
7446 buffer_add_int (buf, 0);
7447 buffer_add_string (buf, "");
7448 buffer_add_int (buf, 0);
7452 minfo = mono_debug_lookup_method (method);
7454 buffer_add_int (buf, header->code_size);
7455 buffer_add_string (buf, "");
7456 buffer_add_int (buf, 0);
7457 mono_metadata_free_mh (header);
7461 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &source_files);
7462 buffer_add_int (buf, header->code_size);
7463 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7464 buffer_add_int (buf, source_file_list->len);
7465 for (i = 0; i < source_file_list->len; ++i) {
7466 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7467 buffer_add_string (buf, sinfo->source_file);
7468 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7469 for (j = 0; j < 16; ++j)
7470 buffer_add_byte (buf, sinfo->hash [j]);
7474 buffer_add_string (buf, source_file);
7476 buffer_add_int (buf, n_il_offsets);
7477 DEBUG (10, printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7478 for (i = 0; i < n_il_offsets; ++i) {
7479 const char *srcfile = "";
7481 if (source_files [i] != -1) {
7482 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7483 srcfile = sinfo->source_file;
7485 DEBUG (10, printf ("IL%x -> %s:%d\n", il_offsets [i], srcfile, line_numbers [i]));
7486 buffer_add_int (buf, il_offsets [i]);
7487 buffer_add_int (buf, line_numbers [i]);
7488 if (CHECK_PROTOCOL_VERSION (2, 13))
7489 buffer_add_int (buf, source_files [i]);
7491 g_free (source_file);
7492 g_free (il_offsets);
7493 g_free (line_numbers);
7494 g_free (source_files);
7495 g_ptr_array_free (source_file_list, TRUE);
7496 mono_metadata_free_mh (header);
7499 case CMD_METHOD_GET_PARAM_INFO: {
7500 MonoMethodSignature *sig = mono_method_signature (method);
7504 /* FIXME: mono_class_from_mono_type () and byrefs */
7506 /* FIXME: Use a smaller encoding */
7507 buffer_add_int (buf, sig->call_convention);
7508 buffer_add_int (buf, sig->param_count);
7509 buffer_add_int (buf, sig->generic_param_count);
7510 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7511 for (i = 0; i < sig->param_count; ++i) {
7513 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7516 /* Emit parameter names */
7517 names = g_new (char *, sig->param_count);
7518 mono_method_get_param_names (method, (const char **) names);
7519 for (i = 0; i < sig->param_count; ++i)
7520 buffer_add_string (buf, names [i]);
7525 case CMD_METHOD_GET_LOCALS_INFO: {
7526 int i, j, num_locals;
7527 MonoDebugLocalsInfo *locals;
7529 header = mono_method_get_header (method);
7531 return ERR_INVALID_ARGUMENT;
7533 buffer_add_int (buf, header->num_locals);
7536 for (i = 0; i < header->num_locals; ++i)
7537 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7540 locals = mono_debug_lookup_locals (method);
7542 num_locals = locals->num_locals;
7545 for (i = 0; i < header->num_locals; ++i) {
7546 for (j = 0; j < num_locals; ++j)
7547 if (locals->locals [j].index == i)
7550 buffer_add_string (buf, locals->locals [j].name);
7552 buffer_add_string (buf, "");
7556 for (i = 0; i < header->num_locals; ++i) {
7557 for (j = 0; j < num_locals; ++j)
7558 if (locals->locals [j].index == i)
7560 if (j < num_locals && locals->locals [j].block) {
7561 buffer_add_int (buf, locals->locals [j].block->start_offset);
7562 buffer_add_int (buf, locals->locals [j].block->end_offset);
7564 buffer_add_int (buf, 0);
7565 buffer_add_int (buf, header->code_size);
7568 mono_metadata_free_mh (header);
7571 mono_debug_symfile_free_locals (locals);
7575 case CMD_METHOD_GET_INFO:
7576 buffer_add_int (buf, method->flags);
7577 buffer_add_int (buf, method->iflags);
7578 buffer_add_int (buf, method->token);
7579 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7581 if (method->is_generic)
7583 if (mono_method_signature (method)->generic_param_count)
7585 buffer_add_byte (buf, attrs);
7586 if (method->is_generic || method->is_inflated) {
7589 if (method->is_generic) {
7592 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7594 result = imethod->declaring;
7595 if (imethod->context.class_inst) {
7596 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7597 /*Generic methods gets the context of the GTD.*/
7598 if (mono_class_get_context (klass))
7599 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7603 buffer_add_methodid (buf, domain, result);
7605 buffer_add_id (buf, 0);
7607 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7608 if (mono_method_signature (method)->generic_param_count) {
7611 if (method->is_inflated) {
7612 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7614 count = inst->type_argc;
7615 buffer_add_int (buf, count);
7617 for (i = 0; i < count; i++)
7618 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7620 buffer_add_int (buf, 0);
7622 } else if (method->is_generic) {
7623 MonoGenericContainer *container = mono_method_get_generic_container (method);
7625 count = mono_method_signature (method)->generic_param_count;
7626 buffer_add_int (buf, count);
7627 for (i = 0; i < count; i++) {
7628 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7629 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7630 buffer_add_typeid (buf, domain, pklass);
7633 buffer_add_int (buf, 0);
7636 buffer_add_int (buf, 0);
7641 case CMD_METHOD_GET_BODY: {
7644 header = mono_method_get_header (method);
7646 buffer_add_int (buf, 0);
7648 buffer_add_int (buf, header->code_size);
7649 for (i = 0; i < header->code_size; ++i)
7650 buffer_add_byte (buf, header->code [i]);
7652 mono_metadata_free_mh (header);
7655 case CMD_METHOD_RESOLVE_TOKEN: {
7656 guint32 token = decode_int (p, &p, end);
7659 switch (mono_metadata_token_code (token)) {
7660 case MONO_TOKEN_STRING: {
7664 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7667 s2 = mono_string_to_utf8 (s);
7669 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7670 buffer_add_string (buf, s2);
7676 MonoClass *handle_class;
7678 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7679 val = mono_method_get_wrapper_data (method, token);
7680 handle_class = mono_method_get_wrapper_data (method, token + 1);
7682 if (handle_class == NULL) {
7683 // Can't figure out the token type
7684 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7688 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7692 if (handle_class == mono_defaults.typehandle_class) {
7693 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7694 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7695 buffer_add_typeid (buf, domain, (MonoClass *) val);
7697 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7698 } else if (handle_class == mono_defaults.fieldhandle_class) {
7699 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7700 buffer_add_fieldid (buf, domain, val);
7701 } else if (handle_class == mono_defaults.methodhandle_class) {
7702 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7703 buffer_add_methodid (buf, domain, val);
7704 } else if (handle_class == mono_defaults.string_class) {
7707 s = mono_string_to_utf8 (val);
7708 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7709 buffer_add_string (buf, s);
7712 g_assert_not_reached ();
7720 return ERR_NOT_IMPLEMENTED;
7727 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7730 MonoDomain *old_domain;
7734 method = decode_methodid (p, &p, end, &domain, &err);
7738 old_domain = mono_domain_get ();
7740 mono_domain_set (domain, TRUE);
7742 err = method_commands_internal (command, method, domain, p, end, buf);
7744 mono_domain_set (old_domain, TRUE);
7750 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7752 int objid = decode_objid (p, &p, end);
7754 MonoThread *thread_obj;
7755 MonoInternalThread *thread;
7757 err = get_object (objid, (MonoObject**)&thread_obj);
7761 thread = THREAD_TO_INTERNAL (thread_obj);
7764 case CMD_THREAD_GET_NAME: {
7766 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7769 buffer_add_int (buf, 0);
7774 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7776 buffer_add_int (buf, len);
7777 buffer_add_data (buf, (guint8*)name, len);
7782 case CMD_THREAD_GET_FRAME_INFO: {
7783 DebuggerTlsData *tls;
7784 int i, start_frame, length;
7786 // Wait for suspending if it already started
7787 // FIXME: Races with suspend_count
7788 while (!is_suspended ()) {
7790 wait_for_suspend ();
7794 wait_for_suspend ();
7795 if (!is_suspended ())
7796 return ERR_NOT_SUSPENDED;
7799 start_frame = decode_int (p, &p, end);
7800 length = decode_int (p, &p, end);
7802 if (start_frame != 0 || length != -1)
7803 return ERR_NOT_IMPLEMENTED;
7805 mono_loader_lock ();
7806 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7807 mono_loader_unlock ();
7810 compute_frame_info (thread, tls);
7812 buffer_add_int (buf, tls->frame_count);
7813 for (i = 0; i < tls->frame_count; ++i) {
7814 buffer_add_int (buf, tls->frames [i]->id);
7815 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
7816 buffer_add_int (buf, tls->frames [i]->il_offset);
7818 * Instead of passing the frame type directly to the client, we associate
7819 * it with the previous frame using a set of flags. This avoids lots of
7820 * conditional code in the client, since a frame whose type isn't
7821 * FRAME_TYPE_MANAGED has no method, location, etc.
7823 buffer_add_byte (buf, tls->frames [i]->flags);
7828 case CMD_THREAD_GET_STATE:
7829 buffer_add_int (buf, thread->state);
7831 case CMD_THREAD_GET_INFO:
7832 buffer_add_byte (buf, thread->threadpool_thread);
7834 case CMD_THREAD_GET_ID:
7835 buffer_add_long (buf, (guint64)(gsize)thread);
7837 case CMD_THREAD_GET_TID:
7838 buffer_add_long (buf, (guint64)thread->tid);
7841 return ERR_NOT_IMPLEMENTED;
7848 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7852 MonoThread *thread_obj;
7853 MonoInternalThread *thread;
7854 int pos, i, len, frame_idx;
7855 DebuggerTlsData *tls;
7857 MonoDebugMethodJitInfo *jit;
7858 MonoDebugVarInfo *var;
7859 MonoMethodSignature *sig;
7861 MonoMethodHeader *header;
7863 objid = decode_objid (p, &p, end);
7864 err = get_object (objid, (MonoObject**)&thread_obj);
7868 thread = THREAD_TO_INTERNAL (thread_obj);
7870 id = decode_id (p, &p, end);
7872 mono_loader_lock ();
7873 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7874 mono_loader_unlock ();
7877 for (i = 0; i < tls->frame_count; ++i) {
7878 if (tls->frames [i]->id == id)
7881 if (i == tls->frame_count)
7882 return ERR_INVALID_FRAMEID;
7885 frame = tls->frames [frame_idx];
7887 if (!frame->has_ctx)
7889 return ERR_INVALID_FRAMEID;
7892 frame->jit = mono_debug_find_method (frame->method, frame->domain);
7893 if (!frame->jit && frame->method->is_inflated)
7894 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->method), frame->domain);
7898 /* This could happen for aot images with no jit debug info */
7899 s = mono_method_full_name (frame->method, TRUE);
7900 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
7902 return ERR_ABSENT_INFORMATION;
7907 sig = mono_method_signature (frame->actual_method);
7909 if (!get_seq_points (frame->domain, frame->actual_method))
7911 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
7913 return ERR_ABSENT_INFORMATION;
7916 case CMD_STACK_FRAME_GET_VALUES: {
7917 len = decode_int (p, &p, end);
7918 header = mono_method_get_header (frame->actual_method);
7920 for (i = 0; i < len; ++i) {
7921 pos = decode_int (p, &p, end);
7926 g_assert (pos >= 0 && pos < jit->num_params);
7928 var = &jit->params [pos];
7930 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
7932 g_assert (pos >= 0 && pos < jit->num_locals);
7934 var = &jit->locals [pos];
7936 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
7939 mono_metadata_free_mh (header);
7942 case CMD_STACK_FRAME_GET_THIS: {
7943 if (frame->method->klass->valuetype) {
7944 if (!sig->hasthis) {
7945 MonoObject *p = NULL;
7946 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
7948 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7951 if (!sig->hasthis) {
7952 MonoObject *p = NULL;
7953 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
7955 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7960 case CMD_STACK_FRAME_SET_VALUES: {
7963 MonoDebugVarInfo *var;
7965 len = decode_int (p, &p, end);
7966 header = mono_method_get_header (frame->actual_method);
7968 for (i = 0; i < len; ++i) {
7969 pos = decode_int (p, &p, end);
7974 g_assert (pos >= 0 && pos < jit->num_params);
7976 t = sig->params [pos];
7977 var = &jit->params [pos];
7979 g_assert (pos >= 0 && pos < jit->num_locals);
7981 t = header->locals [pos];
7982 var = &jit->locals [pos];
7985 if (MONO_TYPE_IS_REFERENCE (t))
7986 val_buf = g_alloca (sizeof (MonoObject*));
7988 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
7989 err = decode_value (t, frame->domain, val_buf, p, &p, end);
7993 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
7995 mono_metadata_free_mh (header);
7999 return ERR_NOT_IMPLEMENTED;
8006 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8009 int objid, err, index, len, i, esize;
8012 objid = decode_objid (p, &p, end);
8013 err = get_object (objid, (MonoObject**)&arr);
8018 case CMD_ARRAY_REF_GET_LENGTH:
8019 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8021 buffer_add_int (buf, arr->max_length);
8022 buffer_add_int (buf, 0);
8024 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8025 buffer_add_int (buf, arr->bounds [i].length);
8026 buffer_add_int (buf, arr->bounds [i].lower_bound);
8030 case CMD_ARRAY_REF_GET_VALUES:
8031 index = decode_int (p, &p, end);
8032 len = decode_int (p, &p, end);
8034 g_assert (index >= 0 && len >= 0);
8035 // Reordered to avoid integer overflow
8036 g_assert (!(index > arr->max_length - len));
8038 esize = mono_array_element_size (arr->obj.vtable->klass);
8039 for (i = index; i < index + len; ++i) {
8040 elem = (gpointer*)((char*)arr->vector + (i * esize));
8041 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8044 case CMD_ARRAY_REF_SET_VALUES:
8045 index = decode_int (p, &p, end);
8046 len = decode_int (p, &p, end);
8048 g_assert (index >= 0 && len >= 0);
8049 // Reordered to avoid integer overflow
8050 g_assert (!(index > arr->max_length - len));
8052 esize = mono_array_element_size (arr->obj.vtable->klass);
8053 for (i = index; i < index + len; ++i) {
8054 elem = (gpointer*)((char*)arr->vector + (i * esize));
8056 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8060 return ERR_NOT_IMPLEMENTED;
8067 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8072 int i, index, length;
8075 objid = decode_objid (p, &p, end);
8076 err = get_object (objid, (MonoObject**)&str);
8081 case CMD_STRING_REF_GET_VALUE:
8082 s = mono_string_to_utf8 (str);
8083 buffer_add_string (buf, s);
8086 case CMD_STRING_REF_GET_LENGTH:
8087 buffer_add_long (buf, mono_string_length (str));
8089 case CMD_STRING_REF_GET_CHARS:
8090 index = decode_long (p, &p, end);
8091 length = decode_long (p, &p, end);
8092 if (index > mono_string_length (str) - length)
8093 return ERR_INVALID_ARGUMENT;
8094 c = mono_string_chars (str) + index;
8095 for (i = 0; i < length; ++i)
8096 buffer_add_short (buf, c [i]);
8099 return ERR_NOT_IMPLEMENTED;
8106 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8115 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8116 objid = decode_objid (p, &p, end);
8117 err = get_object (objid, &obj);
8119 buffer_add_int (buf, 1);
8121 buffer_add_int (buf, 0);
8125 objid = decode_objid (p, &p, end);
8126 err = get_object (objid, &obj);
8131 case CMD_OBJECT_REF_GET_TYPE:
8132 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8134 case CMD_OBJECT_REF_GET_VALUES:
8135 len = decode_int (p, &p, end);
8137 for (i = 0; i < len; ++i) {
8138 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8142 /* Check that the field belongs to the object */
8144 for (k = obj->vtable->klass; k; k = k->parent) {
8145 if (k == f->parent) {
8151 return ERR_INVALID_FIELDID;
8153 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8157 if (mono_class_field_is_special_static (f))
8158 return ERR_INVALID_FIELDID;
8160 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8161 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8162 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8163 mono_field_static_get_value (vtable, f, val);
8164 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8167 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8171 case CMD_OBJECT_REF_SET_VALUES:
8172 len = decode_int (p, &p, end);
8174 for (i = 0; i < len; ++i) {
8175 f = decode_fieldid (p, &p, end, NULL, &err);
8179 /* Check that the field belongs to the object */
8181 for (k = obj->vtable->klass; k; k = k->parent) {
8182 if (k == f->parent) {
8188 return ERR_INVALID_FIELDID;
8190 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8194 if (mono_class_field_is_special_static (f))
8195 return ERR_INVALID_FIELDID;
8197 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8198 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8200 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8201 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8206 mono_field_static_set_value (vtable, f, val);
8209 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8215 case CMD_OBJECT_REF_GET_ADDRESS:
8216 buffer_add_long (buf, (gssize)obj);
8218 case CMD_OBJECT_REF_GET_DOMAIN:
8219 buffer_add_domainid (buf, obj->vtable->domain);
8221 case CMD_OBJECT_REF_GET_INFO:
8222 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8223 buffer_add_domainid (buf, obj->vtable->domain);
8226 return ERR_NOT_IMPLEMENTED;
8233 command_set_to_string (CommandSet command_set)
8235 switch (command_set) {
8238 case CMD_SET_OBJECT_REF:
8239 return "OBJECT_REF";
8240 case CMD_SET_STRING_REF:
8241 return "STRING_REF";
8242 case CMD_SET_THREAD:
8244 case CMD_SET_ARRAY_REF:
8246 case CMD_SET_EVENT_REQUEST:
8247 return "EVENT_REQUEST";
8248 case CMD_SET_STACK_FRAME:
8249 return "STACK_FRAME";
8250 case CMD_SET_APPDOMAIN:
8252 case CMD_SET_ASSEMBLY:
8254 case CMD_SET_METHOD:
8258 case CMD_SET_MODULE:
8268 cmd_to_string (CommandSet set, int command)
8273 case CMD_VM_VERSION:
8275 case CMD_VM_ALL_THREADS:
8276 return "ALL_THREADS";
8277 case CMD_VM_SUSPEND:
8283 case CMD_VM_DISPOSE:
8285 case CMD_VM_INVOKE_METHOD:
8286 return "INVOKE_METHOD";
8287 case CMD_VM_SET_PROTOCOL_VERSION:
8288 return "SET_PROTOCOL_VERSION";
8289 case CMD_VM_ABORT_INVOKE:
8290 return "ABORT_INVOKE";
8303 wait_for_attach (void)
8305 #ifndef DISABLE_SOCKET_TRANSPORT
8306 if (listen_fd == -1) {
8307 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8311 /* Block and wait for client connection */
8312 conn_fd = socket_transport_accept (listen_fd);
8313 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8314 if (conn_fd == -1) {
8315 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8319 g_assert_not_reached ();
8323 disconnected = !transport_handshake ();
8325 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8335 * This thread handles communication with the debugger client using a JDWP
8338 static guint32 WINAPI
8339 debugger_thread (void *arg)
8341 int res, len, id, flags, command_set = 0, command = 0;
8342 guint8 header [HEADER_LENGTH];
8343 guint8 *data, *p, *end;
8347 gboolean attach_failed = FALSE;
8349 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8351 debugger_thread_id = GetCurrentThreadId ();
8353 mono_jit_thread_attach (mono_get_root_domain ());
8355 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8357 mono_set_is_debugger_attached (TRUE);
8359 if (agent_config.defer) {
8360 if (!wait_for_attach ()) {
8361 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8362 attach_failed = TRUE; // Don't abort process when we can't listen
8364 /* Send start event to client */
8365 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8369 while (!attach_failed) {
8370 res = transport_recv (header, HEADER_LENGTH);
8372 /* This will break if the socket is closed during shutdown too */
8373 if (res != HEADER_LENGTH)
8377 end = header + HEADER_LENGTH;
8379 len = decode_int (p, &p, end);
8380 id = decode_int (p, &p, end);
8381 flags = decode_byte (p, &p, end);
8382 command_set = decode_byte (p, &p, end);
8383 command = decode_byte (p, &p, end);
8385 g_assert (flags == 0);
8388 const char *cmd_str;
8391 cmd_str = cmd_to_string (command_set, command);
8393 sprintf (cmd_num, "%d", command);
8397 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8400 data = g_malloc (len - HEADER_LENGTH);
8401 if (len - HEADER_LENGTH > 0)
8403 res = transport_recv (data, len - HEADER_LENGTH);
8404 if (res != len - HEADER_LENGTH)
8409 end = data + (len - HEADER_LENGTH);
8411 buffer_init (&buf, 128);
8416 /* Process the request */
8417 switch (command_set) {
8419 err = vm_commands (command, id, p, end, &buf);
8420 if (!err && command == CMD_VM_INVOKE_METHOD)
8421 /* Sent after the invoke is complete */
8424 case CMD_SET_EVENT_REQUEST:
8425 err = event_commands (command, p, end, &buf);
8427 case CMD_SET_APPDOMAIN:
8428 err = domain_commands (command, p, end, &buf);
8430 case CMD_SET_ASSEMBLY:
8431 err = assembly_commands (command, p, end, &buf);
8433 case CMD_SET_MODULE:
8434 err = module_commands (command, p, end, &buf);
8437 err = type_commands (command, p, end, &buf);
8439 case CMD_SET_METHOD:
8440 err = method_commands (command, p, end, &buf);
8442 case CMD_SET_THREAD:
8443 err = thread_commands (command, p, end, &buf);
8445 case CMD_SET_STACK_FRAME:
8446 err = frame_commands (command, p, end, &buf);
8448 case CMD_SET_ARRAY_REF:
8449 err = array_commands (command, p, end, &buf);
8451 case CMD_SET_STRING_REF:
8452 err = string_commands (command, p, end, &buf);
8454 case CMD_SET_OBJECT_REF:
8455 err = object_commands (command, p, end, &buf);
8458 err = ERR_NOT_IMPLEMENTED;
8462 send_reply_packet (id, err, &buf);
8467 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8471 mono_set_is_debugger_attached (FALSE);
8473 mono_mutex_lock (&debugger_thread_exited_mutex);
8474 debugger_thread_exited = TRUE;
8475 mono_cond_signal (&debugger_thread_exited_cond);
8476 mono_mutex_unlock (&debugger_thread_exited_mutex);
8478 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8480 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8481 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8482 start_debugger_thread ();
8488 #else /* DISABLE_DEBUGGER_AGENT */
8491 mono_debugger_agent_parse_options (char *options)
8493 g_error ("This runtime is configured with the debugger agent disabled.");
8497 mono_debugger_agent_init (void)
8502 mono_debugger_agent_breakpoint_hit (void *sigctx)
8507 mono_debugger_agent_single_step_event (void *sigctx)
8512 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8517 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8523 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8524 MonoContext *catch_ctx)
8529 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8534 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8539 mono_debugger_agent_user_break (void)
8545 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8550 mono_debugger_agent_debug_log_is_enabled (void)