2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
43 #ifdef HAVE_UCONTEXT_H
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
62 #ifdef PLATFORM_ANDROID
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/utils/mono-semaphore.h>
76 #include <mono/utils/mono-error-internals.h>
77 #include <mono/utils/mono-stack-unwinding.h>
78 #include <mono/utils/mono-time.h>
79 #include "debugger-agent.h"
82 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
83 #define DISABLE_DEBUGGER_AGENT 1
86 #ifdef DISABLE_SOFT_DEBUG
87 #define DISABLE_DEBUGGER_AGENT 1
91 #include <mono/utils/mono-threads.h>
94 #ifndef DISABLE_DEBUGGER_AGENT
96 #include <mono/io-layer/mono-mutex.h>
98 /* Definitions to make backporting to 2.6 easier */
99 //#define MonoInternalThread MonoThread
100 //#define mono_thread_internal_current mono_thread_current
101 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
123 guint32 il_offset, native_offset;
127 * If method is gshared, this is the actual instance, otherwise this is equal to
130 MonoMethod *actual_method;
132 MonoDebugMethodJitInfo *jit;
134 mgreg_t *reg_locations [MONO_MAX_IREGS];
136 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
137 * the frame can become invalid.
142 typedef struct _InvokeData InvokeData;
150 /* This is the context which needs to be restored after the invoke */
154 * If this is set, invoke this method with the arguments given by ARGS.
158 guint32 suspend_count;
160 InvokeData *last_invoke;
164 MonoThreadUnwindState context;
166 gpointer resume_event;
167 /* This is computed on demand when it is requested using the wire protocol */
168 /* It is freed up when the thread is resumed */
172 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
175 gboolean frames_up_to_date;
177 * Points to data about a pending invoke which needs to be executed after the thread
180 InvokeData *pending_invoke;
182 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
187 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
188 * within a finite amount of time.
192 * Set to TRUE if this thread is suspended in suspend_current ().
194 gboolean really_suspended;
195 /* Used to pass the context to the breakpoint/single step handler */
196 MonoContext handler_ctx;
197 /* Whenever thread_stop () was called for this thread */
200 /* Number of thread interruptions not yet processed */
201 gint32 interrupt_count;
203 /* Whenever to disable breakpoints (used during invokes) */
204 gboolean disable_breakpoints;
207 * Number of times this thread has been resumed using resume_thread ().
209 guint32 resume_count;
211 MonoInternalThread *thread;
214 * Information about the frame which transitioned to native code for running
217 StackFrameInfo async_last_frame;
220 * The context where the stack walk can be started for running threads.
222 MonoThreadUnwindState async_state;
225 * The context used for filter clauses
227 MonoThreadUnwindState filter_state;
230 * The callee address of the last mono_runtime_invoke call
232 gpointer invoke_addr;
234 gboolean abort_requested;
237 * The current mono_runtime_invoke invocation.
242 * The context where single stepping should resume while the thread is suspended because
243 * of an EXCEPTION event.
245 MonoContext catch_ctx;
247 gboolean has_catch_ctx;
250 * The context which needs to be restored after handling a single step/breakpoint
251 * event. This is the same as the ctx at step/breakpoint site, but includes changes
252 * to caller saved registers done by set_var ().
254 MonoContext restore_ctx;
259 void (*connect) (const char *address);
260 void (*close1) (void);
261 void (*close2) (void);
262 gboolean (*send) (void *buf, int len);
263 int (*recv) (void *buf, int len);
267 * Wire Protocol definitions
270 #define HEADER_LENGTH 11
272 #define MAJOR_VERSION 2
273 #define MINOR_VERSION 17
277 CMD_SET_OBJECT_REF = 9,
278 CMD_SET_STRING_REF = 10,
280 CMD_SET_ARRAY_REF = 13,
281 CMD_SET_EVENT_REQUEST = 15,
282 CMD_SET_STACK_FRAME = 16,
283 CMD_SET_APPDOMAIN = 20,
284 CMD_SET_ASSEMBLY = 21,
292 EVENT_KIND_VM_START = 0,
293 EVENT_KIND_VM_DEATH = 1,
294 EVENT_KIND_THREAD_START = 2,
295 EVENT_KIND_THREAD_DEATH = 3,
296 EVENT_KIND_APPDOMAIN_CREATE = 4,
297 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
298 EVENT_KIND_METHOD_ENTRY = 6,
299 EVENT_KIND_METHOD_EXIT = 7,
300 EVENT_KIND_ASSEMBLY_LOAD = 8,
301 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
302 EVENT_KIND_BREAKPOINT = 10,
303 EVENT_KIND_STEP = 11,
304 EVENT_KIND_TYPE_LOAD = 12,
305 EVENT_KIND_EXCEPTION = 13,
306 EVENT_KIND_KEEPALIVE = 14,
307 EVENT_KIND_USER_BREAK = 15,
308 EVENT_KIND_USER_LOG = 16
312 SUSPEND_POLICY_NONE = 0,
313 SUSPEND_POLICY_EVENT_THREAD = 1,
314 SUSPEND_POLICY_ALL = 2
319 ERR_INVALID_OBJECT = 20,
320 ERR_INVALID_FIELDID = 25,
321 ERR_INVALID_FRAMEID = 30,
322 ERR_NOT_IMPLEMENTED = 100,
323 ERR_NOT_SUSPENDED = 101,
324 ERR_INVALID_ARGUMENT = 102,
326 ERR_NO_INVOCATION = 104,
327 ERR_ABSENT_INFORMATION = 105,
328 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
329 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
334 MOD_KIND_THREAD_ONLY = 3,
335 MOD_KIND_LOCATION_ONLY = 7,
336 MOD_KIND_EXCEPTION_ONLY = 8,
338 MOD_KIND_ASSEMBLY_ONLY = 11,
339 MOD_KIND_SOURCE_FILE_ONLY = 12,
340 MOD_KIND_TYPE_NAME_ONLY = 13
355 STEP_FILTER_NONE = 0,
356 STEP_FILTER_STATIC_CTOR = 1
360 TOKEN_TYPE_STRING = 0,
362 TOKEN_TYPE_FIELD = 2,
363 TOKEN_TYPE_METHOD = 3,
364 TOKEN_TYPE_UNKNOWN = 4
368 VALUE_TYPE_ID_NULL = 0xf0,
369 VALUE_TYPE_ID_TYPE = 0xf1
373 FRAME_FLAG_DEBUGGER_INVOKE = 1,
374 FRAME_FLAG_NATIVE_TRANSITION = 2
378 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
379 INVOKE_FLAG_SINGLE_THREADED = 2
383 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
384 } BindingFlagsExtensions;
388 CMD_VM_ALL_THREADS = 2,
393 CMD_VM_INVOKE_METHOD = 7,
394 CMD_VM_SET_PROTOCOL_VERSION = 8,
395 CMD_VM_ABORT_INVOKE = 9,
396 CMD_VM_SET_KEEPALIVE = 10,
397 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
398 CMD_VM_GET_TYPES = 12
402 CMD_THREAD_GET_FRAME_INFO = 1,
403 CMD_THREAD_GET_NAME = 2,
404 CMD_THREAD_GET_STATE = 3,
405 CMD_THREAD_GET_INFO = 4,
406 CMD_THREAD_GET_ID = 5,
407 CMD_THREAD_GET_TID = 6
411 CMD_EVENT_REQUEST_SET = 1,
412 CMD_EVENT_REQUEST_CLEAR = 2,
413 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
421 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
422 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
423 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
424 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
425 CMD_APPDOMAIN_CREATE_STRING = 5,
426 CMD_APPDOMAIN_GET_CORLIB = 6,
427 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
431 CMD_ASSEMBLY_GET_LOCATION = 1,
432 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
433 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
434 CMD_ASSEMBLY_GET_OBJECT = 4,
435 CMD_ASSEMBLY_GET_TYPE = 5,
436 CMD_ASSEMBLY_GET_NAME = 6
440 CMD_MODULE_GET_INFO = 1,
444 CMD_METHOD_GET_NAME = 1,
445 CMD_METHOD_GET_DECLARING_TYPE = 2,
446 CMD_METHOD_GET_DEBUG_INFO = 3,
447 CMD_METHOD_GET_PARAM_INFO = 4,
448 CMD_METHOD_GET_LOCALS_INFO = 5,
449 CMD_METHOD_GET_INFO = 6,
450 CMD_METHOD_GET_BODY = 7,
451 CMD_METHOD_RESOLVE_TOKEN = 8,
455 CMD_TYPE_GET_INFO = 1,
456 CMD_TYPE_GET_METHODS = 2,
457 CMD_TYPE_GET_FIELDS = 3,
458 CMD_TYPE_GET_VALUES = 4,
459 CMD_TYPE_GET_OBJECT = 5,
460 CMD_TYPE_GET_SOURCE_FILES = 6,
461 CMD_TYPE_SET_VALUES = 7,
462 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
463 CMD_TYPE_GET_PROPERTIES = 9,
464 CMD_TYPE_GET_CATTRS = 10,
465 CMD_TYPE_GET_FIELD_CATTRS = 11,
466 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
467 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
468 CMD_TYPE_GET_VALUES_2 = 14,
469 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
470 CMD_TYPE_GET_INTERFACES = 16,
471 CMD_TYPE_GET_INTERFACE_MAP = 17,
475 CMD_STACK_FRAME_GET_VALUES = 1,
476 CMD_STACK_FRAME_GET_THIS = 2,
477 CMD_STACK_FRAME_SET_VALUES = 3
481 CMD_ARRAY_REF_GET_LENGTH = 1,
482 CMD_ARRAY_REF_GET_VALUES = 2,
483 CMD_ARRAY_REF_SET_VALUES = 3,
487 CMD_STRING_REF_GET_VALUE = 1,
488 CMD_STRING_REF_GET_LENGTH = 2,
489 CMD_STRING_REF_GET_CHARS = 3
493 CMD_OBJECT_REF_GET_TYPE = 1,
494 CMD_OBJECT_REF_GET_VALUES = 2,
495 CMD_OBJECT_REF_IS_COLLECTED = 3,
496 CMD_OBJECT_REF_GET_ADDRESS = 4,
497 CMD_OBJECT_REF_GET_DOMAIN = 5,
498 CMD_OBJECT_REF_SET_VALUES = 6,
499 CMD_OBJECT_REF_GET_INFO = 7,
505 int count; /* For kind == MOD_KIND_COUNT */
506 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
507 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
508 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
509 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
510 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
511 StepFilter filter; /* For kind == MOD_KIND_STEP */
513 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
522 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
526 * Describes a single step request.
530 MonoInternalThread *thread;
536 MonoMethod *last_method;
538 /* Whenever single stepping is performed using start/stop_single_stepping () */
540 /* The list of breakpoints used to implement step-over */
545 * Contains additional information for an event
548 /* For EVENT_KIND_EXCEPTION */
550 MonoContext catch_ctx;
552 /* For EVENT_KIND_USER_LOG */
554 char *category, *message;
555 /* For EVENT_KIND_TYPE_LOAD */
559 /* Dummy structure used for the profiler callbacks */
564 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
567 #define get_last_sock_error() WSAGetLastError()
568 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
569 #define MONO_EINTR WSAEINTR
571 #define get_last_sock_error() errno
572 #define MONO_EWOULDBLOCK EWOULDBLOCK
573 #define MONO_EINTR EINTR
576 #define CHECK_PROTOCOL_VERSION(major,minor) \
577 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
583 static AgentConfig agent_config;
586 * Whenever the agent is fully initialized.
587 * When using the onuncaught or onthrow options, only some parts of the agent are
588 * initialized on startup, and the full initialization which includes connection
589 * establishment and the startup of the agent thread is only done in response to
592 static gint32 inited;
594 #ifndef DISABLE_SOCKET_TRANSPORT
596 static int listen_fd;
599 static int packet_id = 0;
601 static int objref_id = 0;
603 static int event_request_id = 0;
605 static int frame_id = 0;
607 static GPtrArray *event_requests;
609 static MonoNativeTlsKey debugger_tls_id;
611 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
613 /* Maps MonoInternalThread -> DebuggerTlsData */
614 static MonoGHashTable *thread_to_tls;
616 /* Maps tid -> MonoInternalThread */
617 static MonoGHashTable *tid_to_thread;
619 /* Maps tid -> MonoThread (not MonoInternalThread) */
620 static MonoGHashTable *tid_to_thread_obj;
622 static gsize debugger_thread_id;
624 static HANDLE debugger_thread_handle;
626 static int log_level;
628 static gboolean embedding;
630 static FILE *log_file;
632 /* Assemblies whose assembly load event has no been sent yet */
633 static GPtrArray *pending_assembly_loads;
635 /* Whenever the debugger thread has exited */
636 static gboolean debugger_thread_exited;
638 /* Cond variable used to wait for debugger_thread_exited becoming true */
639 static mono_cond_t debugger_thread_exited_cond;
641 /* Mutex for the cond var above */
642 static mono_mutex_t debugger_thread_exited_mutex;
644 static DebuggerProfiler debugger_profiler;
646 /* The single step request instance */
647 static SingleStepReq *ss_req = NULL;
648 static gpointer ss_invoke_addr = NULL;
650 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
651 /* Number of single stepping operations in progress */
655 /* The protocol version of the client */
656 static int major_version, minor_version;
658 /* Whenever the variables above are set by the client */
659 static gboolean protocol_version_set;
661 /* A hash table containing all active domains */
662 static GHashTable *domains;
664 static void transport_init (void);
665 static void transport_connect (const char *address);
666 static gboolean transport_handshake (void);
667 static void register_transport (DebuggerTransport *trans);
669 static guint32 WINAPI debugger_thread (void *arg);
671 static void runtime_initialized (MonoProfiler *prof);
673 static void runtime_shutdown (MonoProfiler *prof);
675 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
677 static void thread_end (MonoProfiler *prof, uintptr_t tid);
679 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
681 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
683 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
685 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
687 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
689 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
691 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
693 static void emit_assembly_load (gpointer assembly, gpointer user_data);
695 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
697 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
699 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
701 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
703 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
705 static void start_single_stepping (void);
707 static void stop_single_stepping (void);
709 static void suspend_current (void);
711 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
713 static void clear_types_for_assembly (MonoAssembly *assembly);
715 static void clear_breakpoints_for_domain (MonoDomain *domain);
717 static void process_profiler_event (EventKind event, gpointer arg);
719 /* Submodule init/cleanup */
720 static void breakpoints_init (void);
721 static void breakpoints_cleanup (void);
723 static void objrefs_init (void);
724 static void objrefs_cleanup (void);
726 static void ids_init (void);
727 static void ids_cleanup (void);
729 static void suspend_init (void);
731 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
732 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
733 static void ss_destroy (SingleStepReq *req);
735 static void start_debugger_thread (void);
736 static void stop_debugger_thread (void);
738 static void finish_agent_init (gboolean on_startup);
740 static void process_profiler_event (EventKind event, gpointer arg);
742 #ifndef DISABLE_SOCKET_TRANSPORT
744 register_socket_transport (void);
748 parse_address (char *address, char **host, int *port)
750 char *pos = strchr (address, ':');
752 if (pos == NULL || pos == address)
755 *host = g_malloc (pos - address + 1);
756 strncpy (*host, address, pos - address);
757 (*host) [pos - address] = '\0';
759 *port = atoi (pos + 1);
767 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
768 fprintf (stderr, "Available options:\n");
769 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
770 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
771 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
772 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
773 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
774 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
775 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
776 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
777 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
781 parse_flag (const char *option, char *flag)
783 if (!strcmp (flag, "y"))
785 else if (!strcmp (flag, "n"))
788 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
795 mono_debugger_agent_parse_options (char *options)
802 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
803 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
807 extra = getenv ("MONO_SDB_ENV_OPTIONS");
809 options = g_strdup_printf ("%s,%s", options, extra);
811 agent_config.enabled = TRUE;
812 agent_config.suspend = TRUE;
813 agent_config.server = FALSE;
814 agent_config.defer = FALSE;
815 agent_config.address = NULL;
817 args = g_strsplit (options, ",", -1);
818 for (ptr = args; ptr && *ptr; ptr ++) {
821 if (strncmp (arg, "transport=", 10) == 0) {
822 agent_config.transport = g_strdup (arg + 10);
823 } else if (strncmp (arg, "address=", 8) == 0) {
824 agent_config.address = g_strdup (arg + 8);
825 } else if (strncmp (arg, "loglevel=", 9) == 0) {
826 agent_config.log_level = atoi (arg + 9);
827 } else if (strncmp (arg, "logfile=", 8) == 0) {
828 agent_config.log_file = g_strdup (arg + 8);
829 } else if (strncmp (arg, "suspend=", 8) == 0) {
830 agent_config.suspend = parse_flag ("suspend", arg + 8);
831 } else if (strncmp (arg, "server=", 7) == 0) {
832 agent_config.server = parse_flag ("server", arg + 7);
833 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
834 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
835 } else if (strncmp (arg, "onthrow=", 8) == 0) {
836 /* We support multiple onthrow= options */
837 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
838 } else if (strncmp (arg, "onthrow", 7) == 0) {
839 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
840 } else if (strncmp (arg, "help", 4) == 0) {
843 } else if (strncmp (arg, "timeout=", 8) == 0) {
844 agent_config.timeout = atoi (arg + 8);
845 } else if (strncmp (arg, "launch=", 7) == 0) {
846 agent_config.launch = g_strdup (arg + 7);
847 } else if (strncmp (arg, "embedding=", 10) == 0) {
848 agent_config.embedding = atoi (arg + 10) == 1;
849 } else if (strncmp (arg, "keepalive=", 10) == 0) {
850 agent_config.keepalive = atoi (arg + 10);
857 if (agent_config.server && !agent_config.suspend) {
858 /* Waiting for deferred attachment */
859 agent_config.defer = TRUE;
860 if (agent_config.address == NULL) {
861 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
865 //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, &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 = 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 ();
5532 /* Set value on the stack or in the return ctx */
5533 if (reg_locations [reg]) {
5534 /* Saved on the stack */
5535 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5536 *(reg_locations [reg]) = v;
5539 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5540 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5543 // FIXME: Move these to mono-context.h/c.
5544 mono_arch_context_set_int_reg (ctx, reg, v);
5546 // FIXME: Can't set registers, so we disable linears
5551 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5552 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5553 addr += (gint32)var->offset;
5555 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5557 // FIXME: Write barriers
5558 memcpy (addr, val, size);
5560 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5564 g_assert_not_reached ();
5569 clear_event_request (int req_id, int etype)
5573 mono_loader_lock ();
5574 for (i = 0; i < event_requests->len; ++i) {
5575 EventRequest *req = g_ptr_array_index (event_requests, i);
5577 if (req->id == req_id && req->event_kind == etype) {
5578 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5579 clear_breakpoint (req->info);
5580 if (req->event_kind == EVENT_KIND_STEP)
5581 ss_destroy (req->info);
5582 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5583 clear_breakpoint (req->info);
5584 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5585 clear_breakpoint (req->info);
5586 g_ptr_array_remove_index_fast (event_requests, i);
5591 mono_loader_unlock ();
5595 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5597 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5598 return breakpoint_matches_assembly (req->info, assembly);
5602 for (i = 0; i < req->nmodifiers; ++i) {
5603 Modifier *m = &req->modifiers [i];
5605 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5607 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5608 for (j = 0; m->data.assemblies [j]; ++j)
5609 if (m->data.assemblies [j] == assembly)
5619 * clear_event_requests_for_assembly:
5621 * Clear all events requests which reference ASSEMBLY.
5624 clear_event_requests_for_assembly (MonoAssembly *assembly)
5629 mono_loader_lock ();
5633 for (i = 0; i < event_requests->len; ++i) {
5634 EventRequest *req = g_ptr_array_index (event_requests, i);
5636 if (event_req_matches_assembly (req, assembly)) {
5637 clear_event_request (req->id, req->event_kind);
5643 mono_loader_unlock ();
5647 * type_comes_from_assembly:
5649 * GHRFunc that returns TRUE if klass comes from assembly
5652 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5654 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5658 * clear_types_for_assembly:
5660 * Clears types from loaded_classes for a given assembly
5663 clear_types_for_assembly (MonoAssembly *assembly)
5665 MonoDomain *domain = mono_domain_get ();
5666 AgentDomainInfo *info = NULL;
5668 mono_loader_lock ();
5669 info = get_agent_domain_info (domain);
5670 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5671 mono_loader_unlock ();
5675 add_thread (gpointer key, gpointer value, gpointer user_data)
5677 MonoInternalThread *thread = value;
5678 Buffer *buf = user_data;
5680 buffer_add_objid (buf, (MonoObject*)thread);
5684 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5686 guint8 *p = invoke->p;
5687 guint8 *end = invoke->endp;
5690 MonoMethodSignature *sig;
5693 MonoObject *this, *res, *exc;
5696 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5699 MonoStopwatch watch;
5701 if (invoke->method) {
5703 * Invoke this method directly, currently only Environment.Exit () is supported.
5706 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>"));
5707 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5708 g_assert_not_reached ();
5711 m = decode_methodid (p, &p, end, &domain, &err);
5714 sig = mono_method_signature (m);
5716 if (m->klass->valuetype)
5717 this_buf = g_alloca (mono_class_instance_size (m->klass));
5719 this_buf = g_alloca (sizeof (MonoObject*));
5720 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5721 /* Should be null */
5722 int type = decode_byte (p, &p, end);
5723 if (type != VALUE_TYPE_ID_NULL)
5724 return ERR_INVALID_ARGUMENT;
5725 memset (this_buf, 0, mono_class_instance_size (m->klass));
5727 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5732 if (!m->klass->valuetype)
5733 this = *(MonoObject**)this_buf;
5737 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>"));
5739 if (this && this->vtable->domain != domain)
5742 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5743 if (!strcmp (m->name, ".ctor")) {
5744 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5745 return ERR_INVALID_ARGUMENT;
5747 this = mono_object_new (domain, m->klass);
5749 return ERR_INVALID_ARGUMENT;
5753 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5754 return ERR_INVALID_ARGUMENT;
5756 nargs = decode_int (p, &p, end);
5757 if (nargs != sig->param_count)
5758 return ERR_INVALID_ARGUMENT;
5759 /* Use alloca to get gc tracking */
5760 arg_buf = g_alloca (nargs * sizeof (gpointer));
5761 memset (arg_buf, 0, nargs * sizeof (gpointer));
5762 args = g_alloca (nargs * sizeof (gpointer));
5763 for (i = 0; i < nargs; ++i) {
5764 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5765 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5769 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5772 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5773 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5776 args [i] = arg_buf [i];
5783 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5784 tls->disable_breakpoints = TRUE;
5786 tls->disable_breakpoints = FALSE;
5789 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5791 /* FIXME: Move this to arch specific code */
5792 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5793 if (invoke->has_ctx) {
5796 lmf_addr = mono_get_lmf_addr ();
5799 memset (&ext, 0, sizeof (ext));
5801 ext.lmf.previous_lmf = *(lmf_addr);
5802 /* Mark that this is a MonoLMFExt */
5803 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5804 ext.lmf.rsp = (gssize)&ext;
5805 #elif defined(TARGET_X86)
5806 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5807 /* Mark that this is a MonoLMFExt */
5808 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5809 ext.lmf.ebp = (gssize)&ext;
5810 #elif defined(TARGET_ARM)
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.sp = (gssize)&ext;
5815 #elif defined(TARGET_POWERPC)
5816 ext.lmf.previous_lmf = *(lmf_addr);
5817 /* Mark that this is a MonoLMFExt */
5818 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5819 ext.lmf.ebp = (gssize)&ext;
5820 #elif defined(TARGET_S390X)
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.ebp = (gssize)&ext;
5825 #elif defined(TARGET_MIPS)
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.iregs [mips_sp] = (gssize)&ext;
5831 g_assert_not_reached ();
5834 ext.debugger_invoke = TRUE;
5835 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5837 mono_set_lmf ((MonoLMF*)&ext);
5841 mono_stopwatch_start (&watch);
5842 if (m->klass->valuetype)
5843 res = mono_runtime_invoke (m, this_buf, args, &exc);
5845 res = mono_runtime_invoke (m, this, args, &exc);
5846 mono_stopwatch_stop (&watch);
5847 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)));
5849 buffer_add_byte (buf, 0);
5850 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5852 buffer_add_byte (buf, 1);
5853 if (sig->ret->type == MONO_TYPE_VOID) {
5854 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5855 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5858 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5859 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5860 buffer_add_value (buf, sig->ret, &res, domain);
5861 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
5862 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5864 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &res, domain);
5866 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5869 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5876 tls->disable_breakpoints = FALSE;
5878 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5879 if (invoke->has_ctx)
5880 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5883 // FIXME: byref arguments
5891 * Invoke the method given by tls->pending_invoke in the current thread.
5894 invoke_method (void)
5896 DebuggerTlsData *tls;
5901 static void (*restore_context) (void *);
5902 MonoContext restore_ctx;
5904 if (!restore_context)
5905 restore_context = mono_get_restore_context ();
5907 tls = mono_native_tls_get_value (debugger_tls_id);
5911 * Store the `InvokeData *' in `tls->invoke' until we're done with
5912 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5915 mono_loader_lock ();
5917 invoke = tls->pending_invoke;
5919 tls->pending_invoke = NULL;
5921 invoke->last_invoke = tls->invoke;
5922 tls->invoke = invoke;
5924 mono_loader_unlock ();
5926 tls->frames_up_to_date = FALSE;
5930 buffer_init (&buf, 128);
5932 err = do_invoke_method (tls, &buf, invoke);
5934 /* Start suspending before sending the reply */
5935 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
5936 for (i = 0; i < invoke->suspend_count; ++i)
5940 send_reply_packet (id, err, &buf);
5944 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5946 if (invoke->has_ctx)
5947 save_thread_context (&restore_ctx);
5949 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5950 g_assert (tls->resume_count);
5951 tls->resume_count -= invoke->suspend_count;
5954 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5957 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5959 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5960 * after the mono_runtime_invoke() already returned, but it doesn't matter
5961 * because we reset the abort here.
5964 mono_loader_lock ();
5966 if (tls->abort_requested)
5967 mono_thread_internal_reset_abort (tls->thread);
5969 tls->invoke = tls->invoke->last_invoke;
5970 tls->abort_requested = FALSE;
5972 mono_loader_unlock ();
5981 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5983 MonoThread *thread = value;
5984 DebuggerTlsData *tls;
5987 mono_loader_lock ();
5988 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5990 res = tls->really_suspended;
5991 mono_loader_unlock ();
5997 get_source_files_for_type (MonoClass *klass)
5999 gpointer iter = NULL;
6001 MonoDebugSourceInfo *sinfo;
6005 files = g_ptr_array_new ();
6007 while ((method = mono_class_get_methods (klass, &iter))) {
6008 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6009 GPtrArray *source_file_list;
6012 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL);
6013 for (j = 0; j < source_file_list->len; ++j) {
6014 sinfo = g_ptr_array_index (source_file_list, j);
6015 for (i = 0; i < files->len; ++i)
6016 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6018 if (i == files->len)
6019 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6021 g_ptr_array_free (source_file_list, TRUE);
6029 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6032 case CMD_VM_VERSION: {
6033 char *build_info, *version;
6035 build_info = mono_get_runtime_build_info ();
6036 version = g_strdup_printf ("mono %s", build_info);
6038 buffer_add_string (buf, version); /* vm version */
6039 buffer_add_int (buf, MAJOR_VERSION);
6040 buffer_add_int (buf, MINOR_VERSION);
6041 g_free (build_info);
6045 case CMD_VM_SET_PROTOCOL_VERSION: {
6046 major_version = decode_int (p, &p, end);
6047 minor_version = decode_int (p, &p, end);
6048 protocol_version_set = TRUE;
6049 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6052 case CMD_VM_ALL_THREADS: {
6054 mono_loader_lock ();
6055 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6056 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6057 mono_loader_unlock ();
6060 case CMD_VM_SUSPEND:
6062 wait_for_suspend ();
6065 if (suspend_count == 0)
6066 return ERR_NOT_SUSPENDED;
6069 case CMD_VM_DISPOSE:
6070 /* Clear all event requests */
6071 mono_loader_lock ();
6072 while (event_requests->len > 0) {
6073 EventRequest *req = g_ptr_array_index (event_requests, 0);
6075 clear_event_request (req->id, req->event_kind);
6077 mono_loader_unlock ();
6079 while (suspend_count > 0)
6081 disconnected = TRUE;
6082 vm_start_event_sent = FALSE;
6085 MonoInternalThread *thread;
6086 DebuggerTlsData *tls;
6087 MonoClass *env_class;
6088 MonoMethod *exit_method = NULL;
6092 exit_code = decode_int (p, &p, end);
6094 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6096 /* Have to send a reply before exiting */
6097 send_reply_packet (id, 0, buf);
6099 /* Clear all event requests */
6100 mono_loader_lock ();
6101 while (event_requests->len > 0) {
6102 EventRequest *req = g_ptr_array_index (event_requests, 0);
6104 clear_event_request (req->id, req->event_kind);
6106 mono_loader_unlock ();
6109 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6110 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6111 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6112 * better than doing the shutdown ourselves, since it avoids various races.
6116 wait_for_suspend ();
6118 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6120 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6122 mono_loader_lock ();
6123 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6124 mono_loader_unlock ();
6126 if (thread && exit_method) {
6127 mono_loader_lock ();
6128 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6129 mono_loader_unlock ();
6131 args = g_new0 (gpointer, 1);
6132 args [0] = g_malloc (sizeof (int));
6133 *(int*)(args [0]) = exit_code;
6135 tls->pending_invoke = g_new0 (InvokeData, 1);
6136 tls->pending_invoke->method = exit_method;
6137 tls->pending_invoke->args = args;
6139 while (suspend_count > 0)
6143 * No thread found, do it ourselves.
6144 * FIXME: This can race with normal shutdown etc.
6146 while (suspend_count > 0)
6149 mono_runtime_set_shutting_down ();
6151 mono_threads_set_shutting_down ();
6153 /* Suspend all managed threads since the runtime is going away */
6154 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6155 mono_thread_suspend_all_other_threads ();
6156 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6157 mono_runtime_quit ();
6158 transport_close2 ();
6159 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6165 case CMD_VM_INVOKE_METHOD: {
6166 int objid = decode_objid (p, &p, end);
6168 DebuggerTlsData *tls;
6169 int i, count, err, flags;
6171 err = get_object (objid, (MonoObject**)&thread);
6175 flags = decode_int (p, &p, end);
6177 // Wait for suspending if it already started
6179 wait_for_suspend ();
6180 if (!is_suspended ())
6181 return ERR_NOT_SUSPENDED;
6183 mono_loader_lock ();
6184 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6185 mono_loader_unlock ();
6188 if (!tls->really_suspended)
6189 /* The thread is still running native code, can't do invokes */
6190 return ERR_NOT_SUSPENDED;
6193 * Store the invoke data into tls, the thread will execute it after it is
6196 if (tls->pending_invoke)
6197 return ERR_NOT_SUSPENDED;
6198 tls->pending_invoke = g_new0 (InvokeData, 1);
6199 tls->pending_invoke->id = id;
6200 tls->pending_invoke->flags = flags;
6201 tls->pending_invoke->p = g_malloc (end - p);
6202 memcpy (tls->pending_invoke->p, p, end - p);
6203 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6204 tls->pending_invoke->suspend_count = suspend_count;
6206 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6207 resume_thread (THREAD_TO_INTERNAL (thread));
6210 count = suspend_count;
6211 for (i = 0; i < count; ++i)
6216 case CMD_VM_ABORT_INVOKE: {
6217 int objid = decode_objid (p, &p, end);
6219 DebuggerTlsData *tls;
6222 err = get_object (objid, (MonoObject**)&thread);
6226 invoke_id = decode_int (p, &p, end);
6228 mono_loader_lock ();
6229 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6232 if (tls->abort_requested) {
6233 mono_loader_unlock ();
6238 * Check whether we're still inside the mono_runtime_invoke() and that it's
6239 * actually the correct invocation.
6241 * Careful, we do not stop the thread that's doing the invocation, so we can't
6242 * inspect its stack. However, invoke_method() also acquires the loader lock
6243 * when it's done, so we're safe here.
6247 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6248 mono_loader_unlock ();
6249 return ERR_NO_INVOCATION;
6252 tls->abort_requested = TRUE;
6254 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6255 mono_loader_unlock ();
6259 case CMD_VM_SET_KEEPALIVE: {
6260 int timeout = decode_int (p, &p, end);
6261 agent_config.keepalive = timeout;
6263 #ifndef DISABLE_SOCKET_TRANSPORT
6270 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6271 GHashTableIter iter, kiter;
6276 char *fname, *basename;
6277 gboolean ignore_case;
6278 GSList *class_list, *l;
6279 GPtrArray *res_classes, *res_domains;
6281 fname = decode_string (p, &p, end);
6282 ignore_case = decode_byte (p, &p, end);
6284 basename = g_path_get_basename (fname);
6286 res_classes = g_ptr_array_new ();
6287 res_domains = g_ptr_array_new ();
6289 mono_loader_lock ();
6290 g_hash_table_iter_init (&iter, domains);
6291 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6292 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6294 /* Update 'source_file_to_class' cache */
6295 g_hash_table_iter_init (&kiter, info->loaded_classes);
6296 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6297 if (!g_hash_table_lookup (info->source_files, klass)) {
6298 files = get_source_files_for_type (klass);
6299 g_hash_table_insert (info->source_files, klass, files);
6301 for (i = 0; i < files->len; ++i) {
6302 char *s = g_ptr_array_index (files, i);
6303 char *s2 = g_path_get_basename (s);
6306 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6308 class_list = g_slist_prepend (class_list, klass);
6309 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6311 class_list = g_slist_prepend (class_list, klass);
6312 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6315 /* The _ignorecase hash contains the lowercase path */
6316 s3 = strdup_tolower (s2);
6317 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6319 class_list = g_slist_prepend (class_list, klass);
6320 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6322 class_list = g_slist_prepend (class_list, klass);
6323 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6335 s = strdup_tolower (basename);
6336 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6339 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6342 for (l = class_list; l; l = l->next) {
6345 g_ptr_array_add (res_classes, klass);
6346 g_ptr_array_add (res_domains, domain);
6349 mono_loader_unlock ();
6354 buffer_add_int (buf, res_classes->len);
6355 for (i = 0; i < res_classes->len; ++i)
6356 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6357 g_ptr_array_free (res_classes, TRUE);
6358 g_ptr_array_free (res_domains, TRUE);
6361 case CMD_VM_GET_TYPES: {
6362 GHashTableIter iter;
6366 gboolean ignore_case;
6367 GPtrArray *res_classes, *res_domains;
6368 MonoTypeNameParse info;
6370 name = decode_string (p, &p, end);
6371 ignore_case = decode_byte (p, &p, end);
6373 if (!mono_reflection_parse_type (name, &info)) {
6375 mono_reflection_free_type_info (&info);
6376 return ERR_INVALID_ARGUMENT;
6379 res_classes = g_ptr_array_new ();
6380 res_domains = g_ptr_array_new ();
6382 mono_loader_lock ();
6383 g_hash_table_iter_init (&iter, domains);
6384 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6386 gboolean type_resolve;
6390 mono_domain_assemblies_lock (domain);
6391 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6395 type_resolve = TRUE;
6396 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6398 g_ptr_array_add (res_classes, mono_type_get_class (t));
6399 g_ptr_array_add (res_domains, domain);
6403 mono_domain_assemblies_unlock (domain);
6405 mono_loader_unlock ();
6408 mono_reflection_free_type_info (&info);
6410 buffer_add_int (buf, res_classes->len);
6411 for (i = 0; i < res_classes->len; ++i)
6412 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6413 g_ptr_array_free (res_classes, TRUE);
6414 g_ptr_array_free (res_domains, TRUE);
6419 return ERR_NOT_IMPLEMENTED;
6426 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6432 case CMD_EVENT_REQUEST_SET: {
6434 int i, event_kind, suspend_policy, nmodifiers, mod;
6437 MonoThread *step_thread;
6438 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6442 event_kind = decode_byte (p, &p, end);
6443 suspend_policy = decode_byte (p, &p, end);
6444 nmodifiers = decode_byte (p, &p, end);
6446 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6447 req->id = InterlockedIncrement (&event_request_id);
6448 req->event_kind = event_kind;
6449 req->suspend_policy = suspend_policy;
6450 req->nmodifiers = nmodifiers;
6453 for (i = 0; i < nmodifiers; ++i) {
6454 mod = decode_byte (p, &p, end);
6456 req->modifiers [i].kind = mod;
6457 if (mod == MOD_KIND_COUNT) {
6458 req->modifiers [i].data.count = decode_int (p, &p, end);
6459 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6460 method = decode_methodid (p, &p, end, &domain, &err);
6463 location = decode_long (p, &p, end);
6464 } else if (mod == MOD_KIND_STEP) {
6465 step_thread_id = decode_id (p, &p, end);
6466 size = decode_int (p, &p, end);
6467 depth = decode_int (p, &p, end);
6468 if (CHECK_PROTOCOL_VERSION (2, 16))
6469 filter = decode_int (p, &p, end);
6470 req->modifiers [i].data.filter = filter;
6471 } else if (mod == MOD_KIND_THREAD_ONLY) {
6472 int id = decode_id (p, &p, end);
6474 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6479 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6480 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6484 req->modifiers [i].caught = decode_byte (p, &p, end);
6485 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6486 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" : ""));
6488 req->modifiers [i].data.exc_class = exc_class;
6490 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6492 return ERR_INVALID_ARGUMENT;
6495 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6496 int n = decode_int (p, &p, end);
6499 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6500 for (j = 0; j < n; ++j) {
6501 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6503 g_free (req->modifiers [i].data.assemblies);
6507 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6508 int n = decode_int (p, &p, end);
6511 modifier = &req->modifiers [i];
6512 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6513 for (j = 0; j < n; ++j) {
6514 char *s = decode_string (p, &p, end);
6518 s2 = strdup_tolower (s);
6519 g_hash_table_insert (modifier->data.source_files, s2, s2);
6523 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6524 int n = decode_int (p, &p, end);
6527 modifier = &req->modifiers [i];
6528 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6529 for (j = 0; j < n; ++j) {
6530 char *s = decode_string (p, &p, end);
6533 g_hash_table_insert (modifier->data.type_names, s, s);
6537 return ERR_NOT_IMPLEMENTED;
6541 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6544 req->info = set_breakpoint (method, location, req, &error);
6545 if (!mono_error_ok (&error)) {
6547 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6548 mono_error_cleanup (&error);
6549 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6551 } else if (req->event_kind == EVENT_KIND_STEP) {
6552 g_assert (step_thread_id);
6554 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6560 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6565 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6566 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6567 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6568 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6569 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6570 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6572 if (req->nmodifiers) {
6574 return ERR_NOT_IMPLEMENTED;
6578 mono_loader_lock ();
6579 g_ptr_array_add (event_requests, req);
6581 if (agent_config.defer) {
6582 /* Transmit cached data to the client on receipt of the event request */
6583 switch (req->event_kind) {
6584 case EVENT_KIND_APPDOMAIN_CREATE:
6585 /* Emit load events for currently loaded domains */
6586 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6588 case EVENT_KIND_ASSEMBLY_LOAD:
6589 /* Emit load events for currently loaded assemblies */
6590 mono_assembly_foreach (emit_assembly_load, NULL);
6592 case EVENT_KIND_THREAD_START:
6593 /* Emit start events for currently started threads */
6594 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6596 case EVENT_KIND_TYPE_LOAD:
6597 /* Emit type load events for currently loaded types */
6598 mono_domain_foreach (send_types_for_domain, NULL);
6604 mono_loader_unlock ();
6606 buffer_add_int (buf, req->id);
6609 case CMD_EVENT_REQUEST_CLEAR: {
6610 int etype = decode_byte (p, &p, end);
6611 int req_id = decode_int (p, &p, end);
6613 // FIXME: Make a faster mapping from req_id to request
6614 mono_loader_lock ();
6615 clear_event_request (req_id, etype);
6616 mono_loader_unlock ();
6619 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6622 mono_loader_lock ();
6624 while (i < event_requests->len) {
6625 EventRequest *req = g_ptr_array_index (event_requests, i);
6627 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6628 clear_breakpoint (req->info);
6630 g_ptr_array_remove_index_fast (event_requests, i);
6636 mono_loader_unlock ();
6640 return ERR_NOT_IMPLEMENTED;
6647 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6653 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6654 buffer_add_domainid (buf, mono_get_root_domain ());
6657 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6658 domain = decode_domainid (p, &p, end, NULL, &err);
6661 buffer_add_string (buf, domain->friendly_name);
6664 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6669 domain = decode_domainid (p, &p, end, NULL, &err);
6672 mono_loader_lock ();
6674 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6677 buffer_add_int (buf, count);
6678 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6680 buffer_add_assemblyid (buf, domain, ass);
6682 mono_loader_unlock ();
6685 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6686 domain = decode_domainid (p, &p, end, NULL, &err);
6690 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6693 case CMD_APPDOMAIN_GET_CORLIB: {
6694 domain = decode_domainid (p, &p, end, NULL, &err);
6698 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6701 case CMD_APPDOMAIN_CREATE_STRING: {
6705 domain = decode_domainid (p, &p, end, NULL, &err);
6708 s = decode_string (p, &p, end);
6710 o = mono_string_new (domain, s);
6711 buffer_add_objid (buf, (MonoObject*)o);
6714 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6716 MonoDomain *domain2;
6719 domain = decode_domainid (p, &p, end, NULL, &err);
6722 klass = decode_typeid (p, &p, end, &domain2, &err);
6727 g_assert (domain == domain2);
6729 o = mono_object_new (domain, klass);
6731 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6735 buffer_add_objid (buf, o);
6739 return ERR_NOT_IMPLEMENTED;
6746 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6752 ass = decode_assemblyid (p, &p, end, &domain, &err);
6757 case CMD_ASSEMBLY_GET_LOCATION: {
6758 buffer_add_string (buf, mono_image_get_filename (ass->image));
6761 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6765 if (ass->image->dynamic) {
6766 buffer_add_id (buf, 0);
6768 token = mono_image_get_entry_point (ass->image);
6770 buffer_add_id (buf, 0);
6772 m = mono_get_method (ass->image, token, NULL);
6773 buffer_add_methodid (buf, domain, m);
6778 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6779 buffer_add_moduleid (buf, domain, ass->image);
6782 case CMD_ASSEMBLY_GET_OBJECT: {
6783 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
6784 buffer_add_objid (buf, o);
6787 case CMD_ASSEMBLY_GET_TYPE: {
6788 char *s = decode_string (p, &p, end);
6789 gboolean ignorecase = decode_byte (p, &p, end);
6790 MonoTypeNameParse info;
6792 gboolean type_resolve, res;
6793 MonoDomain *d = mono_domain_get ();
6795 /* This is needed to be able to find referenced assemblies */
6796 res = mono_domain_set (domain, FALSE);
6799 if (!mono_reflection_parse_type (s, &info)) {
6802 if (info.assembly.name)
6804 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6806 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6807 mono_reflection_free_type_info (&info);
6810 mono_domain_set (d, TRUE);
6814 case CMD_ASSEMBLY_GET_NAME: {
6816 MonoAssembly *mass = ass;
6818 name = g_strdup_printf (
6819 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6821 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6822 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6823 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6824 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6826 buffer_add_string (buf, name);
6831 return ERR_NOT_IMPLEMENTED;
6838 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6844 case CMD_MODULE_GET_INFO: {
6845 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
6848 basename = g_path_get_basename (image->name);
6849 buffer_add_string (buf, basename); // name
6850 buffer_add_string (buf, image->module_name); // scopename
6851 buffer_add_string (buf, image->name); // fqname
6852 buffer_add_string (buf, mono_image_get_guid (image)); // guid
6853 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
6858 return ERR_NOT_IMPLEMENTED;
6865 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6867 if (val && val->vtable->klass == mono_defaults.monotype_class) {
6868 /* Special case these so the client doesn't have to handle Type objects */
6870 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6871 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
6872 } else if (MONO_TYPE_IS_REFERENCE (t))
6873 buffer_add_value (buf, t, &val, domain);
6875 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6879 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6885 buffer_add_int (buf, 0);
6889 for (i = 0; i < cinfo->num_attrs; ++i) {
6890 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6893 buffer_add_int (buf, nattrs);
6895 for (i = 0; i < cinfo->num_attrs; ++i) {
6896 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6897 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6898 MonoArray *typed_args, *named_args;
6900 CattrNamedArg *arginfo;
6902 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6904 buffer_add_methodid (buf, domain, attr->ctor);
6908 buffer_add_int (buf, mono_array_length (typed_args));
6909 for (j = 0; j < mono_array_length (typed_args); ++j) {
6910 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6912 t = mono_method_signature (attr->ctor)->params [j];
6914 buffer_add_cattr_arg (buf, t, domain, val);
6917 buffer_add_int (buf, 0);
6922 buffer_add_int (buf, mono_array_length (named_args));
6924 for (j = 0; j < mono_array_length (named_args); ++j) {
6925 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
6927 if (arginfo [j].prop) {
6928 buffer_add_byte (buf, 0x54);
6929 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6930 } else if (arginfo [j].field) {
6931 buffer_add_byte (buf, 0x53);
6932 buffer_add_fieldid (buf, domain, arginfo [j].field);
6934 g_assert_not_reached ();
6937 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6940 buffer_add_int (buf, 0);
6946 /* FIXME: Code duplication with icall.c */
6948 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
6953 mono_class_setup_interfaces (klass, error);
6954 if (!mono_error_ok (error))
6957 for (i = 0; i < klass->interface_count; i++) {
6958 ic = klass->interfaces [i];
6959 g_hash_table_insert (ifaces, ic, ic);
6961 collect_interfaces (ic, ifaces, error);
6962 if (!mono_error_ok (error))
6968 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6978 case CMD_TYPE_GET_INFO: {
6979 buffer_add_string (buf, klass->name_space);
6980 buffer_add_string (buf, klass->name);
6982 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
6983 buffer_add_string (buf, name);
6985 buffer_add_assemblyid (buf, domain, klass->image->assembly);
6986 buffer_add_moduleid (buf, domain, klass->image);
6987 buffer_add_typeid (buf, domain, klass->parent);
6988 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
6989 buffer_add_typeid (buf, domain, klass->element_class);
6991 buffer_add_id (buf, 0);
6992 buffer_add_int (buf, klass->type_token);
6993 buffer_add_byte (buf, klass->rank);
6994 buffer_add_int (buf, klass->flags);
6996 type = &klass->byval_arg;
6997 // FIXME: Can't decide whenever a class represents a byref type
7000 if (type->type == MONO_TYPE_PTR)
7002 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7004 if (type->type == MONO_TYPE_VALUETYPE)
7006 if (klass->enumtype)
7008 if (klass->generic_container)
7010 if (klass->generic_container || klass->generic_class)
7012 buffer_add_byte (buf, b);
7015 while ((nested = mono_class_get_nested_types (klass, &iter)))
7017 buffer_add_int (buf, nnested);
7019 while ((nested = mono_class_get_nested_types (klass, &iter)))
7020 buffer_add_typeid (buf, domain, nested);
7021 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7022 if (klass->generic_container)
7023 buffer_add_typeid (buf, domain, klass);
7024 else if (klass->generic_class)
7025 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7027 buffer_add_id (buf, 0);
7029 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7032 if (klass->generic_class) {
7033 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7035 count = inst->type_argc;
7036 buffer_add_int (buf, count);
7037 for (i = 0; i < count; i++)
7038 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7039 } else if (klass->generic_container) {
7040 MonoGenericContainer *container = klass->generic_container;
7043 count = container->type_argc;
7044 buffer_add_int (buf, count);
7045 for (i = 0; i < count; i++) {
7046 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7047 buffer_add_typeid (buf, domain, pklass);
7050 buffer_add_int (buf, 0);
7055 case CMD_TYPE_GET_METHODS: {
7058 gpointer iter = NULL;
7061 mono_class_setup_methods (klass);
7063 nmethods = mono_class_num_methods (klass);
7065 buffer_add_int (buf, nmethods);
7067 while ((m = mono_class_get_methods (klass, &iter))) {
7068 buffer_add_methodid (buf, domain, m);
7071 g_assert (i == nmethods);
7074 case CMD_TYPE_GET_FIELDS: {
7077 gpointer iter = NULL;
7080 nfields = mono_class_num_fields (klass);
7082 buffer_add_int (buf, nfields);
7084 while ((f = mono_class_get_fields (klass, &iter))) {
7085 buffer_add_fieldid (buf, domain, f);
7086 buffer_add_string (buf, f->name);
7087 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7088 buffer_add_int (buf, f->type->attrs);
7091 g_assert (i == nfields);
7094 case CMD_TYPE_GET_PROPERTIES: {
7097 gpointer iter = NULL;
7100 nprops = mono_class_num_properties (klass);
7102 buffer_add_int (buf, nprops);
7104 while ((p = mono_class_get_properties (klass, &iter))) {
7105 buffer_add_propertyid (buf, domain, p);
7106 buffer_add_string (buf, p->name);
7107 buffer_add_methodid (buf, domain, p->get);
7108 buffer_add_methodid (buf, domain, p->set);
7109 buffer_add_int (buf, p->attrs);
7112 g_assert (i == nprops);
7115 case CMD_TYPE_GET_CATTRS: {
7116 MonoClass *attr_klass;
7117 MonoCustomAttrInfo *cinfo;
7119 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7120 /* attr_klass can be NULL */
7124 cinfo = mono_custom_attrs_from_class (klass);
7126 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7129 case CMD_TYPE_GET_FIELD_CATTRS: {
7130 MonoClass *attr_klass;
7131 MonoCustomAttrInfo *cinfo;
7132 MonoClassField *field;
7134 field = decode_fieldid (p, &p, end, NULL, &err);
7137 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7141 cinfo = mono_custom_attrs_from_field (klass, field);
7143 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7146 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7147 MonoClass *attr_klass;
7148 MonoCustomAttrInfo *cinfo;
7151 prop = decode_propertyid (p, &p, end, NULL, &err);
7154 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7158 cinfo = mono_custom_attrs_from_property (klass, prop);
7160 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7163 case CMD_TYPE_GET_VALUES:
7164 case CMD_TYPE_GET_VALUES_2: {
7171 MonoThread *thread_obj;
7172 MonoInternalThread *thread = NULL;
7173 guint32 special_static_type;
7175 if (command == CMD_TYPE_GET_VALUES_2) {
7176 int objid = decode_objid (p, &p, end);
7179 err = get_object (objid, (MonoObject**)&thread_obj);
7183 thread = THREAD_TO_INTERNAL (thread_obj);
7186 len = decode_int (p, &p, end);
7187 for (i = 0; i < len; ++i) {
7188 f = decode_fieldid (p, &p, end, NULL, &err);
7192 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7193 return ERR_INVALID_FIELDID;
7194 special_static_type = mono_class_field_get_special_static_type (f);
7195 if (special_static_type != SPECIAL_STATIC_NONE) {
7196 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7197 return ERR_INVALID_FIELDID;
7200 /* Check that the field belongs to the object */
7202 for (k = klass; k; k = k->parent) {
7203 if (k == f->parent) {
7209 return ERR_INVALID_FIELDID;
7211 vtable = mono_class_vtable (domain, f->parent);
7212 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7213 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7214 buffer_add_value (buf, f->type, val, domain);
7219 case CMD_TYPE_SET_VALUES: {
7227 len = decode_int (p, &p, end);
7228 for (i = 0; i < len; ++i) {
7229 f = decode_fieldid (p, &p, end, NULL, &err);
7233 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7234 return ERR_INVALID_FIELDID;
7235 if (mono_class_field_is_special_static (f))
7236 return ERR_INVALID_FIELDID;
7238 /* Check that the field belongs to the object */
7240 for (k = klass; k; k = k->parent) {
7241 if (k == f->parent) {
7247 return ERR_INVALID_FIELDID;
7249 // FIXME: Check for literal/const
7251 vtable = mono_class_vtable (domain, f->parent);
7252 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7253 err = decode_value (f->type, domain, val, p, &p, end);
7258 if (MONO_TYPE_IS_REFERENCE (f->type))
7259 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7261 mono_field_static_set_value (vtable, f, val);
7266 case CMD_TYPE_GET_OBJECT: {
7267 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7268 buffer_add_objid (buf, o);
7271 case CMD_TYPE_GET_SOURCE_FILES:
7272 case CMD_TYPE_GET_SOURCE_FILES_2: {
7273 char *source_file, *base;
7277 files = get_source_files_for_type (klass);
7279 buffer_add_int (buf, files->len);
7280 for (i = 0; i < files->len; ++i) {
7281 source_file = g_ptr_array_index (files, i);
7282 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7283 buffer_add_string (buf, source_file);
7285 base = g_path_get_basename (source_file);
7286 buffer_add_string (buf, base);
7289 g_free (source_file);
7291 g_ptr_array_free (files, TRUE);
7294 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7295 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7299 if (mono_class_is_assignable_from (klass, oklass))
7300 buffer_add_byte (buf, 1);
7302 buffer_add_byte (buf, 0);
7305 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7306 char *name = decode_string (p, &p, end);
7307 int i, flags = decode_int (p, &p, end);
7308 MonoException *ex = NULL;
7309 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7312 return ERR_LOADER_ERROR;
7313 buffer_add_int (buf, array->len);
7314 for (i = 0; i < array->len; ++i) {
7315 MonoMethod *method = g_ptr_array_index (array, i);
7316 buffer_add_methodid (buf, domain, method);
7319 g_ptr_array_free (array, TRUE);
7323 case CMD_TYPE_GET_INTERFACES: {
7325 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7327 MonoClass *tclass, *iface;
7328 GHashTableIter iter;
7332 for (parent = tclass; parent; parent = parent->parent) {
7333 mono_class_setup_interfaces (parent, &error);
7334 if (!mono_error_ok (&error))
7335 return ERR_LOADER_ERROR;
7336 collect_interfaces (parent, iface_hash, &error);
7337 if (!mono_error_ok (&error))
7338 return ERR_LOADER_ERROR;
7341 buffer_add_int (buf, g_hash_table_size (iface_hash));
7343 g_hash_table_iter_init (&iter, iface_hash);
7344 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7345 buffer_add_typeid (buf, domain, iface);
7346 g_hash_table_destroy (iface_hash);
7349 case CMD_TYPE_GET_INTERFACE_MAP: {
7350 int tindex, ioffset;
7351 gboolean variance_used;
7353 int len, nmethods, i;
7357 len = decode_int (p, &p, end);
7358 mono_class_setup_vtable (klass);
7360 for (tindex = 0; tindex < len; ++tindex) {
7361 iclass = decode_typeid (p, &p, end, NULL, &err);
7365 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7367 return ERR_INVALID_ARGUMENT;
7369 nmethods = mono_class_num_methods (iclass);
7370 buffer_add_int (buf, nmethods);
7373 while ((method = mono_class_get_methods (iclass, &iter))) {
7374 buffer_add_methodid (buf, domain, method);
7376 for (i = 0; i < nmethods; ++i)
7377 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7382 return ERR_NOT_IMPLEMENTED;
7389 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7392 MonoDomain *old_domain;
7396 klass = decode_typeid (p, &p, end, &domain, &err);
7400 old_domain = mono_domain_get ();
7402 mono_domain_set (domain, TRUE);
7404 err = type_commands_internal (command, klass, domain, p, end, buf);
7406 mono_domain_set (old_domain, TRUE);
7412 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7414 MonoMethodHeader *header;
7417 case CMD_METHOD_GET_NAME: {
7418 buffer_add_string (buf, method->name);
7421 case CMD_METHOD_GET_DECLARING_TYPE: {
7422 buffer_add_typeid (buf, domain, method->klass);
7425 case CMD_METHOD_GET_DEBUG_INFO: {
7426 MonoDebugMethodInfo *minfo;
7428 int i, j, n_il_offsets;
7432 GPtrArray *source_file_list;
7434 header = mono_method_get_header (method);
7436 buffer_add_int (buf, 0);
7437 buffer_add_string (buf, "");
7438 buffer_add_int (buf, 0);
7442 minfo = mono_debug_lookup_method (method);
7444 buffer_add_int (buf, header->code_size);
7445 buffer_add_string (buf, "");
7446 buffer_add_int (buf, 0);
7447 mono_metadata_free_mh (header);
7451 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &source_files);
7452 buffer_add_int (buf, header->code_size);
7453 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7454 buffer_add_int (buf, source_file_list->len);
7455 for (i = 0; i < source_file_list->len; ++i) {
7456 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7457 buffer_add_string (buf, sinfo->source_file);
7458 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7459 for (j = 0; j < 16; ++j)
7460 buffer_add_byte (buf, sinfo->hash [j]);
7464 buffer_add_string (buf, source_file);
7466 buffer_add_int (buf, n_il_offsets);
7467 DEBUG (10, printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7468 for (i = 0; i < n_il_offsets; ++i) {
7469 const char *srcfile = "";
7471 if (source_files [i] != -1) {
7472 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7473 srcfile = sinfo->source_file;
7475 DEBUG (10, printf ("IL%x -> %s:%d\n", il_offsets [i], srcfile, line_numbers [i]));
7476 buffer_add_int (buf, il_offsets [i]);
7477 buffer_add_int (buf, line_numbers [i]);
7478 if (CHECK_PROTOCOL_VERSION (2, 13))
7479 buffer_add_int (buf, source_files [i]);
7481 g_free (source_file);
7482 g_free (il_offsets);
7483 g_free (line_numbers);
7484 g_free (source_files);
7485 g_ptr_array_free (source_file_list, TRUE);
7486 mono_metadata_free_mh (header);
7489 case CMD_METHOD_GET_PARAM_INFO: {
7490 MonoMethodSignature *sig = mono_method_signature (method);
7494 /* FIXME: mono_class_from_mono_type () and byrefs */
7496 /* FIXME: Use a smaller encoding */
7497 buffer_add_int (buf, sig->call_convention);
7498 buffer_add_int (buf, sig->param_count);
7499 buffer_add_int (buf, sig->generic_param_count);
7500 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7501 for (i = 0; i < sig->param_count; ++i) {
7503 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7506 /* Emit parameter names */
7507 names = g_new (char *, sig->param_count);
7508 mono_method_get_param_names (method, (const char **) names);
7509 for (i = 0; i < sig->param_count; ++i)
7510 buffer_add_string (buf, names [i]);
7515 case CMD_METHOD_GET_LOCALS_INFO: {
7516 int i, j, num_locals;
7517 MonoDebugLocalsInfo *locals;
7519 header = mono_method_get_header (method);
7521 return ERR_INVALID_ARGUMENT;
7523 buffer_add_int (buf, header->num_locals);
7526 for (i = 0; i < header->num_locals; ++i)
7527 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7530 locals = mono_debug_lookup_locals (method);
7532 num_locals = locals->num_locals;
7535 for (i = 0; i < header->num_locals; ++i) {
7536 for (j = 0; j < num_locals; ++j)
7537 if (locals->locals [j].index == i)
7540 buffer_add_string (buf, locals->locals [j].name);
7542 buffer_add_string (buf, "");
7546 for (i = 0; i < header->num_locals; ++i) {
7547 for (j = 0; j < num_locals; ++j)
7548 if (locals->locals [j].index == i)
7550 if (j < num_locals && locals->locals [j].block) {
7551 buffer_add_int (buf, locals->locals [j].block->start_offset);
7552 buffer_add_int (buf, locals->locals [j].block->end_offset);
7554 buffer_add_int (buf, 0);
7555 buffer_add_int (buf, header->code_size);
7558 mono_metadata_free_mh (header);
7561 mono_debug_symfile_free_locals (locals);
7565 case CMD_METHOD_GET_INFO:
7566 buffer_add_int (buf, method->flags);
7567 buffer_add_int (buf, method->iflags);
7568 buffer_add_int (buf, method->token);
7569 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7571 if (method->is_generic)
7573 if (mono_method_signature (method)->generic_param_count)
7575 buffer_add_byte (buf, attrs);
7576 if (method->is_generic || method->is_inflated) {
7579 if (method->is_generic) {
7582 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7584 result = imethod->declaring;
7585 if (imethod->context.class_inst) {
7586 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7587 /*Generic methods gets the context of the GTD.*/
7588 if (mono_class_get_context (klass))
7589 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7593 buffer_add_methodid (buf, domain, result);
7595 buffer_add_id (buf, 0);
7597 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7598 if (mono_method_signature (method)->generic_param_count) {
7601 if (method->is_inflated) {
7602 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7604 count = inst->type_argc;
7605 buffer_add_int (buf, count);
7607 for (i = 0; i < count; i++)
7608 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7610 buffer_add_int (buf, 0);
7612 } else if (method->is_generic) {
7613 MonoGenericContainer *container = mono_method_get_generic_container (method);
7615 count = mono_method_signature (method)->generic_param_count;
7616 buffer_add_int (buf, count);
7617 for (i = 0; i < count; i++) {
7618 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7619 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7620 buffer_add_typeid (buf, domain, pklass);
7623 buffer_add_int (buf, 0);
7626 buffer_add_int (buf, 0);
7631 case CMD_METHOD_GET_BODY: {
7634 header = mono_method_get_header (method);
7636 buffer_add_int (buf, 0);
7638 buffer_add_int (buf, header->code_size);
7639 for (i = 0; i < header->code_size; ++i)
7640 buffer_add_byte (buf, header->code [i]);
7642 mono_metadata_free_mh (header);
7645 case CMD_METHOD_RESOLVE_TOKEN: {
7646 guint32 token = decode_int (p, &p, end);
7649 switch (mono_metadata_token_code (token)) {
7650 case MONO_TOKEN_STRING: {
7654 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7657 s2 = mono_string_to_utf8 (s);
7659 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7660 buffer_add_string (buf, s2);
7666 MonoClass *handle_class;
7668 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7669 val = mono_method_get_wrapper_data (method, token);
7670 handle_class = mono_method_get_wrapper_data (method, token + 1);
7672 if (handle_class == NULL) {
7673 // Can't figure out the token type
7674 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7678 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7682 if (handle_class == mono_defaults.typehandle_class) {
7683 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7684 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7685 buffer_add_typeid (buf, domain, (MonoClass *) val);
7687 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7688 } else if (handle_class == mono_defaults.fieldhandle_class) {
7689 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7690 buffer_add_fieldid (buf, domain, val);
7691 } else if (handle_class == mono_defaults.methodhandle_class) {
7692 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7693 buffer_add_methodid (buf, domain, val);
7694 } else if (handle_class == mono_defaults.string_class) {
7697 s = mono_string_to_utf8 (val);
7698 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7699 buffer_add_string (buf, s);
7702 g_assert_not_reached ();
7710 return ERR_NOT_IMPLEMENTED;
7717 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7720 MonoDomain *old_domain;
7724 method = decode_methodid (p, &p, end, &domain, &err);
7728 old_domain = mono_domain_get ();
7730 mono_domain_set (domain, TRUE);
7732 err = method_commands_internal (command, method, domain, p, end, buf);
7734 mono_domain_set (old_domain, TRUE);
7740 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7742 int objid = decode_objid (p, &p, end);
7744 MonoThread *thread_obj;
7745 MonoInternalThread *thread;
7747 err = get_object (objid, (MonoObject**)&thread_obj);
7751 thread = THREAD_TO_INTERNAL (thread_obj);
7754 case CMD_THREAD_GET_NAME: {
7756 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7759 buffer_add_int (buf, 0);
7764 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7766 buffer_add_int (buf, len);
7767 buffer_add_data (buf, (guint8*)name, len);
7772 case CMD_THREAD_GET_FRAME_INFO: {
7773 DebuggerTlsData *tls;
7774 int i, start_frame, length;
7776 // Wait for suspending if it already started
7777 // FIXME: Races with suspend_count
7778 while (!is_suspended ()) {
7780 wait_for_suspend ();
7784 wait_for_suspend ();
7785 if (!is_suspended ())
7786 return ERR_NOT_SUSPENDED;
7789 start_frame = decode_int (p, &p, end);
7790 length = decode_int (p, &p, end);
7792 if (start_frame != 0 || length != -1)
7793 return ERR_NOT_IMPLEMENTED;
7795 mono_loader_lock ();
7796 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7797 mono_loader_unlock ();
7800 compute_frame_info (thread, tls);
7802 buffer_add_int (buf, tls->frame_count);
7803 for (i = 0; i < tls->frame_count; ++i) {
7804 buffer_add_int (buf, tls->frames [i]->id);
7805 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
7806 buffer_add_int (buf, tls->frames [i]->il_offset);
7808 * Instead of passing the frame type directly to the client, we associate
7809 * it with the previous frame using a set of flags. This avoids lots of
7810 * conditional code in the client, since a frame whose type isn't
7811 * FRAME_TYPE_MANAGED has no method, location, etc.
7813 buffer_add_byte (buf, tls->frames [i]->flags);
7818 case CMD_THREAD_GET_STATE:
7819 buffer_add_int (buf, thread->state);
7821 case CMD_THREAD_GET_INFO:
7822 buffer_add_byte (buf, thread->threadpool_thread);
7824 case CMD_THREAD_GET_ID:
7825 buffer_add_long (buf, (guint64)(gsize)thread);
7827 case CMD_THREAD_GET_TID:
7828 buffer_add_long (buf, (guint64)thread->tid);
7831 return ERR_NOT_IMPLEMENTED;
7838 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7842 MonoThread *thread_obj;
7843 MonoInternalThread *thread;
7844 int pos, i, len, frame_idx;
7845 DebuggerTlsData *tls;
7847 MonoDebugMethodJitInfo *jit;
7848 MonoDebugVarInfo *var;
7849 MonoMethodSignature *sig;
7851 MonoMethodHeader *header;
7853 objid = decode_objid (p, &p, end);
7854 err = get_object (objid, (MonoObject**)&thread_obj);
7858 thread = THREAD_TO_INTERNAL (thread_obj);
7860 id = decode_id (p, &p, end);
7862 mono_loader_lock ();
7863 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7864 mono_loader_unlock ();
7867 for (i = 0; i < tls->frame_count; ++i) {
7868 if (tls->frames [i]->id == id)
7871 if (i == tls->frame_count)
7872 return ERR_INVALID_FRAMEID;
7875 frame = tls->frames [frame_idx];
7877 if (!frame->has_ctx)
7879 return ERR_INVALID_FRAMEID;
7882 frame->jit = mono_debug_find_method (frame->method, frame->domain);
7883 if (!frame->jit && frame->method->is_inflated)
7884 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->method), frame->domain);
7888 /* This could happen for aot images with no jit debug info */
7889 s = mono_method_full_name (frame->method, TRUE);
7890 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
7892 return ERR_ABSENT_INFORMATION;
7897 sig = mono_method_signature (frame->actual_method);
7899 if (!get_seq_points (frame->domain, frame->actual_method))
7901 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
7903 return ERR_ABSENT_INFORMATION;
7906 case CMD_STACK_FRAME_GET_VALUES: {
7907 len = decode_int (p, &p, end);
7908 header = mono_method_get_header (frame->actual_method);
7910 for (i = 0; i < len; ++i) {
7911 pos = decode_int (p, &p, end);
7916 g_assert (pos >= 0 && pos < jit->num_params);
7918 var = &jit->params [pos];
7920 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
7922 g_assert (pos >= 0 && pos < jit->num_locals);
7924 var = &jit->locals [pos];
7926 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
7929 mono_metadata_free_mh (header);
7932 case CMD_STACK_FRAME_GET_THIS: {
7933 if (frame->method->klass->valuetype) {
7934 if (!sig->hasthis) {
7935 MonoObject *p = NULL;
7936 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
7938 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7941 if (!sig->hasthis) {
7942 MonoObject *p = NULL;
7943 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
7945 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7950 case CMD_STACK_FRAME_SET_VALUES: {
7953 MonoDebugVarInfo *var;
7955 len = decode_int (p, &p, end);
7956 header = mono_method_get_header (frame->actual_method);
7958 for (i = 0; i < len; ++i) {
7959 pos = decode_int (p, &p, end);
7964 g_assert (pos >= 0 && pos < jit->num_params);
7966 t = sig->params [pos];
7967 var = &jit->params [pos];
7969 g_assert (pos >= 0 && pos < jit->num_locals);
7971 t = header->locals [pos];
7972 var = &jit->locals [pos];
7975 if (MONO_TYPE_IS_REFERENCE (t))
7976 val_buf = g_alloca (sizeof (MonoObject*));
7978 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
7979 err = decode_value (t, frame->domain, val_buf, p, &p, end);
7983 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
7985 mono_metadata_free_mh (header);
7989 return ERR_NOT_IMPLEMENTED;
7996 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7999 int objid, err, index, len, i, esize;
8002 objid = decode_objid (p, &p, end);
8003 err = get_object (objid, (MonoObject**)&arr);
8008 case CMD_ARRAY_REF_GET_LENGTH:
8009 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8011 buffer_add_int (buf, arr->max_length);
8012 buffer_add_int (buf, 0);
8014 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8015 buffer_add_int (buf, arr->bounds [i].length);
8016 buffer_add_int (buf, arr->bounds [i].lower_bound);
8020 case CMD_ARRAY_REF_GET_VALUES:
8021 index = decode_int (p, &p, end);
8022 len = decode_int (p, &p, end);
8024 g_assert (index >= 0 && len >= 0);
8025 // Reordered to avoid integer overflow
8026 g_assert (!(index > arr->max_length - len));
8028 esize = mono_array_element_size (arr->obj.vtable->klass);
8029 for (i = index; i < index + len; ++i) {
8030 elem = (gpointer*)((char*)arr->vector + (i * esize));
8031 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8034 case CMD_ARRAY_REF_SET_VALUES:
8035 index = decode_int (p, &p, end);
8036 len = decode_int (p, &p, end);
8038 g_assert (index >= 0 && len >= 0);
8039 // Reordered to avoid integer overflow
8040 g_assert (!(index > arr->max_length - len));
8042 esize = mono_array_element_size (arr->obj.vtable->klass);
8043 for (i = index; i < index + len; ++i) {
8044 elem = (gpointer*)((char*)arr->vector + (i * esize));
8046 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8050 return ERR_NOT_IMPLEMENTED;
8057 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8062 int i, index, length;
8065 objid = decode_objid (p, &p, end);
8066 err = get_object (objid, (MonoObject**)&str);
8071 case CMD_STRING_REF_GET_VALUE:
8072 s = mono_string_to_utf8 (str);
8073 buffer_add_string (buf, s);
8076 case CMD_STRING_REF_GET_LENGTH:
8077 buffer_add_long (buf, mono_string_length (str));
8079 case CMD_STRING_REF_GET_CHARS:
8080 index = decode_long (p, &p, end);
8081 length = decode_long (p, &p, end);
8082 if (index > mono_string_length (str) - length)
8083 return ERR_INVALID_ARGUMENT;
8084 c = mono_string_chars (str) + index;
8085 for (i = 0; i < length; ++i)
8086 buffer_add_short (buf, c [i]);
8089 return ERR_NOT_IMPLEMENTED;
8096 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8105 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8106 objid = decode_objid (p, &p, end);
8107 err = get_object (objid, &obj);
8109 buffer_add_int (buf, 1);
8111 buffer_add_int (buf, 0);
8115 objid = decode_objid (p, &p, end);
8116 err = get_object (objid, &obj);
8121 case CMD_OBJECT_REF_GET_TYPE:
8122 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8124 case CMD_OBJECT_REF_GET_VALUES:
8125 len = decode_int (p, &p, end);
8127 for (i = 0; i < len; ++i) {
8128 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8132 /* Check that the field belongs to the object */
8134 for (k = obj->vtable->klass; k; k = k->parent) {
8135 if (k == f->parent) {
8141 return ERR_INVALID_FIELDID;
8143 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8147 if (mono_class_field_is_special_static (f))
8148 return ERR_INVALID_FIELDID;
8150 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8151 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8152 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8153 mono_field_static_get_value (vtable, f, val);
8154 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8157 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8161 case CMD_OBJECT_REF_SET_VALUES:
8162 len = decode_int (p, &p, end);
8164 for (i = 0; i < len; ++i) {
8165 f = decode_fieldid (p, &p, end, NULL, &err);
8169 /* Check that the field belongs to the object */
8171 for (k = obj->vtable->klass; k; k = k->parent) {
8172 if (k == f->parent) {
8178 return ERR_INVALID_FIELDID;
8180 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8184 if (mono_class_field_is_special_static (f))
8185 return ERR_INVALID_FIELDID;
8187 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8188 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8190 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8191 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8196 mono_field_static_set_value (vtable, f, val);
8199 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8205 case CMD_OBJECT_REF_GET_ADDRESS:
8206 buffer_add_long (buf, (gssize)obj);
8208 case CMD_OBJECT_REF_GET_DOMAIN:
8209 buffer_add_domainid (buf, obj->vtable->domain);
8211 case CMD_OBJECT_REF_GET_INFO:
8212 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8213 buffer_add_domainid (buf, obj->vtable->domain);
8216 return ERR_NOT_IMPLEMENTED;
8223 command_set_to_string (CommandSet command_set)
8225 switch (command_set) {
8228 case CMD_SET_OBJECT_REF:
8229 return "OBJECT_REF";
8230 case CMD_SET_STRING_REF:
8231 return "STRING_REF";
8232 case CMD_SET_THREAD:
8234 case CMD_SET_ARRAY_REF:
8236 case CMD_SET_EVENT_REQUEST:
8237 return "EVENT_REQUEST";
8238 case CMD_SET_STACK_FRAME:
8239 return "STACK_FRAME";
8240 case CMD_SET_APPDOMAIN:
8242 case CMD_SET_ASSEMBLY:
8244 case CMD_SET_METHOD:
8248 case CMD_SET_MODULE:
8258 cmd_to_string (CommandSet set, int command)
8263 case CMD_VM_VERSION:
8265 case CMD_VM_ALL_THREADS:
8266 return "ALL_THREADS";
8267 case CMD_VM_SUSPEND:
8273 case CMD_VM_DISPOSE:
8275 case CMD_VM_INVOKE_METHOD:
8276 return "INVOKE_METHOD";
8277 case CMD_VM_SET_PROTOCOL_VERSION:
8278 return "SET_PROTOCOL_VERSION";
8279 case CMD_VM_ABORT_INVOKE:
8280 return "ABORT_INVOKE";
8293 wait_for_attach (void)
8295 #ifndef DISABLE_SOCKET_TRANSPORT
8296 if (listen_fd == -1) {
8297 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8301 /* Block and wait for client connection */
8302 conn_fd = socket_transport_accept (listen_fd);
8303 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8304 if (conn_fd == -1) {
8305 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8309 g_assert_not_reached ();
8313 disconnected = !transport_handshake ();
8315 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8325 * This thread handles communication with the debugger client using a JDWP
8328 static guint32 WINAPI
8329 debugger_thread (void *arg)
8331 int res, len, id, flags, command_set = 0, command = 0;
8332 guint8 header [HEADER_LENGTH];
8333 guint8 *data, *p, *end;
8337 gboolean attach_failed = FALSE;
8339 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8341 debugger_thread_id = GetCurrentThreadId ();
8343 mono_jit_thread_attach (mono_get_root_domain ());
8345 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8347 mono_set_is_debugger_attached (TRUE);
8349 if (agent_config.defer) {
8350 if (!wait_for_attach ()) {
8351 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8352 attach_failed = TRUE; // Don't abort process when we can't listen
8354 /* Send start event to client */
8355 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8359 while (!attach_failed) {
8360 res = transport_recv (header, HEADER_LENGTH);
8362 /* This will break if the socket is closed during shutdown too */
8363 if (res != HEADER_LENGTH)
8367 end = header + HEADER_LENGTH;
8369 len = decode_int (p, &p, end);
8370 id = decode_int (p, &p, end);
8371 flags = decode_byte (p, &p, end);
8372 command_set = decode_byte (p, &p, end);
8373 command = decode_byte (p, &p, end);
8375 g_assert (flags == 0);
8378 const char *cmd_str;
8381 cmd_str = cmd_to_string (command_set, command);
8383 sprintf (cmd_num, "%d", command);
8387 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8390 data = g_malloc (len - HEADER_LENGTH);
8391 if (len - HEADER_LENGTH > 0)
8393 res = transport_recv (data, len - HEADER_LENGTH);
8394 if (res != len - HEADER_LENGTH)
8399 end = data + (len - HEADER_LENGTH);
8401 buffer_init (&buf, 128);
8406 /* Process the request */
8407 switch (command_set) {
8409 err = vm_commands (command, id, p, end, &buf);
8410 if (!err && command == CMD_VM_INVOKE_METHOD)
8411 /* Sent after the invoke is complete */
8414 case CMD_SET_EVENT_REQUEST:
8415 err = event_commands (command, p, end, &buf);
8417 case CMD_SET_APPDOMAIN:
8418 err = domain_commands (command, p, end, &buf);
8420 case CMD_SET_ASSEMBLY:
8421 err = assembly_commands (command, p, end, &buf);
8423 case CMD_SET_MODULE:
8424 err = module_commands (command, p, end, &buf);
8427 err = type_commands (command, p, end, &buf);
8429 case CMD_SET_METHOD:
8430 err = method_commands (command, p, end, &buf);
8432 case CMD_SET_THREAD:
8433 err = thread_commands (command, p, end, &buf);
8435 case CMD_SET_STACK_FRAME:
8436 err = frame_commands (command, p, end, &buf);
8438 case CMD_SET_ARRAY_REF:
8439 err = array_commands (command, p, end, &buf);
8441 case CMD_SET_STRING_REF:
8442 err = string_commands (command, p, end, &buf);
8444 case CMD_SET_OBJECT_REF:
8445 err = object_commands (command, p, end, &buf);
8448 err = ERR_NOT_IMPLEMENTED;
8452 send_reply_packet (id, err, &buf);
8457 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8461 mono_set_is_debugger_attached (FALSE);
8463 mono_mutex_lock (&debugger_thread_exited_mutex);
8464 debugger_thread_exited = TRUE;
8465 mono_cond_signal (&debugger_thread_exited_cond);
8466 mono_mutex_unlock (&debugger_thread_exited_mutex);
8468 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8470 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8471 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8472 start_debugger_thread ();
8478 #else /* DISABLE_DEBUGGER_AGENT */
8481 mono_debugger_agent_parse_options (char *options)
8483 g_error ("This runtime is configured with the debugger agent disabled.");
8487 mono_debugger_agent_init (void)
8492 mono_debugger_agent_breakpoint_hit (void *sigctx)
8497 mono_debugger_agent_single_step_event (void *sigctx)
8502 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8507 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8513 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8514 MonoContext *catch_ctx)
8519 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8524 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8529 mono_debugger_agent_user_break (void)
8535 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8540 mono_debugger_agent_debug_log_is_enabled (void)