2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
14 #ifdef HAVE_SYS_TYPES_H
15 #include <sys/types.h>
17 #ifdef HAVE_SYS_SELECT_H
18 #include <sys/select.h>
20 #ifdef HAVE_SYS_SOCKET_H
21 #include <sys/socket.h>
23 #ifdef HAVE_NETINET_TCP_H
24 #include <netinet/tcp.h>
26 #ifdef HAVE_NETINET_IN_H
27 #include <netinet/in.h>
42 #ifdef HAVE_UCONTEXT_H
52 /* cygwin's headers do not seem to define these */
53 void WSAAPI freeaddrinfo (struct addrinfo*);
54 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
56 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
61 #ifdef PLATFORM_ANDROID
63 #include <linux/tcp.h>
64 #include <sys/endian.h>
67 #include <mono/metadata/mono-debug.h>
68 #include <mono/metadata/mono-debug-debugger.h>
69 #include <mono/metadata/debug-mono-symfile.h>
70 #include <mono/metadata/gc-internal.h>
71 #include <mono/metadata/threads-types.h>
72 #include <mono/metadata/socket-io.h>
73 #include <mono/metadata/assembly.h>
74 #include <mono/utils/mono-semaphore.h>
75 #include <mono/utils/mono-error-internals.h>
76 #include <mono/utils/mono-stack-unwinding.h>
77 #include "debugger-agent.h"
80 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
81 #define DISABLE_DEBUGGER_AGENT 1
84 #ifdef DISABLE_SOFT_DEBUG
85 #define DISABLE_DEBUGGER_AGENT 1
88 #ifndef DISABLE_DEBUGGER_AGENT
90 #include <mono/io-layer/mono-mutex.h>
92 /* Definitions to make backporting to 2.6 easier */
93 //#define MonoInternalThread MonoThread
94 //#define mono_thread_internal_current mono_thread_current
95 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
116 guint32 il_offset, native_offset;
120 * If method is gshared, this is the actual instance, otherwise this is equal to
123 MonoMethod *actual_method;
125 MonoDebugMethodJitInfo *jit;
127 mgreg_t *reg_locations [MONO_MAX_IREGS];
129 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
130 * the frame can become invalid.
135 typedef struct _InvokeData InvokeData;
143 /* This is the context which needs to be restored after the invoke */
147 * If this is set, invoke this method with the arguments given by ARGS.
151 guint32 suspend_count;
153 InvokeData *last_invoke;
157 MonoThreadUnwindState context;
159 gpointer resume_event;
160 /* This is computed on demand when it is requested using the wire protocol */
161 /* It is freed up when the thread is resumed */
165 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
168 gboolean frames_up_to_date;
170 * Points to data about a pending invoke which needs to be executed after the thread
173 InvokeData *pending_invoke;
175 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
180 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
181 * within a finite amount of time.
185 * Set to TRUE if this thread is suspended in suspend_current ().
187 gboolean really_suspended;
188 /* Used to pass the context to the breakpoint/single step handler */
189 MonoContext handler_ctx;
190 /* Whenever thread_stop () was called for this thread */
193 /* Number of thread interruptions not yet processed */
194 gint32 interrupt_count;
196 /* Whenever to disable breakpoints (used during invokes) */
197 gboolean disable_breakpoints;
200 * Number of times this thread has been resumed using resume_thread ().
202 guint32 resume_count;
204 MonoInternalThread *thread;
207 * Information about the frame which transitioned to native code for running
210 StackFrameInfo async_last_frame;
213 * The context where the stack walk can be started for running threads.
215 MonoThreadUnwindState async_state;
218 * The context used for filter clauses
220 MonoThreadUnwindState filter_state;
223 * The callee address of the last mono_runtime_invoke call
225 gpointer invoke_addr;
227 gboolean abort_requested;
230 * The current mono_runtime_invoke invocation.
235 * The context where single stepping should resume while the thread is suspended because
236 * of an EXCEPTION event.
238 MonoContext catch_ctx;
240 gboolean has_catch_ctx;
243 * The context which needs to be restored after handling a single step/breakpoint
244 * event. This is the same as the ctx at step/breakpoint site, but includes changes
245 * to caller saved registers done by set_var ().
247 MonoContext restore_ctx;
251 * Wire Protocol definitions
254 #define HEADER_LENGTH 11
256 #define MAJOR_VERSION 2
257 #define MINOR_VERSION 3
261 CMD_SET_OBJECT_REF = 9,
262 CMD_SET_STRING_REF = 10,
264 CMD_SET_ARRAY_REF = 13,
265 CMD_SET_EVENT_REQUEST = 15,
266 CMD_SET_STACK_FRAME = 16,
267 CMD_SET_APPDOMAIN = 20,
268 CMD_SET_ASSEMBLY = 21,
276 EVENT_KIND_VM_START = 0,
277 EVENT_KIND_VM_DEATH = 1,
278 EVENT_KIND_THREAD_START = 2,
279 EVENT_KIND_THREAD_DEATH = 3,
280 EVENT_KIND_APPDOMAIN_CREATE = 4,
281 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
282 EVENT_KIND_METHOD_ENTRY = 6,
283 EVENT_KIND_METHOD_EXIT = 7,
284 EVENT_KIND_ASSEMBLY_LOAD = 8,
285 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
286 EVENT_KIND_BREAKPOINT = 10,
287 EVENT_KIND_STEP = 11,
288 EVENT_KIND_TYPE_LOAD = 12,
289 EVENT_KIND_EXCEPTION = 13
293 SUSPEND_POLICY_NONE = 0,
294 SUSPEND_POLICY_EVENT_THREAD = 1,
295 SUSPEND_POLICY_ALL = 2
300 ERR_INVALID_OBJECT = 20,
301 ERR_INVALID_FIELDID = 25,
302 ERR_INVALID_FRAMEID = 30,
303 ERR_NOT_IMPLEMENTED = 100,
304 ERR_NOT_SUSPENDED = 101,
305 ERR_INVALID_ARGUMENT = 102,
307 ERR_NO_INVOCATION = 104,
308 ERR_ABSENT_INFORMATION = 105,
309 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106
314 MOD_KIND_THREAD_ONLY = 3,
315 MOD_KIND_LOCATION_ONLY = 7,
316 MOD_KIND_EXCEPTION_ONLY = 8,
318 MOD_KIND_ASSEMBLY_ONLY = 11
333 TOKEN_TYPE_STRING = 0,
335 TOKEN_TYPE_FIELD = 2,
336 TOKEN_TYPE_METHOD = 3,
337 TOKEN_TYPE_UNKNOWN = 4
341 VALUE_TYPE_ID_NULL = 0xf0,
342 VALUE_TYPE_ID_TYPE = 0xf1
346 FRAME_FLAG_DEBUGGER_INVOKE = 1
350 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
351 INVOKE_FLAG_SINGLE_THREADED = 2
356 CMD_VM_ALL_THREADS = 2,
361 CMD_VM_INVOKE_METHOD = 7,
362 CMD_VM_SET_PROTOCOL_VERSION = 8,
363 CMD_VM_ABORT_INVOKE = 9
367 CMD_THREAD_GET_FRAME_INFO = 1,
368 CMD_THREAD_GET_NAME = 2,
369 CMD_THREAD_GET_STATE = 3,
370 CMD_THREAD_GET_INFO = 4,
371 CMD_THREAD_GET_ID = 5,
372 CMD_THREAD_GET_TID = 6
376 CMD_EVENT_REQUEST_SET = 1,
377 CMD_EVENT_REQUEST_CLEAR = 2,
378 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
386 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
387 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
388 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
389 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
390 CMD_APPDOMAIN_CREATE_STRING = 5,
391 CMD_APPDOMAIN_GET_CORLIB = 6,
392 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
396 CMD_ASSEMBLY_GET_LOCATION = 1,
397 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
398 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
399 CMD_ASSEMBLY_GET_OBJECT = 4,
400 CMD_ASSEMBLY_GET_TYPE = 5,
401 CMD_ASSEMBLY_GET_NAME = 6
405 CMD_MODULE_GET_INFO = 1,
409 CMD_METHOD_GET_NAME = 1,
410 CMD_METHOD_GET_DECLARING_TYPE = 2,
411 CMD_METHOD_GET_DEBUG_INFO = 3,
412 CMD_METHOD_GET_PARAM_INFO = 4,
413 CMD_METHOD_GET_LOCALS_INFO = 5,
414 CMD_METHOD_GET_INFO = 6,
415 CMD_METHOD_GET_BODY = 7,
416 CMD_METHOD_RESOLVE_TOKEN = 8,
420 CMD_TYPE_GET_INFO = 1,
421 CMD_TYPE_GET_METHODS = 2,
422 CMD_TYPE_GET_FIELDS = 3,
423 CMD_TYPE_GET_VALUES = 4,
424 CMD_TYPE_GET_OBJECT = 5,
425 CMD_TYPE_GET_SOURCE_FILES = 6,
426 CMD_TYPE_SET_VALUES = 7,
427 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
428 CMD_TYPE_GET_PROPERTIES = 9,
429 CMD_TYPE_GET_CATTRS = 10,
430 CMD_TYPE_GET_FIELD_CATTRS = 11,
431 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
432 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
433 CMD_TYPE_GET_VALUES_2 = 14
437 CMD_STACK_FRAME_GET_VALUES = 1,
438 CMD_STACK_FRAME_GET_THIS = 2,
439 CMD_STACK_FRAME_SET_VALUES = 3
443 CMD_ARRAY_REF_GET_LENGTH = 1,
444 CMD_ARRAY_REF_GET_VALUES = 2,
445 CMD_ARRAY_REF_SET_VALUES = 3,
449 CMD_STRING_REF_GET_VALUE = 1,
453 CMD_OBJECT_REF_GET_TYPE = 1,
454 CMD_OBJECT_REF_GET_VALUES = 2,
455 CMD_OBJECT_REF_IS_COLLECTED = 3,
456 CMD_OBJECT_REF_GET_ADDRESS = 4,
457 CMD_OBJECT_REF_GET_DOMAIN = 5,
458 CMD_OBJECT_REF_SET_VALUES = 6
464 int count; /* For kind == MOD_KIND_COUNT */
465 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
466 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
467 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
469 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
478 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
482 * Describes a single step request.
486 MonoInternalThread *thread;
491 MonoMethod *last_method;
493 /* Whenever single stepping is performed using start/stop_single_stepping () */
495 /* The list of breakpoints used to implement step-over */
500 * Contains additional information for an event
503 /* For EVENT_KIND_EXCEPTION */
505 MonoContext catch_ctx;
509 /* Dummy structure used for the profiler callbacks */
514 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
520 static AgentConfig agent_config;
523 * Whenever the agent is fully initialized.
524 * When using the onuncaught or onthrow options, only some parts of the agent are
525 * initialized on startup, and the full initialization which includes connection
526 * establishment and the startup of the agent thread is only done in response to
529 static gint32 inited;
532 static int listen_fd;
534 static int packet_id = 0;
536 static int objref_id = 0;
538 static int event_request_id = 0;
540 static int frame_id = 0;
542 static GPtrArray *event_requests;
544 static guint32 debugger_tls_id;
546 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
548 /* Maps MonoInternalThread -> DebuggerTlsData */
549 static MonoGHashTable *thread_to_tls;
551 /* Maps tid -> MonoInternalThread */
552 static MonoGHashTable *tid_to_thread;
554 /* Maps tid -> MonoThread (not MonoInternalThread) */
555 static MonoGHashTable *tid_to_thread_obj;
557 static gsize debugger_thread_id;
559 static HANDLE debugger_thread_handle;
561 static int log_level;
563 static gboolean embedding;
565 static FILE *log_file;
567 /* Assemblies whose assembly load event has no been sent yet */
568 static GPtrArray *pending_assembly_loads;
570 /* Whenever the debugger thread has exited */
571 static gboolean debugger_thread_exited;
573 /* Cond variable used to wait for debugger_thread_exited becoming true */
574 static mono_cond_t debugger_thread_exited_cond;
576 /* Mutex for the cond var above */
577 static mono_mutex_t debugger_thread_exited_mutex;
579 static DebuggerProfiler debugger_profiler;
581 /* The single step request instance */
582 static SingleStepReq *ss_req = NULL;
583 static gpointer ss_invoke_addr = NULL;
585 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
586 /* Number of single stepping operations in progress */
590 /* The protocol version of the client */
591 static int major_version, minor_version;
593 /* Whenever the variables above are set by the client */
594 static gboolean protocol_version_set;
596 /* A hash table containing all active domains */
597 static GHashTable *domains;
599 static void transport_connect (const char *host, int port);
601 static guint32 WINAPI debugger_thread (void *arg);
603 static void runtime_initialized (MonoProfiler *prof);
605 static void runtime_shutdown (MonoProfiler *prof);
607 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
609 static void thread_end (MonoProfiler *prof, uintptr_t tid);
611 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
613 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
615 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
617 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
619 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
621 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
623 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
625 static void emit_assembly_load (gpointer assembly, gpointer user_data);
627 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
629 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
631 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
633 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
635 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
637 static void start_single_stepping (void);
639 static void stop_single_stepping (void);
641 static void suspend_current (void);
643 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
645 static void clear_types_for_assembly (MonoAssembly *assembly);
647 static void clear_breakpoints_for_domain (MonoDomain *domain);
649 static void process_profiler_event (EventKind event, gpointer arg);
651 /* Submodule init/cleanup */
652 static void breakpoints_init (void);
653 static void breakpoints_cleanup (void);
655 static void objrefs_init (void);
656 static void objrefs_cleanup (void);
658 static void ids_init (void);
659 static void ids_cleanup (void);
661 static void suspend_init (void);
663 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
664 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
665 static void ss_destroy (SingleStepReq *req);
667 static void start_debugger_thread (void);
668 static void stop_debugger_thread (void);
670 static void finish_agent_init (gboolean on_startup);
673 parse_address (char *address, char **host, int *port)
675 char *pos = strchr (address, ':');
677 if (pos == NULL || pos == address)
680 *host = g_malloc (pos - address + 1);
681 strncpy (*host, address, pos - address);
682 (*host) [pos - address] = '\0';
684 *port = atoi (pos + 1);
692 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
693 fprintf (stderr, "Available options:\n");
694 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
695 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
696 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
697 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
698 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
699 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
700 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
701 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
705 parse_flag (const char *option, char *flag)
707 if (!strcmp (flag, "y"))
709 else if (!strcmp (flag, "n"))
712 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
719 mono_debugger_agent_parse_options (char *options)
725 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
726 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
730 agent_config.enabled = TRUE;
731 agent_config.suspend = TRUE;
732 agent_config.server = FALSE;
733 agent_config.defer = FALSE;
734 agent_config.address = NULL;
736 args = g_strsplit (options, ",", -1);
737 for (ptr = args; ptr && *ptr; ptr ++) {
740 if (strncmp (arg, "transport=", 10) == 0) {
741 agent_config.transport = g_strdup (arg + 10);
742 } else if (strncmp (arg, "address=", 8) == 0) {
743 agent_config.address = g_strdup (arg + 8);
744 } else if (strncmp (arg, "loglevel=", 9) == 0) {
745 agent_config.log_level = atoi (arg + 9);
746 } else if (strncmp (arg, "logfile=", 8) == 0) {
747 agent_config.log_file = g_strdup (arg + 8);
748 } else if (strncmp (arg, "suspend=", 8) == 0) {
749 agent_config.suspend = parse_flag ("suspend", arg + 8);
750 } else if (strncmp (arg, "server=", 7) == 0) {
751 agent_config.server = parse_flag ("server", arg + 7);
752 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
753 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
754 } else if (strncmp (arg, "onthrow=", 8) == 0) {
755 /* We support multiple onthrow= options */
756 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
757 } else if (strncmp (arg, "onthrow", 7) == 0) {
758 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
759 } else if (strncmp (arg, "help", 4) == 0) {
762 } else if (strncmp (arg, "timeout=", 8) == 0) {
763 agent_config.timeout = atoi (arg + 8);
764 } else if (strncmp (arg, "launch=", 7) == 0) {
765 agent_config.launch = g_strdup (arg + 7);
766 } else if (strncmp (arg, "embedding=", 10) == 0) {
767 agent_config.embedding = atoi (arg + 10) == 1;
774 if (agent_config.server && !agent_config.suspend) {
775 /* Waiting for deferred attachment */
776 agent_config.defer = TRUE;
777 if (agent_config.address == NULL) {
778 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
782 if (agent_config.transport == NULL) {
783 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
786 if (strcmp (agent_config.transport, "dt_socket") != 0) {
787 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
791 if (agent_config.address == NULL && !agent_config.server) {
792 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
796 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
797 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
803 mono_debugger_agent_init (void)
805 if (!agent_config.enabled)
808 /* Need to know whenever a thread has acquired the loader mutex */
809 mono_loader_lock_track_ownership (TRUE);
811 event_requests = g_ptr_array_new ();
813 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
814 mono_cond_init (&debugger_thread_exited_cond, NULL);
816 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
817 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
818 mono_profiler_install_runtime_initialized (runtime_initialized);
819 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
820 mono_profiler_install_thread (thread_startup, thread_end);
821 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
822 mono_profiler_install_jit_end (jit_end);
823 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
825 debugger_tls_id = TlsAlloc ();
827 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
828 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
830 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
831 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
833 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
834 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
836 pending_assembly_loads = g_ptr_array_new ();
837 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
839 log_level = agent_config.log_level;
841 embedding = agent_config.embedding;
844 if (agent_config.log_file) {
845 log_file = fopen (agent_config.log_file, "w+");
847 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
859 mini_get_debug_options ()->gen_seq_points = TRUE;
861 * This is needed because currently we don't handle liveness info.
863 mini_get_debug_options ()->mdb_optimizations = TRUE;
865 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
866 /* This is needed because we can't set local variables in registers yet */
867 mono_disable_optimizations (MONO_OPT_LINEARS);
870 if (!agent_config.onuncaught && !agent_config.onthrow)
871 finish_agent_init (TRUE);
877 * Finish the initialization of the agent. This involves connecting the transport
878 * and starting the agent thread. This is either done at startup, or
879 * in response to some event like an unhandled exception.
882 finish_agent_init (gboolean on_startup)
888 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
891 if (agent_config.launch) {
894 // FIXME: Generated address
895 // FIXME: Races with transport_connect ()
897 argv [0] = agent_config.launch;
898 argv [1] = agent_config.transport;
899 argv [2] = agent_config.address;
902 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
904 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
909 if (agent_config.address) {
910 res = parse_address (agent_config.address, &host, &port);
917 transport_connect (host, port);
920 /* Do some which is usually done after sending the VMStart () event */
921 vm_start_event_sent = TRUE;
922 start_debugger_thread ();
927 mono_debugger_agent_cleanup (void)
932 stop_debugger_thread ();
934 breakpoints_cleanup ();
938 mono_mutex_destroy (&debugger_thread_exited_mutex);
939 mono_cond_destroy (&debugger_thread_exited_cond);
945 * recv() + handle incomplete reads and EINTR
948 recv_length (int fd, void *buf, int len, int flags)
954 res = recv (fd, (char *) buf + total, len - total, flags);
957 } while ((res > 0 && total < len) || (res == -1 && errno == EINTR));
962 #define HAVE_GETADDRINFO 1
966 transport_accept (int socket_fd)
968 conn_fd = accept (socket_fd, NULL, NULL);
970 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
972 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
979 transport_handshake (void)
981 char handshake_msg [128];
985 /* Write handshake message */
986 sprintf (handshake_msg, "DWP-Handshake");
988 res = send (conn_fd, handshake_msg, strlen (handshake_msg), 0);
989 } while (res == -1 && errno == EINTR);
990 g_assert (res != -1);
993 res = recv_length (conn_fd, buf, strlen (handshake_msg), 0);
994 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
995 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1000 * To support older clients, the client sends its protocol version after connecting
1001 * using a command. Until that is received, default to our protocol version.
1003 major_version = MAJOR_VERSION;
1004 minor_version = MINOR_VERSION;
1005 protocol_version_set = FALSE;
1008 * Set TCP_NODELAY on the socket so the client receives events/command
1009 * results immediately.
1013 int result = setsockopt (conn_fd,
1018 g_assert (result >= 0);
1025 * transport_connect:
1027 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1030 transport_connect (const char *host, int port)
1032 #ifdef HAVE_GETADDRINFO
1033 struct addrinfo hints;
1034 struct addrinfo *result, *rp;
1036 struct hostent *result;
1039 char port_string [128];
1045 sprintf (port_string, "%d", port);
1047 mono_network_init ();
1049 /* Obtain address(es) matching host/port */
1050 #ifdef HAVE_GETADDRINFO
1051 memset (&hints, 0, sizeof (struct addrinfo));
1052 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1053 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1055 hints.ai_protocol = 0; /* Any protocol */
1057 s = getaddrinfo (host, port_string, &hints, &result);
1059 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1063 /* The PS3 doesn't even have _r or hstrerror () */
1064 result = gethostbyname (host);
1066 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1071 if (agent_config.server) {
1072 #ifdef HAVE_GETADDRINFO
1073 /* Wait for a connection */
1075 struct sockaddr_in addr;
1078 /* No address, generate one */
1079 sfd = socket (AF_INET, SOCK_STREAM, 0);
1082 /* This will bind the socket to a random port */
1083 res = listen (sfd, 16);
1085 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
1090 addrlen = sizeof (addr);
1091 memset (&addr, 0, sizeof (addr));
1092 res = getsockname (sfd, &addr, &addrlen);
1093 g_assert (res == 0);
1096 port = ntohs (addr.sin_port);
1098 /* Emit the address to stdout */
1099 /* FIXME: Should print another interface, not localhost */
1100 printf ("%s:%d\n", host, port);
1102 /* Listen on the provided address */
1103 for (rp = result; rp != NULL; rp = rp->ai_next) {
1106 sfd = socket (rp->ai_family, rp->ai_socktype,
1111 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1114 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1118 res = listen (sfd, 16);
1127 * this function is not present on win2000 which we still support, and the
1128 * workaround described here:
1129 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1130 * only works with MSVC.
1132 #ifdef HAVE_GETADDRINFO
1133 freeaddrinfo (result);
1138 if (agent_config.defer)
1141 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1143 if (agent_config.timeout) {
1148 tv.tv_usec = agent_config.timeout * 1000;
1150 FD_SET (sfd, &readfds);
1151 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1153 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1158 conn_fd = transport_accept (sfd);
1162 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1165 #endif /* HAVE_GETADDRINFO */
1167 /* Connect to the specified address */
1168 #ifdef HAVE_GETADDRINFO
1169 /* FIXME: Respect the timeout */
1170 for (rp = result; rp != NULL; rp = rp->ai_next) {
1171 sfd = socket (rp->ai_family, rp->ai_socktype,
1176 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1177 break; /* Success */
1183 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1187 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1189 g_assert_not_reached ();
1190 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1192 g_assert_not_reached ();
1198 /* See the comment above */
1199 #ifdef HAVE_GETADDRINFO
1200 freeaddrinfo (result);
1205 disconnected = !transport_handshake ();
1211 transport_send (guint8 *data, int len)
1216 res = send (conn_fd, data, len, 0);
1217 } while (res == -1 && errno == EINTR);
1225 stop_debugger_thread (void)
1230 /* This will interrupt the agent thread */
1231 /* Close the read part only so it can still send back replies */
1232 /* Also shut down the connection listener so that we can exit normally */
1234 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1235 shutdown (conn_fd, SD_BOTH);
1236 shutdown (listen_fd, SD_BOTH);
1237 closesocket (listen_fd);
1239 shutdown (conn_fd, SHUT_RD);
1240 shutdown (listen_fd, SHUT_RDWR);
1245 * Wait for the thread to exit.
1247 * If we continue with the shutdown without waiting for it, then the client might
1248 * not receive an answer to its last command like a resume.
1249 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1252 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1253 if (GetCurrentThreadId () != debugger_thread_id) {
1255 mono_mutex_lock (&debugger_thread_exited_mutex);
1256 if (!debugger_thread_exited) {
1258 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1259 mono_mutex_unlock (&debugger_thread_exited_mutex);
1261 mono_mutex_lock (&debugger_thread_exited_mutex);
1264 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1267 mono_mutex_unlock (&debugger_thread_exited_mutex);
1268 } while (!debugger_thread_exited);
1272 shutdown (conn_fd, SD_BOTH);
1274 shutdown (conn_fd, SHUT_RDWR);
1279 start_debugger_thread (void)
1283 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1284 g_assert (debugger_thread_handle);
1288 * Functions to decode protocol data
1292 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1295 g_assert (*endbuf <= limit);
1300 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1303 g_assert (*endbuf <= limit);
1305 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1308 static inline gint64
1309 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1311 guint32 high = decode_int (buf, &buf, limit);
1312 guint32 low = decode_int (buf, &buf, limit);
1316 return ((((guint64)high) << 32) | ((guint64)low));
1320 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1322 return decode_int (buf, endbuf, limit);
1326 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1328 int len = decode_int (buf, &buf, limit);
1331 s = g_malloc (len + 1);
1334 memcpy (s, buf, len);
1343 * Functions to encode protocol data
1347 guint8 *buf, *p, *end;
1351 buffer_init (Buffer *buf, int size)
1353 buf->buf = g_malloc (size);
1355 buf->end = buf->buf + size;
1359 buffer_make_room (Buffer *buf, int size)
1361 if (buf->end - buf->p < size) {
1362 int new_size = buf->end - buf->buf + size + 32;
1363 guint8 *p = g_realloc (buf->buf, new_size);
1364 size = buf->p - buf->buf;
1367 buf->end = buf->buf + new_size;
1372 buffer_add_byte (Buffer *buf, guint8 val)
1374 buffer_make_room (buf, 1);
1380 buffer_add_int (Buffer *buf, guint32 val)
1382 buffer_make_room (buf, 4);
1383 buf->p [0] = (val >> 24) & 0xff;
1384 buf->p [1] = (val >> 16) & 0xff;
1385 buf->p [2] = (val >> 8) & 0xff;
1386 buf->p [3] = (val >> 0) & 0xff;
1391 buffer_add_long (Buffer *buf, guint64 l)
1393 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1394 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1398 buffer_add_id (Buffer *buf, int id)
1400 buffer_add_int (buf, (guint64)id);
1404 buffer_add_data (Buffer *buf, guint8 *data, int len)
1406 buffer_make_room (buf, len);
1407 memcpy (buf->p, data, len);
1412 buffer_add_string (Buffer *buf, const char *str)
1417 buffer_add_int (buf, 0);
1420 buffer_add_int (buf, len);
1421 buffer_add_data (buf, (guint8*)str, len);
1426 buffer_free (Buffer *buf)
1432 send_packet (int command_set, int command, Buffer *data)
1438 id = InterlockedIncrement (&packet_id);
1440 len = data->p - data->buf + 11;
1441 buffer_init (&buf, len);
1442 buffer_add_int (&buf, len);
1443 buffer_add_int (&buf, id);
1444 buffer_add_byte (&buf, 0); /* flags */
1445 buffer_add_byte (&buf, command_set);
1446 buffer_add_byte (&buf, command);
1447 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1449 res = transport_send (buf.buf, len);
1457 send_reply_packet (int id, int error, Buffer *data)
1463 len = data->p - data->buf + 11;
1464 buffer_init (&buf, len);
1465 buffer_add_int (&buf, len);
1466 buffer_add_int (&buf, id);
1467 buffer_add_byte (&buf, 0x80); /* flags */
1468 buffer_add_byte (&buf, (error >> 8) & 0xff);
1469 buffer_add_byte (&buf, error);
1470 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1472 res = transport_send (buf.buf, len);
1484 * Represents an object accessible by the debugger client.
1487 /* Unique id used in the wire protocol to refer to objects */
1490 * A weakref gc handle pointing to the object. The gc handle is used to
1491 * detect if the object was garbage collected.
1496 /* Maps objid -> ObjRef */
1497 static GHashTable *objrefs;
1500 free_objref (gpointer value)
1504 mono_gchandle_free (o->handle);
1512 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1516 objrefs_cleanup (void)
1518 g_hash_table_destroy (objrefs);
1522 static GHashTable *obj_to_objref;
1525 * Return an ObjRef for OBJ.
1528 get_objref (MonoObject *obj)
1531 GSList *reflist = NULL, *l;
1537 mono_loader_lock ();
1540 obj_to_objref = g_hash_table_new (NULL, NULL);
1542 /* FIXME: The tables can grow indefinitely */
1544 if (mono_gc_is_moving ()) {
1546 * Objects can move, so use a hash table mapping hash codes to lists of
1547 * ObjRef structures.
1549 hash = mono_object_hash (obj);
1551 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1552 for (l = reflist; l; l = l->next) {
1554 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1555 mono_loader_unlock ();
1560 /* Use a hash table with masked pointers to internalize object references */
1561 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1562 /* ref might refer to a different object with the same addr which was GCd */
1563 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1564 mono_loader_unlock ();
1569 ref = g_new0 (ObjRef, 1);
1570 ref->id = InterlockedIncrement (&objref_id);
1571 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1573 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1575 if (mono_gc_is_moving ()) {
1576 reflist = g_slist_append (reflist, ref);
1577 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1579 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1582 mono_loader_unlock ();
1588 get_objid (MonoObject *obj)
1590 return get_objref (obj)->id;
1594 * Set OBJ to the object identified by OBJID.
1595 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1599 get_object_allow_null (int objid, MonoObject **obj)
1609 return ERR_INVALID_OBJECT;
1611 mono_loader_lock ();
1613 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1616 *obj = mono_gchandle_get_target (ref->handle);
1617 mono_loader_unlock ();
1619 return ERR_INVALID_OBJECT;
1622 mono_loader_unlock ();
1623 return ERR_INVALID_OBJECT;
1628 get_object (int objid, MonoObject **obj)
1630 int err = get_object_allow_null (objid, obj);
1635 return ERR_INVALID_OBJECT;
1640 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1642 return decode_id (buf, endbuf, limit);
1646 buffer_add_objid (Buffer *buf, MonoObject *o)
1648 buffer_add_id (buf, get_objid (o));
1667 * Represents a runtime structure accessible to the debugger client
1670 /* Unique id used in the wire protocol */
1672 /* Domain of the runtime structure, NULL if the domain was unloaded */
1679 MonoAssembly *assembly;
1680 MonoClassField *field;
1682 MonoProperty *property;
1687 /* Maps runtime structure -> Id */
1688 GHashTable *val_to_id [ID_NUM];
1689 /* Classes whose class load event has been sent */
1690 GHashTable *loaded_classes;
1694 static GPtrArray *ids [ID_NUM];
1701 for (i = 0; i < ID_NUM; ++i)
1702 ids [i] = g_ptr_array_new ();
1710 for (i = 0; i < ID_NUM; ++i) {
1712 for (j = 0; j < ids [i]->len; ++j)
1713 g_free (g_ptr_array_index (ids [i], j));
1714 g_ptr_array_free (ids [i], TRUE);
1721 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1723 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1727 for (i = 0; i < ID_NUM; ++i)
1728 if (info->val_to_id [i])
1729 g_hash_table_destroy (info->val_to_id [i]);
1730 g_hash_table_destroy (info->loaded_classes);
1734 domain_jit_info (domain)->agent_info = NULL;
1736 /* Clear ids referencing structures in the domain */
1737 for (i = 0; i < ID_NUM; ++i) {
1739 for (j = 0; j < ids [i]->len; ++j) {
1740 Id *id = g_ptr_array_index (ids [i], j);
1741 if (id->domain == domain)
1747 mono_loader_lock ();
1748 g_hash_table_remove (domains, domain);
1749 mono_loader_unlock ();
1753 * Called when deferred debugger session is attached,
1754 * after the VM start event has been sent successfully
1757 mono_debugger_agent_on_attach (void)
1759 /* Emit load events for currently loaded appdomains, assemblies, and types */
1760 mono_loader_lock ();
1761 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
1762 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
1763 mono_assembly_foreach (emit_assembly_load, NULL);
1764 mono_loader_unlock ();
1767 static AgentDomainInfo*
1768 get_agent_domain_info (MonoDomain *domain)
1770 AgentDomainInfo *info = NULL;
1772 mono_domain_lock (domain);
1774 info = domain_jit_info (domain)->agent_info;
1776 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1777 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
1780 mono_domain_unlock (domain);
1786 get_id (MonoDomain *domain, IdType type, gpointer val)
1789 AgentDomainInfo *info;
1794 mono_loader_lock ();
1796 mono_domain_lock (domain);
1798 info = get_agent_domain_info (domain);
1800 if (info->val_to_id [type] == NULL)
1801 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1803 id = g_hash_table_lookup (info->val_to_id [type], val);
1805 mono_domain_unlock (domain);
1806 mono_loader_unlock ();
1810 id = g_new0 (Id, 1);
1812 id->id = ids [type]->len + 1;
1813 id->domain = domain;
1816 g_hash_table_insert (info->val_to_id [type], val, id);
1818 mono_domain_unlock (domain);
1820 g_ptr_array_add (ids [type], id);
1822 mono_loader_unlock ();
1827 static inline gpointer
1828 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1832 int id = decode_id (buf, endbuf, limit);
1841 // FIXME: error handling
1842 mono_loader_lock ();
1843 g_assert (id > 0 && id <= ids [type]->len);
1845 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1846 mono_loader_unlock ();
1848 if (res->domain == NULL) {
1849 *err = ERR_UNLOADED;
1854 *domain = res->domain;
1856 return res->data.val;
1860 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1862 buffer_add_id (buf, get_id (domain, type, val));
1865 static inline MonoClass*
1866 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1868 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1871 static inline MonoAssembly*
1872 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1874 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1877 static inline MonoImage*
1878 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1880 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1883 static inline MonoMethod*
1884 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1886 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1889 static inline MonoClassField*
1890 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1892 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1895 static inline MonoDomain*
1896 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1898 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1901 static inline MonoProperty*
1902 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1904 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1908 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1910 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1914 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1916 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1920 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1922 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1926 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1928 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1932 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1934 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1938 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1940 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1944 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1946 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1949 static void invoke_method (void);
1956 * save_thread_context:
1958 * Set CTX as the current threads context which is used for computing stack traces.
1959 * This function is signal-safe.
1962 save_thread_context (MonoContext *ctx)
1964 DebuggerTlsData *tls;
1966 tls = TlsGetValue (debugger_tls_id);
1970 mono_thread_state_init_from_monoctx (&tls->context, ctx);
1972 mono_thread_state_init_from_current (&tls->context);
1975 /* The number of times the runtime is suspended */
1976 static gint32 suspend_count;
1978 /* Number of threads suspended */
1980 * If this is equal to the size of thread_to_tls, the runtime is considered
1983 static gint32 threads_suspend_count;
1985 static mono_mutex_t suspend_mutex;
1987 /* Cond variable used to wait for suspend_count becoming 0 */
1988 static mono_cond_t suspend_cond;
1990 /* Semaphore used to wait for a thread becoming suspended */
1991 static MonoSemType suspend_sem;
1996 mono_mutex_init (&suspend_mutex, NULL);
1997 mono_cond_init (&suspend_cond, NULL);
1998 MONO_SEM_INIT (&suspend_sem, 0);
2003 StackFrameInfo last_frame;
2004 gboolean last_frame_set;
2007 } GetLastFrameUserData;
2010 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2012 GetLastFrameUserData *data = user_data;
2014 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2017 if (!data->last_frame_set) {
2018 /* Store the last frame */
2019 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2020 data->last_frame_set = TRUE;
2023 /* Store the context/lmf for the frame above the last frame */
2024 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2025 data->lmf = info->lmf;
2032 * mono_debugger_agent_thread_interrupt:
2034 * Called by the abort signal handler.
2035 * Should be signal safe.
2038 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2040 DebuggerTlsData *tls;
2045 tls = TlsGetValue (debugger_tls_id);
2050 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2051 * guarantee the signal handler will be called that many times. Instead of tracking
2052 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2053 * has been requested that hasn't been handled yet, otherwise we can have threads
2054 * refuse to die when VM_EXIT is called
2056 #if defined(__APPLE__)
2057 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2061 * We use interrupt_count to determine whenever this interrupt should be processed
2062 * by us or the normal interrupt processing code in the signal handler.
2063 * There is no race here with notify_thread (), since the signal is sent after
2064 * incrementing interrupt_count.
2066 if (tls->interrupt_count == 0)
2069 InterlockedDecrement (&tls->interrupt_count);
2072 // FIXME: Races when the thread leaves managed code before hitting a single step
2076 /* Running managed code, will be suspended by the single step code */
2077 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)GetCurrentThreadId (), ji->method->name, mono_arch_ip_from_context (sigctx)));
2081 * Running native code, will be suspended when it returns to/enters
2082 * managed code. Treat it as already suspended.
2083 * This might interrupt the code in process_single_step_inner (), we use the
2084 * tls->suspending flag to avoid races when that happens.
2086 if (!tls->suspended && !tls->suspending) {
2088 GetLastFrameUserData data;
2090 // FIXME: printf is not signal safe, but this is only used during
2091 // debugger debugging
2093 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)GetCurrentThreadId (), mono_arch_ip_from_context (sigctx)));
2094 //save_thread_context (&ctx);
2097 /* Already terminated */
2101 * We are in a difficult position: we want to be able to provide stack
2102 * traces for this thread, but we can't use the current ctx+lmf, since
2103 * the thread is still running, so it might return to managed code,
2104 * making these invalid.
2105 * So we start a stack walk and save the first frame, along with the
2106 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2107 * suspended when it returns to managed code, so the parent's ctx should
2110 data.last_frame_set = FALSE;
2112 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2113 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_DEFAULT, &data);
2115 if (data.last_frame_set) {
2116 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2117 g_assert (mono_thread_state_init_from_monoctx (&tls->async_state, sigctx));
2118 g_assert (mono_thread_state_init_from_monoctx (&tls->context, sigctx));
2120 tls->async_state.valid = FALSE;
2123 mono_memory_barrier ();
2125 tls->suspended = TRUE;
2126 MONO_SEM_POST (&suspend_sem);
2133 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2136 mono_debugger_agent_thread_interrupt (NULL, NULL);
2138 #endif /* HOST_WIN32 */
2141 * reset_native_thread_suspend_state:
2143 * Reset the suspended flag on native threads
2146 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2148 DebuggerTlsData *tls = value;
2150 if (!tls->really_suspended && tls->suspended)
2151 tls->suspended = FALSE;
2157 * Notify a thread that it needs to suspend.
2160 notify_thread (gpointer key, gpointer value, gpointer user_data)
2162 MonoInternalThread *thread = key;
2163 DebuggerTlsData *tls = value;
2164 gsize tid = thread->tid;
2166 if (GetCurrentThreadId () == tid || tls->terminated)
2169 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2172 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2173 * guarantee the signal handler will be called that many times. Instead of tracking
2174 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2175 * has been requested that hasn't been handled yet, otherwise we can have threads
2176 * refuse to die when VM_EXIT is called
2178 #if defined(__APPLE__)
2179 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2183 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2184 * of things like breaking waits etc. which we don't want.
2186 InterlockedIncrement (&tls->interrupt_count);
2189 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2191 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2193 mono_thread_kill (thread, mono_thread_get_abort_signal ());
2198 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2200 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2203 if (mono_loader_lock_is_owned_by_self ()) {
2205 * Shortcut for the check in suspend_current (). This speeds up processing
2206 * when executing long running code inside the loader lock, i.e. assembly load
2212 if (debugger_thread_id == GetCurrentThreadId ())
2215 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2216 if (suspend_count - tls->resume_count > 0)
2217 tls->suspending = TRUE;
2219 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2221 if (suspend_count - tls->resume_count == 0) {
2223 * We are executing a single threaded invoke but the single step for
2224 * suspending is still active.
2225 * FIXME: This slows down single threaded invokes.
2227 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2231 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2233 /* Can't suspend in these methods */
2234 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2237 save_thread_context (ctx);
2245 * Increase the suspend count of the VM. While the suspend count is greater
2246 * than 0, runtime threads are suspended at certain points during execution.
2251 mono_loader_lock ();
2253 mono_mutex_lock (&suspend_mutex);
2257 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2259 if (suspend_count == 1) {
2260 // FIXME: Is it safe to call this inside the lock ?
2261 start_single_stepping ();
2262 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2265 mono_mutex_unlock (&suspend_mutex);
2267 mono_loader_unlock ();
2273 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2281 g_assert (debugger_thread_id == GetCurrentThreadId ());
2283 mono_loader_lock ();
2285 mono_mutex_lock (&suspend_mutex);
2287 g_assert (suspend_count > 0);
2290 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2292 if (suspend_count == 0) {
2293 // FIXME: Is it safe to call this inside the lock ?
2294 stop_single_stepping ();
2295 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2298 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2299 err = mono_cond_broadcast (&suspend_cond);
2300 g_assert (err == 0);
2302 mono_mutex_unlock (&suspend_mutex);
2303 //g_assert (err == 0);
2305 mono_loader_unlock ();
2311 * Resume just one thread.
2314 resume_thread (MonoInternalThread *thread)
2317 DebuggerTlsData *tls;
2319 g_assert (debugger_thread_id == GetCurrentThreadId ());
2321 mono_loader_lock ();
2323 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2326 mono_mutex_lock (&suspend_mutex);
2328 g_assert (suspend_count > 0);
2330 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2332 tls->resume_count += suspend_count;
2335 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2336 * but only the one whose resume_count field is > 0 will be resumed.
2338 err = mono_cond_broadcast (&suspend_cond);
2339 g_assert (err == 0);
2341 mono_mutex_unlock (&suspend_mutex);
2342 //g_assert (err == 0);
2344 mono_loader_unlock ();
2348 invalidate_frames (DebuggerTlsData *tls)
2353 tls = TlsGetValue (debugger_tls_id);
2356 for (i = 0; i < tls->frame_count; ++i) {
2357 if (tls->frames [i]->jit)
2358 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2359 g_free (tls->frames [i]);
2361 g_free (tls->frames);
2362 tls->frame_count = 0;
2369 * Suspend the current thread until the runtime is resumed. If the thread has a
2370 * pending invoke, then the invoke is executed before this function returns.
2373 suspend_current (void)
2376 DebuggerTlsData *tls;
2378 g_assert (debugger_thread_id != GetCurrentThreadId ());
2380 if (mono_loader_lock_is_owned_by_self ()) {
2382 * If we own the loader mutex, can't suspend until we release it, since the
2383 * whole runtime can deadlock otherwise.
2388 tls = TlsGetValue (debugger_tls_id);
2391 mono_mutex_lock (&suspend_mutex);
2393 tls->suspending = FALSE;
2394 tls->really_suspended = TRUE;
2396 if (!tls->suspended) {
2397 tls->suspended = TRUE;
2398 MONO_SEM_POST (&suspend_sem);
2401 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2403 while (suspend_count - tls->resume_count > 0) {
2405 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2407 mono_mutex_unlock (&suspend_mutex);
2409 mono_mutex_lock (&suspend_mutex);
2415 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2416 g_assert (err == 0);
2420 tls->suspended = FALSE;
2421 tls->really_suspended = FALSE;
2423 threads_suspend_count --;
2425 mono_mutex_unlock (&suspend_mutex);
2427 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2429 if (tls->pending_invoke) {
2430 /* Save the original context */
2431 tls->pending_invoke->has_ctx = TRUE;
2432 tls->pending_invoke->ctx = tls->context.ctx;
2437 /* The frame info becomes invalid after a resume */
2438 tls->context.valid = FALSE;
2439 tls->async_state.valid = FALSE;
2440 invalidate_frames (NULL);
2444 count_thread (gpointer key, gpointer value, gpointer user_data)
2446 DebuggerTlsData *tls = value;
2448 if (!tls->suspended && !tls->terminated)
2449 *(int*)user_data = *(int*)user_data + 1;
2453 count_threads_to_wait_for (void)
2457 mono_loader_lock ();
2458 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2459 mono_loader_unlock ();
2467 * Wait until the runtime is completely suspended.
2470 wait_for_suspend (void)
2472 int nthreads, nwait, err;
2473 gboolean waited = FALSE;
2475 // FIXME: Threads starting/stopping ?
2476 mono_loader_lock ();
2477 nthreads = mono_g_hash_table_size (thread_to_tls);
2478 mono_loader_unlock ();
2481 nwait = count_threads_to_wait_for ();
2483 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2484 err = MONO_SEM_WAIT (&suspend_sem);
2485 g_assert (err == 0);
2493 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2499 * Return whenever the runtime is suspended.
2504 return count_threads_to_wait_for () == 0;
2508 * find_seq_point_for_native_offset:
2510 * Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2511 * should be the location of a sequence point.
2514 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2516 MonoSeqPointInfo *seq_points;
2519 mono_domain_lock (domain);
2520 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2521 mono_domain_unlock (domain);
2522 g_assert (seq_points);
2526 for (i = 0; i < seq_points->len; ++i) {
2527 if (seq_points->seq_points [i].native_offset == native_offset)
2528 return &seq_points->seq_points [i];
2535 * find_next_seq_point_for_native_offset:
2537 * Find the first sequence point after NATIVE_OFFSET.
2540 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2542 MonoSeqPointInfo *seq_points;
2545 mono_domain_lock (domain);
2546 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2547 mono_domain_unlock (domain);
2548 g_assert (seq_points);
2552 for (i = 0; i < seq_points->len; ++i) {
2553 if (seq_points->seq_points [i].native_offset >= native_offset)
2554 return &seq_points->seq_points [i];
2561 * find_prev_seq_point_for_native_offset:
2563 * Find the first sequence point before NATIVE_OFFSET.
2566 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2568 MonoSeqPointInfo *seq_points;
2571 mono_domain_lock (domain);
2572 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2573 mono_domain_unlock (domain);
2574 g_assert (seq_points);
2578 for (i = seq_points->len - 1; i >= 0; --i) {
2579 if (seq_points->seq_points [i].native_offset <= native_offset)
2580 return &seq_points->seq_points [i];
2589 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2590 * should be the location of a sequence point.
2593 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2595 MonoSeqPointInfo *seq_points;
2598 mono_domain_lock (domain);
2599 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2600 mono_domain_unlock (domain);
2601 g_assert (seq_points);
2605 for (i = 0; i < seq_points->len; ++i) {
2606 if (seq_points->seq_points [i].il_offset == il_offset)
2607 return &seq_points->seq_points [i];
2614 * compute_il_offset:
2616 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2617 * a location of a sequence point.
2618 * We use this function instead of mono_debug_il_offset_from_address () etc,
2619 * which doesn't seem to work in a lot of cases.
2622 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2624 MonoSeqPointInfo *seq_points;
2625 int i, last_il_offset, seq_il_offset, seq_native_offset;
2627 mono_domain_lock (domain);
2628 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2629 mono_domain_unlock (domain);
2630 g_assert (seq_points);
2632 last_il_offset = -1;
2634 /* Find the sequence point */
2635 for (i = 0; i < seq_points->len; ++i) {
2636 seq_il_offset = seq_points->seq_points [i].il_offset;
2637 seq_native_offset = seq_points->seq_points [i].native_offset;
2639 if (seq_native_offset > native_offset)
2641 last_il_offset = seq_il_offset;
2644 return last_il_offset;
2648 DebuggerTlsData *tls;
2650 } ComputeFramesUserData;
2653 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2655 ComputeFramesUserData *ud = user_data;
2657 MonoMethod *method, *actual_method;
2659 if (info->type != FRAME_TYPE_MANAGED) {
2660 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2661 /* Mark the last frame as an invoke frame */
2663 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2669 method = info->ji->method;
2671 method = info->method;
2672 actual_method = info->actual_method;
2674 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2677 if (info->il_offset == -1) {
2678 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2679 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2682 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));
2684 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2686 * mono_arch_find_jit_info () returns the context stored in the LMF for
2687 * native frames, but it should unwind once. This is why we have duplicate
2688 * frames on the stack sometimes.
2689 * !managed also seems to be set for dynamic methods.
2694 frame = g_new0 (StackFrame, 1);
2695 frame->method = method;
2696 frame->actual_method = actual_method;
2697 frame->il_offset = info->il_offset;
2698 frame->native_offset = info->native_offset;
2699 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
2702 frame->has_ctx = TRUE;
2704 frame->domain = info->domain;
2706 ud->frames = g_slist_append (ud->frames, frame);
2712 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2714 ComputeFramesUserData *ud = user_data;
2717 * 'tls->filter_ctx' is the location of the throw site.
2719 * mono_walk_stack() will never actually hit the throw site, but unwind
2720 * directly from the filter to the call site; we abort stack unwinding here
2721 * once this happens and resume from the throw site.
2724 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
2727 return process_frame (info, ctx, user_data);
2731 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2733 ComputeFramesUserData user_data;
2735 int i, findex, new_frame_count;
2736 StackFrame **new_frames, *f;
2737 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
2739 // FIXME: Locking on tls
2740 if (tls->frames && tls->frames_up_to_date)
2743 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2745 user_data.tls = tls;
2746 user_data.frames = NULL;
2747 if (tls->terminated) {
2748 tls->frame_count = 0;
2750 } if (!tls->really_suspended && tls->async_state.valid) {
2751 /* Have to use the state saved by the signal handler */
2752 process_frame (&tls->async_last_frame, NULL, &user_data);
2753 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
2754 } else if (tls->filter_state.valid) {
2756 * We are inside an exception filter.
2758 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
2760 if (tls->context.valid)
2761 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
2763 * After that, we resume unwinding from the location where the exception has been thrown.
2765 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
2766 } else if (tls->context.valid) {
2767 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
2770 tls->frame_count = 0;
2774 new_frame_count = g_slist_length (user_data.frames);
2775 new_frames = g_new0 (StackFrame*, new_frame_count);
2777 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2781 * Reuse the id for already existing stack frames, so invokes don't invalidate
2782 * the still valid stack frames.
2784 for (i = 0; i < tls->frame_count; ++i) {
2785 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2786 f->id = tls->frames [i]->id;
2791 if (i >= tls->frame_count)
2792 f->id = InterlockedIncrement (&frame_id);
2794 new_frames [findex ++] = f;
2797 g_slist_free (user_data.frames);
2799 invalidate_frames (tls);
2801 tls->frames = new_frames;
2802 tls->frame_count = new_frame_count;
2803 tls->frames_up_to_date = TRUE;
2807 * GHFunc to emit an appdomain creation event
2808 * @param key Don't care
2809 * @param value A loaded appdomain
2810 * @param user_data Don't care
2813 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
2815 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
2816 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
2820 * GHFunc to emit a thread start event
2821 * @param key A thread id
2822 * @param value A thread object
2823 * @param user_data Don't care
2826 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
2828 if (GPOINTER_TO_INT (key) != debugger_thread_id)
2829 process_profiler_event (EVENT_KIND_THREAD_START, value);
2833 * GFunc to emit an assembly load event
2834 * @param value A loaded assembly
2835 * @param user_data Don't care
2838 emit_assembly_load (gpointer value, gpointer user_data)
2840 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
2844 * GFunc to emit a type load event
2845 * @param value A loaded type
2846 * @param user_data Don't care
2849 emit_type_load (gpointer key, gpointer value, gpointer user_data)
2851 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
2860 * create_event_list:
2862 * Return a list of event request ids matching EVENT, starting from REQS, which
2863 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2865 * We return request ids, instead of requests, to simplify threading, since
2866 * requests could be deleted anytime when the loader lock is not held.
2867 * LOCKING: Assumes the loader lock is held.
2870 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
2873 GSList *events = NULL;
2875 *suspend_policy = SUSPEND_POLICY_NONE;
2878 reqs = event_requests;
2883 for (i = 0; i < reqs->len; ++i) {
2884 EventRequest *req = g_ptr_array_index (reqs, i);
2885 if (req->event_kind == event) {
2886 gboolean filtered = FALSE;
2889 for (j = 0; j < req->nmodifiers; ++j) {
2890 Modifier *mod = &req->modifiers [j];
2892 if (mod->kind == MOD_KIND_COUNT) {
2894 if (mod->data.count > 0) {
2895 if (mod->data.count > 0) {
2897 if (mod->data.count == 0)
2901 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2902 if (mod->data.thread != mono_thread_internal_current ())
2904 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
2905 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
2907 if (ei->caught && !mod->caught)
2909 if (!ei->caught && !mod->uncaught)
2911 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2913 gboolean found = FALSE;
2914 MonoAssembly **assemblies = mod->data.assemblies;
2917 for (k = 0; assemblies [k]; ++k)
2918 if (assemblies [k] == ji->method->klass->image->assembly)
2927 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2928 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2933 /* Send a VM START/DEATH event by default */
2934 if (event == EVENT_KIND_VM_START)
2935 events = g_slist_append (events, GINT_TO_POINTER (0));
2936 if (event == EVENT_KIND_VM_DEATH)
2937 events = g_slist_append (events, GINT_TO_POINTER (0));
2942 static G_GNUC_UNUSED const char*
2943 event_to_string (EventKind event)
2946 case EVENT_KIND_VM_START: return "VM_START";
2947 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2948 case EVENT_KIND_THREAD_START: return "THREAD_START";
2949 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2950 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2951 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2952 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2953 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2954 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2955 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2956 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2957 case EVENT_KIND_STEP: return "STEP";
2958 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2959 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2961 g_assert_not_reached ();
2968 * Send an event to the client, suspending the vm if needed.
2969 * LOCKING: Since this can suspend the calling thread, no locks should be held
2971 * The EVENTS list is freed by this function.
2974 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2978 MonoDomain *domain = mono_domain_get ();
2979 MonoThread *thread = NULL;
2980 gboolean send_success = FALSE;
2983 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
2987 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
2988 // FIXME: We miss those events
2989 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
2993 if (vm_death_event_sent) {
2994 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
2998 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
2999 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3004 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3011 if (agent_config.defer) {
3012 /* Make sure the thread id is always set when doing deferred debugging */
3013 if (debugger_thread_id == GetCurrentThreadId ())
3014 thread = mono_thread_get_main ();
3015 else thread = mono_thread_current ();
3017 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3018 // FIXME: Send these with a NULL thread, don't suspend the current thread
3022 buffer_init (&buf, 128);
3023 buffer_add_byte (&buf, suspend_policy);
3024 buffer_add_int (&buf, g_slist_length (events)); // n of events
3026 for (l = events; l; l = l->next) {
3027 buffer_add_byte (&buf, event); // event kind
3028 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3031 thread = mono_thread_current ();
3033 if (event == EVENT_KIND_VM_START && arg != NULL)
3036 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3039 case EVENT_KIND_THREAD_START:
3040 case EVENT_KIND_THREAD_DEATH:
3042 case EVENT_KIND_APPDOMAIN_CREATE:
3043 case EVENT_KIND_APPDOMAIN_UNLOAD:
3044 buffer_add_domainid (&buf, arg);
3046 case EVENT_KIND_METHOD_ENTRY:
3047 case EVENT_KIND_METHOD_EXIT:
3048 buffer_add_methodid (&buf, domain, arg);
3050 case EVENT_KIND_ASSEMBLY_LOAD:
3051 case EVENT_KIND_ASSEMBLY_UNLOAD:
3052 buffer_add_assemblyid (&buf, domain, arg);
3054 case EVENT_KIND_TYPE_LOAD:
3055 buffer_add_typeid (&buf, domain, arg);
3057 case EVENT_KIND_BREAKPOINT:
3058 case EVENT_KIND_STEP:
3059 buffer_add_methodid (&buf, domain, arg);
3060 buffer_add_long (&buf, il_offset);
3062 case EVENT_KIND_VM_START:
3063 buffer_add_domainid (&buf, mono_get_root_domain ());
3065 case EVENT_KIND_VM_DEATH:
3067 case EVENT_KIND_EXCEPTION: {
3068 EventInfo *ei = arg;
3069 buffer_add_objid (&buf, ei->exc);
3073 g_assert_not_reached ();
3077 if (event == EVENT_KIND_VM_START) {
3078 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3079 if (!agent_config.defer)
3080 start_debugger_thread ();
3083 if (event == EVENT_KIND_VM_DEATH) {
3084 vm_death_event_sent = TRUE;
3085 suspend_policy = SUSPEND_POLICY_NONE;
3088 if (mono_runtime_is_shutting_down ())
3089 suspend_policy = SUSPEND_POLICY_NONE;
3091 if (suspend_policy != SUSPEND_POLICY_NONE) {
3093 * Save the thread context and start suspending before sending the packet,
3094 * since we could be receiving the resume request before send_packet ()
3097 save_thread_context (ctx);
3101 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3105 g_slist_free (events);
3108 if (!send_success) {
3109 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3113 if (event == EVENT_KIND_VM_START) {
3114 vm_start_event_sent = TRUE;
3115 if (agent_config.defer)
3116 mono_debugger_agent_on_attach ();
3119 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
3122 switch (suspend_policy) {
3123 case SUSPEND_POLICY_NONE:
3125 case SUSPEND_POLICY_ALL:
3128 case SUSPEND_POLICY_EVENT_THREAD:
3132 g_assert_not_reached ();
3137 process_profiler_event (EventKind event, gpointer arg)
3142 mono_loader_lock ();
3143 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
3144 mono_loader_unlock ();
3146 process_event (event, arg, 0, NULL, events, suspend_policy);
3150 runtime_initialized (MonoProfiler *prof)
3152 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3153 if (agent_config.defer)
3154 start_debugger_thread ();
3158 runtime_shutdown (MonoProfiler *prof)
3160 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3162 mono_debugger_agent_cleanup ();
3166 thread_startup (MonoProfiler *prof, uintptr_t tid)
3168 MonoInternalThread *thread = mono_thread_internal_current ();
3169 MonoInternalThread *old_thread;
3170 DebuggerTlsData *tls;
3172 if (tid == debugger_thread_id)
3175 g_assert (thread->tid == tid);
3177 mono_loader_lock ();
3178 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3179 mono_loader_unlock ();
3181 if (thread == old_thread) {
3183 * For some reason, thread_startup () might be called for the same thread
3184 * multiple times (attach ?).
3186 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3190 * thread_end () might not be called for some threads, and the tid could
3193 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3194 mono_loader_lock ();
3195 mono_g_hash_table_remove (thread_to_tls, old_thread);
3196 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3197 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3198 mono_loader_unlock ();
3202 tls = TlsGetValue (debugger_tls_id);
3204 // FIXME: Free this somewhere
3205 tls = g_new0 (DebuggerTlsData, 1);
3206 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3207 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3208 tls->thread = thread;
3209 TlsSetValue (debugger_tls_id, tls);
3211 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3213 mono_loader_lock ();
3214 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3215 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3216 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3217 mono_loader_unlock ();
3219 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3222 * suspend_vm () could have missed this thread, so wait for a resume.
3228 thread_end (MonoProfiler *prof, uintptr_t tid)
3230 MonoInternalThread *thread;
3231 DebuggerTlsData *tls = NULL;
3233 mono_loader_lock ();
3234 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3236 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3237 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3238 tls->terminated = TRUE;
3239 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3240 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3241 MONO_GC_UNREGISTER_ROOT (tls->thread);
3244 mono_loader_unlock ();
3246 /* We might be called for threads started before we registered the start callback */
3248 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3249 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3254 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3256 mono_loader_lock ();
3257 g_hash_table_insert (domains, domain, domain);
3258 mono_loader_unlock ();
3260 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3264 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3266 clear_breakpoints_for_domain (domain);
3268 mono_loader_lock ();
3269 /* Invalidate each thread's frame stack */
3270 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3271 mono_loader_unlock ();
3273 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3277 * invalidate_each_thread:
3279 * A GHFunc to invalidate frames.
3280 * value must be a DebuggerTlsData*
3283 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3285 invalidate_frames (value);
3289 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3291 /* Sent later in jit_end () */
3292 mono_loader_lock ();
3293 g_ptr_array_add (pending_assembly_loads, assembly);
3294 mono_loader_unlock ();
3298 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3300 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3302 clear_event_requests_for_assembly (assembly);
3303 clear_types_for_assembly (assembly);
3307 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3309 #if defined(HOST_WIN32) && !defined(__GNUC__)
3310 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3312 gpointer stackptr = __builtin_frame_address (1);
3314 MonoInternalThread *thread = mono_thread_internal_current ();
3315 DebuggerTlsData *tls;
3317 mono_loader_lock ();
3319 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3320 /* Could be the debugger thread with assembly/type load hooks */
3322 tls->invoke_addr = stackptr;
3324 mono_loader_unlock ();
3328 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3331 #if defined(HOST_WIN32) && !defined(__GNUC__)
3332 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3334 gpointer stackptr = __builtin_frame_address (1);
3337 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3341 * We need to stop single stepping when exiting a runtime invoke, since if it is
3342 * a step out, it may return to native code, and thus never end.
3344 mono_loader_lock ();
3345 ss_invoke_addr = NULL;
3347 for (i = 0; i < event_requests->len; ++i) {
3348 EventRequest *req = g_ptr_array_index (event_requests, i);
3350 if (req->event_kind == EVENT_KIND_STEP) {
3351 ss_destroy (req->info);
3352 g_ptr_array_remove_index_fast (event_requests, i);
3357 mono_loader_unlock ();
3361 send_type_load (MonoClass *klass)
3363 gboolean type_load = FALSE;
3364 MonoDomain *domain = mono_domain_get ();
3365 AgentDomainInfo *info = NULL;
3367 mono_loader_lock ();
3368 mono_domain_lock (domain);
3370 info = get_agent_domain_info (domain);
3372 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3374 g_hash_table_insert (info->loaded_classes, klass, klass);
3377 mono_domain_unlock (domain);
3378 mono_loader_unlock ();
3380 emit_type_load (klass, klass, NULL);
3384 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3387 * We emit type load events when the first method of the type is JITted,
3388 * since the class load profiler callbacks might be called with the
3389 * loader lock held. They could also occur in the debugger thread.
3390 * Same for assembly load events.
3393 MonoAssembly *assembly = NULL;
3395 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3396 mono_loader_lock ();
3397 if (pending_assembly_loads->len > 0) {
3398 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3399 g_ptr_array_remove_index (pending_assembly_loads, 0);
3401 mono_loader_unlock ();
3404 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3410 send_type_load (method->klass);
3413 add_pending_breakpoints (method, jinfo);
3417 * BREAKPOINTS/SINGLE STEPPING
3421 * Contains information about an inserted breakpoint.
3424 long il_offset, native_offset;
3428 } BreakpointInstance;
3431 * Contains generic information about a breakpoint.
3435 * The method where the breakpoint is placed. Can be NULL in which case it
3436 * is inserted into every method. This is used to implement method entry/
3437 * exit events. Can be a generic method definition, in which case the
3438 * breakpoint is inserted into every instance.
3444 * A list of BreakpointInstance structures describing where the breakpoint
3445 * was inserted. There could be more than one because of
3446 * generics/appdomains/method entry/exit.
3448 GPtrArray *children;
3451 /* List of breakpoints */
3452 static GPtrArray *breakpoints;
3453 /* Maps breakpoint locations to the number of breakpoints at that location */
3454 static GHashTable *bp_locs;
3457 breakpoints_init (void)
3459 breakpoints = g_ptr_array_new ();
3460 bp_locs = g_hash_table_new (NULL, NULL);
3464 * insert_breakpoint:
3466 * Insert the breakpoint described by BP into the method described by
3470 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3473 gint32 il_offset = -1, native_offset;
3474 BreakpointInstance *inst;
3477 mono_error_init (error);
3480 for (i = 0; i < seq_points->len; ++i) {
3481 il_offset = seq_points->seq_points [i].il_offset;
3482 native_offset = seq_points->seq_points [i].native_offset;
3484 if (il_offset == bp->il_offset)
3488 if (i == seq_points->len) {
3489 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);
3491 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3500 inst = g_new0 (BreakpointInstance, 1);
3501 inst->native_offset = native_offset;
3502 inst->ip = (guint8*)ji->code_start + native_offset;
3504 inst->domain = domain;
3506 mono_loader_lock ();
3508 g_ptr_array_add (bp->children, inst);
3510 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3511 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3512 mono_loader_unlock ();
3515 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3516 mono_arch_set_breakpoint (ji, inst->ip);
3522 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)il_offset));
3526 remove_breakpoint (BreakpointInstance *inst)
3528 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3530 MonoJitInfo *ji = inst->ji;
3531 guint8 *ip = inst->ip;
3533 mono_loader_lock ();
3534 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3535 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3536 mono_loader_unlock ();
3538 g_assert (count > 0);
3541 mono_arch_clear_breakpoint (ji, ip);
3548 static inline gboolean
3549 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3551 return (!bp->method || method == bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method));
3555 * add_pending_breakpoints:
3557 * Insert pending breakpoints into the newly JITted method METHOD.
3560 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3563 MonoSeqPointInfo *seq_points;
3569 domain = mono_domain_get ();
3571 mono_loader_lock ();
3573 for (i = 0; i < breakpoints->len; ++i) {
3574 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3575 gboolean found = FALSE;
3577 if (!bp_matches_method (bp, method))
3580 for (j = 0; j < bp->children->len; ++j) {
3581 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3588 mono_domain_lock (domain);
3589 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3590 mono_domain_unlock (domain);
3592 /* Could be AOT code */
3594 g_assert (seq_points);
3596 insert_breakpoint (seq_points, domain, ji, bp, NULL);
3600 mono_loader_unlock ();
3604 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
3610 mono_error_init (error);
3612 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3614 /* Might be AOTed code */
3615 code = mono_aot_get_method (domain, method);
3617 ji = mono_jit_info_table_find (domain, code);
3622 insert_breakpoint (seq_points, domain, ji, bp, error);
3626 clear_breakpoint (MonoBreakpoint *bp);
3631 * Set a breakpoint at IL_OFFSET in METHOD.
3632 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3633 * METHOD can also be a generic method definition, in which case a breakpoint
3634 * is placed in all instances of the method.
3635 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
3638 static MonoBreakpoint*
3639 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
3642 GHashTableIter iter, iter2;
3645 MonoSeqPointInfo *seq_points;
3648 mono_error_init (error);
3651 // - suspend/resume the vm to prevent code patching problems
3652 // - multiple breakpoints on the same location
3653 // - dynamic methods
3656 bp = g_new0 (MonoBreakpoint, 1);
3657 bp->method = method;
3658 bp->il_offset = il_offset;
3660 bp->children = g_ptr_array_new ();
3662 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));
3664 mono_loader_lock ();
3666 g_hash_table_iter_init (&iter, domains);
3667 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
3668 mono_domain_lock (domain);
3670 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
3671 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
3672 if (bp_matches_method (bp, m))
3673 set_bp_in_method (domain, m, seq_points, bp, error);
3676 mono_domain_unlock (domain);
3679 mono_loader_unlock ();
3681 mono_loader_lock ();
3682 g_ptr_array_add (breakpoints, bp);
3683 mono_loader_unlock ();
3685 if (error && !mono_error_ok (error)) {
3686 clear_breakpoint (bp);
3694 clear_breakpoint (MonoBreakpoint *bp)
3698 // FIXME: locking, races
3699 for (i = 0; i < bp->children->len; ++i) {
3700 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3702 remove_breakpoint (inst);
3707 mono_loader_lock ();
3708 g_ptr_array_remove (breakpoints, bp);
3709 mono_loader_unlock ();
3711 g_ptr_array_free (bp->children, TRUE);
3716 breakpoints_cleanup (void)
3720 mono_loader_lock ();
3722 while (i < event_requests->len) {
3723 EventRequest *req = g_ptr_array_index (event_requests, i);
3725 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
3726 clear_breakpoint (req->info);
3727 g_ptr_array_remove_index_fast (event_requests, i);
3734 for (i = 0; i < breakpoints->len; ++i)
3735 g_free (g_ptr_array_index (breakpoints, i));
3737 g_ptr_array_free (breakpoints, TRUE);
3738 g_hash_table_destroy (bp_locs);
3743 mono_loader_unlock ();
3747 * clear_breakpoints_for_domain:
3749 * Clear breakpoint instances which reference DOMAIN.
3752 clear_breakpoints_for_domain (MonoDomain *domain)
3756 /* This could be called after shutdown */
3760 mono_loader_lock ();
3761 for (i = 0; i < breakpoints->len; ++i) {
3762 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3765 while (j < bp->children->len) {
3766 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3768 if (inst->domain == domain) {
3769 remove_breakpoint (inst);
3773 g_ptr_array_remove_index_fast (bp->children, j);
3779 mono_loader_unlock ();
3783 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
3785 return bp->method && bp->method->klass->image->assembly == assembly;
3789 process_breakpoint_inner (DebuggerTlsData *tls)
3792 guint8 *orig_ip, *ip;
3793 int i, j, suspend_policy;
3794 guint32 native_offset;
3796 BreakpointInstance *inst;
3797 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3798 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3799 EventKind kind = EVENT_KIND_BREAKPOINT;
3800 MonoContext *ctx = &tls->restore_ctx;
3802 // FIXME: Speed this up
3804 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3805 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
3807 g_assert (ji->method);
3809 /* Compute the native offset of the breakpoint from the ip */
3810 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3811 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3812 native_offset = ip - (guint8*)ji->code_start;
3818 * Skip the instruction causing the breakpoint signal.
3820 mono_arch_skip_breakpoint (ctx);
3822 if (ji->method->wrapper_type || tls->disable_breakpoints)
3825 bp_reqs = g_ptr_array_new ();
3826 ss_reqs = g_ptr_array_new ();
3827 ss_reqs_orig = g_ptr_array_new ();
3829 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3831 mono_loader_lock ();
3834 for (i = 0; i < breakpoints->len; ++i) {
3835 bp = g_ptr_array_index (breakpoints, i);
3840 for (j = 0; j < bp->children->len; ++j) {
3841 inst = g_ptr_array_index (bp->children, j);
3842 if (inst->ji == ji && inst->native_offset == native_offset) {
3843 if (bp->req->event_kind == EVENT_KIND_STEP) {
3844 g_ptr_array_add (ss_reqs_orig, bp->req);
3846 g_ptr_array_add (bp_reqs, bp->req);
3851 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3852 MonoSeqPointInfo *seq_points;
3853 int seq_il_offset, seq_native_offset;
3854 MonoDomain *domain = mono_domain_get ();
3856 /* Maybe a method entry/exit event */
3857 mono_domain_lock (domain);
3858 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3859 mono_domain_unlock (domain);
3861 // FIXME: Generic sharing */
3862 mono_loader_unlock ();
3865 g_assert (seq_points);
3867 for (i = 0; i < seq_points->len; ++i) {
3868 seq_il_offset = seq_points->seq_points [i].il_offset;
3869 seq_native_offset = seq_points->seq_points [i].native_offset;
3871 if (native_offset == seq_native_offset) {
3872 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3873 kind = EVENT_KIND_METHOD_ENTRY;
3874 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3875 kind = EVENT_KIND_METHOD_EXIT;
3881 /* Process single step requests */
3882 for (i = 0; i < ss_reqs_orig->len; ++i) {
3883 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3884 SingleStepReq *ss_req = req->info;
3885 gboolean hit = TRUE;
3886 MonoSeqPointInfo *info;
3889 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3892 if (ss_req->size == STEP_SIZE_LINE) {
3893 /* Have to check whenever a different source line was reached */
3894 MonoDebugMethodInfo *minfo;
3895 MonoDebugSourceLocation *loc = NULL;
3897 minfo = mono_debug_lookup_method (ji->method);
3900 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3902 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3903 /* Have to continue single stepping */
3907 ss_req->last_method = ji->method;
3908 ss_req->last_line = loc->row;
3909 mono_debug_free_source_location (loc);
3914 g_ptr_array_add (ss_reqs, req);
3916 /* Start single stepping again from the current sequence point */
3917 ss_start (ss_req, ji->method, sp, info, ctx, NULL, FALSE);
3920 if (ss_reqs->len > 0)
3921 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3922 if (bp_reqs->len > 0)
3923 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3924 if (kind != EVENT_KIND_BREAKPOINT)
3925 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3927 mono_loader_unlock ();
3929 g_ptr_array_free (bp_reqs, TRUE);
3930 g_ptr_array_free (ss_reqs, TRUE);
3933 * FIXME: The first event will suspend, so the second will only be sent after the
3937 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3939 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3940 if (enter_leave_events)
3941 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3944 /* Process a breakpoint/single step event after resuming from a signal handler */
3946 process_signal_event (void (*func) (DebuggerTlsData*))
3948 DebuggerTlsData *tls;
3949 MonoContext orig_restore_ctx, ctx;
3950 static void (*restore_context) (void *);
3952 if (!restore_context)
3953 restore_context = mono_get_restore_context ();
3955 tls = TlsGetValue (debugger_tls_id);
3956 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
3957 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
3958 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
3962 /* This is called when resuming from a signal handler, so it shouldn't return */
3963 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
3964 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
3965 restore_context (&ctx);
3966 g_assert_not_reached ();
3970 process_breakpoint (void)
3972 process_signal_event (process_breakpoint_inner);
3976 resume_from_signal_handler (void *sigctx, void *func)
3978 DebuggerTlsData *tls;
3981 /* Save the original context in TLS */
3982 // FIXME: This might not work on an altstack ?
3983 tls = TlsGetValue (debugger_tls_id);
3986 // FIXME: MonoContext usually doesn't include the fp registers, so these are
3987 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3988 // clob:c could be added to op_seq_point.
3990 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3991 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3992 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
3993 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
3995 MONO_CONTEXT_SET_IP (&ctx, func);
3997 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3999 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4000 mono_ppc_set_func_into_sigctx (sigctx, func);
4005 mono_debugger_agent_breakpoint_hit (void *sigctx)
4008 * We are called from a signal handler, and running code there causes all kinds of
4009 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4010 * So set up the signal context to return to the real breakpoint handler function.
4013 resume_from_signal_handler (sigctx, process_breakpoint);
4017 ss_depth_to_string (StepDepth depth)
4020 case STEP_DEPTH_OVER:
4022 case STEP_DEPTH_OUT:
4024 case STEP_DEPTH_INTO:
4027 g_assert_not_reached ();
4033 process_single_step_inner (DebuggerTlsData *tls)
4038 int il_offset, suspend_policy;
4041 MonoContext *ctx = &tls->restore_ctx;
4043 // FIXME: Speed this up
4045 ip = MONO_CONTEXT_GET_IP (ctx);
4047 /* Skip the instruction causing the single step */
4048 mono_arch_skip_single_step (ctx);
4050 if (suspend_count > 0) {
4051 process_suspend (tls, ctx);
4056 // FIXME: A suspend race
4059 if (mono_thread_internal_current () != ss_req->thread)
4062 if (log_level > 0) {
4063 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4065 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));
4069 * We implement step over/out by single stepping until we reach the same
4070 * frame/parent frame.
4073 * - stack growing upward
4077 if (ss_req->depth != STEP_DEPTH_INTO) {
4078 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
4080 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
4083 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
4086 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4088 g_assert (ji->method);
4090 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4095 * Stopping in memset makes half-initialized vtypes visible.
4096 * Stopping in memcpy makes half-copied vtypes visible.
4098 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4102 * The ip points to the instruction causing the single step event, convert it
4103 * to the offset stored in seq_points.
4105 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4106 ip = mono_arch_get_ip_for_single_step (ji, ctx);
4108 g_assert_not_reached ();
4112 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
4113 * example, so do things by hand.
4115 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
4117 if (il_offset == -1)
4120 if (ss_req->size == STEP_SIZE_LINE) {
4121 /* Step until a different source line is reached */
4122 MonoDebugMethodInfo *minfo;
4124 minfo = mono_debug_lookup_method (ji->method);
4127 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4129 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4130 mono_debug_free_source_location (loc);
4135 * Step until we reach a location with line number info,
4136 * otherwise the client can't show a location.
4137 * This can happen for example with statics initialized inline
4138 * outside of a cctor.
4143 ss_req->last_method = ji->method;
4144 ss_req->last_line = loc->row;
4145 mono_debug_free_source_location (loc);
4150 // FIXME: Has to lock earlier
4152 reqs = g_ptr_array_new ();
4154 mono_loader_lock ();
4156 g_ptr_array_add (reqs, ss_req->req);
4158 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4160 g_ptr_array_free (reqs, TRUE);
4162 mono_loader_unlock ();
4164 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4168 process_single_step (void)
4170 process_signal_event (process_single_step_inner);
4174 * mono_debugger_agent_single_step_event:
4176 * Called from a signal handler to handle a single step event.
4179 mono_debugger_agent_single_step_event (void *sigctx)
4181 /* Resume to process_single_step through the signal context */
4183 // FIXME: Since step out/over is implemented using step in, the step in case should
4184 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4187 if (GetCurrentThreadId () == debugger_thread_id) {
4189 * This could happen despite our best effors when the runtime calls
4190 * assembly/type resolve hooks.
4191 * FIXME: Breakpoints too.
4195 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4196 mono_arch_skip_single_step (&ctx);
4197 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4201 resume_from_signal_handler (sigctx, process_single_step);
4205 * start_single_stepping:
4207 * Turn on single stepping. Can be called multiple times, for example,
4208 * by a single step event request + a suspend.
4211 start_single_stepping (void)
4213 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4214 int val = InterlockedIncrement (&ss_count);
4217 mono_arch_start_single_stepping ();
4219 if (ss_req != NULL && ss_invoke_addr == NULL) {
4220 DebuggerTlsData *tls;
4222 mono_loader_lock ();
4224 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4225 ss_invoke_addr = tls->invoke_addr;
4227 mono_loader_unlock ();
4230 g_assert_not_reached ();
4235 stop_single_stepping (void)
4237 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4238 int val = InterlockedDecrement (&ss_count);
4241 mono_arch_stop_single_stepping ();
4243 g_assert_not_reached ();
4250 * Stop the single stepping operation given by SS_REQ.
4253 ss_stop (SingleStepReq *ss_req)
4255 gboolean use_bps = FALSE;
4262 for (l = ss_req->bps; l; l = l->next) {
4263 clear_breakpoint (l->data);
4265 g_slist_free (ss_req->bps);
4269 if (ss_req->global) {
4270 stop_single_stepping ();
4271 ss_req->global = FALSE;
4278 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4281 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4287 /* Stop the previous operation */
4291 * Implement single stepping using breakpoints if possible.
4293 if (step_to_catch) {
4294 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4295 ss_req->bps = g_slist_append (ss_req->bps, bp);
4296 } else if (ss_req->depth == STEP_DEPTH_OVER) {
4299 * Find the first sequence point in the current or in a previous frame which
4300 * is not the last in its method.
4302 while (sp && sp->next_len == 0) {
4304 if (tls && frame_index < tls->frame_count) {
4305 StackFrame *frame = tls->frames [frame_index];
4307 method = frame->method;
4308 if (frame->il_offset != -1) {
4309 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
4315 if (sp && sp->next_len > 0) {
4316 for (i = 0; i < sp->next_len; ++i) {
4317 next_sp = &info->seq_points [sp->next [i]];
4319 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4320 ss_req->bps = g_slist_append (ss_req->bps, bp);
4326 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4327 ss_req->global = TRUE;
4328 start_single_stepping ();
4330 ss_req->global = FALSE;
4335 * Start single stepping of thread THREAD
4338 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4340 DebuggerTlsData *tls;
4341 MonoSeqPointInfo *info = NULL;
4342 SeqPoint *sp = NULL;
4343 MonoMethod *method = NULL;
4344 MonoDebugMethodInfo *minfo;
4345 gboolean step_to_catch = FALSE;
4347 if (suspend_count == 0)
4348 return ERR_NOT_SUSPENDED;
4350 wait_for_suspend ();
4352 // FIXME: Multiple requests
4354 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4355 return ERR_NOT_IMPLEMENTED;
4358 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4360 ss_req = g_new0 (SingleStepReq, 1);
4362 ss_req->thread = thread;
4363 ss_req->size = size;
4364 ss_req->depth = depth;
4367 mono_loader_lock ();
4368 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4369 mono_loader_unlock ();
4371 g_assert (tls->context.valid);
4372 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4374 if (tls->has_catch_ctx) {
4376 StackFrameInfo frame;
4377 MonoContext new_ctx;
4378 MonoLMF *lmf = NULL;
4381 * We are stopped at a throw site. Stepping should go to the catch site.
4384 /* Find the the jit info for the catch context */
4385 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4387 g_assert (frame.type == FRAME_TYPE_MANAGED);
4390 * Find the seq point corresponding to the landing site ip, which is the first seq
4393 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4396 method = frame.method;
4398 step_to_catch = TRUE;
4399 /* This make sure the seq point is not skipped by process_single_step () */
4400 ss_req->last_sp = NULL;
4403 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4406 /* Compute the initial line info */
4407 compute_frame_info (thread, tls);
4409 g_assert (tls->frame_count);
4410 frame = tls->frames [0];
4412 ss_req->last_method = frame->method;
4413 ss_req->last_line = -1;
4415 minfo = mono_debug_lookup_method (frame->method);
4416 if (minfo && frame->il_offset != -1) {
4417 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4420 ss_req->last_line = loc->row;
4426 if (!step_to_catch && ss_req->depth == STEP_DEPTH_OVER) {
4429 compute_frame_info (thread, tls);
4431 g_assert (tls->frame_count);
4432 frame = tls->frames [0];
4434 if (!method && frame->il_offset != -1) {
4435 /* FIXME: Sort the table and use a binary search */
4436 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4438 method = frame->method;
4442 ss_start (ss_req, method, sp, info, NULL, tls, step_to_catch);
4448 ss_destroy (SingleStepReq *req)
4451 g_assert (ss_req == req);
4460 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
4461 MonoContext *catch_ctx)
4467 DebuggerTlsData *tls = NULL;
4469 if (thread_to_tls != NULL) {
4470 MonoInternalThread *thread = mono_thread_internal_current ();
4472 mono_loader_lock ();
4473 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4474 mono_loader_unlock ();
4476 if (tls && tls->abort_requested)
4478 if (tls && tls->disable_breakpoints)
4482 memset (&ei, 0, sizeof (EventInfo));
4484 /* Just-In-Time debugging */
4486 if (agent_config.onuncaught && !inited) {
4487 finish_agent_init (FALSE);
4490 * Send an unsolicited EXCEPTION event with a dummy request id.
4492 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4493 ei.exc = (MonoObject*)exc;
4494 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4497 } else if (agent_config.onthrow && !inited) {
4499 gboolean found = FALSE;
4501 for (l = agent_config.onthrow; l; l = l->next) {
4502 char *ex_type = l->data;
4503 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
4505 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
4512 finish_agent_init (FALSE);
4515 * Send an unsolicited EXCEPTION event with a dummy request id.
4517 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4518 ei.exc = (MonoObject*)exc;
4519 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4527 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
4529 ei.exc = (MonoObject*)exc;
4530 ei.caught = catch_ctx != NULL;
4532 mono_loader_lock ();
4533 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
4534 mono_loader_unlock ();
4536 if (tls && catch_ctx) {
4537 tls->catch_ctx = *catch_ctx;
4538 tls->has_catch_ctx = TRUE;
4541 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
4544 tls->has_catch_ctx = FALSE;
4548 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4550 DebuggerTlsData *tls;
4555 tls = TlsGetValue (debugger_tls_id);
4560 * We're about to invoke an exception filter during the first pass of exception handling.
4562 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
4563 * 'orig_ctx' is the context where the exception has been thrown.
4566 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
4568 * If we're stopped in Filter(), normal stack unwinding would first unwind to
4569 * the call site (line 37) and then continue to Main(), but it would never
4570 * include the throw site (line 32).
4572 * Since exception filters are invoked during the first pass of exception handling,
4573 * the stack frames of the throw site are still intact, so we should include them
4576 * We do this here by saving the context of the throw site in 'tls->filter_state'.
4578 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
4579 * but report the location of the 'throw' to the user.
4583 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
4587 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4589 DebuggerTlsData *tls;
4594 tls = TlsGetValue (debugger_tls_id);
4598 tls->filter_state.valid = FALSE;
4602 * buffer_add_value_full:
4604 * Add the encoding of the value at ADDR described by T to the buffer.
4605 * AS_VTYPE determines whenever to treat primitive types as primitive types or
4609 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
4615 g_assert (*(void**)addr);
4616 addr = *(void**)addr;
4621 case MONO_TYPE_BOOLEAN:
4624 case MONO_TYPE_CHAR:
4644 case MONO_TYPE_VOID:
4645 buffer_add_byte (buf, t->type);
4647 case MONO_TYPE_BOOLEAN:
4650 buffer_add_byte (buf, t->type);
4651 buffer_add_int (buf, *(gint8*)addr);
4653 case MONO_TYPE_CHAR:
4656 buffer_add_byte (buf, t->type);
4657 buffer_add_int (buf, *(gint16*)addr);
4662 buffer_add_byte (buf, t->type);
4663 buffer_add_int (buf, *(gint32*)addr);
4668 buffer_add_byte (buf, t->type);
4669 buffer_add_long (buf, *(gint64*)addr);
4673 /* Treat it as a vtype */
4675 case MONO_TYPE_PTR: {
4676 gssize val = *(gssize*)addr;
4678 buffer_add_byte (buf, t->type);
4679 buffer_add_long (buf, val);
4683 case MONO_TYPE_STRING:
4684 case MONO_TYPE_SZARRAY:
4685 case MONO_TYPE_OBJECT:
4686 case MONO_TYPE_CLASS:
4687 case MONO_TYPE_ARRAY:
4688 obj = *(MonoObject**)addr;
4691 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4693 if (obj->vtable->klass->valuetype) {
4694 t = &obj->vtable->klass->byval_arg;
4695 addr = mono_object_unbox (obj);
4697 } else if (obj->vtable->klass->rank) {
4698 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4699 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4700 buffer_add_byte (buf, MONO_TYPE_CLASS);
4702 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4704 buffer_add_objid (buf, obj);
4708 case MONO_TYPE_VALUETYPE: {
4712 MonoClass *klass = mono_class_from_mono_type (t);
4714 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4715 buffer_add_byte (buf, klass->enumtype);
4716 buffer_add_typeid (buf, domain, klass);
4720 while ((f = mono_class_get_fields (klass, &iter))) {
4721 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4723 if (mono_field_is_deleted (f))
4727 buffer_add_int (buf, nfields);
4730 while ((f = mono_class_get_fields (klass, &iter))) {
4731 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4733 if (mono_field_is_deleted (f))
4735 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4739 case MONO_TYPE_GENERICINST:
4740 if (mono_type_generic_inst_is_valuetype (t)) {
4752 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4754 buffer_add_value_full (buf, t, addr, domain, FALSE);
4758 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4761 int type = decode_byte (buf, &buf, limit);
4763 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4764 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4765 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4766 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
4767 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
4768 char *name = mono_type_full_name (t);
4769 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
4771 return ERR_INVALID_ARGUMENT;
4775 case MONO_TYPE_BOOLEAN:
4776 *(guint8*)addr = decode_int (buf, &buf, limit);
4778 case MONO_TYPE_CHAR:
4779 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4782 *(gint8*)addr = decode_int (buf, &buf, limit);
4785 *(guint8*)addr = decode_int (buf, &buf, limit);
4788 *(gint16*)addr = decode_int (buf, &buf, limit);
4791 *(guint16*)addr = decode_int (buf, &buf, limit);
4794 *(gint32*)addr = decode_int (buf, &buf, limit);
4797 *(guint32*)addr = decode_int (buf, &buf, limit);
4800 *(gint64*)addr = decode_long (buf, &buf, limit);
4803 *(guint64*)addr = decode_long (buf, &buf, limit);
4806 *(guint32*)addr = decode_int (buf, &buf, limit);
4809 *(guint64*)addr = decode_long (buf, &buf, limit);
4812 /* We send these as I8, so we get them back as such */
4813 g_assert (type == MONO_TYPE_I8);
4814 *(gssize*)addr = decode_long (buf, &buf, limit);
4816 case MONO_TYPE_GENERICINST:
4817 if (MONO_TYPE_ISSTRUCT (t)) {
4818 /* The client sends these as a valuetype */
4826 /* We send these as vtypes, so we get them back as such */
4827 g_assert (type == MONO_TYPE_VALUETYPE);
4830 case MONO_TYPE_VALUETYPE: {
4831 gboolean is_enum = decode_byte (buf, &buf, limit);
4835 gpointer iter = NULL;
4838 /* Enums are sent as a normal vtype */
4840 return ERR_NOT_IMPLEMENTED;
4841 klass = decode_typeid (buf, &buf, limit, &d, &err);
4845 if (klass != mono_class_from_mono_type (t))
4846 return ERR_INVALID_ARGUMENT;
4848 nfields = decode_int (buf, &buf, limit);
4849 while ((f = mono_class_get_fields (klass, &iter))) {
4850 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4852 if (mono_field_is_deleted (f))
4854 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4859 g_assert (nfields == 0);
4864 if (MONO_TYPE_IS_REFERENCE (t)) {
4865 if (type == MONO_TYPE_OBJECT) {
4866 int objid = decode_objid (buf, &buf, limit);
4870 err = get_object (objid, (MonoObject**)&obj);
4874 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4875 return ERR_INVALID_ARGUMENT;
4876 if (obj && obj->vtable->domain != domain)
4877 return ERR_INVALID_ARGUMENT;
4879 mono_gc_wbarrier_generic_store (addr, obj);
4880 } else if (type == VALUE_TYPE_ID_NULL) {
4881 *(MonoObject**)addr = NULL;
4883 return ERR_INVALID_ARGUMENT;
4897 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4904 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4905 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4908 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4909 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4911 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
4913 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4914 addr = mono_arch_context_get_int_reg (ctx, reg);
4915 addr += (gint32)var->offset;
4917 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4919 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4921 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4925 g_assert_not_reached ();
4930 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
4936 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4937 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4939 if (MONO_TYPE_IS_REFERENCE (t))
4940 size = sizeof (gpointer);
4942 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4945 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
4946 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
4948 gboolean is_signed = FALSE;
4950 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
4955 v = is_signed ? *(gint8*)val : *(guint8*)val;
4958 v = is_signed ? *(gint16*)val : *(guint16*)val;
4961 v = is_signed ? *(gint32*)val : *(guint32*)val;
4964 v = is_signed ? *(gint64*)val : *(guint64*)val;
4967 g_assert_not_reached ();
4970 /* Set value on the stack or in the return ctx */
4971 if (reg_locations [reg]) {
4972 /* Saved on the stack */
4973 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
4974 *(reg_locations [reg]) = v;
4977 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
4978 mono_arch_context_set_int_reg (restore_ctx, reg, v);
4981 // FIXME: Move these to mono-context.h/c.
4982 mono_arch_context_set_int_reg (ctx, reg, v);
4984 // FIXME: Can't set registers, so we disable linears
4989 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4990 addr = mono_arch_context_get_int_reg (ctx, reg);
4991 addr += (gint32)var->offset;
4993 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4995 // FIXME: Write barriers
4996 memcpy (addr, val, size);
4998 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5002 g_assert_not_reached ();
5007 clear_event_request (int req_id, int etype)
5011 mono_loader_lock ();
5012 for (i = 0; i < event_requests->len; ++i) {
5013 EventRequest *req = g_ptr_array_index (event_requests, i);
5015 if (req->id == req_id && req->event_kind == etype) {
5016 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5017 clear_breakpoint (req->info);
5018 if (req->event_kind == EVENT_KIND_STEP)
5019 ss_destroy (req->info);
5020 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5021 clear_breakpoint (req->info);
5022 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5023 clear_breakpoint (req->info);
5024 g_ptr_array_remove_index_fast (event_requests, i);
5029 mono_loader_unlock ();
5033 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5035 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5036 return breakpoint_matches_assembly (req->info, assembly);
5040 for (i = 0; i < req->nmodifiers; ++i) {
5041 Modifier *m = &req->modifiers [i];
5043 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5045 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5046 for (j = 0; m->data.assemblies [j]; ++j)
5047 if (m->data.assemblies [j] == assembly)
5057 * clear_event_requests_for_assembly:
5059 * Clear all events requests which reference ASSEMBLY.
5062 clear_event_requests_for_assembly (MonoAssembly *assembly)
5067 mono_loader_lock ();
5071 for (i = 0; i < event_requests->len; ++i) {
5072 EventRequest *req = g_ptr_array_index (event_requests, i);
5074 if (event_req_matches_assembly (req, assembly)) {
5075 clear_event_request (req->id, req->event_kind);
5081 mono_loader_unlock ();
5085 * type_comes_from_assembly:
5087 * GHRFunc that returns TRUE if klass comes from assembly
5090 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5092 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5096 * clear_types_for_assembly:
5098 * Clears types from loaded_classes for a given assembly
5101 clear_types_for_assembly (MonoAssembly *assembly)
5103 MonoDomain *domain = mono_domain_get ();
5104 AgentDomainInfo *info = NULL;
5106 mono_loader_lock ();
5107 info = get_agent_domain_info (domain);
5108 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5109 mono_loader_unlock ();
5113 add_thread (gpointer key, gpointer value, gpointer user_data)
5115 MonoInternalThread *thread = value;
5116 Buffer *buf = user_data;
5118 buffer_add_objid (buf, (MonoObject*)thread);
5122 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5124 guint8 *p = invoke->p;
5125 guint8 *end = invoke->endp;
5128 MonoMethodSignature *sig;
5131 MonoObject *this, *res, *exc;
5134 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5138 if (invoke->method) {
5140 * Invoke this method directly, currently only Environment.Exit () is supported.
5143 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>"));
5144 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5145 g_assert_not_reached ();
5148 m = decode_methodid (p, &p, end, &domain, &err);
5151 sig = mono_method_signature (m);
5153 if (m->klass->valuetype)
5154 this_buf = g_alloca (mono_class_instance_size (m->klass));
5156 this_buf = g_alloca (sizeof (MonoObject*));
5157 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5158 /* Should be null */
5159 int type = decode_byte (p, &p, end);
5160 if (type != VALUE_TYPE_ID_NULL)
5161 return ERR_INVALID_ARGUMENT;
5162 memset (this_buf, 0, mono_class_instance_size (m->klass));
5164 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5169 if (!m->klass->valuetype)
5170 this = *(MonoObject**)this_buf;
5174 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>"));
5176 if (this && this->vtable->domain != domain)
5179 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5180 if (!strcmp (m->name, ".ctor")) {
5181 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5182 return ERR_INVALID_ARGUMENT;
5184 this = mono_object_new (domain, m->klass);
5186 return ERR_INVALID_ARGUMENT;
5190 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5191 return ERR_INVALID_ARGUMENT;
5193 nargs = decode_int (p, &p, end);
5194 if (nargs != sig->param_count)
5195 return ERR_INVALID_ARGUMENT;
5196 /* Use alloca to get gc tracking */
5197 arg_buf = g_alloca (nargs * sizeof (gpointer));
5198 memset (arg_buf, 0, nargs * sizeof (gpointer));
5199 args = g_alloca (nargs * sizeof (gpointer));
5200 for (i = 0; i < nargs; ++i) {
5201 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5202 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5206 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5209 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5210 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5213 args [i] = arg_buf [i];
5220 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5221 tls->disable_breakpoints = TRUE;
5223 tls->disable_breakpoints = FALSE;
5226 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5228 /* FIXME: Move this to arch specific code */
5229 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5230 if (invoke->has_ctx) {
5233 lmf_addr = mono_get_lmf_addr ();
5236 memset (&ext, 0, sizeof (ext));
5238 ext.lmf.previous_lmf = *(lmf_addr);
5239 /* Mark that this is a MonoLMFExt */
5240 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5241 ext.lmf.rsp = (gssize)&ext;
5242 #elif defined(TARGET_X86)
5243 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5244 /* Mark that this is a MonoLMFExt */
5245 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5246 ext.lmf.ebp = (gssize)&ext;
5247 #elif defined(TARGET_ARM)
5248 ext.lmf.previous_lmf = *(lmf_addr);
5249 /* Mark that this is a MonoLMFExt */
5250 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5251 #elif defined(TARGET_POWERPC)
5252 ext.lmf.previous_lmf = *(lmf_addr);
5253 /* Mark that this is a MonoLMFExt */
5254 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5255 ext.lmf.ebp = (gssize)&ext;
5257 g_assert_not_reached ();
5260 ext.debugger_invoke = TRUE;
5261 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5263 mono_set_lmf ((MonoLMF*)&ext);
5267 if (m->klass->valuetype)
5268 res = mono_runtime_invoke (m, this_buf, args, &exc);
5270 res = mono_runtime_invoke (m, this, args, &exc);
5272 buffer_add_byte (buf, 0);
5273 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5275 buffer_add_byte (buf, 1);
5276 if (sig->ret->type == MONO_TYPE_VOID) {
5277 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5278 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5281 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5282 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5283 buffer_add_value (buf, sig->ret, &res, domain);
5284 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5285 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5287 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &res, domain);
5289 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5292 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5299 tls->disable_breakpoints = FALSE;
5301 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5302 if (invoke->has_ctx)
5303 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5306 // FIXME: byref arguments
5314 * Invoke the method given by tls->pending_invoke in the current thread.
5317 invoke_method (void)
5319 DebuggerTlsData *tls;
5324 static void (*restore_context) (void *);
5325 MonoContext restore_ctx;
5327 if (!restore_context)
5328 restore_context = mono_get_restore_context ();
5330 tls = TlsGetValue (debugger_tls_id);
5334 * Store the `InvokeData *' in `tls->invoke' until we're done with
5335 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5338 mono_loader_lock ();
5340 invoke = tls->pending_invoke;
5342 tls->pending_invoke = NULL;
5344 invoke->last_invoke = tls->invoke;
5345 tls->invoke = invoke;
5347 mono_loader_unlock ();
5349 tls->frames_up_to_date = FALSE;
5353 buffer_init (&buf, 128);
5355 err = do_invoke_method (tls, &buf, invoke);
5357 /* Start suspending before sending the reply */
5358 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5361 send_reply_packet (id, err, &buf);
5365 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5367 if (invoke->has_ctx)
5368 save_thread_context (&restore_ctx);
5370 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5371 g_assert (tls->resume_count);
5372 tls->resume_count -= invoke->suspend_count;
5375 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5378 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5380 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5381 * after the mono_runtime_invoke() already returned, but it doesn't matter
5382 * because we reset the abort here.
5385 mono_loader_lock ();
5387 if (tls->abort_requested)
5388 mono_thread_internal_reset_abort (tls->thread);
5390 tls->invoke = tls->invoke->last_invoke;
5391 tls->abort_requested = FALSE;
5393 mono_loader_unlock ();
5402 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5404 MonoThread *thread = value;
5405 DebuggerTlsData *tls;
5408 mono_loader_lock ();
5409 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5411 res = tls->really_suspended;
5412 mono_loader_unlock ();
5418 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
5421 case CMD_VM_VERSION: {
5422 char *build_info, *version;
5424 build_info = mono_get_runtime_build_info ();
5425 version = g_strdup_printf ("mono %s", build_info);
5427 buffer_add_string (buf, version); /* vm version */
5428 buffer_add_int (buf, MAJOR_VERSION);
5429 buffer_add_int (buf, MINOR_VERSION);
5430 g_free (build_info);
5434 case CMD_VM_SET_PROTOCOL_VERSION: {
5435 major_version = decode_int (p, &p, end);
5436 minor_version = decode_int (p, &p, end);
5437 protocol_version_set = TRUE;
5438 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
5441 case CMD_VM_ALL_THREADS: {
5443 mono_loader_lock ();
5444 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
5445 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
5446 mono_loader_unlock ();
5449 case CMD_VM_SUSPEND:
5451 wait_for_suspend ();
5454 if (suspend_count == 0)
5455 return ERR_NOT_SUSPENDED;
5458 case CMD_VM_DISPOSE:
5459 /* Clear all event requests */
5460 mono_loader_lock ();
5461 while (event_requests->len > 0) {
5462 EventRequest *req = g_ptr_array_index (event_requests, 0);
5464 clear_event_request (req->id, req->event_kind);
5466 mono_loader_unlock ();
5468 while (suspend_count > 0)
5470 disconnected = TRUE;
5471 vm_start_event_sent = FALSE;
5474 MonoInternalThread *thread;
5475 DebuggerTlsData *tls;
5476 MonoClass *env_class;
5477 MonoMethod *exit_method = NULL;
5481 exit_code = decode_int (p, &p, end);
5483 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
5485 /* Have to send a reply before exiting */
5486 send_reply_packet (id, 0, buf);
5488 /* Clear all event requests */
5489 mono_loader_lock ();
5490 while (event_requests->len > 0) {
5491 EventRequest *req = g_ptr_array_index (event_requests, 0);
5493 clear_event_request (req->id, req->event_kind);
5495 mono_loader_unlock ();
5498 * The JDWP documentation says that the shutdown is not orderly. It doesn't
5499 * specify whenever a VM_DEATH event is sent. We currently do an orderly
5500 * shutdown by hijacking a thread to execute Environment.Exit (). This is
5501 * better than doing the shutdown ourselves, since it avoids various races.
5505 wait_for_suspend ();
5507 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
5509 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
5511 mono_loader_lock ();
5512 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
5513 mono_loader_unlock ();
5515 if (thread && exit_method) {
5516 mono_loader_lock ();
5517 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5518 mono_loader_unlock ();
5520 args = g_new0 (gpointer, 1);
5521 args [0] = g_malloc (sizeof (int));
5522 *(int*)(args [0]) = exit_code;
5524 tls->pending_invoke = g_new0 (InvokeData, 1);
5525 tls->pending_invoke->method = exit_method;
5526 tls->pending_invoke->args = args;
5528 while (suspend_count > 0)
5532 * No thread found, do it ourselves.
5533 * FIXME: This can race with normal shutdown etc.
5535 while (suspend_count > 0)
5538 mono_runtime_set_shutting_down ();
5540 mono_threads_set_shutting_down ();
5542 /* Suspend all managed threads since the runtime is going away */
5543 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
5544 mono_thread_suspend_all_other_threads ();
5545 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
5546 mono_runtime_quit ();
5548 shutdown (conn_fd, SD_BOTH);
5550 shutdown (conn_fd, SHUT_RDWR);
5552 DEBUG(1, fprintf (log_file, "Exiting...\n"));
5558 case CMD_VM_INVOKE_METHOD: {
5559 int objid = decode_objid (p, &p, end);
5561 DebuggerTlsData *tls;
5564 err = get_object (objid, (MonoObject**)&thread);
5568 flags = decode_int (p, &p, end);
5570 // Wait for suspending if it already started
5572 wait_for_suspend ();
5573 if (!is_suspended ())
5574 return ERR_NOT_SUSPENDED;
5576 mono_loader_lock ();
5577 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5578 mono_loader_unlock ();
5581 if (!tls->really_suspended)
5582 /* The thread is still running native code, can't do invokes */
5583 return ERR_NOT_SUSPENDED;
5586 * Store the invoke data into tls, the thread will execute it after it is
5589 if (tls->pending_invoke)
5591 tls->pending_invoke = g_new0 (InvokeData, 1);
5592 tls->pending_invoke->id = id;
5593 tls->pending_invoke->flags = flags;
5594 tls->pending_invoke->p = g_malloc (end - p);
5595 memcpy (tls->pending_invoke->p, p, end - p);
5596 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
5597 tls->pending_invoke->suspend_count = suspend_count;
5599 if (flags & INVOKE_FLAG_SINGLE_THREADED)
5600 resume_thread (THREAD_TO_INTERNAL (thread));
5605 case CMD_VM_ABORT_INVOKE: {
5606 int objid = decode_objid (p, &p, end);
5608 DebuggerTlsData *tls;
5611 err = get_object (objid, (MonoObject**)&thread);
5615 invoke_id = decode_int (p, &p, end);
5617 mono_loader_lock ();
5618 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5621 if (tls->abort_requested) {
5622 mono_loader_unlock ();
5627 * Check whether we're still inside the mono_runtime_invoke() and that it's
5628 * actually the correct invocation.
5630 * Careful, we do not stop the thread that's doing the invocation, so we can't
5631 * inspect its stack. However, invoke_method() also acquires the loader lock
5632 * when it's done, so we're safe here.
5636 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
5637 mono_loader_unlock ();
5638 return ERR_NO_INVOCATION;
5641 tls->abort_requested = TRUE;
5643 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
5644 mono_loader_unlock ();
5649 return ERR_NOT_IMPLEMENTED;
5656 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5662 case CMD_EVENT_REQUEST_SET: {
5664 int i, event_kind, suspend_policy, nmodifiers, mod;
5667 MonoThread *step_thread;
5668 int size = 0, depth = 0, step_thread_id = 0;
5671 event_kind = decode_byte (p, &p, end);
5672 suspend_policy = decode_byte (p, &p, end);
5673 nmodifiers = decode_byte (p, &p, end);
5675 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
5676 req->id = InterlockedIncrement (&event_request_id);
5677 req->event_kind = event_kind;
5678 req->suspend_policy = suspend_policy;
5679 req->nmodifiers = nmodifiers;
5682 for (i = 0; i < nmodifiers; ++i) {
5683 mod = decode_byte (p, &p, end);
5685 req->modifiers [i].kind = mod;
5686 if (mod == MOD_KIND_COUNT) {
5687 req->modifiers [i].data.count = decode_int (p, &p, end);
5688 } else if (mod == MOD_KIND_LOCATION_ONLY) {
5689 method = decode_methodid (p, &p, end, &domain, &err);
5692 location = decode_long (p, &p, end);
5693 } else if (mod == MOD_KIND_STEP) {
5694 step_thread_id = decode_id (p, &p, end);
5695 size = decode_int (p, &p, end);
5696 depth = decode_int (p, &p, end);
5697 } else if (mod == MOD_KIND_THREAD_ONLY) {
5698 int id = decode_id (p, &p, end);
5700 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
5705 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
5706 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
5710 req->modifiers [i].caught = decode_byte (p, &p, end);
5711 req->modifiers [i].uncaught = decode_byte (p, &p, end);
5712 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" : ""));
5714 req->modifiers [i].data.exc_class = exc_class;
5716 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
5718 return ERR_INVALID_ARGUMENT;
5721 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
5722 int n = decode_int (p, &p, end);
5725 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
5726 for (j = 0; j < n; ++j) {
5727 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
5729 g_free (req->modifiers [i].data.assemblies);
5735 return ERR_NOT_IMPLEMENTED;
5739 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5742 req->info = set_breakpoint (method, location, req, &error);
5743 if (!mono_error_ok (&error)) {
5745 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
5746 mono_error_cleanup (&error);
5747 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
5749 } else if (req->event_kind == EVENT_KIND_STEP) {
5750 g_assert (step_thread_id);
5752 err = get_object (step_thread_id, (MonoObject**)&step_thread);
5758 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
5763 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
5764 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
5765 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
5766 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
5767 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
5769 if (req->nmodifiers) {
5771 return ERR_NOT_IMPLEMENTED;
5775 mono_loader_lock ();
5776 g_ptr_array_add (event_requests, req);
5777 mono_loader_unlock ();
5779 buffer_add_int (buf, req->id);
5782 case CMD_EVENT_REQUEST_CLEAR: {
5783 int etype = decode_byte (p, &p, end);
5784 int req_id = decode_int (p, &p, end);
5786 // FIXME: Make a faster mapping from req_id to request
5787 mono_loader_lock ();
5788 clear_event_request (req_id, etype);
5789 mono_loader_unlock ();
5792 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
5795 mono_loader_lock ();
5797 while (i < event_requests->len) {
5798 EventRequest *req = g_ptr_array_index (event_requests, i);
5800 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5801 clear_breakpoint (req->info);
5803 g_ptr_array_remove_index_fast (event_requests, i);
5809 mono_loader_unlock ();
5813 return ERR_NOT_IMPLEMENTED;
5820 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5826 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
5827 buffer_add_domainid (buf, mono_get_root_domain ());
5830 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
5831 domain = decode_domainid (p, &p, end, NULL, &err);
5834 buffer_add_string (buf, domain->friendly_name);
5837 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
5842 domain = decode_domainid (p, &p, end, NULL, &err);
5845 mono_loader_lock ();
5847 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5850 buffer_add_int (buf, count);
5851 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5853 buffer_add_assemblyid (buf, domain, ass);
5855 mono_loader_unlock ();
5858 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
5859 domain = decode_domainid (p, &p, end, NULL, &err);
5863 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
5866 case CMD_APPDOMAIN_GET_CORLIB: {
5867 domain = decode_domainid (p, &p, end, NULL, &err);
5871 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
5874 case CMD_APPDOMAIN_CREATE_STRING: {
5878 domain = decode_domainid (p, &p, end, NULL, &err);
5881 s = decode_string (p, &p, end);
5883 o = mono_string_new (domain, s);
5884 buffer_add_objid (buf, (MonoObject*)o);
5887 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
5889 MonoDomain *domain2;
5892 domain = decode_domainid (p, &p, end, NULL, &err);
5895 klass = decode_typeid (p, &p, end, &domain2, &err);
5900 g_assert (domain == domain2);
5902 o = mono_object_new (domain, klass);
5904 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
5908 buffer_add_objid (buf, o);
5912 return ERR_NOT_IMPLEMENTED;
5919 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5925 ass = decode_assemblyid (p, &p, end, &domain, &err);
5930 case CMD_ASSEMBLY_GET_LOCATION: {
5931 buffer_add_string (buf, mono_image_get_filename (ass->image));
5934 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
5938 if (ass->image->dynamic) {
5939 buffer_add_id (buf, 0);
5941 token = mono_image_get_entry_point (ass->image);
5943 buffer_add_id (buf, 0);
5945 m = mono_get_method (ass->image, token, NULL);
5946 buffer_add_methodid (buf, domain, m);
5951 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5952 buffer_add_moduleid (buf, domain, ass->image);
5955 case CMD_ASSEMBLY_GET_OBJECT: {
5956 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5957 buffer_add_objid (buf, o);
5960 case CMD_ASSEMBLY_GET_TYPE: {
5961 char *s = decode_string (p, &p, end);
5962 gboolean ignorecase = decode_byte (p, &p, end);
5963 MonoTypeNameParse info;
5965 gboolean type_resolve, res;
5966 MonoDomain *d = mono_domain_get ();
5968 /* This is needed to be able to find referenced assemblies */
5969 res = mono_domain_set (domain, FALSE);
5972 if (!mono_reflection_parse_type (s, &info)) {
5975 if (info.assembly.name)
5977 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5979 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5980 mono_reflection_free_type_info (&info);
5983 mono_domain_set (d, TRUE);
5987 case CMD_ASSEMBLY_GET_NAME: {
5989 MonoAssembly *mass = ass;
5991 name = g_strdup_printf (
5992 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5994 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5995 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5996 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5997 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5999 buffer_add_string (buf, name);
6004 return ERR_NOT_IMPLEMENTED;
6011 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6017 case CMD_MODULE_GET_INFO: {
6018 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
6021 basename = g_path_get_basename (image->name);
6022 buffer_add_string (buf, basename); // name
6023 buffer_add_string (buf, image->module_name); // scopename
6024 buffer_add_string (buf, image->name); // fqname
6025 buffer_add_string (buf, mono_image_get_guid (image)); // guid
6026 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
6031 return ERR_NOT_IMPLEMENTED;
6038 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6040 if (val && val->vtable->klass == mono_defaults.monotype_class) {
6041 /* Special case these so the client doesn't have to handle Type objects */
6043 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6044 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
6045 } else if (MONO_TYPE_IS_REFERENCE (t))
6046 buffer_add_value (buf, t, &val, domain);
6048 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6052 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6058 buffer_add_int (buf, 0);
6062 for (i = 0; i < cinfo->num_attrs; ++i) {
6063 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6066 buffer_add_int (buf, nattrs);
6068 for (i = 0; i < cinfo->num_attrs; ++i) {
6069 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6070 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6071 MonoArray *typed_args, *named_args;
6073 CattrNamedArg *arginfo;
6075 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6077 buffer_add_methodid (buf, domain, attr->ctor);
6081 buffer_add_int (buf, mono_array_length (typed_args));
6082 for (j = 0; j < mono_array_length (typed_args); ++j) {
6083 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6085 t = mono_method_signature (attr->ctor)->params [j];
6087 buffer_add_cattr_arg (buf, t, domain, val);
6090 buffer_add_int (buf, 0);
6095 buffer_add_int (buf, mono_array_length (named_args));
6097 for (j = 0; j < mono_array_length (named_args); ++j) {
6098 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
6100 if (arginfo [j].prop) {
6101 buffer_add_byte (buf, 0x54);
6102 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6103 } else if (arginfo [j].field) {
6104 buffer_add_byte (buf, 0x53);
6106 g_assert_not_reached ();
6109 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6112 buffer_add_int (buf, 0);
6119 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6129 case CMD_TYPE_GET_INFO: {
6130 buffer_add_string (buf, klass->name_space);
6131 buffer_add_string (buf, klass->name);
6133 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
6134 buffer_add_string (buf, name);
6136 buffer_add_assemblyid (buf, domain, klass->image->assembly);
6137 buffer_add_moduleid (buf, domain, klass->image);
6138 buffer_add_typeid (buf, domain, klass->parent);
6139 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
6140 buffer_add_typeid (buf, domain, klass->element_class);
6142 buffer_add_id (buf, 0);
6143 buffer_add_int (buf, klass->type_token);
6144 buffer_add_byte (buf, klass->rank);
6145 buffer_add_int (buf, klass->flags);
6147 type = &klass->byval_arg;
6148 // FIXME: Can't decide whenever a class represents a byref type
6151 if (type->type == MONO_TYPE_PTR)
6153 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
6155 if (type->type == MONO_TYPE_VALUETYPE)
6157 if (klass->enumtype)
6159 buffer_add_byte (buf, b);
6162 while ((nested = mono_class_get_nested_types (klass, &iter)))
6164 buffer_add_int (buf, nnested);
6166 while ((nested = mono_class_get_nested_types (klass, &iter)))
6167 buffer_add_typeid (buf, domain, nested);
6170 case CMD_TYPE_GET_METHODS: {
6173 gpointer iter = NULL;
6176 mono_class_setup_methods (klass);
6178 nmethods = mono_class_num_methods (klass);
6180 buffer_add_int (buf, nmethods);
6182 while ((m = mono_class_get_methods (klass, &iter))) {
6183 buffer_add_methodid (buf, domain, m);
6186 g_assert (i == nmethods);
6189 case CMD_TYPE_GET_FIELDS: {
6192 gpointer iter = NULL;
6195 nfields = mono_class_num_fields (klass);
6197 buffer_add_int (buf, nfields);
6199 while ((f = mono_class_get_fields (klass, &iter))) {
6200 buffer_add_fieldid (buf, domain, f);
6201 buffer_add_string (buf, f->name);
6202 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
6203 buffer_add_int (buf, f->type->attrs);
6206 g_assert (i == nfields);
6209 case CMD_TYPE_GET_PROPERTIES: {
6212 gpointer iter = NULL;
6215 nprops = mono_class_num_properties (klass);
6217 buffer_add_int (buf, nprops);
6219 while ((p = mono_class_get_properties (klass, &iter))) {
6220 buffer_add_propertyid (buf, domain, p);
6221 buffer_add_string (buf, p->name);
6222 buffer_add_methodid (buf, domain, p->get);
6223 buffer_add_methodid (buf, domain, p->set);
6224 buffer_add_int (buf, p->attrs);
6227 g_assert (i == nprops);
6230 case CMD_TYPE_GET_CATTRS: {
6231 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
6232 MonoCustomAttrInfo *cinfo;
6234 cinfo = mono_custom_attrs_from_class (klass);
6236 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6239 case CMD_TYPE_GET_FIELD_CATTRS: {
6240 MonoClass *attr_klass;
6241 MonoCustomAttrInfo *cinfo;
6242 MonoClassField *field;
6244 field = decode_fieldid (p, &p, end, NULL, &err);
6247 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6251 cinfo = mono_custom_attrs_from_field (klass, field);
6253 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6256 case CMD_TYPE_GET_PROPERTY_CATTRS: {
6257 MonoClass *attr_klass;
6258 MonoCustomAttrInfo *cinfo;
6261 prop = decode_propertyid (p, &p, end, NULL, &err);
6264 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6268 cinfo = mono_custom_attrs_from_property (klass, prop);
6270 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6273 case CMD_TYPE_GET_VALUES:
6274 case CMD_TYPE_GET_VALUES_2: {
6281 MonoThread *thread_obj;
6282 MonoInternalThread *thread = NULL;
6283 guint32 special_static_type;
6285 if (command == CMD_TYPE_GET_VALUES_2) {
6286 int objid = decode_objid (p, &p, end);
6289 err = get_object (objid, (MonoObject**)&thread_obj);
6293 thread = THREAD_TO_INTERNAL (thread_obj);
6296 len = decode_int (p, &p, end);
6297 for (i = 0; i < len; ++i) {
6298 f = decode_fieldid (p, &p, end, NULL, &err);
6302 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6303 return ERR_INVALID_FIELDID;
6304 special_static_type = mono_class_field_get_special_static_type (f);
6305 if (special_static_type != SPECIAL_STATIC_NONE) {
6306 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
6307 return ERR_INVALID_FIELDID;
6310 /* Check that the field belongs to the object */
6312 for (k = klass; k; k = k->parent) {
6313 if (k == f->parent) {
6319 return ERR_INVALID_FIELDID;
6321 vtable = mono_class_vtable (domain, f->parent);
6322 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6323 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
6324 buffer_add_value (buf, f->type, val, domain);
6329 case CMD_TYPE_SET_VALUES: {
6337 len = decode_int (p, &p, end);
6338 for (i = 0; i < len; ++i) {
6339 f = decode_fieldid (p, &p, end, NULL, &err);
6343 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6344 return ERR_INVALID_FIELDID;
6345 if (mono_class_field_is_special_static (f))
6346 return ERR_INVALID_FIELDID;
6348 /* Check that the field belongs to the object */
6350 for (k = klass; k; k = k->parent) {
6351 if (k == f->parent) {
6357 return ERR_INVALID_FIELDID;
6359 // FIXME: Check for literal/const
6361 vtable = mono_class_vtable (domain, f->parent);
6362 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6363 err = decode_value (f->type, domain, val, p, &p, end);
6368 if (MONO_TYPE_IS_REFERENCE (f->type))
6369 mono_field_static_set_value (vtable, f, *(gpointer*)val);
6371 mono_field_static_set_value (vtable, f, val);
6376 case CMD_TYPE_GET_OBJECT: {
6377 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
6378 buffer_add_objid (buf, o);
6381 case CMD_TYPE_GET_SOURCE_FILES:
6382 case CMD_TYPE_GET_SOURCE_FILES_2: {
6383 gpointer iter = NULL;
6385 char *source_file, *base;
6389 files = g_ptr_array_new ();
6391 while ((method = mono_class_get_methods (klass, &iter))) {
6392 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6395 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
6399 for (i = 0; i < files->len; ++i)
6400 if (!strcmp (g_ptr_array_index (files, i), source_file))
6402 if (i == files->len)
6403 g_ptr_array_add (files, g_strdup (source_file));
6404 g_free (source_file);
6408 buffer_add_int (buf, files->len);
6409 for (i = 0; i < files->len; ++i) {
6410 source_file = g_ptr_array_index (files, i);
6411 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
6412 buffer_add_string (buf, source_file);
6414 base = g_path_get_basename (source_file);
6415 buffer_add_string (buf, base);
6418 g_free (source_file);
6420 g_ptr_array_free (files, TRUE);
6423 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
6424 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
6428 if (mono_class_is_assignable_from (klass, oklass))
6429 buffer_add_byte (buf, 1);
6431 buffer_add_byte (buf, 0);
6435 return ERR_NOT_IMPLEMENTED;
6442 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6445 MonoDomain *old_domain;
6449 klass = decode_typeid (p, &p, end, &domain, &err);
6453 old_domain = mono_domain_get ();
6455 mono_domain_set (domain, TRUE);
6457 err = type_commands_internal (command, klass, domain, p, end, buf);
6459 mono_domain_set (old_domain, TRUE);
6465 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6467 MonoMethodHeader *header;
6470 case CMD_METHOD_GET_NAME: {
6471 buffer_add_string (buf, method->name);
6474 case CMD_METHOD_GET_DECLARING_TYPE: {
6475 buffer_add_typeid (buf, domain, method->klass);
6478 case CMD_METHOD_GET_DEBUG_INFO: {
6479 MonoDebugMethodInfo *minfo;
6481 int i, n_il_offsets;
6485 header = mono_method_get_header (method);
6487 buffer_add_int (buf, 0);
6488 buffer_add_string (buf, "");
6489 buffer_add_int (buf, 0);
6493 minfo = mono_debug_lookup_method (method);
6495 buffer_add_int (buf, header->code_size);
6496 buffer_add_string (buf, "");
6497 buffer_add_int (buf, 0);
6498 mono_metadata_free_mh (header);
6502 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
6503 buffer_add_int (buf, header->code_size);
6504 buffer_add_string (buf, source_file);
6505 buffer_add_int (buf, n_il_offsets);
6506 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
6507 for (i = 0; i < n_il_offsets; ++i) {
6508 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
6509 buffer_add_int (buf, il_offsets [i]);
6510 buffer_add_int (buf, line_numbers [i]);
6512 g_free (source_file);
6513 g_free (il_offsets);
6514 g_free (line_numbers);
6515 mono_metadata_free_mh (header);
6518 case CMD_METHOD_GET_PARAM_INFO: {
6519 MonoMethodSignature *sig = mono_method_signature (method);
6523 /* FIXME: mono_class_from_mono_type () and byrefs */
6525 /* FIXME: Use a smaller encoding */
6526 buffer_add_int (buf, sig->call_convention);
6527 buffer_add_int (buf, sig->param_count);
6528 buffer_add_int (buf, sig->generic_param_count);
6529 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
6530 for (i = 0; i < sig->param_count; ++i) {
6532 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
6535 /* Emit parameter names */
6536 names = g_new (char *, sig->param_count);
6537 mono_method_get_param_names (method, (const char **) names);
6538 for (i = 0; i < sig->param_count; ++i)
6539 buffer_add_string (buf, names [i]);
6544 case CMD_METHOD_GET_LOCALS_INFO: {
6545 int i, j, num_locals;
6546 MonoDebugLocalsInfo *locals;
6548 header = mono_method_get_header (method);
6551 buffer_add_int (buf, header->num_locals);
6554 for (i = 0; i < header->num_locals; ++i)
6555 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
6558 locals = mono_debug_lookup_locals (method);
6560 num_locals = locals->num_locals;
6563 for (i = 0; i < header->num_locals; ++i) {
6564 for (j = 0; j < num_locals; ++j)
6565 if (locals->locals [j].index == i)
6568 buffer_add_string (buf, locals->locals [j].name);
6570 buffer_add_string (buf, "");
6574 for (i = 0; i < header->num_locals; ++i) {
6575 for (j = 0; j < num_locals; ++j)
6576 if (locals->locals [j].index == i)
6578 if (j < num_locals && locals->locals [j].block) {
6579 buffer_add_int (buf, locals->locals [j].block->start_offset);
6580 buffer_add_int (buf, locals->locals [j].block->end_offset);
6582 buffer_add_int (buf, 0);
6583 buffer_add_int (buf, header->code_size);
6586 mono_metadata_free_mh (header);
6589 mono_debug_symfile_free_locals (locals);
6593 case CMD_METHOD_GET_INFO:
6594 buffer_add_int (buf, method->flags);
6595 buffer_add_int (buf, method->iflags);
6596 buffer_add_int (buf, method->token);
6598 case CMD_METHOD_GET_BODY: {
6601 header = mono_method_get_header (method);
6603 buffer_add_int (buf, 0);
6605 buffer_add_int (buf, header->code_size);
6606 for (i = 0; i < header->code_size; ++i)
6607 buffer_add_byte (buf, header->code [i]);
6609 mono_metadata_free_mh (header);
6612 case CMD_METHOD_RESOLVE_TOKEN: {
6613 guint32 token = decode_int (p, &p, end);
6616 switch (mono_metadata_token_code (token)) {
6617 case MONO_TOKEN_STRING: {
6621 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
6624 s2 = mono_string_to_utf8 (s);
6626 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6627 buffer_add_string (buf, s2);
6633 MonoClass *handle_class;
6635 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6636 val = mono_method_get_wrapper_data (method, token);
6637 handle_class = mono_method_get_wrapper_data (method, token + 1);
6639 if (handle_class == NULL) {
6640 // Can't figure out the token type
6641 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
6645 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
6649 if (handle_class == mono_defaults.typehandle_class) {
6650 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
6651 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
6652 buffer_add_typeid (buf, domain, (MonoClass *) val);
6654 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
6655 } else if (handle_class == mono_defaults.fieldhandle_class) {
6656 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
6657 buffer_add_fieldid (buf, domain, val);
6658 } else if (handle_class == mono_defaults.methodhandle_class) {
6659 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
6660 buffer_add_methodid (buf, domain, val);
6661 } else if (handle_class == mono_defaults.string_class) {
6664 s = mono_string_to_utf8 (val);
6665 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6666 buffer_add_string (buf, s);
6669 g_assert_not_reached ();
6677 return ERR_NOT_IMPLEMENTED;
6684 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6687 MonoDomain *old_domain;
6691 method = decode_methodid (p, &p, end, &domain, &err);
6695 old_domain = mono_domain_get ();
6697 mono_domain_set (domain, TRUE);
6699 err = method_commands_internal (command, method, domain, p, end, buf);
6701 mono_domain_set (old_domain, TRUE);
6707 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6709 int objid = decode_objid (p, &p, end);
6711 MonoThread *thread_obj;
6712 MonoInternalThread *thread;
6714 err = get_object (objid, (MonoObject**)&thread_obj);
6718 thread = THREAD_TO_INTERNAL (thread_obj);
6721 case CMD_THREAD_GET_NAME: {
6723 gunichar2 *s = mono_thread_get_name (thread, &name_len);
6726 buffer_add_int (buf, 0);
6731 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
6733 buffer_add_int (buf, len);
6734 buffer_add_data (buf, (guint8*)name, len);
6739 case CMD_THREAD_GET_FRAME_INFO: {
6740 DebuggerTlsData *tls;
6741 int i, start_frame, length;
6743 // Wait for suspending if it already started
6745 wait_for_suspend ();
6746 if (!is_suspended ())
6747 return ERR_NOT_SUSPENDED;
6749 start_frame = decode_int (p, &p, end);
6750 length = decode_int (p, &p, end);
6752 if (start_frame != 0 || length != -1)
6753 return ERR_NOT_IMPLEMENTED;
6755 mono_loader_lock ();
6756 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6757 mono_loader_unlock ();
6760 compute_frame_info (thread, tls);
6762 buffer_add_int (buf, tls->frame_count);
6763 for (i = 0; i < tls->frame_count; ++i) {
6764 buffer_add_int (buf, tls->frames [i]->id);
6765 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
6766 buffer_add_int (buf, tls->frames [i]->il_offset);
6768 * Instead of passing the frame type directly to the client, we associate
6769 * it with the previous frame using a set of flags. This avoids lots of
6770 * conditional code in the client, since a frame whose type isn't
6771 * FRAME_TYPE_MANAGED has no method, location, etc.
6773 buffer_add_byte (buf, tls->frames [i]->flags);
6778 case CMD_THREAD_GET_STATE:
6779 buffer_add_int (buf, thread->state);
6781 case CMD_THREAD_GET_INFO:
6782 buffer_add_byte (buf, thread->threadpool_thread);
6784 case CMD_THREAD_GET_ID:
6785 buffer_add_long (buf, (guint64)(gsize)thread);
6787 case CMD_THREAD_GET_TID:
6788 buffer_add_long (buf, (guint64)thread->tid);
6791 return ERR_NOT_IMPLEMENTED;
6798 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6802 MonoThread *thread_obj;
6803 MonoInternalThread *thread;
6804 int pos, i, len, frame_idx;
6805 DebuggerTlsData *tls;
6807 MonoDebugMethodJitInfo *jit;
6808 MonoDebugVarInfo *var;
6809 MonoMethodSignature *sig;
6811 MonoMethodHeader *header;
6813 objid = decode_objid (p, &p, end);
6814 err = get_object (objid, (MonoObject**)&thread_obj);
6818 thread = THREAD_TO_INTERNAL (thread_obj);
6820 id = decode_id (p, &p, end);
6822 mono_loader_lock ();
6823 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6824 mono_loader_unlock ();
6827 for (i = 0; i < tls->frame_count; ++i) {
6828 if (tls->frames [i]->id == id)
6831 if (i == tls->frame_count)
6832 return ERR_INVALID_FRAMEID;
6835 frame = tls->frames [frame_idx];
6837 if (!frame->has_ctx)
6839 return ERR_INVALID_FRAMEID;
6842 frame->jit = mono_debug_find_method (frame->method, frame->domain);
6844 /* This could happen for aot images with no jit debug info */
6845 return ERR_ABSENT_INFORMATION;
6849 sig = mono_method_signature (frame->actual_method);
6852 case CMD_STACK_FRAME_GET_VALUES: {
6853 len = decode_int (p, &p, end);
6854 header = mono_method_get_header (frame->actual_method);
6856 for (i = 0; i < len; ++i) {
6857 pos = decode_int (p, &p, end);
6862 g_assert (pos >= 0 && pos < jit->num_params);
6864 var = &jit->params [pos];
6866 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
6868 g_assert (pos >= 0 && pos < jit->num_locals);
6870 var = &jit->locals [pos];
6872 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
6875 mono_metadata_free_mh (header);
6878 case CMD_STACK_FRAME_GET_THIS: {
6879 if (frame->method->klass->valuetype) {
6880 if (!sig->hasthis) {
6881 MonoObject *p = NULL;
6882 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
6884 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6887 if (!sig->hasthis) {
6888 MonoObject *p = NULL;
6889 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
6891 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6896 case CMD_STACK_FRAME_SET_VALUES: {
6899 MonoDebugVarInfo *var;
6901 len = decode_int (p, &p, end);
6902 header = mono_method_get_header (frame->actual_method);
6904 for (i = 0; i < len; ++i) {
6905 pos = decode_int (p, &p, end);
6910 g_assert (pos >= 0 && pos < jit->num_params);
6912 t = sig->params [pos];
6913 var = &jit->params [pos];
6915 g_assert (pos >= 0 && pos < jit->num_locals);
6917 t = header->locals [pos];
6918 var = &jit->locals [pos];
6921 if (MONO_TYPE_IS_REFERENCE (t))
6922 val_buf = g_alloca (sizeof (MonoObject*));
6924 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
6925 err = decode_value (t, frame->domain, val_buf, p, &p, end);
6929 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
6931 mono_metadata_free_mh (header);
6935 return ERR_NOT_IMPLEMENTED;
6942 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6945 int objid, err, index, len, i, esize;
6948 objid = decode_objid (p, &p, end);
6949 err = get_object (objid, (MonoObject**)&arr);
6954 case CMD_ARRAY_REF_GET_LENGTH:
6955 buffer_add_int (buf, arr->obj.vtable->klass->rank);
6957 buffer_add_int (buf, arr->max_length);
6958 buffer_add_int (buf, 0);
6960 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
6961 buffer_add_int (buf, arr->bounds [i].length);
6962 buffer_add_int (buf, arr->bounds [i].lower_bound);
6966 case CMD_ARRAY_REF_GET_VALUES:
6967 index = decode_int (p, &p, end);
6968 len = decode_int (p, &p, end);
6970 g_assert (index >= 0 && len >= 0);
6971 // Reordered to avoid integer overflow
6972 g_assert (!(index > arr->max_length - len));
6974 esize = mono_array_element_size (arr->obj.vtable->klass);
6975 for (i = index; i < index + len; ++i) {
6976 elem = (gpointer*)((char*)arr->vector + (i * esize));
6977 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
6980 case CMD_ARRAY_REF_SET_VALUES:
6981 index = decode_int (p, &p, end);
6982 len = decode_int (p, &p, end);
6984 g_assert (index >= 0 && len >= 0);
6985 // Reordered to avoid integer overflow
6986 g_assert (!(index > arr->max_length - len));
6988 esize = mono_array_element_size (arr->obj.vtable->klass);
6989 for (i = index; i < index + len; ++i) {
6990 elem = (gpointer*)((char*)arr->vector + (i * esize));
6992 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
6996 return ERR_NOT_IMPLEMENTED;
7003 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7009 objid = decode_objid (p, &p, end);
7010 err = get_object (objid, (MonoObject**)&str);
7015 case CMD_STRING_REF_GET_VALUE:
7016 s = mono_string_to_utf8 (str);
7017 buffer_add_string (buf, s);
7021 return ERR_NOT_IMPLEMENTED;
7028 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7037 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
7038 objid = decode_objid (p, &p, end);
7039 err = get_object (objid, &obj);
7041 buffer_add_int (buf, 1);
7043 buffer_add_int (buf, 0);
7047 objid = decode_objid (p, &p, end);
7048 err = get_object (objid, &obj);
7053 case CMD_OBJECT_REF_GET_TYPE:
7054 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
7056 case CMD_OBJECT_REF_GET_VALUES:
7057 len = decode_int (p, &p, end);
7059 for (i = 0; i < len; ++i) {
7060 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
7064 /* Check that the field belongs to the object */
7066 for (k = obj->vtable->klass; k; k = k->parent) {
7067 if (k == f->parent) {
7073 return ERR_INVALID_FIELDID;
7075 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
7079 if (mono_class_field_is_special_static (f))
7080 return ERR_INVALID_FIELDID;
7082 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
7083 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
7084 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7085 mono_field_static_get_value (vtable, f, val);
7086 buffer_add_value (buf, f->type, val, obj->vtable->domain);
7089 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
7093 case CMD_OBJECT_REF_SET_VALUES:
7094 len = decode_int (p, &p, end);
7096 for (i = 0; i < len; ++i) {
7097 f = decode_fieldid (p, &p, end, NULL, &err);
7101 /* Check that the field belongs to the object */
7103 for (k = obj->vtable->klass; k; k = k->parent) {
7104 if (k == f->parent) {
7110 return ERR_INVALID_FIELDID;
7112 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
7116 if (mono_class_field_is_special_static (f))
7117 return ERR_INVALID_FIELDID;
7119 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
7120 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
7122 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7123 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
7128 mono_field_static_set_value (vtable, f, val);
7131 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
7137 case CMD_OBJECT_REF_GET_ADDRESS:
7138 buffer_add_long (buf, (gssize)obj);
7140 case CMD_OBJECT_REF_GET_DOMAIN:
7141 buffer_add_domainid (buf, obj->vtable->domain);
7144 return ERR_NOT_IMPLEMENTED;
7151 command_set_to_string (CommandSet command_set)
7153 switch (command_set) {
7156 case CMD_SET_OBJECT_REF:
7157 return "OBJECT_REF";
7158 case CMD_SET_STRING_REF:
7159 return "STRING_REF";
7160 case CMD_SET_THREAD:
7162 case CMD_SET_ARRAY_REF:
7164 case CMD_SET_EVENT_REQUEST:
7165 return "EVENT_REQUEST";
7166 case CMD_SET_STACK_FRAME:
7167 return "STACK_FRAME";
7168 case CMD_SET_APPDOMAIN:
7170 case CMD_SET_ASSEMBLY:
7172 case CMD_SET_METHOD:
7176 case CMD_SET_MODULE:
7186 cmd_to_string (CommandSet set, int command)
7191 case CMD_VM_VERSION:
7193 case CMD_VM_ALL_THREADS:
7194 return "ALL_THREADS";
7195 case CMD_VM_SUSPEND:
7201 case CMD_VM_DISPOSE:
7203 case CMD_VM_INVOKE_METHOD:
7204 return "INVOKE_METHOD";
7205 case CMD_VM_SET_PROTOCOL_VERSION:
7206 return "SET_PROTOCOL_VERSION";
7207 case CMD_VM_ABORT_INVOKE:
7208 return "ABORT_INVOKE";
7221 wait_for_attach (void)
7223 if (listen_fd == -1) {
7224 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
7228 /* Block and wait for client connection */
7229 conn_fd = transport_accept (listen_fd);
7230 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
7231 if (conn_fd == -1) {
7232 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
7237 disconnected = !transport_handshake ();
7239 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
7249 * This thread handles communication with the debugger client using a JDWP
7252 static guint32 WINAPI
7253 debugger_thread (void *arg)
7255 int res, len, id, flags, command_set = 0, command = 0;
7256 guint8 header [HEADER_LENGTH];
7257 guint8 *data, *p, *end;
7261 gboolean attach_failed = FALSE;
7263 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
7265 debugger_thread_id = GetCurrentThreadId ();
7267 mono_jit_thread_attach (mono_get_root_domain ());
7269 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
7271 mono_set_is_debugger_attached (TRUE);
7273 if (agent_config.defer) {
7274 if (!wait_for_attach ()) {
7275 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
7276 attach_failed = TRUE; // Don't abort process when we can't listen
7278 /* Send start event to client */
7279 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
7283 while (!attach_failed) {
7284 res = recv_length (conn_fd, header, HEADER_LENGTH, 0);
7286 /* This will break if the socket is closed during shutdown too */
7287 if (res != HEADER_LENGTH)
7291 end = header + HEADER_LENGTH;
7293 len = decode_int (p, &p, end);
7294 id = decode_int (p, &p, end);
7295 flags = decode_byte (p, &p, end);
7296 command_set = decode_byte (p, &p, end);
7297 command = decode_byte (p, &p, end);
7299 g_assert (flags == 0);
7302 const char *cmd_str;
7305 cmd_str = cmd_to_string (command_set, command);
7307 sprintf (cmd_num, "%d", command);
7311 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
7314 data = g_malloc (len - HEADER_LENGTH);
7315 if (len - HEADER_LENGTH > 0)
7317 res = recv_length (conn_fd, data, len - HEADER_LENGTH, 0);
7318 if (res != len - HEADER_LENGTH)
7323 end = data + (len - HEADER_LENGTH);
7325 buffer_init (&buf, 128);
7330 /* Process the request */
7331 switch (command_set) {
7333 err = vm_commands (command, id, p, end, &buf);
7334 if (!err && command == CMD_VM_INVOKE_METHOD)
7335 /* Sent after the invoke is complete */
7338 case CMD_SET_EVENT_REQUEST:
7339 err = event_commands (command, p, end, &buf);
7341 case CMD_SET_APPDOMAIN:
7342 err = domain_commands (command, p, end, &buf);
7344 case CMD_SET_ASSEMBLY:
7345 err = assembly_commands (command, p, end, &buf);
7347 case CMD_SET_MODULE:
7348 err = module_commands (command, p, end, &buf);
7351 err = type_commands (command, p, end, &buf);
7353 case CMD_SET_METHOD:
7354 err = method_commands (command, p, end, &buf);
7356 case CMD_SET_THREAD:
7357 err = thread_commands (command, p, end, &buf);
7359 case CMD_SET_STACK_FRAME:
7360 err = frame_commands (command, p, end, &buf);
7362 case CMD_SET_ARRAY_REF:
7363 err = array_commands (command, p, end, &buf);
7365 case CMD_SET_STRING_REF:
7366 err = string_commands (command, p, end, &buf);
7368 case CMD_SET_OBJECT_REF:
7369 err = object_commands (command, p, end, &buf);
7372 err = ERR_NOT_IMPLEMENTED;
7376 send_reply_packet (id, err, &buf);
7381 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
7385 mono_set_is_debugger_attached (FALSE);
7387 mono_mutex_lock (&debugger_thread_exited_mutex);
7388 debugger_thread_exited = TRUE;
7389 mono_cond_signal (&debugger_thread_exited_cond);
7390 mono_mutex_unlock (&debugger_thread_exited_mutex);
7392 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
7394 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
7395 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
7396 start_debugger_thread ();
7402 #else /* DISABLE_DEBUGGER_AGENT */
7405 mono_debugger_agent_parse_options (char *options)
7407 g_error ("This runtime is configured with the debugger agent disabled.");
7411 mono_debugger_agent_init (void)
7416 mono_debugger_agent_breakpoint_hit (void *sigctx)
7421 mono_debugger_agent_single_step_event (void *sigctx)
7426 mono_debugger_agent_free_domain_info (MonoDomain *domain)
7431 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
7437 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
7438 MonoContext *catch_ctx)
7443 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
7448 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)