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 "debugger-agent.h"
79 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
80 #define DISABLE_DEBUGGER_AGENT 1
83 #ifdef DISABLE_SOFT_DEBUG
84 #define DISABLE_DEBUGGER_AGENT 1
87 #ifndef DISABLE_DEBUGGER_AGENT
89 #include <mono/io-layer/mono-mutex.h>
91 /* Definitions to make backporting to 2.6 easier */
92 //#define MonoInternalThread MonoThread
93 //#define mono_thread_internal_current mono_thread_current
94 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
115 guint32 il_offset, native_offset;
119 * If method is gshared, this is the actual instance, otherwise this is equal to
122 MonoMethod *actual_method;
124 MonoDebugMethodJitInfo *jit;
127 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
128 * the frame can become invalid.
133 typedef struct _InvokeData InvokeData;
141 /* This is the context which needs to be restored after the invoke */
145 * If this is set, invoke this method with the arguments given by ARGS.
149 guint32 suspend_count;
151 InvokeData *last_invoke;
158 gboolean has_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 MonoContext async_ctx;
217 gboolean has_async_ctx;
219 gboolean has_filter_ctx;
220 MonoContext filter_ctx;
224 * The lmf where the stack walk can be started for running threads.
229 * The callee address of the last mono_runtime_invoke call
231 gpointer invoke_addr;
233 gboolean abort_requested;
236 * The current mono_runtime_invoke invocation.
241 * The context where single stepping should resume while the thread is suspended because
242 * of an EXCEPTION event.
244 MonoContext catch_ctx;
246 gboolean has_catch_ctx;
250 * Wire Protocol definitions
253 #define HEADER_LENGTH 11
255 #define MAJOR_VERSION 2
256 #define MINOR_VERSION 3
260 CMD_SET_OBJECT_REF = 9,
261 CMD_SET_STRING_REF = 10,
263 CMD_SET_ARRAY_REF = 13,
264 CMD_SET_EVENT_REQUEST = 15,
265 CMD_SET_STACK_FRAME = 16,
266 CMD_SET_APPDOMAIN = 20,
267 CMD_SET_ASSEMBLY = 21,
275 EVENT_KIND_VM_START = 0,
276 EVENT_KIND_VM_DEATH = 1,
277 EVENT_KIND_THREAD_START = 2,
278 EVENT_KIND_THREAD_DEATH = 3,
279 EVENT_KIND_APPDOMAIN_CREATE = 4,
280 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
281 EVENT_KIND_METHOD_ENTRY = 6,
282 EVENT_KIND_METHOD_EXIT = 7,
283 EVENT_KIND_ASSEMBLY_LOAD = 8,
284 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
285 EVENT_KIND_BREAKPOINT = 10,
286 EVENT_KIND_STEP = 11,
287 EVENT_KIND_TYPE_LOAD = 12,
288 EVENT_KIND_EXCEPTION = 13
292 SUSPEND_POLICY_NONE = 0,
293 SUSPEND_POLICY_EVENT_THREAD = 1,
294 SUSPEND_POLICY_ALL = 2
299 ERR_INVALID_OBJECT = 20,
300 ERR_INVALID_FIELDID = 25,
301 ERR_INVALID_FRAMEID = 30,
302 ERR_NOT_IMPLEMENTED = 100,
303 ERR_NOT_SUSPENDED = 101,
304 ERR_INVALID_ARGUMENT = 102,
306 ERR_NO_INVOCATION = 104,
307 ERR_ABSENT_INFORMATION = 105,
308 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106
313 MOD_KIND_THREAD_ONLY = 3,
314 MOD_KIND_LOCATION_ONLY = 7,
315 MOD_KIND_EXCEPTION_ONLY = 8,
317 MOD_KIND_ASSEMBLY_ONLY = 11
332 TOKEN_TYPE_STRING = 0,
334 TOKEN_TYPE_FIELD = 2,
335 TOKEN_TYPE_METHOD = 3,
336 TOKEN_TYPE_UNKNOWN = 4
340 VALUE_TYPE_ID_NULL = 0xf0,
341 VALUE_TYPE_ID_TYPE = 0xf1
345 FRAME_FLAG_DEBUGGER_INVOKE = 1
349 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
350 INVOKE_FLAG_SINGLE_THREADED = 2
355 CMD_VM_ALL_THREADS = 2,
360 CMD_VM_INVOKE_METHOD = 7,
361 CMD_VM_SET_PROTOCOL_VERSION = 8,
362 CMD_VM_ABORT_INVOKE = 9
366 CMD_THREAD_GET_FRAME_INFO = 1,
367 CMD_THREAD_GET_NAME = 2,
368 CMD_THREAD_GET_STATE = 3,
369 CMD_THREAD_GET_INFO = 4,
370 CMD_THREAD_GET_ID = 5,
371 CMD_THREAD_GET_TID = 6
375 CMD_EVENT_REQUEST_SET = 1,
376 CMD_EVENT_REQUEST_CLEAR = 2,
377 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
385 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
386 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
387 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
388 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
389 CMD_APPDOMAIN_CREATE_STRING = 5,
390 CMD_APPDOMAIN_GET_CORLIB = 6,
391 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
395 CMD_ASSEMBLY_GET_LOCATION = 1,
396 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
397 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
398 CMD_ASSEMBLY_GET_OBJECT = 4,
399 CMD_ASSEMBLY_GET_TYPE = 5,
400 CMD_ASSEMBLY_GET_NAME = 6
404 CMD_MODULE_GET_INFO = 1,
408 CMD_METHOD_GET_NAME = 1,
409 CMD_METHOD_GET_DECLARING_TYPE = 2,
410 CMD_METHOD_GET_DEBUG_INFO = 3,
411 CMD_METHOD_GET_PARAM_INFO = 4,
412 CMD_METHOD_GET_LOCALS_INFO = 5,
413 CMD_METHOD_GET_INFO = 6,
414 CMD_METHOD_GET_BODY = 7,
415 CMD_METHOD_RESOLVE_TOKEN = 8,
419 CMD_TYPE_GET_INFO = 1,
420 CMD_TYPE_GET_METHODS = 2,
421 CMD_TYPE_GET_FIELDS = 3,
422 CMD_TYPE_GET_VALUES = 4,
423 CMD_TYPE_GET_OBJECT = 5,
424 CMD_TYPE_GET_SOURCE_FILES = 6,
425 CMD_TYPE_SET_VALUES = 7,
426 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
427 CMD_TYPE_GET_PROPERTIES = 9,
428 CMD_TYPE_GET_CATTRS = 10,
429 CMD_TYPE_GET_FIELD_CATTRS = 11,
430 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
431 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
432 CMD_TYPE_GET_VALUES_2 = 14
436 CMD_STACK_FRAME_GET_VALUES = 1,
437 CMD_STACK_FRAME_GET_THIS = 2,
438 CMD_STACK_FRAME_SET_VALUES = 3
442 CMD_ARRAY_REF_GET_LENGTH = 1,
443 CMD_ARRAY_REF_GET_VALUES = 2,
444 CMD_ARRAY_REF_SET_VALUES = 3,
448 CMD_STRING_REF_GET_VALUE = 1,
452 CMD_OBJECT_REF_GET_TYPE = 1,
453 CMD_OBJECT_REF_GET_VALUES = 2,
454 CMD_OBJECT_REF_IS_COLLECTED = 3,
455 CMD_OBJECT_REF_GET_ADDRESS = 4,
456 CMD_OBJECT_REF_GET_DOMAIN = 5,
457 CMD_OBJECT_REF_SET_VALUES = 6
463 int count; /* For kind == MOD_KIND_COUNT */
464 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
465 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
466 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
468 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
477 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
481 * Describes a single step request.
485 MonoInternalThread *thread;
490 MonoMethod *last_method;
492 /* Whenever single stepping is performed using start/stop_single_stepping () */
494 /* The list of breakpoints used to implement step-over */
499 * Contains additional information for an event
502 /* For EVENT_KIND_EXCEPTION */
504 MonoContext catch_ctx;
508 /* Dummy structure used for the profiler callbacks */
513 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
519 static AgentConfig agent_config;
522 * Whenever the agent is fully initialized.
523 * When using the onuncaught or onthrow options, only some parts of the agent are
524 * initialized on startup, and the full initialization which includes connection
525 * establishment and the startup of the agent thread is only done in response to
528 static gint32 inited;
531 static int listen_fd;
533 static int packet_id = 0;
535 static int objref_id = 0;
537 static int event_request_id = 0;
539 static int frame_id = 0;
541 static GPtrArray *event_requests;
543 static guint32 debugger_tls_id;
545 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
547 /* Maps MonoInternalThread -> DebuggerTlsData */
548 static MonoGHashTable *thread_to_tls;
550 /* Maps tid -> MonoInternalThread */
551 static MonoGHashTable *tid_to_thread;
553 /* Maps tid -> MonoThread (not MonoInternalThread) */
554 static MonoGHashTable *tid_to_thread_obj;
556 static gsize debugger_thread_id;
558 static HANDLE debugger_thread_handle;
560 static int log_level;
562 static gboolean embedding;
564 static FILE *log_file;
566 /* Assemblies whose assembly load event has no been sent yet */
567 static GPtrArray *pending_assembly_loads;
569 /* Whenever the debugger thread has exited */
570 static gboolean debugger_thread_exited;
572 /* Cond variable used to wait for debugger_thread_exited becoming true */
573 static mono_cond_t debugger_thread_exited_cond;
575 /* Mutex for the cond var above */
576 static mono_mutex_t debugger_thread_exited_mutex;
578 static DebuggerProfiler debugger_profiler;
580 /* The single step request instance */
581 static SingleStepReq *ss_req = NULL;
582 static gpointer ss_invoke_addr = NULL;
584 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
585 /* Number of single stepping operations in progress */
589 /* The protocol version of the client */
590 static int major_version, minor_version;
592 /* Whenever the variables above are set by the client */
593 static gboolean protocol_version_set;
595 /* A hash table containing all active domains */
596 static GHashTable *domains;
598 static void transport_connect (const char *host, int port);
600 static guint32 WINAPI debugger_thread (void *arg);
602 static void runtime_initialized (MonoProfiler *prof);
604 static void runtime_shutdown (MonoProfiler *prof);
606 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
608 static void thread_end (MonoProfiler *prof, uintptr_t tid);
610 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
612 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
614 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
616 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
618 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
620 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
622 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
624 static void emit_assembly_load (gpointer assembly, gpointer user_data);
626 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
628 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
630 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
632 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
634 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
636 static void start_single_stepping (void);
638 static void stop_single_stepping (void);
640 static void suspend_current (void);
642 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
644 static void clear_types_for_assembly (MonoAssembly *assembly);
646 static void clear_breakpoints_for_domain (MonoDomain *domain);
648 static void process_profiler_event (EventKind event, gpointer arg);
650 /* Submodule init/cleanup */
651 static void breakpoints_init (void);
652 static void breakpoints_cleanup (void);
654 static void objrefs_init (void);
655 static void objrefs_cleanup (void);
657 static void ids_init (void);
658 static void ids_cleanup (void);
660 static void suspend_init (void);
662 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
663 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
664 static void ss_destroy (SingleStepReq *req);
666 static void start_debugger_thread (void);
667 static void stop_debugger_thread (void);
669 static void finish_agent_init (gboolean on_startup);
672 parse_address (char *address, char **host, int *port)
674 char *pos = strchr (address, ':');
676 if (pos == NULL || pos == address)
679 *host = g_malloc (pos - address + 1);
680 strncpy (*host, address, pos - address);
681 (*host) [pos - address] = '\0';
683 *port = atoi (pos + 1);
691 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
692 fprintf (stderr, "Available options:\n");
693 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
694 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
695 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
696 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
697 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
698 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
699 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
700 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
704 parse_flag (const char *option, char *flag)
706 if (!strcmp (flag, "y"))
708 else if (!strcmp (flag, "n"))
711 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
718 mono_debugger_agent_parse_options (char *options)
724 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
725 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
729 agent_config.enabled = TRUE;
730 agent_config.suspend = TRUE;
731 agent_config.server = FALSE;
732 agent_config.defer = FALSE;
733 agent_config.address = NULL;
735 args = g_strsplit (options, ",", -1);
736 for (ptr = args; ptr && *ptr; ptr ++) {
739 if (strncmp (arg, "transport=", 10) == 0) {
740 agent_config.transport = g_strdup (arg + 10);
741 } else if (strncmp (arg, "address=", 8) == 0) {
742 agent_config.address = g_strdup (arg + 8);
743 } else if (strncmp (arg, "loglevel=", 9) == 0) {
744 agent_config.log_level = atoi (arg + 9);
745 } else if (strncmp (arg, "logfile=", 8) == 0) {
746 agent_config.log_file = g_strdup (arg + 8);
747 } else if (strncmp (arg, "suspend=", 8) == 0) {
748 agent_config.suspend = parse_flag ("suspend", arg + 8);
749 } else if (strncmp (arg, "server=", 7) == 0) {
750 agent_config.server = parse_flag ("server", arg + 7);
751 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
752 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
753 } else if (strncmp (arg, "onthrow=", 8) == 0) {
754 /* We support multiple onthrow= options */
755 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
756 } else if (strncmp (arg, "onthrow", 7) == 0) {
757 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
758 } else if (strncmp (arg, "help", 4) == 0) {
761 } else if (strncmp (arg, "timeout=", 8) == 0) {
762 agent_config.timeout = atoi (arg + 8);
763 } else if (strncmp (arg, "launch=", 7) == 0) {
764 agent_config.launch = g_strdup (arg + 7);
765 } else if (strncmp (arg, "embedding=", 10) == 0) {
766 agent_config.embedding = atoi (arg + 10) == 1;
773 if (agent_config.server && !agent_config.suspend) {
774 /* Waiting for deferred attachment */
775 agent_config.defer = TRUE;
776 if (agent_config.address == NULL) {
777 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
781 if (agent_config.transport == NULL) {
782 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
785 if (strcmp (agent_config.transport, "dt_socket") != 0) {
786 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
790 if (agent_config.address == NULL && !agent_config.server) {
791 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
795 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
796 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
802 mono_debugger_agent_init (void)
804 if (!agent_config.enabled)
807 /* Need to know whenever a thread has acquired the loader mutex */
808 mono_loader_lock_track_ownership (TRUE);
810 event_requests = g_ptr_array_new ();
812 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
813 mono_cond_init (&debugger_thread_exited_cond, NULL);
815 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
816 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
817 mono_profiler_install_runtime_initialized (runtime_initialized);
818 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
819 mono_profiler_install_thread (thread_startup, thread_end);
820 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
821 mono_profiler_install_jit_end (jit_end);
822 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
824 debugger_tls_id = TlsAlloc ();
826 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
827 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
829 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
830 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
832 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
833 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
835 pending_assembly_loads = g_ptr_array_new ();
836 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
838 log_level = agent_config.log_level;
840 embedding = agent_config.embedding;
843 if (agent_config.log_file) {
844 log_file = fopen (agent_config.log_file, "w+");
846 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
858 mini_get_debug_options ()->gen_seq_points = TRUE;
860 * This is needed because currently we don't handle liveness info.
862 mini_get_debug_options ()->mdb_optimizations = TRUE;
864 /* This is needed because we can't set local variables in registers yet */
865 mono_disable_optimizations (MONO_OPT_LINEARS);
867 if (!agent_config.onuncaught && !agent_config.onthrow)
868 finish_agent_init (TRUE);
874 * Finish the initialization of the agent. This involves connecting the transport
875 * and starting the agent thread. This is either done at startup, or
876 * in response to some event like an unhandled exception.
879 finish_agent_init (gboolean on_startup)
885 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
888 if (agent_config.launch) {
891 // FIXME: Generated address
892 // FIXME: Races with transport_connect ()
894 argv [0] = agent_config.launch;
895 argv [1] = agent_config.transport;
896 argv [2] = agent_config.address;
899 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
901 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
906 if (agent_config.address) {
907 res = parse_address (agent_config.address, &host, &port);
914 transport_connect (host, port);
917 /* Do some which is usually done after sending the VMStart () event */
918 vm_start_event_sent = TRUE;
919 start_debugger_thread ();
924 mono_debugger_agent_cleanup (void)
929 stop_debugger_thread ();
931 breakpoints_cleanup ();
935 mono_mutex_destroy (&debugger_thread_exited_mutex);
936 mono_cond_destroy (&debugger_thread_exited_cond);
942 * recv() + handle incomplete reads and EINTR
945 recv_length (int fd, void *buf, int len, int flags)
951 res = recv (fd, (char *) buf + total, len - total, flags);
954 } while ((res > 0 && total < len) || (res == -1 && errno == EINTR));
959 #define HAVE_GETADDRINFO 1
963 transport_accept (int socket_fd)
965 conn_fd = accept (socket_fd, NULL, NULL);
967 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
969 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
976 transport_handshake (void)
978 char handshake_msg [128];
982 /* Write handshake message */
983 sprintf (handshake_msg, "DWP-Handshake");
985 res = send (conn_fd, handshake_msg, strlen (handshake_msg), 0);
986 } while (res == -1 && errno == EINTR);
987 g_assert (res != -1);
990 res = recv_length (conn_fd, buf, strlen (handshake_msg), 0);
991 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
992 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
997 * To support older clients, the client sends its protocol version after connecting
998 * using a command. Until that is received, default to our protocol version.
1000 major_version = MAJOR_VERSION;
1001 minor_version = MINOR_VERSION;
1002 protocol_version_set = FALSE;
1005 * Set TCP_NODELAY on the socket so the client receives events/command
1006 * results immediately.
1010 int result = setsockopt (conn_fd,
1015 g_assert (result >= 0);
1022 * transport_connect:
1024 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1027 transport_connect (const char *host, int port)
1029 #ifdef HAVE_GETADDRINFO
1030 struct addrinfo hints;
1031 struct addrinfo *result, *rp;
1033 struct hostent *result;
1036 char port_string [128];
1042 sprintf (port_string, "%d", port);
1044 mono_network_init ();
1046 /* Obtain address(es) matching host/port */
1047 #ifdef HAVE_GETADDRINFO
1048 memset (&hints, 0, sizeof (struct addrinfo));
1049 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1050 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1052 hints.ai_protocol = 0; /* Any protocol */
1054 s = getaddrinfo (host, port_string, &hints, &result);
1056 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1060 /* The PS3 doesn't even have _r or hstrerror () */
1061 result = gethostbyname (host);
1063 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1068 if (agent_config.server) {
1069 #ifdef HAVE_GETADDRINFO
1070 /* Wait for a connection */
1072 struct sockaddr_in addr;
1075 /* No address, generate one */
1076 sfd = socket (AF_INET, SOCK_STREAM, 0);
1079 /* This will bind the socket to a random port */
1080 res = listen (sfd, 16);
1082 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
1087 addrlen = sizeof (addr);
1088 memset (&addr, 0, sizeof (addr));
1089 res = getsockname (sfd, &addr, &addrlen);
1090 g_assert (res == 0);
1093 port = ntohs (addr.sin_port);
1095 /* Emit the address to stdout */
1096 /* FIXME: Should print another interface, not localhost */
1097 printf ("%s:%d\n", host, port);
1099 /* Listen on the provided address */
1100 for (rp = result; rp != NULL; rp = rp->ai_next) {
1101 sfd = socket (rp->ai_family, rp->ai_socktype,
1106 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1110 res = listen (sfd, 16);
1119 * this function is not present on win2000 which we still support, and the
1120 * workaround described here:
1121 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1122 * only works with MSVC.
1124 #ifdef HAVE_GETADDRINFO
1125 freeaddrinfo (result);
1130 if (agent_config.defer)
1133 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1135 if (agent_config.timeout) {
1140 tv.tv_usec = agent_config.timeout * 1000;
1142 FD_SET (sfd, &readfds);
1143 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1145 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1150 conn_fd = transport_accept (sfd);
1154 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1157 #endif /* HAVE_GETADDRINFO */
1159 /* Connect to the specified address */
1160 #ifdef HAVE_GETADDRINFO
1161 /* FIXME: Respect the timeout */
1162 for (rp = result; rp != NULL; rp = rp->ai_next) {
1163 sfd = socket (rp->ai_family, rp->ai_socktype,
1168 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1169 break; /* Success */
1175 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1179 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1181 g_assert_not_reached ();
1182 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1184 g_assert_not_reached ();
1190 /* See the comment above */
1191 #ifdef HAVE_GETADDRINFO
1192 freeaddrinfo (result);
1197 disconnected = !transport_handshake ();
1203 transport_send (guint8 *data, int len)
1208 res = send (conn_fd, data, len, 0);
1209 } while (res == -1 && errno == EINTR);
1217 stop_debugger_thread (void)
1222 /* This will interrupt the agent thread */
1223 /* Close the read part only so it can still send back replies */
1224 /* Also shut down the connection listener so that we can exit normally */
1226 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1227 shutdown (conn_fd, SD_BOTH);
1228 shutdown (listen_fd, SD_BOTH);
1229 closesocket (listen_fd);
1231 shutdown (conn_fd, SHUT_RD);
1232 shutdown (listen_fd, SHUT_RDWR);
1237 * Wait for the thread to exit.
1239 * If we continue with the shutdown without waiting for it, then the client might
1240 * not receive an answer to its last command like a resume.
1241 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1244 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1245 if (GetCurrentThreadId () != debugger_thread_id) {
1247 mono_mutex_lock (&debugger_thread_exited_mutex);
1248 if (!debugger_thread_exited) {
1250 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1251 mono_mutex_unlock (&debugger_thread_exited_mutex);
1253 mono_mutex_lock (&debugger_thread_exited_mutex);
1256 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1259 mono_mutex_unlock (&debugger_thread_exited_mutex);
1260 } while (!debugger_thread_exited);
1264 shutdown (conn_fd, SD_BOTH);
1266 shutdown (conn_fd, SHUT_RDWR);
1271 start_debugger_thread (void)
1275 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1276 g_assert (debugger_thread_handle);
1280 * Functions to decode protocol data
1284 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1287 g_assert (*endbuf <= limit);
1292 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1295 g_assert (*endbuf <= limit);
1297 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1300 static inline gint64
1301 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1303 guint32 high = decode_int (buf, &buf, limit);
1304 guint32 low = decode_int (buf, &buf, limit);
1308 return ((((guint64)high) << 32) | ((guint64)low));
1312 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1314 return decode_int (buf, endbuf, limit);
1318 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1320 int len = decode_int (buf, &buf, limit);
1323 s = g_malloc (len + 1);
1326 memcpy (s, buf, len);
1335 * Functions to encode protocol data
1339 guint8 *buf, *p, *end;
1343 buffer_init (Buffer *buf, int size)
1345 buf->buf = g_malloc (size);
1347 buf->end = buf->buf + size;
1351 buffer_make_room (Buffer *buf, int size)
1353 if (buf->end - buf->p < size) {
1354 int new_size = buf->end - buf->buf + size + 32;
1355 guint8 *p = g_realloc (buf->buf, new_size);
1356 size = buf->p - buf->buf;
1359 buf->end = buf->buf + new_size;
1364 buffer_add_byte (Buffer *buf, guint8 val)
1366 buffer_make_room (buf, 1);
1372 buffer_add_int (Buffer *buf, guint32 val)
1374 buffer_make_room (buf, 4);
1375 buf->p [0] = (val >> 24) & 0xff;
1376 buf->p [1] = (val >> 16) & 0xff;
1377 buf->p [2] = (val >> 8) & 0xff;
1378 buf->p [3] = (val >> 0) & 0xff;
1383 buffer_add_long (Buffer *buf, guint64 l)
1385 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1386 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1390 buffer_add_id (Buffer *buf, int id)
1392 buffer_add_int (buf, (guint64)id);
1396 buffer_add_data (Buffer *buf, guint8 *data, int len)
1398 buffer_make_room (buf, len);
1399 memcpy (buf->p, data, len);
1404 buffer_add_string (Buffer *buf, const char *str)
1409 buffer_add_int (buf, 0);
1412 buffer_add_int (buf, len);
1413 buffer_add_data (buf, (guint8*)str, len);
1418 buffer_free (Buffer *buf)
1424 send_packet (int command_set, int command, Buffer *data)
1430 id = InterlockedIncrement (&packet_id);
1432 len = data->p - data->buf + 11;
1433 buffer_init (&buf, len);
1434 buffer_add_int (&buf, len);
1435 buffer_add_int (&buf, id);
1436 buffer_add_byte (&buf, 0); /* flags */
1437 buffer_add_byte (&buf, command_set);
1438 buffer_add_byte (&buf, command);
1439 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1441 res = transport_send (buf.buf, len);
1449 send_reply_packet (int id, int error, Buffer *data)
1455 len = data->p - data->buf + 11;
1456 buffer_init (&buf, len);
1457 buffer_add_int (&buf, len);
1458 buffer_add_int (&buf, id);
1459 buffer_add_byte (&buf, 0x80); /* flags */
1460 buffer_add_byte (&buf, (error >> 8) & 0xff);
1461 buffer_add_byte (&buf, error);
1462 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1464 res = transport_send (buf.buf, len);
1476 * Represents an object accessible by the debugger client.
1479 /* Unique id used in the wire protocol to refer to objects */
1482 * A weakref gc handle pointing to the object. The gc handle is used to
1483 * detect if the object was garbage collected.
1488 /* Maps objid -> ObjRef */
1489 static GHashTable *objrefs;
1492 free_objref (gpointer value)
1496 mono_gchandle_free (o->handle);
1504 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1508 objrefs_cleanup (void)
1510 g_hash_table_destroy (objrefs);
1514 static GHashTable *obj_to_objref;
1517 * Return an ObjRef for OBJ.
1520 get_objref (MonoObject *obj)
1523 GSList *reflist = NULL, *l;
1529 mono_loader_lock ();
1532 obj_to_objref = g_hash_table_new (NULL, NULL);
1534 /* FIXME: The tables can grow indefinitely */
1536 if (mono_gc_is_moving ()) {
1538 * Objects can move, so use a hash table mapping hash codes to lists of
1539 * ObjRef structures.
1541 hash = mono_object_hash (obj);
1543 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1544 for (l = reflist; l; l = l->next) {
1546 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1547 mono_loader_unlock ();
1552 /* Use a hash table with masked pointers to internalize object references */
1553 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1554 /* ref might refer to a different object with the same addr which was GCd */
1555 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1556 mono_loader_unlock ();
1561 ref = g_new0 (ObjRef, 1);
1562 ref->id = InterlockedIncrement (&objref_id);
1563 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1565 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1567 if (mono_gc_is_moving ()) {
1568 reflist = g_slist_append (reflist, ref);
1569 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1571 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1574 mono_loader_unlock ();
1580 get_objid (MonoObject *obj)
1582 return get_objref (obj)->id;
1586 * Set OBJ to the object identified by OBJID.
1587 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1591 get_object_allow_null (int objid, MonoObject **obj)
1601 return ERR_INVALID_OBJECT;
1603 mono_loader_lock ();
1605 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1608 *obj = mono_gchandle_get_target (ref->handle);
1609 mono_loader_unlock ();
1611 return ERR_INVALID_OBJECT;
1614 mono_loader_unlock ();
1615 return ERR_INVALID_OBJECT;
1620 get_object (int objid, MonoObject **obj)
1622 int err = get_object_allow_null (objid, obj);
1627 return ERR_INVALID_OBJECT;
1632 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1634 return decode_id (buf, endbuf, limit);
1638 buffer_add_objid (Buffer *buf, MonoObject *o)
1640 buffer_add_id (buf, get_objid (o));
1659 * Represents a runtime structure accessible to the debugger client
1662 /* Unique id used in the wire protocol */
1664 /* Domain of the runtime structure, NULL if the domain was unloaded */
1671 MonoAssembly *assembly;
1672 MonoClassField *field;
1674 MonoProperty *property;
1679 /* Maps runtime structure -> Id */
1680 GHashTable *val_to_id [ID_NUM];
1681 /* Classes whose class load event has been sent */
1682 GHashTable *loaded_classes;
1686 static GPtrArray *ids [ID_NUM];
1693 for (i = 0; i < ID_NUM; ++i)
1694 ids [i] = g_ptr_array_new ();
1702 for (i = 0; i < ID_NUM; ++i) {
1704 for (j = 0; j < ids [i]->len; ++j)
1705 g_free (g_ptr_array_index (ids [i], j));
1706 g_ptr_array_free (ids [i], TRUE);
1713 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1715 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1719 for (i = 0; i < ID_NUM; ++i)
1720 if (info->val_to_id [i])
1721 g_hash_table_destroy (info->val_to_id [i]);
1722 g_hash_table_destroy (info->loaded_classes);
1726 domain_jit_info (domain)->agent_info = NULL;
1728 /* Clear ids referencing structures in the domain */
1729 for (i = 0; i < ID_NUM; ++i) {
1731 for (j = 0; j < ids [i]->len; ++j) {
1732 Id *id = g_ptr_array_index (ids [i], j);
1733 if (id->domain == domain)
1739 mono_loader_lock ();
1740 g_hash_table_remove (domains, domain);
1741 mono_loader_unlock ();
1745 * Called when deferred debugger session is attached,
1746 * after the VM start event has been sent successfully
1749 mono_debugger_agent_on_attach (void)
1751 /* Emit load events for currently loaded appdomains, assemblies, and types */
1752 mono_loader_lock ();
1753 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
1754 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
1755 mono_assembly_foreach (emit_assembly_load, NULL);
1756 mono_loader_unlock ();
1759 static AgentDomainInfo*
1760 get_agent_domain_info (MonoDomain *domain)
1762 AgentDomainInfo *info = NULL;
1764 mono_domain_lock (domain);
1766 info = domain_jit_info (domain)->agent_info;
1768 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1769 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
1772 mono_domain_unlock (domain);
1778 get_id (MonoDomain *domain, IdType type, gpointer val)
1781 AgentDomainInfo *info;
1786 mono_loader_lock ();
1788 mono_domain_lock (domain);
1790 info = get_agent_domain_info (domain);
1792 if (info->val_to_id [type] == NULL)
1793 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1795 id = g_hash_table_lookup (info->val_to_id [type], val);
1797 mono_domain_unlock (domain);
1798 mono_loader_unlock ();
1802 id = g_new0 (Id, 1);
1804 id->id = ids [type]->len + 1;
1805 id->domain = domain;
1808 g_hash_table_insert (info->val_to_id [type], val, id);
1810 mono_domain_unlock (domain);
1812 g_ptr_array_add (ids [type], id);
1814 mono_loader_unlock ();
1819 static inline gpointer
1820 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1824 int id = decode_id (buf, endbuf, limit);
1833 // FIXME: error handling
1834 mono_loader_lock ();
1835 g_assert (id > 0 && id <= ids [type]->len);
1837 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1838 mono_loader_unlock ();
1840 if (res->domain == NULL) {
1841 *err = ERR_UNLOADED;
1846 *domain = res->domain;
1848 return res->data.val;
1852 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1854 buffer_add_id (buf, get_id (domain, type, val));
1857 static inline MonoClass*
1858 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1860 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1863 static inline MonoAssembly*
1864 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1866 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1869 static inline MonoImage*
1870 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1872 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1875 static inline MonoMethod*
1876 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1878 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1881 static inline MonoClassField*
1882 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1884 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1887 static inline MonoDomain*
1888 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1890 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1893 static inline MonoProperty*
1894 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1896 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1900 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1902 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1906 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1908 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1912 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1914 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1918 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1920 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1924 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1926 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1930 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1932 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1936 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1938 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1941 static void invoke_method (void);
1948 * save_thread_context:
1950 * Set CTX as the current threads context which is used for computing stack traces.
1951 * This function is signal-safe.
1954 save_thread_context (MonoContext *ctx)
1956 DebuggerTlsData *tls;
1958 tls = TlsGetValue (debugger_tls_id);
1962 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1964 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1965 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1967 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1971 tls->lmf = mono_get_lmf ();
1972 tls->domain = mono_domain_get ();
1973 tls->has_context = TRUE;
1976 /* The number of times the runtime is suspended */
1977 static gint32 suspend_count;
1979 /* Number of threads suspended */
1981 * If this is equal to the size of thread_to_tls, the runtime is considered
1984 static gint32 threads_suspend_count;
1986 static mono_mutex_t suspend_mutex;
1988 /* Cond variable used to wait for suspend_count becoming 0 */
1989 static mono_cond_t suspend_cond;
1991 /* Semaphore used to wait for a thread becoming suspended */
1992 static MonoSemType suspend_sem;
1997 mono_mutex_init (&suspend_mutex, NULL);
1998 mono_cond_init (&suspend_cond, NULL);
1999 MONO_SEM_INIT (&suspend_sem, 0);
2004 StackFrameInfo last_frame;
2005 gboolean last_frame_set;
2008 } GetLastFrameUserData;
2011 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2013 GetLastFrameUserData *data = user_data;
2015 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2018 if (!data->last_frame_set) {
2019 /* Store the last frame */
2020 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2021 data->last_frame_set = TRUE;
2024 /* Store the context/lmf for the frame above the last frame */
2025 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2026 data->lmf = info->lmf;
2033 * mono_debugger_agent_thread_interrupt:
2035 * Called by the abort signal handler.
2036 * Should be signal safe.
2039 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2041 DebuggerTlsData *tls;
2046 tls = TlsGetValue (debugger_tls_id);
2051 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2052 * guarantee the signal handler will be called that many times. Instead of tracking
2053 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2054 * has been requested that hasn't been handled yet, otherwise we can have threads
2055 * refuse to die when VM_EXIT is called
2057 #if defined(__APPLE__)
2058 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2062 * We use interrupt_count to determine whenever this interrupt should be processed
2063 * by us or the normal interrupt processing code in the signal handler.
2064 * There is no race here with notify_thread (), since the signal is sent after
2065 * incrementing interrupt_count.
2067 if (tls->interrupt_count == 0)
2070 InterlockedDecrement (&tls->interrupt_count);
2073 // FIXME: Races when the thread leaves managed code before hitting a single step
2077 /* Running managed code, will be suspended by the single step code */
2078 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)));
2082 * Running native code, will be suspended when it returns to/enters
2083 * managed code. Treat it as already suspended.
2084 * This might interrupt the code in process_single_step_inner (), we use the
2085 * tls->suspending flag to avoid races when that happens.
2087 if (!tls->suspended && !tls->suspending) {
2089 GetLastFrameUserData data;
2091 // FIXME: printf is not signal safe, but this is only used during
2092 // debugger debugging
2094 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)GetCurrentThreadId (), mono_arch_ip_from_context (sigctx)));
2095 //save_thread_context (&ctx);
2098 /* Already terminated */
2102 * We are in a difficult position: we want to be able to provide stack
2103 * traces for this thread, but we can't use the current ctx+lmf, since
2104 * the thread is still running, so it might return to managed code,
2105 * making these invalid.
2106 * So we start a stack walk and save the first frame, along with the
2107 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2108 * suspended when it returns to managed code, so the parent's ctx should
2111 data.last_frame_set = FALSE;
2113 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2114 mono_walk_stack (get_last_frame, mono_domain_get (), &ctx, MONO_UNWIND_DEFAULT, tls->thread, mono_get_lmf (), &data);
2116 if (data.last_frame_set) {
2117 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2118 memcpy (&tls->async_ctx, &data.ctx, sizeof (MonoContext));
2119 tls->async_lmf = data.lmf;
2120 tls->has_async_ctx = TRUE;
2121 tls->domain = mono_domain_get ();
2122 memcpy (&tls->ctx, &ctx, sizeof (MonoContext));
2124 tls->has_async_ctx = FALSE;
2127 mono_memory_barrier ();
2129 tls->suspended = TRUE;
2130 MONO_SEM_POST (&suspend_sem);
2137 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2140 mono_debugger_agent_thread_interrupt (NULL, NULL);
2142 #endif /* HOST_WIN32 */
2145 * reset_native_thread_suspend_state:
2147 * Reset the suspended flag on native threads
2150 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2152 DebuggerTlsData *tls = value;
2154 if (!tls->really_suspended && tls->suspended)
2155 tls->suspended = FALSE;
2161 * Notify a thread that it needs to suspend.
2164 notify_thread (gpointer key, gpointer value, gpointer user_data)
2166 MonoInternalThread *thread = key;
2167 DebuggerTlsData *tls = value;
2168 gsize tid = thread->tid;
2170 if (GetCurrentThreadId () == tid || tls->terminated)
2173 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2176 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2177 * guarantee the signal handler will be called that many times. Instead of tracking
2178 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2179 * has been requested that hasn't been handled yet, otherwise we can have threads
2180 * refuse to die when VM_EXIT is called
2182 #if defined(__APPLE__)
2183 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2187 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2188 * of things like breaking waits etc. which we don't want.
2190 InterlockedIncrement (&tls->interrupt_count);
2193 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2195 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2197 mono_thread_kill (thread, mono_thread_get_abort_signal ());
2202 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2204 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2207 if (mono_loader_lock_is_owned_by_self ()) {
2209 * Shortcut for the check in suspend_current (). This speeds up processing
2210 * when executing long running code inside the loader lock, i.e. assembly load
2216 if (debugger_thread_id == GetCurrentThreadId ())
2219 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2220 if (suspend_count - tls->resume_count > 0)
2221 tls->suspending = TRUE;
2223 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2225 if (suspend_count - tls->resume_count == 0) {
2227 * We are executing a single threaded invoke but the single step for
2228 * suspending is still active.
2229 * FIXME: This slows down single threaded invokes.
2231 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2235 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2237 /* Can't suspend in these methods */
2238 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2241 save_thread_context (ctx);
2249 * Increase the suspend count of the VM. While the suspend count is greater
2250 * than 0, runtime threads are suspended at certain points during execution.
2255 mono_loader_lock ();
2257 mono_mutex_lock (&suspend_mutex);
2261 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2263 if (suspend_count == 1) {
2264 // FIXME: Is it safe to call this inside the lock ?
2265 start_single_stepping ();
2266 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2269 mono_mutex_unlock (&suspend_mutex);
2271 mono_loader_unlock ();
2277 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2285 g_assert (debugger_thread_id == GetCurrentThreadId ());
2287 mono_loader_lock ();
2289 mono_mutex_lock (&suspend_mutex);
2291 g_assert (suspend_count > 0);
2294 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2296 if (suspend_count == 0) {
2297 // FIXME: Is it safe to call this inside the lock ?
2298 stop_single_stepping ();
2299 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2302 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2303 err = mono_cond_broadcast (&suspend_cond);
2304 g_assert (err == 0);
2306 mono_mutex_unlock (&suspend_mutex);
2307 //g_assert (err == 0);
2309 mono_loader_unlock ();
2315 * Resume just one thread.
2318 resume_thread (MonoInternalThread *thread)
2321 DebuggerTlsData *tls;
2323 g_assert (debugger_thread_id == GetCurrentThreadId ());
2325 mono_loader_lock ();
2327 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2330 mono_mutex_lock (&suspend_mutex);
2332 g_assert (suspend_count > 0);
2334 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2336 tls->resume_count += suspend_count;
2339 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2340 * but only the one whose resume_count field is > 0 will be resumed.
2342 err = mono_cond_broadcast (&suspend_cond);
2343 g_assert (err == 0);
2345 mono_mutex_unlock (&suspend_mutex);
2346 //g_assert (err == 0);
2348 mono_loader_unlock ();
2352 invalidate_frames (DebuggerTlsData *tls)
2357 tls = TlsGetValue (debugger_tls_id);
2360 for (i = 0; i < tls->frame_count; ++i) {
2361 if (tls->frames [i]->jit)
2362 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2363 g_free (tls->frames [i]);
2365 g_free (tls->frames);
2366 tls->frame_count = 0;
2373 * Suspend the current thread until the runtime is resumed. If the thread has a
2374 * pending invoke, then the invoke is executed before this function returns.
2377 suspend_current (void)
2380 DebuggerTlsData *tls;
2382 g_assert (debugger_thread_id != GetCurrentThreadId ());
2384 if (mono_loader_lock_is_owned_by_self ()) {
2386 * If we own the loader mutex, can't suspend until we release it, since the
2387 * whole runtime can deadlock otherwise.
2392 tls = TlsGetValue (debugger_tls_id);
2395 mono_mutex_lock (&suspend_mutex);
2397 tls->suspending = FALSE;
2398 tls->really_suspended = TRUE;
2400 if (!tls->suspended) {
2401 tls->suspended = TRUE;
2402 MONO_SEM_POST (&suspend_sem);
2405 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2407 while (suspend_count - tls->resume_count > 0) {
2409 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2411 mono_mutex_unlock (&suspend_mutex);
2413 mono_mutex_lock (&suspend_mutex);
2419 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2420 g_assert (err == 0);
2424 tls->suspended = FALSE;
2425 tls->really_suspended = FALSE;
2427 threads_suspend_count --;
2429 mono_mutex_unlock (&suspend_mutex);
2431 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2433 if (tls->pending_invoke) {
2434 /* Save the original context */
2435 tls->pending_invoke->has_ctx = TRUE;
2436 memcpy (&tls->pending_invoke->ctx, &tls->ctx, sizeof (MonoContext));
2441 /* The frame info becomes invalid after a resume */
2442 tls->has_context = FALSE;
2443 tls->has_async_ctx = FALSE;
2444 invalidate_frames (NULL);
2448 count_thread (gpointer key, gpointer value, gpointer user_data)
2450 DebuggerTlsData *tls = value;
2452 if (!tls->suspended && !tls->terminated)
2453 *(int*)user_data = *(int*)user_data + 1;
2457 count_threads_to_wait_for (void)
2461 mono_loader_lock ();
2462 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2463 mono_loader_unlock ();
2471 * Wait until the runtime is completely suspended.
2474 wait_for_suspend (void)
2476 int nthreads, nwait, err;
2477 gboolean waited = FALSE;
2479 // FIXME: Threads starting/stopping ?
2480 mono_loader_lock ();
2481 nthreads = mono_g_hash_table_size (thread_to_tls);
2482 mono_loader_unlock ();
2485 nwait = count_threads_to_wait_for ();
2487 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2488 err = MONO_SEM_WAIT (&suspend_sem);
2489 g_assert (err == 0);
2497 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2503 * Return whenever the runtime is suspended.
2508 return count_threads_to_wait_for () == 0;
2512 * find_seq_point_for_native_offset:
2514 * Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2515 * should be the location of a sequence point.
2518 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2520 MonoSeqPointInfo *seq_points;
2523 mono_domain_lock (domain);
2524 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2525 mono_domain_unlock (domain);
2526 g_assert (seq_points);
2530 for (i = 0; i < seq_points->len; ++i) {
2531 if (seq_points->seq_points [i].native_offset == native_offset)
2532 return &seq_points->seq_points [i];
2539 * find_next_seq_point_for_native_offset:
2541 * Find the first sequence point after NATIVE_OFFSET.
2544 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2546 MonoSeqPointInfo *seq_points;
2549 mono_domain_lock (domain);
2550 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2551 mono_domain_unlock (domain);
2552 g_assert (seq_points);
2556 for (i = 0; i < seq_points->len; ++i) {
2557 if (seq_points->seq_points [i].native_offset >= native_offset)
2558 return &seq_points->seq_points [i];
2565 * find_prev_seq_point_for_native_offset:
2567 * Find the first sequence point before NATIVE_OFFSET.
2570 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2572 MonoSeqPointInfo *seq_points;
2575 mono_domain_lock (domain);
2576 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2577 mono_domain_unlock (domain);
2578 g_assert (seq_points);
2582 for (i = seq_points->len - 1; i >= 0; --i) {
2583 if (seq_points->seq_points [i].native_offset <= native_offset)
2584 return &seq_points->seq_points [i];
2593 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2594 * should be the location of a sequence point.
2597 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2599 MonoSeqPointInfo *seq_points;
2602 mono_domain_lock (domain);
2603 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2604 mono_domain_unlock (domain);
2605 g_assert (seq_points);
2609 for (i = 0; i < seq_points->len; ++i) {
2610 if (seq_points->seq_points [i].il_offset == il_offset)
2611 return &seq_points->seq_points [i];
2618 * compute_il_offset:
2620 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2621 * a location of a sequence point.
2622 * We use this function instead of mono_debug_il_offset_from_address () etc,
2623 * which doesn't seem to work in a lot of cases.
2626 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2628 MonoSeqPointInfo *seq_points;
2629 int i, last_il_offset, seq_il_offset, seq_native_offset;
2631 mono_domain_lock (domain);
2632 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2633 mono_domain_unlock (domain);
2634 g_assert (seq_points);
2636 last_il_offset = -1;
2638 /* Find the sequence point */
2639 for (i = 0; i < seq_points->len; ++i) {
2640 seq_il_offset = seq_points->seq_points [i].il_offset;
2641 seq_native_offset = seq_points->seq_points [i].native_offset;
2643 if (seq_native_offset > native_offset)
2645 last_il_offset = seq_il_offset;
2648 return last_il_offset;
2652 DebuggerTlsData *tls;
2654 } ComputeFramesUserData;
2657 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2659 ComputeFramesUserData *ud = user_data;
2661 MonoMethod *method, *actual_method;
2663 if (info->type != FRAME_TYPE_MANAGED) {
2664 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2665 /* Mark the last frame as an invoke frame */
2667 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2673 method = info->ji->method;
2675 method = info->method;
2676 actual_method = info->actual_method;
2678 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2681 if (info->il_offset == -1) {
2682 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2683 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2686 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));
2688 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2690 * mono_arch_find_jit_info () returns the context stored in the LMF for
2691 * native frames, but it should unwind once. This is why we have duplicate
2692 * frames on the stack sometimes.
2693 * !managed also seems to be set for dynamic methods.
2698 frame = g_new0 (StackFrame, 1);
2699 frame->method = method;
2700 frame->actual_method = actual_method;
2701 frame->il_offset = info->il_offset;
2702 frame->native_offset = info->native_offset;
2705 frame->has_ctx = TRUE;
2707 frame->domain = info->domain;
2709 ud->frames = g_slist_append (ud->frames, frame);
2715 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2717 ComputeFramesUserData *ud = user_data;
2720 * 'tls->filter_ctx' is the location of the throw site.
2722 * mono_walk_stack() will never actually hit the throw site, but unwind
2723 * directly from the filter to the call site; we abort stack unwinding here
2724 * once this happens and resume from the throw site.
2727 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_ctx))
2730 return process_frame (info, ctx, user_data);
2734 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2736 ComputeFramesUserData user_data;
2738 int i, findex, new_frame_count;
2739 StackFrame **new_frames, *f;
2741 // FIXME: Locking on tls
2742 if (tls->frames && tls->frames_up_to_date)
2745 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2747 user_data.tls = tls;
2748 user_data.frames = NULL;
2749 if (tls->terminated) {
2750 tls->frame_count = 0;
2752 } if (!tls->really_suspended && tls->has_async_ctx) {
2753 /* Have to use the state saved by the signal handler */
2754 process_frame (&tls->async_last_frame, NULL, &user_data);
2755 mono_walk_stack (process_frame, tls->domain, &tls->async_ctx, MONO_UNWIND_DEFAULT, thread, tls->async_lmf, &user_data);
2756 } else if (tls->has_filter_ctx) {
2758 * We are inside an exception filter.
2760 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
2762 if (tls->has_context)
2763 mono_walk_stack (process_filter_frame, tls->domain, &tls->ctx, MONO_UNWIND_DEFAULT, thread, tls->lmf, &user_data);
2765 * After that, we resume unwinding from the location where the exception has been thrown.
2767 mono_walk_stack (process_frame, tls->domain, &tls->filter_ctx, MONO_UNWIND_DEFAULT, thread, tls->filter_lmf, &user_data);
2768 } else if (tls->has_context) {
2769 mono_walk_stack (process_frame, tls->domain, &tls->ctx, MONO_UNWIND_DEFAULT, thread, tls->lmf, &user_data);
2772 tls->frame_count = 0;
2776 new_frame_count = g_slist_length (user_data.frames);
2777 new_frames = g_new0 (StackFrame*, new_frame_count);
2779 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2783 * Reuse the id for already existing stack frames, so invokes don't invalidate
2784 * the still valid stack frames.
2786 for (i = 0; i < tls->frame_count; ++i) {
2787 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2788 f->id = tls->frames [i]->id;
2793 if (i >= tls->frame_count)
2794 f->id = InterlockedIncrement (&frame_id);
2796 new_frames [findex ++] = f;
2799 g_slist_free (user_data.frames);
2801 invalidate_frames (tls);
2803 tls->frames = new_frames;
2804 tls->frame_count = new_frame_count;
2805 tls->frames_up_to_date = TRUE;
2809 * GHFunc to emit an appdomain creation event
2810 * @param key Don't care
2811 * @param value A loaded appdomain
2812 * @param user_data Don't care
2815 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
2817 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
2818 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
2822 * GHFunc to emit a thread start event
2823 * @param key A thread id
2824 * @param value A thread object
2825 * @param user_data Don't care
2828 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
2830 if (GPOINTER_TO_INT (key) != debugger_thread_id)
2831 process_profiler_event (EVENT_KIND_THREAD_START, value);
2835 * GFunc to emit an assembly load event
2836 * @param value A loaded assembly
2837 * @param user_data Don't care
2840 emit_assembly_load (gpointer value, gpointer user_data)
2842 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
2846 * GFunc to emit a type load event
2847 * @param value A loaded type
2848 * @param user_data Don't care
2851 emit_type_load (gpointer key, gpointer value, gpointer user_data)
2853 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
2862 * create_event_list:
2864 * Return a list of event request ids matching EVENT, starting from REQS, which
2865 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2867 * We return request ids, instead of requests, to simplify threading, since
2868 * requests could be deleted anytime when the loader lock is not held.
2869 * LOCKING: Assumes the loader lock is held.
2872 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
2875 GSList *events = NULL;
2877 *suspend_policy = SUSPEND_POLICY_NONE;
2880 reqs = event_requests;
2885 for (i = 0; i < reqs->len; ++i) {
2886 EventRequest *req = g_ptr_array_index (reqs, i);
2887 if (req->event_kind == event) {
2888 gboolean filtered = FALSE;
2891 for (j = 0; j < req->nmodifiers; ++j) {
2892 Modifier *mod = &req->modifiers [j];
2894 if (mod->kind == MOD_KIND_COUNT) {
2896 if (mod->data.count > 0) {
2897 if (mod->data.count > 0) {
2899 if (mod->data.count == 0)
2903 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2904 if (mod->data.thread != mono_thread_internal_current ())
2906 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
2907 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
2909 if (ei->caught && !mod->caught)
2911 if (!ei->caught && !mod->uncaught)
2913 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2915 gboolean found = FALSE;
2916 MonoAssembly **assemblies = mod->data.assemblies;
2919 for (k = 0; assemblies [k]; ++k)
2920 if (assemblies [k] == ji->method->klass->image->assembly)
2929 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2930 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2935 /* Send a VM START/DEATH event by default */
2936 if (event == EVENT_KIND_VM_START)
2937 events = g_slist_append (events, GINT_TO_POINTER (0));
2938 if (event == EVENT_KIND_VM_DEATH)
2939 events = g_slist_append (events, GINT_TO_POINTER (0));
2944 static G_GNUC_UNUSED const char*
2945 event_to_string (EventKind event)
2948 case EVENT_KIND_VM_START: return "VM_START";
2949 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2950 case EVENT_KIND_THREAD_START: return "THREAD_START";
2951 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2952 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2953 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2954 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2955 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2956 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2957 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2958 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2959 case EVENT_KIND_STEP: return "STEP";
2960 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2961 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2963 g_assert_not_reached ();
2970 * Send an event to the client, suspending the vm if needed.
2971 * LOCKING: Since this can suspend the calling thread, no locks should be held
2973 * The EVENTS list is freed by this function.
2976 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2980 MonoDomain *domain = mono_domain_get ();
2981 MonoThread *thread = NULL;
2982 gboolean send_success = FALSE;
2985 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
2989 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
2990 // FIXME: We miss those events
2991 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
2995 if (vm_death_event_sent) {
2996 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3000 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3001 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3006 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3013 if (agent_config.defer) {
3014 /* Make sure the thread id is always set when doing deferred debugging */
3015 if (debugger_thread_id == GetCurrentThreadId ())
3016 thread = mono_thread_get_main ();
3017 else thread = mono_thread_current ();
3019 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3020 // FIXME: Send these with a NULL thread, don't suspend the current thread
3024 buffer_init (&buf, 128);
3025 buffer_add_byte (&buf, suspend_policy);
3026 buffer_add_int (&buf, g_slist_length (events)); // n of events
3028 for (l = events; l; l = l->next) {
3029 buffer_add_byte (&buf, event); // event kind
3030 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3033 thread = mono_thread_current ();
3035 if (event == EVENT_KIND_VM_START && arg != NULL)
3038 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3041 case EVENT_KIND_THREAD_START:
3042 case EVENT_KIND_THREAD_DEATH:
3044 case EVENT_KIND_APPDOMAIN_CREATE:
3045 case EVENT_KIND_APPDOMAIN_UNLOAD:
3046 buffer_add_domainid (&buf, arg);
3048 case EVENT_KIND_METHOD_ENTRY:
3049 case EVENT_KIND_METHOD_EXIT:
3050 buffer_add_methodid (&buf, domain, arg);
3052 case EVENT_KIND_ASSEMBLY_LOAD:
3053 case EVENT_KIND_ASSEMBLY_UNLOAD:
3054 buffer_add_assemblyid (&buf, domain, arg);
3056 case EVENT_KIND_TYPE_LOAD:
3057 buffer_add_typeid (&buf, domain, arg);
3059 case EVENT_KIND_BREAKPOINT:
3060 case EVENT_KIND_STEP:
3061 buffer_add_methodid (&buf, domain, arg);
3062 buffer_add_long (&buf, il_offset);
3064 case EVENT_KIND_VM_START:
3065 buffer_add_domainid (&buf, mono_get_root_domain ());
3067 case EVENT_KIND_VM_DEATH:
3069 case EVENT_KIND_EXCEPTION: {
3070 EventInfo *ei = arg;
3071 buffer_add_objid (&buf, ei->exc);
3075 g_assert_not_reached ();
3079 if (event == EVENT_KIND_VM_START) {
3080 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3081 if (!agent_config.defer)
3082 start_debugger_thread ();
3085 if (event == EVENT_KIND_VM_DEATH) {
3086 vm_death_event_sent = TRUE;
3087 suspend_policy = SUSPEND_POLICY_NONE;
3090 if (mono_runtime_is_shutting_down ())
3091 suspend_policy = SUSPEND_POLICY_NONE;
3093 if (suspend_policy != SUSPEND_POLICY_NONE) {
3095 * Save the thread context and start suspending before sending the packet,
3096 * since we could be receiving the resume request before send_packet ()
3099 save_thread_context (ctx);
3103 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3107 g_slist_free (events);
3110 if (!send_success) {
3111 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3115 if (event == EVENT_KIND_VM_START) {
3116 vm_start_event_sent = TRUE;
3117 if (agent_config.defer)
3118 mono_debugger_agent_on_attach ();
3121 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
3124 switch (suspend_policy) {
3125 case SUSPEND_POLICY_NONE:
3127 case SUSPEND_POLICY_ALL:
3130 case SUSPEND_POLICY_EVENT_THREAD:
3134 g_assert_not_reached ();
3139 process_profiler_event (EventKind event, gpointer arg)
3144 mono_loader_lock ();
3145 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
3146 mono_loader_unlock ();
3148 process_event (event, arg, 0, NULL, events, suspend_policy);
3152 runtime_initialized (MonoProfiler *prof)
3154 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3155 if (agent_config.defer)
3156 start_debugger_thread ();
3160 runtime_shutdown (MonoProfiler *prof)
3162 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3164 mono_debugger_agent_cleanup ();
3168 thread_startup (MonoProfiler *prof, uintptr_t tid)
3170 MonoInternalThread *thread = mono_thread_internal_current ();
3171 MonoInternalThread *old_thread;
3172 DebuggerTlsData *tls;
3174 if (tid == debugger_thread_id)
3177 g_assert (thread->tid == tid);
3179 mono_loader_lock ();
3180 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3181 mono_loader_unlock ();
3183 if (thread == old_thread) {
3185 * For some reason, thread_startup () might be called for the same thread
3186 * multiple times (attach ?).
3188 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3192 * thread_end () might not be called for some threads, and the tid could
3195 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3196 mono_loader_lock ();
3197 mono_g_hash_table_remove (thread_to_tls, old_thread);
3198 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3199 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3200 mono_loader_unlock ();
3204 tls = TlsGetValue (debugger_tls_id);
3206 // FIXME: Free this somewhere
3207 tls = g_new0 (DebuggerTlsData, 1);
3208 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3209 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3210 tls->thread = thread;
3211 TlsSetValue (debugger_tls_id, tls);
3213 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3215 mono_loader_lock ();
3216 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3217 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3218 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3219 mono_loader_unlock ();
3221 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3224 * suspend_vm () could have missed this thread, so wait for a resume.
3230 thread_end (MonoProfiler *prof, uintptr_t tid)
3232 MonoInternalThread *thread;
3233 DebuggerTlsData *tls = NULL;
3235 mono_loader_lock ();
3236 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3238 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3239 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3240 tls->terminated = TRUE;
3241 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3242 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3243 MONO_GC_UNREGISTER_ROOT (tls->thread);
3246 mono_loader_unlock ();
3248 /* We might be called for threads started before we registered the start callback */
3250 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3251 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3256 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3258 mono_loader_lock ();
3259 g_hash_table_insert (domains, domain, domain);
3260 mono_loader_unlock ();
3262 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3266 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3268 clear_breakpoints_for_domain (domain);
3270 mono_loader_lock ();
3271 /* Invalidate each thread's frame stack */
3272 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3273 mono_loader_unlock ();
3275 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3279 * invalidate_each_thread:
3281 * A GHFunc to invalidate frames.
3282 * value must be a DebuggerTlsData*
3285 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3287 invalidate_frames (value);
3291 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3293 /* Sent later in jit_end () */
3294 mono_loader_lock ();
3295 g_ptr_array_add (pending_assembly_loads, assembly);
3296 mono_loader_unlock ();
3300 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3302 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3304 clear_event_requests_for_assembly (assembly);
3305 clear_types_for_assembly (assembly);
3309 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3311 #if defined(HOST_WIN32) && !defined(__GNUC__)
3312 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3314 gpointer stackptr = __builtin_frame_address (1);
3316 MonoInternalThread *thread = mono_thread_internal_current ();
3317 DebuggerTlsData *tls;
3319 mono_loader_lock ();
3321 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3322 /* Could be the debugger thread with assembly/type load hooks */
3324 tls->invoke_addr = stackptr;
3326 mono_loader_unlock ();
3330 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3333 #if defined(HOST_WIN32) && !defined(__GNUC__)
3334 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3336 gpointer stackptr = __builtin_frame_address (1);
3339 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3343 * We need to stop single stepping when exiting a runtime invoke, since if it is
3344 * a step out, it may return to native code, and thus never end.
3346 mono_loader_lock ();
3347 ss_invoke_addr = NULL;
3349 for (i = 0; i < event_requests->len; ++i) {
3350 EventRequest *req = g_ptr_array_index (event_requests, i);
3352 if (req->event_kind == EVENT_KIND_STEP) {
3353 ss_destroy (req->info);
3354 g_ptr_array_remove_index_fast (event_requests, i);
3359 mono_loader_unlock ();
3363 send_type_load (MonoClass *klass)
3365 gboolean type_load = FALSE;
3366 MonoDomain *domain = mono_domain_get ();
3367 AgentDomainInfo *info = NULL;
3369 mono_loader_lock ();
3370 mono_domain_lock (domain);
3372 info = get_agent_domain_info (domain);
3374 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3376 g_hash_table_insert (info->loaded_classes, klass, klass);
3379 mono_domain_unlock (domain);
3380 mono_loader_unlock ();
3382 emit_type_load (klass, klass, NULL);
3386 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3389 * We emit type load events when the first method of the type is JITted,
3390 * since the class load profiler callbacks might be called with the
3391 * loader lock held. They could also occur in the debugger thread.
3392 * Same for assembly load events.
3395 MonoAssembly *assembly = NULL;
3397 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3398 mono_loader_lock ();
3399 if (pending_assembly_loads->len > 0) {
3400 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3401 g_ptr_array_remove_index (pending_assembly_loads, 0);
3403 mono_loader_unlock ();
3406 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3412 send_type_load (method->klass);
3415 add_pending_breakpoints (method, jinfo);
3419 * BREAKPOINTS/SINGLE STEPPING
3423 * Contains information about an inserted breakpoint.
3426 long il_offset, native_offset;
3430 } BreakpointInstance;
3433 * Contains generic information about a breakpoint.
3437 * The method where the breakpoint is placed. Can be NULL in which case it
3438 * is inserted into every method. This is used to implement method entry/
3439 * exit events. Can be a generic method definition, in which case the
3440 * breakpoint is inserted into every instance.
3446 * A list of BreakpointInstance structures describing where the breakpoint
3447 * was inserted. There could be more than one because of
3448 * generics/appdomains/method entry/exit.
3450 GPtrArray *children;
3453 /* List of breakpoints */
3454 static GPtrArray *breakpoints;
3455 /* Maps breakpoint locations to the number of breakpoints at that location */
3456 static GHashTable *bp_locs;
3459 breakpoints_init (void)
3461 breakpoints = g_ptr_array_new ();
3462 bp_locs = g_hash_table_new (NULL, NULL);
3466 * insert_breakpoint:
3468 * Insert the breakpoint described by BP into the method described by
3472 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3475 gint32 il_offset = -1, native_offset;
3476 BreakpointInstance *inst;
3479 mono_error_init (error);
3482 for (i = 0; i < seq_points->len; ++i) {
3483 il_offset = seq_points->seq_points [i].il_offset;
3484 native_offset = seq_points->seq_points [i].native_offset;
3486 if (il_offset == bp->il_offset)
3490 if (i == seq_points->len) {
3491 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);
3493 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3502 inst = g_new0 (BreakpointInstance, 1);
3503 inst->native_offset = native_offset;
3504 inst->ip = (guint8*)ji->code_start + native_offset;
3506 inst->domain = domain;
3508 mono_loader_lock ();
3510 g_ptr_array_add (bp->children, inst);
3512 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3513 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3514 mono_loader_unlock ();
3517 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3518 mono_arch_set_breakpoint (ji, inst->ip);
3524 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)il_offset));
3528 remove_breakpoint (BreakpointInstance *inst)
3530 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3532 MonoJitInfo *ji = inst->ji;
3533 guint8 *ip = inst->ip;
3535 mono_loader_lock ();
3536 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3537 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3538 mono_loader_unlock ();
3540 g_assert (count > 0);
3543 mono_arch_clear_breakpoint (ji, ip);
3550 static inline gboolean
3551 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3553 return (!bp->method || method == bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method));
3557 * add_pending_breakpoints:
3559 * Insert pending breakpoints into the newly JITted method METHOD.
3562 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3565 MonoSeqPointInfo *seq_points;
3571 domain = mono_domain_get ();
3573 mono_loader_lock ();
3575 for (i = 0; i < breakpoints->len; ++i) {
3576 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3577 gboolean found = FALSE;
3579 if (!bp_matches_method (bp, method))
3582 for (j = 0; j < bp->children->len; ++j) {
3583 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3590 mono_domain_lock (domain);
3591 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3592 mono_domain_unlock (domain);
3594 /* Could be AOT code */
3596 g_assert (seq_points);
3598 insert_breakpoint (seq_points, domain, ji, bp, NULL);
3602 mono_loader_unlock ();
3606 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
3612 mono_error_init (error);
3614 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3616 /* Might be AOTed code */
3617 code = mono_aot_get_method (domain, method);
3619 ji = mono_jit_info_table_find (domain, code);
3624 insert_breakpoint (seq_points, domain, ji, bp, error);
3628 clear_breakpoint (MonoBreakpoint *bp);
3633 * Set a breakpoint at IL_OFFSET in METHOD.
3634 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3635 * METHOD can also be a generic method definition, in which case a breakpoint
3636 * is placed in all instances of the method.
3637 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
3640 static MonoBreakpoint*
3641 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
3644 GHashTableIter iter, iter2;
3647 MonoSeqPointInfo *seq_points;
3650 mono_error_init (error);
3653 // - suspend/resume the vm to prevent code patching problems
3654 // - multiple breakpoints on the same location
3655 // - dynamic methods
3658 bp = g_new0 (MonoBreakpoint, 1);
3659 bp->method = method;
3660 bp->il_offset = il_offset;
3662 bp->children = g_ptr_array_new ();
3664 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));
3666 mono_loader_lock ();
3668 g_hash_table_iter_init (&iter, domains);
3669 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
3670 mono_domain_lock (domain);
3672 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
3673 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
3674 if (bp_matches_method (bp, m))
3675 set_bp_in_method (domain, m, seq_points, bp, error);
3678 mono_domain_unlock (domain);
3681 mono_loader_unlock ();
3683 mono_loader_lock ();
3684 g_ptr_array_add (breakpoints, bp);
3685 mono_loader_unlock ();
3687 if (error && !mono_error_ok (error)) {
3688 clear_breakpoint (bp);
3696 clear_breakpoint (MonoBreakpoint *bp)
3700 // FIXME: locking, races
3701 for (i = 0; i < bp->children->len; ++i) {
3702 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3704 remove_breakpoint (inst);
3709 mono_loader_lock ();
3710 g_ptr_array_remove (breakpoints, bp);
3711 mono_loader_unlock ();
3713 g_ptr_array_free (bp->children, TRUE);
3718 breakpoints_cleanup (void)
3722 mono_loader_lock ();
3724 while (i < event_requests->len) {
3725 EventRequest *req = g_ptr_array_index (event_requests, i);
3727 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
3728 clear_breakpoint (req->info);
3729 g_ptr_array_remove_index_fast (event_requests, i);
3736 for (i = 0; i < breakpoints->len; ++i)
3737 g_free (g_ptr_array_index (breakpoints, i));
3739 g_ptr_array_free (breakpoints, TRUE);
3740 g_hash_table_destroy (bp_locs);
3745 mono_loader_unlock ();
3749 * clear_breakpoints_for_domain:
3751 * Clear breakpoint instances which reference DOMAIN.
3754 clear_breakpoints_for_domain (MonoDomain *domain)
3758 /* This could be called after shutdown */
3762 mono_loader_lock ();
3763 for (i = 0; i < breakpoints->len; ++i) {
3764 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3767 while (j < bp->children->len) {
3768 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3770 if (inst->domain == domain) {
3771 remove_breakpoint (inst);
3775 g_ptr_array_remove_index_fast (bp->children, j);
3781 mono_loader_unlock ();
3785 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
3787 return bp->method && bp->method->klass->image->assembly == assembly;
3791 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
3794 guint8 *orig_ip, *ip;
3795 int i, j, suspend_policy;
3796 guint32 native_offset;
3798 BreakpointInstance *inst;
3799 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3800 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3801 EventKind kind = EVENT_KIND_BREAKPOINT;
3803 // FIXME: Speed this up
3805 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3806 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
3808 g_assert (ji->method);
3810 /* Compute the native offset of the breakpoint from the ip */
3811 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3812 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3813 native_offset = ip - (guint8*)ji->code_start;
3819 * Skip the instruction causing the breakpoint signal.
3821 mono_arch_skip_breakpoint (ctx);
3823 if (ji->method->wrapper_type || tls->disable_breakpoints)
3826 bp_reqs = g_ptr_array_new ();
3827 ss_reqs = g_ptr_array_new ();
3828 ss_reqs_orig = g_ptr_array_new ();
3830 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3832 mono_loader_lock ();
3835 for (i = 0; i < breakpoints->len; ++i) {
3836 bp = g_ptr_array_index (breakpoints, i);
3841 for (j = 0; j < bp->children->len; ++j) {
3842 inst = g_ptr_array_index (bp->children, j);
3843 if (inst->ji == ji && inst->native_offset == native_offset) {
3844 if (bp->req->event_kind == EVENT_KIND_STEP) {
3845 g_ptr_array_add (ss_reqs_orig, bp->req);
3847 g_ptr_array_add (bp_reqs, bp->req);
3852 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3853 MonoSeqPointInfo *seq_points;
3854 int seq_il_offset, seq_native_offset;
3855 MonoDomain *domain = mono_domain_get ();
3857 /* Maybe a method entry/exit event */
3858 mono_domain_lock (domain);
3859 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3860 mono_domain_unlock (domain);
3862 // FIXME: Generic sharing */
3863 mono_loader_unlock ();
3866 g_assert (seq_points);
3868 for (i = 0; i < seq_points->len; ++i) {
3869 seq_il_offset = seq_points->seq_points [i].il_offset;
3870 seq_native_offset = seq_points->seq_points [i].native_offset;
3872 if (native_offset == seq_native_offset) {
3873 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3874 kind = EVENT_KIND_METHOD_ENTRY;
3875 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3876 kind = EVENT_KIND_METHOD_EXIT;
3882 /* Process single step requests */
3883 for (i = 0; i < ss_reqs_orig->len; ++i) {
3884 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3885 SingleStepReq *ss_req = req->info;
3886 gboolean hit = TRUE;
3887 MonoSeqPointInfo *info;
3890 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3893 if (ss_req->size == STEP_SIZE_LINE) {
3894 /* Have to check whenever a different source line was reached */
3895 MonoDebugMethodInfo *minfo;
3896 MonoDebugSourceLocation *loc = NULL;
3898 minfo = mono_debug_lookup_method (ji->method);
3901 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3903 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3904 /* Have to continue single stepping */
3908 ss_req->last_method = ji->method;
3909 ss_req->last_line = loc->row;
3910 mono_debug_free_source_location (loc);
3915 g_ptr_array_add (ss_reqs, req);
3917 /* Start single stepping again from the current sequence point */
3918 ss_start (ss_req, ji->method, sp, info, ctx, NULL, FALSE);
3921 if (ss_reqs->len > 0)
3922 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3923 if (bp_reqs->len > 0)
3924 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3925 if (kind != EVENT_KIND_BREAKPOINT)
3926 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3928 mono_loader_unlock ();
3930 g_ptr_array_free (bp_reqs, TRUE);
3931 g_ptr_array_free (ss_reqs, TRUE);
3934 * FIXME: The first event will suspend, so the second will only be sent after the
3938 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3940 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3941 if (enter_leave_events)
3942 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3946 process_breakpoint (void)
3948 DebuggerTlsData *tls;
3950 static void (*restore_context) (void *);
3952 if (!restore_context)
3953 restore_context = mono_get_restore_context ();
3955 tls = TlsGetValue (debugger_tls_id);
3956 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3958 process_breakpoint_inner (tls, &ctx);
3960 /* This is called when resuming from a signal handler, so it shouldn't return */
3961 restore_context (&ctx);
3962 g_assert_not_reached ();
3966 resume_from_signal_handler (void *sigctx, void *func)
3968 DebuggerTlsData *tls;
3971 /* Save the original context in TLS */
3972 // FIXME: This might not work on an altstack ?
3973 tls = TlsGetValue (debugger_tls_id);
3976 // FIXME: MonoContext usually doesn't include the fp registers, so these are
3977 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3978 // clob:c could be added to op_seq_point.
3980 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3981 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3982 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
3983 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
3985 MONO_CONTEXT_SET_IP (&ctx, func);
3987 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3989 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3990 mono_ppc_set_func_into_sigctx (sigctx, func);
3995 mono_debugger_agent_breakpoint_hit (void *sigctx)
3998 * We are called from a signal handler, and running code there causes all kinds of
3999 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4000 * So set up the signal context to return to the real breakpoint handler function.
4003 resume_from_signal_handler (sigctx, process_breakpoint);
4007 ss_depth_to_string (StepDepth depth)
4010 case STEP_DEPTH_OVER:
4012 case STEP_DEPTH_OUT:
4014 case STEP_DEPTH_INTO:
4017 g_assert_not_reached ();
4023 process_single_step_inner (DebuggerTlsData *tls, MonoContext *ctx)
4028 int il_offset, suspend_policy;
4032 // FIXME: Speed this up
4034 ip = MONO_CONTEXT_GET_IP (ctx);
4036 /* Skip the instruction causing the single step */
4037 mono_arch_skip_single_step (ctx);
4039 if (suspend_count > 0) {
4040 process_suspend (tls, ctx);
4045 // FIXME: A suspend race
4048 if (mono_thread_internal_current () != ss_req->thread)
4051 if (log_level > 0) {
4052 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4054 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));
4058 * We implement step over/out by single stepping until we reach the same
4059 * frame/parent frame.
4062 * - stack growing upward
4066 if (ss_req->depth != STEP_DEPTH_INTO) {
4067 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
4069 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
4072 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
4075 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4077 g_assert (ji->method);
4079 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4084 * Stopping in memset makes half-initialized vtypes visible.
4085 * Stopping in memcpy makes half-copied vtypes visible.
4087 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4091 * The ip points to the instruction causing the single step event, convert it
4092 * to the offset stored in seq_points.
4094 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4095 ip = mono_arch_get_ip_for_single_step (ji, ctx);
4097 g_assert_not_reached ();
4101 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
4102 * example, so do things by hand.
4104 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
4106 if (il_offset == -1)
4109 if (ss_req->size == STEP_SIZE_LINE) {
4110 /* Step until a different source line is reached */
4111 MonoDebugMethodInfo *minfo;
4113 minfo = mono_debug_lookup_method (ji->method);
4116 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4118 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4119 mono_debug_free_source_location (loc);
4124 * Step until we reach a location with line number info,
4125 * otherwise the client can't show a location.
4126 * This can happen for example with statics initialized inline
4127 * outside of a cctor.
4132 ss_req->last_method = ji->method;
4133 ss_req->last_line = loc->row;
4134 mono_debug_free_source_location (loc);
4139 // FIXME: Has to lock earlier
4141 reqs = g_ptr_array_new ();
4143 mono_loader_lock ();
4145 g_ptr_array_add (reqs, ss_req->req);
4147 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4149 g_ptr_array_free (reqs, TRUE);
4151 mono_loader_unlock ();
4153 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4157 process_single_step (void)
4159 DebuggerTlsData *tls;
4161 static void (*restore_context) (void *);
4163 if (!restore_context)
4164 restore_context = mono_get_restore_context ();
4166 tls = TlsGetValue (debugger_tls_id);
4167 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
4169 process_single_step_inner (tls, &ctx);
4171 /* This is called when resuming from a signal handler, so it shouldn't return */
4172 restore_context (&ctx);
4173 g_assert_not_reached ();
4177 * mono_debugger_agent_single_step_event:
4179 * Called from a signal handler to handle a single step event.
4182 mono_debugger_agent_single_step_event (void *sigctx)
4184 /* Resume to process_single_step through the signal context */
4186 // FIXME: Since step out/over is implemented using step in, the step in case should
4187 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4190 if (GetCurrentThreadId () == debugger_thread_id) {
4192 * This could happen despite our best effors when the runtime calls
4193 * assembly/type resolve hooks.
4194 * FIXME: Breakpoints too.
4198 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4199 mono_arch_skip_single_step (&ctx);
4200 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4204 resume_from_signal_handler (sigctx, process_single_step);
4208 * start_single_stepping:
4210 * Turn on single stepping. Can be called multiple times, for example,
4211 * by a single step event request + a suspend.
4214 start_single_stepping (void)
4216 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4217 int val = InterlockedIncrement (&ss_count);
4220 mono_arch_start_single_stepping ();
4222 if (ss_req != NULL && ss_invoke_addr == NULL) {
4223 DebuggerTlsData *tls;
4225 mono_loader_lock ();
4227 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4228 ss_invoke_addr = tls->invoke_addr;
4230 mono_loader_unlock ();
4233 g_assert_not_reached ();
4238 stop_single_stepping (void)
4240 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4241 int val = InterlockedDecrement (&ss_count);
4244 mono_arch_stop_single_stepping ();
4246 g_assert_not_reached ();
4253 * Stop the single stepping operation given by SS_REQ.
4256 ss_stop (SingleStepReq *ss_req)
4258 gboolean use_bps = FALSE;
4265 for (l = ss_req->bps; l; l = l->next) {
4266 clear_breakpoint (l->data);
4268 g_slist_free (ss_req->bps);
4272 if (ss_req->global) {
4273 stop_single_stepping ();
4274 ss_req->global = FALSE;
4281 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4284 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4290 /* Stop the previous operation */
4294 * Implement single stepping using breakpoints if possible.
4296 if (step_to_catch) {
4297 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4298 ss_req->bps = g_slist_append (ss_req->bps, bp);
4299 } else if (ss_req->depth == STEP_DEPTH_OVER) {
4302 * Find the first sequence point in the current or in a previous frame which
4303 * is not the last in its method.
4305 while (sp && sp->next_len == 0) {
4307 if (tls && frame_index < tls->frame_count) {
4308 StackFrame *frame = tls->frames [frame_index];
4310 method = frame->method;
4311 if (frame->il_offset != -1) {
4312 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
4318 if (sp && sp->next_len > 0) {
4319 for (i = 0; i < sp->next_len; ++i) {
4320 next_sp = &info->seq_points [sp->next [i]];
4322 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4323 ss_req->bps = g_slist_append (ss_req->bps, bp);
4329 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4330 ss_req->global = TRUE;
4331 start_single_stepping ();
4333 ss_req->global = FALSE;
4338 * Start single stepping of thread THREAD
4341 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4343 DebuggerTlsData *tls;
4344 MonoSeqPointInfo *info = NULL;
4345 SeqPoint *sp = NULL;
4346 MonoMethod *method = NULL;
4347 MonoDebugMethodInfo *minfo;
4348 gboolean step_to_catch = FALSE;
4350 if (suspend_count == 0)
4351 return ERR_NOT_SUSPENDED;
4353 wait_for_suspend ();
4355 // FIXME: Multiple requests
4357 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4358 return ERR_NOT_IMPLEMENTED;
4361 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4363 ss_req = g_new0 (SingleStepReq, 1);
4365 ss_req->thread = thread;
4366 ss_req->size = size;
4367 ss_req->depth = depth;
4370 mono_loader_lock ();
4371 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4372 mono_loader_unlock ();
4374 g_assert (tls->has_context);
4375 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
4377 if (tls->has_catch_ctx) {
4379 StackFrameInfo frame;
4380 MonoContext new_ctx;
4381 MonoLMF *lmf = NULL;
4384 * We are stopped at a throw site. Stepping should go to the catch site.
4387 /* Find the the jit info for the catch context */
4388 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4390 g_assert (frame.type == FRAME_TYPE_MANAGED);
4393 * Find the seq point corresponding to the landing site ip, which is the first seq
4396 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4399 method = frame.method;
4401 step_to_catch = TRUE;
4402 /* This make sure the seq point is not skipped by process_single_step () */
4403 ss_req->last_sp = NULL;
4406 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4409 /* Compute the initial line info */
4410 compute_frame_info (thread, tls);
4412 g_assert (tls->frame_count);
4413 frame = tls->frames [0];
4415 ss_req->last_method = frame->method;
4416 ss_req->last_line = -1;
4418 minfo = mono_debug_lookup_method (frame->method);
4419 if (minfo && frame->il_offset != -1) {
4420 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4423 ss_req->last_line = loc->row;
4429 if (!step_to_catch && ss_req->depth == STEP_DEPTH_OVER) {
4432 compute_frame_info (thread, tls);
4434 g_assert (tls->frame_count);
4435 frame = tls->frames [0];
4437 if (!method && frame->il_offset != -1) {
4438 /* FIXME: Sort the table and use a binary search */
4439 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4441 method = frame->method;
4445 ss_start (ss_req, method, sp, info, NULL, tls, step_to_catch);
4451 ss_destroy (SingleStepReq *req)
4454 g_assert (ss_req == req);
4463 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
4464 MonoContext *catch_ctx)
4470 DebuggerTlsData *tls = NULL;
4472 if (thread_to_tls != NULL) {
4473 MonoInternalThread *thread = mono_thread_internal_current ();
4475 mono_loader_lock ();
4476 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4477 mono_loader_unlock ();
4479 if (tls && tls->abort_requested)
4481 if (tls && tls->disable_breakpoints)
4485 memset (&ei, 0, sizeof (EventInfo));
4487 /* Just-In-Time debugging */
4489 if (agent_config.onuncaught && !inited) {
4490 finish_agent_init (FALSE);
4493 * Send an unsolicited EXCEPTION event with a dummy request id.
4495 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4496 ei.exc = (MonoObject*)exc;
4497 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4500 } else if (agent_config.onthrow && !inited) {
4502 gboolean found = FALSE;
4504 for (l = agent_config.onthrow; l; l = l->next) {
4505 char *ex_type = l->data;
4506 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
4508 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
4515 finish_agent_init (FALSE);
4518 * Send an unsolicited EXCEPTION event with a dummy request id.
4520 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4521 ei.exc = (MonoObject*)exc;
4522 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4530 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
4532 ei.exc = (MonoObject*)exc;
4533 ei.caught = catch_ctx != NULL;
4535 mono_loader_lock ();
4536 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
4537 mono_loader_unlock ();
4539 if (tls && catch_ctx) {
4540 tls->catch_ctx = *catch_ctx;
4541 tls->has_catch_ctx = TRUE;
4544 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
4547 tls->has_catch_ctx = FALSE;
4551 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4553 DebuggerTlsData *tls;
4558 tls = TlsGetValue (debugger_tls_id);
4563 * We're about to invoke an exception filter during the first pass of exception handling.
4565 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
4566 * 'orig_ctx' is the context where the exception has been thrown.
4569 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
4571 * If we're stopped in Filter(), normal stack unwinding would first unwind to
4572 * the call site (line 37) and then continue to Main(), but it would never
4573 * include the throw site (line 32).
4575 * Since exception filters are invoked during the first pass of exception handling,
4576 * the stack frames of the throw site are still intact, so we should include them
4579 * We do this here by saving the context of the throw site in 'tls->filter_ctx'.
4581 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
4582 * but report the location of the 'throw' to the user.
4586 memcpy (&tls->filter_ctx, orig_ctx, sizeof (MonoContext));
4587 tls->has_filter_ctx = TRUE;
4589 tls->filter_lmf = mono_get_lmf ();
4590 tls->domain = mono_domain_get ();
4594 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4596 DebuggerTlsData *tls;
4601 tls = TlsGetValue (debugger_tls_id);
4605 tls->has_filter_ctx = FALSE;
4609 * buffer_add_value_full:
4611 * Add the encoding of the value at ADDR described by T to the buffer.
4612 * AS_VTYPE determines whenever to treat primitive types as primitive types or
4616 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
4622 g_assert (*(void**)addr);
4623 addr = *(void**)addr;
4628 case MONO_TYPE_BOOLEAN:
4631 case MONO_TYPE_CHAR:
4651 case MONO_TYPE_VOID:
4652 buffer_add_byte (buf, t->type);
4654 case MONO_TYPE_BOOLEAN:
4657 buffer_add_byte (buf, t->type);
4658 buffer_add_int (buf, *(gint8*)addr);
4660 case MONO_TYPE_CHAR:
4663 buffer_add_byte (buf, t->type);
4664 buffer_add_int (buf, *(gint16*)addr);
4669 buffer_add_byte (buf, t->type);
4670 buffer_add_int (buf, *(gint32*)addr);
4675 buffer_add_byte (buf, t->type);
4676 buffer_add_long (buf, *(gint64*)addr);
4680 /* Treat it as a vtype */
4682 case MONO_TYPE_PTR: {
4683 gssize val = *(gssize*)addr;
4685 buffer_add_byte (buf, t->type);
4686 buffer_add_long (buf, val);
4690 case MONO_TYPE_STRING:
4691 case MONO_TYPE_SZARRAY:
4692 case MONO_TYPE_OBJECT:
4693 case MONO_TYPE_CLASS:
4694 case MONO_TYPE_ARRAY:
4695 obj = *(MonoObject**)addr;
4698 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4700 if (obj->vtable->klass->valuetype) {
4701 t = &obj->vtable->klass->byval_arg;
4702 addr = mono_object_unbox (obj);
4704 } else if (obj->vtable->klass->rank) {
4705 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4706 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4707 buffer_add_byte (buf, MONO_TYPE_CLASS);
4709 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4711 buffer_add_objid (buf, obj);
4715 case MONO_TYPE_VALUETYPE: {
4719 MonoClass *klass = mono_class_from_mono_type (t);
4721 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4722 buffer_add_byte (buf, klass->enumtype);
4723 buffer_add_typeid (buf, domain, klass);
4727 while ((f = mono_class_get_fields (klass, &iter))) {
4728 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4730 if (mono_field_is_deleted (f))
4734 buffer_add_int (buf, nfields);
4737 while ((f = mono_class_get_fields (klass, &iter))) {
4738 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4740 if (mono_field_is_deleted (f))
4742 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4746 case MONO_TYPE_GENERICINST:
4747 if (mono_type_generic_inst_is_valuetype (t)) {
4759 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4761 buffer_add_value_full (buf, t, addr, domain, FALSE);
4765 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4768 int type = decode_byte (buf, &buf, limit);
4770 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4771 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4772 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4773 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
4774 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
4775 char *name = mono_type_full_name (t);
4776 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
4778 return ERR_INVALID_ARGUMENT;
4782 case MONO_TYPE_BOOLEAN:
4783 *(guint8*)addr = decode_int (buf, &buf, limit);
4785 case MONO_TYPE_CHAR:
4786 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4789 *(gint8*)addr = decode_int (buf, &buf, limit);
4792 *(guint8*)addr = decode_int (buf, &buf, limit);
4795 *(gint16*)addr = decode_int (buf, &buf, limit);
4798 *(guint16*)addr = decode_int (buf, &buf, limit);
4801 *(gint32*)addr = decode_int (buf, &buf, limit);
4804 *(guint32*)addr = decode_int (buf, &buf, limit);
4807 *(gint64*)addr = decode_long (buf, &buf, limit);
4810 *(guint64*)addr = decode_long (buf, &buf, limit);
4813 *(guint32*)addr = decode_int (buf, &buf, limit);
4816 *(guint64*)addr = decode_long (buf, &buf, limit);
4819 /* We send these as I8, so we get them back as such */
4820 g_assert (type == MONO_TYPE_I8);
4821 *(gssize*)addr = decode_long (buf, &buf, limit);
4823 case MONO_TYPE_GENERICINST:
4824 if (MONO_TYPE_ISSTRUCT (t)) {
4825 /* The client sends these as a valuetype */
4833 /* We send these as vtypes, so we get them back as such */
4834 g_assert (type == MONO_TYPE_VALUETYPE);
4837 case MONO_TYPE_VALUETYPE: {
4838 gboolean is_enum = decode_byte (buf, &buf, limit);
4842 gpointer iter = NULL;
4845 /* Enums are sent as a normal vtype */
4847 return ERR_NOT_IMPLEMENTED;
4848 klass = decode_typeid (buf, &buf, limit, &d, &err);
4852 if (klass != mono_class_from_mono_type (t))
4853 return ERR_INVALID_ARGUMENT;
4855 nfields = decode_int (buf, &buf, limit);
4856 while ((f = mono_class_get_fields (klass, &iter))) {
4857 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4859 if (mono_field_is_deleted (f))
4861 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4866 g_assert (nfields == 0);
4871 if (MONO_TYPE_IS_REFERENCE (t)) {
4872 if (type == MONO_TYPE_OBJECT) {
4873 int objid = decode_objid (buf, &buf, limit);
4877 err = get_object (objid, (MonoObject**)&obj);
4881 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4882 return ERR_INVALID_ARGUMENT;
4883 if (obj && obj->vtable->domain != domain)
4884 return ERR_INVALID_ARGUMENT;
4886 mono_gc_wbarrier_generic_store (addr, obj);
4887 } else if (type == VALUE_TYPE_ID_NULL) {
4888 *(MonoObject**)addr = NULL;
4890 return ERR_INVALID_ARGUMENT;
4904 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4911 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4912 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4915 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4916 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4918 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
4920 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4921 addr = mono_arch_context_get_int_reg (ctx, reg);
4922 addr += (gint32)var->offset;
4924 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4926 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4928 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4932 g_assert_not_reached ();
4937 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
4943 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4944 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4946 if (MONO_TYPE_IS_REFERENCE (t))
4947 size = sizeof (gpointer);
4949 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4952 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4953 // FIXME: Can't set registers, so we disable linears
4956 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4957 addr = mono_arch_context_get_int_reg (ctx, reg);
4958 addr += (gint32)var->offset;
4960 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4962 // FIXME: Write barriers
4963 memcpy (addr, val, size);
4965 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4969 g_assert_not_reached ();
4974 clear_event_request (int req_id, int etype)
4978 mono_loader_lock ();
4979 for (i = 0; i < event_requests->len; ++i) {
4980 EventRequest *req = g_ptr_array_index (event_requests, i);
4982 if (req->id == req_id && req->event_kind == etype) {
4983 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4984 clear_breakpoint (req->info);
4985 if (req->event_kind == EVENT_KIND_STEP)
4986 ss_destroy (req->info);
4987 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
4988 clear_breakpoint (req->info);
4989 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
4990 clear_breakpoint (req->info);
4991 g_ptr_array_remove_index_fast (event_requests, i);
4996 mono_loader_unlock ();
5000 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5002 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5003 return breakpoint_matches_assembly (req->info, assembly);
5007 for (i = 0; i < req->nmodifiers; ++i) {
5008 Modifier *m = &req->modifiers [i];
5010 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5012 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5013 for (j = 0; m->data.assemblies [j]; ++j)
5014 if (m->data.assemblies [j] == assembly)
5024 * clear_event_requests_for_assembly:
5026 * Clear all events requests which reference ASSEMBLY.
5029 clear_event_requests_for_assembly (MonoAssembly *assembly)
5034 mono_loader_lock ();
5038 for (i = 0; i < event_requests->len; ++i) {
5039 EventRequest *req = g_ptr_array_index (event_requests, i);
5041 if (event_req_matches_assembly (req, assembly)) {
5042 clear_event_request (req->id, req->event_kind);
5048 mono_loader_unlock ();
5052 * type_comes_from_assembly:
5054 * GHRFunc that returns TRUE if klass comes from assembly
5057 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5059 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5063 * clear_types_for_assembly:
5065 * Clears types from loaded_classes for a given assembly
5068 clear_types_for_assembly (MonoAssembly *assembly)
5070 MonoDomain *domain = mono_domain_get ();
5071 AgentDomainInfo *info = NULL;
5073 mono_loader_lock ();
5074 info = get_agent_domain_info (domain);
5075 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5076 mono_loader_unlock ();
5080 add_thread (gpointer key, gpointer value, gpointer user_data)
5082 MonoInternalThread *thread = value;
5083 Buffer *buf = user_data;
5085 buffer_add_objid (buf, (MonoObject*)thread);
5089 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5091 guint8 *p = invoke->p;
5092 guint8 *end = invoke->endp;
5095 MonoMethodSignature *sig;
5098 MonoObject *this, *res, *exc;
5101 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5105 if (invoke->method) {
5107 * Invoke this method directly, currently only Environment.Exit () is supported.
5110 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>"));
5111 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5112 g_assert_not_reached ();
5115 m = decode_methodid (p, &p, end, &domain, &err);
5118 sig = mono_method_signature (m);
5120 if (m->klass->valuetype)
5121 this_buf = g_alloca (mono_class_instance_size (m->klass));
5123 this_buf = g_alloca (sizeof (MonoObject*));
5124 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5125 /* Should be null */
5126 int type = decode_byte (p, &p, end);
5127 if (type != VALUE_TYPE_ID_NULL)
5128 return ERR_INVALID_ARGUMENT;
5129 memset (this_buf, 0, mono_class_instance_size (m->klass));
5131 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5136 if (!m->klass->valuetype)
5137 this = *(MonoObject**)this_buf;
5141 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>"));
5143 if (this && this->vtable->domain != domain)
5146 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5147 if (!strcmp (m->name, ".ctor")) {
5148 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5149 return ERR_INVALID_ARGUMENT;
5151 this = mono_object_new (domain, m->klass);
5153 return ERR_INVALID_ARGUMENT;
5157 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5158 return ERR_INVALID_ARGUMENT;
5160 nargs = decode_int (p, &p, end);
5161 if (nargs != sig->param_count)
5162 return ERR_INVALID_ARGUMENT;
5163 /* Use alloca to get gc tracking */
5164 arg_buf = g_alloca (nargs * sizeof (gpointer));
5165 memset (arg_buf, 0, nargs * sizeof (gpointer));
5166 args = g_alloca (nargs * sizeof (gpointer));
5167 for (i = 0; i < nargs; ++i) {
5168 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5169 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5173 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5176 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5177 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5180 args [i] = arg_buf [i];
5187 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5188 tls->disable_breakpoints = TRUE;
5190 tls->disable_breakpoints = FALSE;
5193 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5195 /* FIXME: Move this to arch specific code */
5196 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5197 if (invoke->has_ctx) {
5200 lmf_addr = mono_get_lmf_addr ();
5203 memset (&ext, 0, sizeof (ext));
5205 ext.lmf.previous_lmf = *(lmf_addr);
5206 /* Mark that this is a MonoLMFExt */
5207 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5208 ext.lmf.rsp = (gssize)&ext;
5209 #elif defined(TARGET_X86)
5210 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5211 /* Mark that this is a MonoLMFExt */
5212 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5213 ext.lmf.ebp = (gssize)&ext;
5214 #elif defined(TARGET_ARM)
5215 ext.lmf.previous_lmf = *(lmf_addr);
5216 /* Mark that this is a MonoLMFExt */
5217 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5218 #elif defined(TARGET_POWERPC)
5219 ext.lmf.previous_lmf = *(lmf_addr);
5220 /* Mark that this is a MonoLMFExt */
5221 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5222 ext.lmf.ebp = (gssize)&ext;
5224 g_assert_not_reached ();
5227 ext.debugger_invoke = TRUE;
5228 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5230 mono_set_lmf ((MonoLMF*)&ext);
5234 if (m->klass->valuetype)
5235 res = mono_runtime_invoke (m, this_buf, args, &exc);
5237 res = mono_runtime_invoke (m, this, args, &exc);
5239 buffer_add_byte (buf, 0);
5240 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5242 buffer_add_byte (buf, 1);
5243 if (sig->ret->type == MONO_TYPE_VOID) {
5244 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5245 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5248 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5249 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5250 buffer_add_value (buf, sig->ret, &res, domain);
5251 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5253 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5259 tls->disable_breakpoints = FALSE;
5261 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5262 if (invoke->has_ctx)
5263 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5266 // FIXME: byref arguments
5274 * Invoke the method given by tls->pending_invoke in the current thread.
5277 invoke_method (void)
5279 DebuggerTlsData *tls;
5284 static void (*restore_context) (void *);
5285 MonoContext restore_ctx;
5287 if (!restore_context)
5288 restore_context = mono_get_restore_context ();
5290 tls = TlsGetValue (debugger_tls_id);
5294 * Store the `InvokeData *' in `tls->invoke' until we're done with
5295 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5298 mono_loader_lock ();
5300 invoke = tls->pending_invoke;
5302 tls->pending_invoke = NULL;
5304 invoke->last_invoke = tls->invoke;
5305 tls->invoke = invoke;
5307 mono_loader_unlock ();
5309 tls->frames_up_to_date = FALSE;
5313 buffer_init (&buf, 128);
5315 err = do_invoke_method (tls, &buf, invoke);
5317 /* Start suspending before sending the reply */
5318 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5321 send_reply_packet (id, err, &buf);
5325 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5327 if (invoke->has_ctx)
5328 save_thread_context (&restore_ctx);
5330 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5331 g_assert (tls->resume_count);
5332 tls->resume_count -= invoke->suspend_count;
5335 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5338 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5340 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5341 * after the mono_runtime_invoke() already returned, but it doesn't matter
5342 * because we reset the abort here.
5345 mono_loader_lock ();
5347 if (tls->abort_requested)
5348 mono_thread_internal_reset_abort (tls->thread);
5350 tls->invoke = tls->invoke->last_invoke;
5351 tls->abort_requested = FALSE;
5353 mono_loader_unlock ();
5362 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5364 MonoThread *thread = value;
5365 DebuggerTlsData *tls;
5368 mono_loader_lock ();
5369 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5371 res = tls->really_suspended;
5372 mono_loader_unlock ();
5378 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
5381 case CMD_VM_VERSION: {
5382 char *build_info, *version;
5384 build_info = mono_get_runtime_build_info ();
5385 version = g_strdup_printf ("mono %s", build_info);
5387 buffer_add_string (buf, version); /* vm version */
5388 buffer_add_int (buf, MAJOR_VERSION);
5389 buffer_add_int (buf, MINOR_VERSION);
5390 g_free (build_info);
5394 case CMD_VM_SET_PROTOCOL_VERSION: {
5395 major_version = decode_int (p, &p, end);
5396 minor_version = decode_int (p, &p, end);
5397 protocol_version_set = TRUE;
5398 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
5401 case CMD_VM_ALL_THREADS: {
5403 mono_loader_lock ();
5404 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
5405 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
5406 mono_loader_unlock ();
5409 case CMD_VM_SUSPEND:
5411 wait_for_suspend ();
5414 if (suspend_count == 0)
5415 return ERR_NOT_SUSPENDED;
5418 case CMD_VM_DISPOSE:
5419 /* Clear all event requests */
5420 mono_loader_lock ();
5421 while (event_requests->len > 0) {
5422 EventRequest *req = g_ptr_array_index (event_requests, 0);
5424 clear_event_request (req->id, req->event_kind);
5426 mono_loader_unlock ();
5428 while (suspend_count > 0)
5430 disconnected = TRUE;
5431 vm_start_event_sent = FALSE;
5434 MonoInternalThread *thread;
5435 DebuggerTlsData *tls;
5436 MonoClass *env_class;
5437 MonoMethod *exit_method;
5441 exit_code = decode_int (p, &p, end);
5443 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
5445 /* Have to send a reply before exiting */
5446 send_reply_packet (id, 0, buf);
5448 /* Clear all event requests */
5449 mono_loader_lock ();
5450 while (event_requests->len > 0) {
5451 EventRequest *req = g_ptr_array_index (event_requests, 0);
5453 clear_event_request (req->id, req->event_kind);
5455 mono_loader_unlock ();
5458 * The JDWP documentation says that the shutdown is not orderly. It doesn't
5459 * specify whenever a VM_DEATH event is sent. We currently do an orderly
5460 * shutdown by hijacking a thread to execute Environment.Exit (). This is
5461 * better than doing the shutdown ourselves, since it avoids various races.
5465 wait_for_suspend ();
5467 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
5469 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
5471 mono_loader_lock ();
5472 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
5473 mono_loader_unlock ();
5475 if (thread && exit_method) {
5476 mono_loader_lock ();
5477 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5478 mono_loader_unlock ();
5480 args = g_new0 (gpointer, 1);
5481 args [0] = g_malloc (sizeof (int));
5482 *(int*)(args [0]) = exit_code;
5484 tls->pending_invoke = g_new0 (InvokeData, 1);
5485 tls->pending_invoke->method = exit_method;
5486 tls->pending_invoke->args = args;
5488 while (suspend_count > 0)
5492 * No thread found, do it ourselves.
5493 * FIXME: This can race with normal shutdown etc.
5495 while (suspend_count > 0)
5498 mono_runtime_set_shutting_down ();
5500 mono_threads_set_shutting_down ();
5502 /* Suspend all managed threads since the runtime is going away */
5503 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
5504 mono_thread_suspend_all_other_threads ();
5505 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
5506 mono_runtime_quit ();
5508 shutdown (conn_fd, SD_BOTH);
5510 shutdown (conn_fd, SHUT_RDWR);
5512 DEBUG(1, fprintf (log_file, "Exiting...\n"));
5518 case CMD_VM_INVOKE_METHOD: {
5519 int objid = decode_objid (p, &p, end);
5521 DebuggerTlsData *tls;
5524 err = get_object (objid, (MonoObject**)&thread);
5528 flags = decode_int (p, &p, end);
5530 // Wait for suspending if it already started
5532 wait_for_suspend ();
5533 if (!is_suspended ())
5534 return ERR_NOT_SUSPENDED;
5536 mono_loader_lock ();
5537 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5538 mono_loader_unlock ();
5541 if (!tls->really_suspended)
5542 /* The thread is still running native code, can't do invokes */
5543 return ERR_NOT_SUSPENDED;
5546 * Store the invoke data into tls, the thread will execute it after it is
5549 if (tls->pending_invoke)
5551 tls->pending_invoke = g_new0 (InvokeData, 1);
5552 tls->pending_invoke->id = id;
5553 tls->pending_invoke->flags = flags;
5554 tls->pending_invoke->p = g_malloc (end - p);
5555 memcpy (tls->pending_invoke->p, p, end - p);
5556 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
5557 tls->pending_invoke->suspend_count = suspend_count;
5559 if (flags & INVOKE_FLAG_SINGLE_THREADED)
5560 resume_thread (THREAD_TO_INTERNAL (thread));
5565 case CMD_VM_ABORT_INVOKE: {
5566 int objid = decode_objid (p, &p, end);
5568 DebuggerTlsData *tls;
5571 err = get_object (objid, (MonoObject**)&thread);
5575 invoke_id = decode_int (p, &p, end);
5577 mono_loader_lock ();
5578 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5581 if (tls->abort_requested) {
5582 mono_loader_unlock ();
5587 * Check whether we're still inside the mono_runtime_invoke() and that it's
5588 * actually the correct invocation.
5590 * Careful, we do not stop the thread that's doing the invocation, so we can't
5591 * inspect its stack. However, invoke_method() also acquires the loader lock
5592 * when it's done, so we're safe here.
5596 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
5597 mono_loader_unlock ();
5598 return ERR_NO_INVOCATION;
5601 tls->abort_requested = TRUE;
5603 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
5604 mono_loader_unlock ();
5609 return ERR_NOT_IMPLEMENTED;
5616 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5622 case CMD_EVENT_REQUEST_SET: {
5624 int i, event_kind, suspend_policy, nmodifiers, mod;
5627 MonoThread *step_thread;
5628 int size = 0, depth = 0, step_thread_id = 0;
5631 event_kind = decode_byte (p, &p, end);
5632 suspend_policy = decode_byte (p, &p, end);
5633 nmodifiers = decode_byte (p, &p, end);
5635 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
5636 req->id = InterlockedIncrement (&event_request_id);
5637 req->event_kind = event_kind;
5638 req->suspend_policy = suspend_policy;
5639 req->nmodifiers = nmodifiers;
5642 for (i = 0; i < nmodifiers; ++i) {
5643 mod = decode_byte (p, &p, end);
5645 req->modifiers [i].kind = mod;
5646 if (mod == MOD_KIND_COUNT) {
5647 req->modifiers [i].data.count = decode_int (p, &p, end);
5648 } else if (mod == MOD_KIND_LOCATION_ONLY) {
5649 method = decode_methodid (p, &p, end, &domain, &err);
5652 location = decode_long (p, &p, end);
5653 } else if (mod == MOD_KIND_STEP) {
5654 step_thread_id = decode_id (p, &p, end);
5655 size = decode_int (p, &p, end);
5656 depth = decode_int (p, &p, end);
5657 } else if (mod == MOD_KIND_THREAD_ONLY) {
5658 int id = decode_id (p, &p, end);
5660 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
5665 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
5666 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
5670 req->modifiers [i].caught = decode_byte (p, &p, end);
5671 req->modifiers [i].uncaught = decode_byte (p, &p, end);
5672 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" : ""));
5674 req->modifiers [i].data.exc_class = exc_class;
5676 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
5678 return ERR_INVALID_ARGUMENT;
5681 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
5682 int n = decode_int (p, &p, end);
5685 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
5686 for (j = 0; j < n; ++j) {
5687 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
5689 g_free (req->modifiers [i].data.assemblies);
5695 return ERR_NOT_IMPLEMENTED;
5699 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5702 req->info = set_breakpoint (method, location, req, &error);
5703 if (!mono_error_ok (&error)) {
5705 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
5706 mono_error_cleanup (&error);
5707 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
5709 } else if (req->event_kind == EVENT_KIND_STEP) {
5710 g_assert (step_thread_id);
5712 err = get_object (step_thread_id, (MonoObject**)&step_thread);
5718 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
5723 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
5724 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
5725 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
5726 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
5727 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
5729 if (req->nmodifiers) {
5731 return ERR_NOT_IMPLEMENTED;
5735 mono_loader_lock ();
5736 g_ptr_array_add (event_requests, req);
5737 mono_loader_unlock ();
5739 buffer_add_int (buf, req->id);
5742 case CMD_EVENT_REQUEST_CLEAR: {
5743 int etype = decode_byte (p, &p, end);
5744 int req_id = decode_int (p, &p, end);
5746 // FIXME: Make a faster mapping from req_id to request
5747 mono_loader_lock ();
5748 clear_event_request (req_id, etype);
5749 mono_loader_unlock ();
5752 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
5755 mono_loader_lock ();
5757 while (i < event_requests->len) {
5758 EventRequest *req = g_ptr_array_index (event_requests, i);
5760 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5761 clear_breakpoint (req->info);
5763 g_ptr_array_remove_index_fast (event_requests, i);
5769 mono_loader_unlock ();
5773 return ERR_NOT_IMPLEMENTED;
5780 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5786 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
5787 buffer_add_domainid (buf, mono_get_root_domain ());
5790 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
5791 domain = decode_domainid (p, &p, end, NULL, &err);
5794 buffer_add_string (buf, domain->friendly_name);
5797 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
5802 domain = decode_domainid (p, &p, end, NULL, &err);
5805 mono_loader_lock ();
5807 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5810 buffer_add_int (buf, count);
5811 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5813 buffer_add_assemblyid (buf, domain, ass);
5815 mono_loader_unlock ();
5818 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
5819 domain = decode_domainid (p, &p, end, NULL, &err);
5823 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
5826 case CMD_APPDOMAIN_GET_CORLIB: {
5827 domain = decode_domainid (p, &p, end, NULL, &err);
5831 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
5834 case CMD_APPDOMAIN_CREATE_STRING: {
5838 domain = decode_domainid (p, &p, end, NULL, &err);
5841 s = decode_string (p, &p, end);
5843 o = mono_string_new (domain, s);
5844 buffer_add_objid (buf, (MonoObject*)o);
5847 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
5849 MonoDomain *domain2;
5852 domain = decode_domainid (p, &p, end, NULL, &err);
5855 klass = decode_typeid (p, &p, end, &domain2, &err);
5860 g_assert (domain == domain2);
5862 o = mono_object_new (domain, klass);
5864 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
5868 buffer_add_objid (buf, o);
5872 return ERR_NOT_IMPLEMENTED;
5879 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5885 ass = decode_assemblyid (p, &p, end, &domain, &err);
5890 case CMD_ASSEMBLY_GET_LOCATION: {
5891 buffer_add_string (buf, mono_image_get_filename (ass->image));
5894 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
5898 if (ass->image->dynamic) {
5899 buffer_add_id (buf, 0);
5901 token = mono_image_get_entry_point (ass->image);
5903 buffer_add_id (buf, 0);
5905 m = mono_get_method (ass->image, token, NULL);
5906 buffer_add_methodid (buf, domain, m);
5911 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5912 buffer_add_moduleid (buf, domain, ass->image);
5915 case CMD_ASSEMBLY_GET_OBJECT: {
5916 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5917 buffer_add_objid (buf, o);
5920 case CMD_ASSEMBLY_GET_TYPE: {
5921 char *s = decode_string (p, &p, end);
5922 gboolean ignorecase = decode_byte (p, &p, end);
5923 MonoTypeNameParse info;
5925 gboolean type_resolve;
5927 if (!mono_reflection_parse_type (s, &info)) {
5930 if (info.assembly.name)
5932 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5934 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5935 mono_reflection_free_type_info (&info);
5940 case CMD_ASSEMBLY_GET_NAME: {
5942 MonoAssembly *mass = ass;
5944 name = g_strdup_printf (
5945 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5947 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5948 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5949 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5950 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5952 buffer_add_string (buf, name);
5957 return ERR_NOT_IMPLEMENTED;
5964 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5970 case CMD_MODULE_GET_INFO: {
5971 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
5974 basename = g_path_get_basename (image->name);
5975 buffer_add_string (buf, basename); // name
5976 buffer_add_string (buf, image->module_name); // scopename
5977 buffer_add_string (buf, image->name); // fqname
5978 buffer_add_string (buf, mono_image_get_guid (image)); // guid
5979 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
5984 return ERR_NOT_IMPLEMENTED;
5991 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
5993 if (val && val->vtable->klass == mono_defaults.monotype_class) {
5994 /* Special case these so the client doesn't have to handle Type objects */
5996 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
5997 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
5998 } else if (MONO_TYPE_IS_REFERENCE (t))
5999 buffer_add_value (buf, t, &val, domain);
6001 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6005 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6011 buffer_add_int (buf, 0);
6015 for (i = 0; i < cinfo->num_attrs; ++i) {
6016 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6019 buffer_add_int (buf, nattrs);
6021 for (i = 0; i < cinfo->num_attrs; ++i) {
6022 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6023 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6024 MonoArray *typed_args, *named_args;
6026 CattrNamedArg *arginfo;
6028 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6030 buffer_add_methodid (buf, domain, attr->ctor);
6034 buffer_add_int (buf, mono_array_length (typed_args));
6035 for (j = 0; j < mono_array_length (typed_args); ++j) {
6036 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6038 t = mono_method_signature (attr->ctor)->params [j];
6040 buffer_add_cattr_arg (buf, t, domain, val);
6043 buffer_add_int (buf, 0);
6048 buffer_add_int (buf, mono_array_length (named_args));
6050 for (j = 0; j < mono_array_length (named_args); ++j) {
6051 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
6053 if (arginfo [j].prop) {
6054 buffer_add_byte (buf, 0x54);
6055 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6056 } else if (arginfo [j].field) {
6057 buffer_add_byte (buf, 0x53);
6059 g_assert_not_reached ();
6062 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6065 buffer_add_int (buf, 0);
6072 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6082 case CMD_TYPE_GET_INFO: {
6083 buffer_add_string (buf, klass->name_space);
6084 buffer_add_string (buf, klass->name);
6086 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
6087 buffer_add_string (buf, name);
6089 buffer_add_assemblyid (buf, domain, klass->image->assembly);
6090 buffer_add_moduleid (buf, domain, klass->image);
6091 buffer_add_typeid (buf, domain, klass->parent);
6092 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
6093 buffer_add_typeid (buf, domain, klass->element_class);
6095 buffer_add_id (buf, 0);
6096 buffer_add_int (buf, klass->type_token);
6097 buffer_add_byte (buf, klass->rank);
6098 buffer_add_int (buf, klass->flags);
6100 type = &klass->byval_arg;
6101 // FIXME: Can't decide whenever a class represents a byref type
6104 if (type->type == MONO_TYPE_PTR)
6106 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
6108 if (type->type == MONO_TYPE_VALUETYPE)
6110 if (klass->enumtype)
6112 buffer_add_byte (buf, b);
6115 while ((nested = mono_class_get_nested_types (klass, &iter)))
6117 buffer_add_int (buf, nnested);
6119 while ((nested = mono_class_get_nested_types (klass, &iter)))
6120 buffer_add_typeid (buf, domain, nested);
6123 case CMD_TYPE_GET_METHODS: {
6126 gpointer iter = NULL;
6129 mono_class_setup_methods (klass);
6131 nmethods = mono_class_num_methods (klass);
6133 buffer_add_int (buf, nmethods);
6135 while ((m = mono_class_get_methods (klass, &iter))) {
6136 buffer_add_methodid (buf, domain, m);
6139 g_assert (i == nmethods);
6142 case CMD_TYPE_GET_FIELDS: {
6145 gpointer iter = NULL;
6148 nfields = mono_class_num_fields (klass);
6150 buffer_add_int (buf, nfields);
6152 while ((f = mono_class_get_fields (klass, &iter))) {
6153 buffer_add_fieldid (buf, domain, f);
6154 buffer_add_string (buf, f->name);
6155 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
6156 buffer_add_int (buf, f->type->attrs);
6159 g_assert (i == nfields);
6162 case CMD_TYPE_GET_PROPERTIES: {
6165 gpointer iter = NULL;
6168 nprops = mono_class_num_properties (klass);
6170 buffer_add_int (buf, nprops);
6172 while ((p = mono_class_get_properties (klass, &iter))) {
6173 buffer_add_propertyid (buf, domain, p);
6174 buffer_add_string (buf, p->name);
6175 buffer_add_methodid (buf, domain, p->get);
6176 buffer_add_methodid (buf, domain, p->set);
6177 buffer_add_int (buf, p->attrs);
6180 g_assert (i == nprops);
6183 case CMD_TYPE_GET_CATTRS: {
6184 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
6185 MonoCustomAttrInfo *cinfo;
6187 cinfo = mono_custom_attrs_from_class (klass);
6189 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6192 case CMD_TYPE_GET_FIELD_CATTRS: {
6193 MonoClass *attr_klass;
6194 MonoCustomAttrInfo *cinfo;
6195 MonoClassField *field;
6197 field = decode_fieldid (p, &p, end, NULL, &err);
6200 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6204 cinfo = mono_custom_attrs_from_field (klass, field);
6206 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6209 case CMD_TYPE_GET_PROPERTY_CATTRS: {
6210 MonoClass *attr_klass;
6211 MonoCustomAttrInfo *cinfo;
6214 prop = decode_propertyid (p, &p, end, NULL, &err);
6217 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6221 cinfo = mono_custom_attrs_from_property (klass, prop);
6223 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6226 case CMD_TYPE_GET_VALUES:
6227 case CMD_TYPE_GET_VALUES_2: {
6234 MonoThread *thread_obj;
6235 MonoInternalThread *thread = NULL;
6236 guint32 special_static_type;
6238 if (command == CMD_TYPE_GET_VALUES_2) {
6239 int objid = decode_objid (p, &p, end);
6242 err = get_object (objid, (MonoObject**)&thread_obj);
6246 thread = THREAD_TO_INTERNAL (thread_obj);
6249 len = decode_int (p, &p, end);
6250 for (i = 0; i < len; ++i) {
6251 f = decode_fieldid (p, &p, end, NULL, &err);
6255 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6256 return ERR_INVALID_FIELDID;
6257 special_static_type = mono_class_field_get_special_static_type (f);
6258 if (special_static_type != SPECIAL_STATIC_NONE) {
6259 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
6260 return ERR_INVALID_FIELDID;
6263 /* Check that the field belongs to the object */
6265 for (k = klass; k; k = k->parent) {
6266 if (k == f->parent) {
6272 return ERR_INVALID_FIELDID;
6274 vtable = mono_class_vtable (domain, f->parent);
6275 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6276 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
6277 buffer_add_value (buf, f->type, val, domain);
6282 case CMD_TYPE_SET_VALUES: {
6290 len = decode_int (p, &p, end);
6291 for (i = 0; i < len; ++i) {
6292 f = decode_fieldid (p, &p, end, NULL, &err);
6296 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6297 return ERR_INVALID_FIELDID;
6298 if (mono_class_field_is_special_static (f))
6299 return ERR_INVALID_FIELDID;
6301 /* Check that the field belongs to the object */
6303 for (k = klass; k; k = k->parent) {
6304 if (k == f->parent) {
6310 return ERR_INVALID_FIELDID;
6312 // FIXME: Check for literal/const
6314 vtable = mono_class_vtable (domain, f->parent);
6315 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6316 err = decode_value (f->type, domain, val, p, &p, end);
6321 if (MONO_TYPE_IS_REFERENCE (f->type))
6322 mono_field_static_set_value (vtable, f, *(gpointer*)val);
6324 mono_field_static_set_value (vtable, f, val);
6329 case CMD_TYPE_GET_OBJECT: {
6330 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
6331 buffer_add_objid (buf, o);
6334 case CMD_TYPE_GET_SOURCE_FILES:
6335 case CMD_TYPE_GET_SOURCE_FILES_2: {
6336 gpointer iter = NULL;
6338 char *source_file, *base;
6342 files = g_ptr_array_new ();
6344 while ((method = mono_class_get_methods (klass, &iter))) {
6345 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6348 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
6352 for (i = 0; i < files->len; ++i)
6353 if (!strcmp (g_ptr_array_index (files, i), source_file))
6355 if (i == files->len)
6356 g_ptr_array_add (files, g_strdup (source_file));
6357 g_free (source_file);
6361 buffer_add_int (buf, files->len);
6362 for (i = 0; i < files->len; ++i) {
6363 source_file = g_ptr_array_index (files, i);
6364 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
6365 buffer_add_string (buf, source_file);
6367 base = g_path_get_basename (source_file);
6368 buffer_add_string (buf, base);
6371 g_free (source_file);
6373 g_ptr_array_free (files, TRUE);
6376 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
6377 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
6381 if (mono_class_is_assignable_from (klass, oklass))
6382 buffer_add_byte (buf, 1);
6384 buffer_add_byte (buf, 0);
6388 return ERR_NOT_IMPLEMENTED;
6395 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6398 MonoDomain *old_domain;
6402 klass = decode_typeid (p, &p, end, &domain, &err);
6406 old_domain = mono_domain_get ();
6408 mono_domain_set (domain, TRUE);
6410 err = type_commands_internal (command, klass, domain, p, end, buf);
6412 mono_domain_set (old_domain, TRUE);
6418 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6420 MonoMethodHeader *header;
6423 case CMD_METHOD_GET_NAME: {
6424 buffer_add_string (buf, method->name);
6427 case CMD_METHOD_GET_DECLARING_TYPE: {
6428 buffer_add_typeid (buf, domain, method->klass);
6431 case CMD_METHOD_GET_DEBUG_INFO: {
6432 MonoDebugMethodInfo *minfo;
6434 int i, n_il_offsets;
6438 header = mono_method_get_header (method);
6440 buffer_add_int (buf, 0);
6441 buffer_add_string (buf, "");
6442 buffer_add_int (buf, 0);
6446 minfo = mono_debug_lookup_method (method);
6448 buffer_add_int (buf, header->code_size);
6449 buffer_add_string (buf, "");
6450 buffer_add_int (buf, 0);
6451 mono_metadata_free_mh (header);
6455 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
6456 buffer_add_int (buf, header->code_size);
6457 buffer_add_string (buf, source_file);
6458 buffer_add_int (buf, n_il_offsets);
6459 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
6460 for (i = 0; i < n_il_offsets; ++i) {
6461 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
6462 buffer_add_int (buf, il_offsets [i]);
6463 buffer_add_int (buf, line_numbers [i]);
6465 g_free (source_file);
6466 g_free (il_offsets);
6467 g_free (line_numbers);
6468 mono_metadata_free_mh (header);
6471 case CMD_METHOD_GET_PARAM_INFO: {
6472 MonoMethodSignature *sig = mono_method_signature (method);
6476 /* FIXME: mono_class_from_mono_type () and byrefs */
6478 /* FIXME: Use a smaller encoding */
6479 buffer_add_int (buf, sig->call_convention);
6480 buffer_add_int (buf, sig->param_count);
6481 buffer_add_int (buf, sig->generic_param_count);
6482 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
6483 for (i = 0; i < sig->param_count; ++i) {
6485 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
6488 /* Emit parameter names */
6489 names = g_new (char *, sig->param_count);
6490 mono_method_get_param_names (method, (const char **) names);
6491 for (i = 0; i < sig->param_count; ++i)
6492 buffer_add_string (buf, names [i]);
6497 case CMD_METHOD_GET_LOCALS_INFO: {
6498 int i, j, num_locals;
6499 MonoDebugLocalsInfo *locals;
6501 header = mono_method_get_header (method);
6504 buffer_add_int (buf, header->num_locals);
6507 for (i = 0; i < header->num_locals; ++i)
6508 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
6511 locals = mono_debug_lookup_locals (method);
6513 num_locals = locals->num_locals;
6516 for (i = 0; i < header->num_locals; ++i) {
6517 for (j = 0; j < num_locals; ++j)
6518 if (locals->locals [j].index == i)
6521 buffer_add_string (buf, locals->locals [j].name);
6523 buffer_add_string (buf, "");
6527 for (i = 0; i < header->num_locals; ++i) {
6528 for (j = 0; j < num_locals; ++j)
6529 if (locals->locals [j].index == i)
6531 if (j < num_locals && locals->locals [j].block) {
6532 buffer_add_int (buf, locals->locals [j].block->start_offset);
6533 buffer_add_int (buf, locals->locals [j].block->end_offset);
6535 buffer_add_int (buf, 0);
6536 buffer_add_int (buf, header->code_size);
6539 mono_metadata_free_mh (header);
6542 mono_debug_symfile_free_locals (locals);
6546 case CMD_METHOD_GET_INFO:
6547 buffer_add_int (buf, method->flags);
6548 buffer_add_int (buf, method->iflags);
6549 buffer_add_int (buf, method->token);
6551 case CMD_METHOD_GET_BODY: {
6554 header = mono_method_get_header (method);
6556 buffer_add_int (buf, 0);
6558 buffer_add_int (buf, header->code_size);
6559 for (i = 0; i < header->code_size; ++i)
6560 buffer_add_byte (buf, header->code [i]);
6562 mono_metadata_free_mh (header);
6565 case CMD_METHOD_RESOLVE_TOKEN: {
6566 guint32 token = decode_int (p, &p, end);
6569 switch (mono_metadata_token_code (token)) {
6570 case MONO_TOKEN_STRING: {
6574 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
6577 s2 = mono_string_to_utf8 (s);
6579 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6580 buffer_add_string (buf, s2);
6586 MonoClass *handle_class;
6588 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6589 val = mono_method_get_wrapper_data (method, token);
6590 handle_class = mono_method_get_wrapper_data (method, token + 1);
6592 if (handle_class == NULL) {
6593 // Can't figure out the token type
6594 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
6598 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
6602 if (handle_class == mono_defaults.typehandle_class) {
6603 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
6604 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
6605 buffer_add_typeid (buf, domain, (MonoClass *) val);
6607 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
6608 } else if (handle_class == mono_defaults.fieldhandle_class) {
6609 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
6610 buffer_add_fieldid (buf, domain, val);
6611 } else if (handle_class == mono_defaults.methodhandle_class) {
6612 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
6613 buffer_add_methodid (buf, domain, val);
6614 } else if (handle_class == mono_defaults.string_class) {
6617 s = mono_string_to_utf8 (val);
6618 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6619 buffer_add_string (buf, s);
6622 g_assert_not_reached ();
6630 return ERR_NOT_IMPLEMENTED;
6637 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6640 MonoDomain *old_domain;
6644 method = decode_methodid (p, &p, end, &domain, &err);
6648 old_domain = mono_domain_get ();
6650 mono_domain_set (domain, TRUE);
6652 err = method_commands_internal (command, method, domain, p, end, buf);
6654 mono_domain_set (old_domain, TRUE);
6660 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6662 int objid = decode_objid (p, &p, end);
6664 MonoThread *thread_obj;
6665 MonoInternalThread *thread;
6667 err = get_object (objid, (MonoObject**)&thread_obj);
6671 thread = THREAD_TO_INTERNAL (thread_obj);
6674 case CMD_THREAD_GET_NAME: {
6676 gunichar2 *s = mono_thread_get_name (thread, &name_len);
6679 buffer_add_int (buf, 0);
6684 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
6686 buffer_add_int (buf, len);
6687 buffer_add_data (buf, (guint8*)name, len);
6692 case CMD_THREAD_GET_FRAME_INFO: {
6693 DebuggerTlsData *tls;
6694 int i, start_frame, length;
6696 // Wait for suspending if it already started
6698 wait_for_suspend ();
6699 if (!is_suspended ())
6700 return ERR_NOT_SUSPENDED;
6702 start_frame = decode_int (p, &p, end);
6703 length = decode_int (p, &p, end);
6705 if (start_frame != 0 || length != -1)
6706 return ERR_NOT_IMPLEMENTED;
6708 mono_loader_lock ();
6709 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6710 mono_loader_unlock ();
6713 compute_frame_info (thread, tls);
6715 buffer_add_int (buf, tls->frame_count);
6716 for (i = 0; i < tls->frame_count; ++i) {
6717 buffer_add_int (buf, tls->frames [i]->id);
6718 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
6719 buffer_add_int (buf, tls->frames [i]->il_offset);
6721 * Instead of passing the frame type directly to the client, we associate
6722 * it with the previous frame using a set of flags. This avoids lots of
6723 * conditional code in the client, since a frame whose type isn't
6724 * FRAME_TYPE_MANAGED has no method, location, etc.
6726 buffer_add_byte (buf, tls->frames [i]->flags);
6731 case CMD_THREAD_GET_STATE:
6732 buffer_add_int (buf, thread->state);
6734 case CMD_THREAD_GET_INFO:
6735 buffer_add_byte (buf, thread->threadpool_thread);
6737 case CMD_THREAD_GET_ID:
6738 buffer_add_long (buf, (guint64)(gsize)thread);
6740 case CMD_THREAD_GET_TID:
6741 buffer_add_long (buf, (guint64)thread->tid);
6744 return ERR_NOT_IMPLEMENTED;
6751 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6755 MonoThread *thread_obj;
6756 MonoInternalThread *thread;
6758 DebuggerTlsData *tls;
6760 MonoDebugMethodJitInfo *jit;
6761 MonoDebugVarInfo *var;
6762 MonoMethodSignature *sig;
6764 MonoMethodHeader *header;
6766 objid = decode_objid (p, &p, end);
6767 err = get_object (objid, (MonoObject**)&thread_obj);
6771 thread = THREAD_TO_INTERNAL (thread_obj);
6773 id = decode_id (p, &p, end);
6775 mono_loader_lock ();
6776 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6777 mono_loader_unlock ();
6780 for (i = 0; i < tls->frame_count; ++i) {
6781 if (tls->frames [i]->id == id)
6784 if (i == tls->frame_count)
6785 return ERR_INVALID_FRAMEID;
6787 frame = tls->frames [i];
6789 if (!frame->has_ctx)
6791 return ERR_INVALID_FRAMEID;
6794 frame->jit = mono_debug_find_method (frame->method, frame->domain);
6796 /* This could happen for aot images with no jit debug info */
6797 return ERR_ABSENT_INFORMATION;
6801 sig = mono_method_signature (frame->actual_method);
6804 case CMD_STACK_FRAME_GET_VALUES: {
6805 len = decode_int (p, &p, end);
6806 header = mono_method_get_header (frame->actual_method);
6808 for (i = 0; i < len; ++i) {
6809 pos = decode_int (p, &p, end);
6814 g_assert (pos >= 0 && pos < jit->num_params);
6816 var = &jit->params [pos];
6818 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
6820 g_assert (pos >= 0 && pos < jit->num_locals);
6822 var = &jit->locals [pos];
6824 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
6827 mono_metadata_free_mh (header);
6830 case CMD_STACK_FRAME_GET_THIS: {
6831 if (frame->method->klass->valuetype) {
6832 if (!sig->hasthis) {
6833 MonoObject *p = NULL;
6834 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
6836 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6839 if (!sig->hasthis) {
6840 MonoObject *p = NULL;
6841 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
6843 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6848 case CMD_STACK_FRAME_SET_VALUES: {
6851 MonoDebugVarInfo *var;
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 t = sig->params [pos];
6865 var = &jit->params [pos];
6867 g_assert (pos >= 0 && pos < jit->num_locals);
6869 t = header->locals [pos];
6870 var = &jit->locals [pos];
6873 if (MONO_TYPE_IS_REFERENCE (t))
6874 val_buf = g_alloca (sizeof (MonoObject*));
6876 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
6877 err = decode_value (t, frame->domain, val_buf, p, &p, end);
6881 set_var (t, var, &frame->ctx, frame->domain, val_buf);
6883 mono_metadata_free_mh (header);
6887 return ERR_NOT_IMPLEMENTED;
6894 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6897 int objid, err, index, len, i, esize;
6900 objid = decode_objid (p, &p, end);
6901 err = get_object (objid, (MonoObject**)&arr);
6906 case CMD_ARRAY_REF_GET_LENGTH:
6907 buffer_add_int (buf, arr->obj.vtable->klass->rank);
6909 buffer_add_int (buf, arr->max_length);
6910 buffer_add_int (buf, 0);
6912 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
6913 buffer_add_int (buf, arr->bounds [i].length);
6914 buffer_add_int (buf, arr->bounds [i].lower_bound);
6918 case CMD_ARRAY_REF_GET_VALUES:
6919 index = decode_int (p, &p, end);
6920 len = decode_int (p, &p, end);
6922 g_assert (index >= 0 && len >= 0);
6923 // Reordered to avoid integer overflow
6924 g_assert (!(index > arr->max_length - len));
6926 esize = mono_array_element_size (arr->obj.vtable->klass);
6927 for (i = index; i < index + len; ++i) {
6928 elem = (gpointer*)((char*)arr->vector + (i * esize));
6929 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
6932 case CMD_ARRAY_REF_SET_VALUES:
6933 index = decode_int (p, &p, end);
6934 len = decode_int (p, &p, end);
6936 g_assert (index >= 0 && len >= 0);
6937 // Reordered to avoid integer overflow
6938 g_assert (!(index > arr->max_length - len));
6940 esize = mono_array_element_size (arr->obj.vtable->klass);
6941 for (i = index; i < index + len; ++i) {
6942 elem = (gpointer*)((char*)arr->vector + (i * esize));
6944 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
6948 return ERR_NOT_IMPLEMENTED;
6955 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6961 objid = decode_objid (p, &p, end);
6962 err = get_object (objid, (MonoObject**)&str);
6967 case CMD_STRING_REF_GET_VALUE:
6968 s = mono_string_to_utf8 (str);
6969 buffer_add_string (buf, s);
6973 return ERR_NOT_IMPLEMENTED;
6980 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6989 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
6990 objid = decode_objid (p, &p, end);
6991 err = get_object (objid, &obj);
6993 buffer_add_int (buf, 1);
6995 buffer_add_int (buf, 0);
6999 objid = decode_objid (p, &p, end);
7000 err = get_object (objid, &obj);
7005 case CMD_OBJECT_REF_GET_TYPE:
7006 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
7008 case CMD_OBJECT_REF_GET_VALUES:
7009 len = decode_int (p, &p, end);
7011 for (i = 0; i < len; ++i) {
7012 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
7016 /* Check that the field belongs to the object */
7018 for (k = obj->vtable->klass; k; k = k->parent) {
7019 if (k == f->parent) {
7025 return ERR_INVALID_FIELDID;
7027 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
7031 if (mono_class_field_is_special_static (f))
7032 return ERR_INVALID_FIELDID;
7034 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
7035 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
7036 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7037 mono_field_static_get_value (vtable, f, val);
7038 buffer_add_value (buf, f->type, val, obj->vtable->domain);
7041 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
7045 case CMD_OBJECT_REF_SET_VALUES:
7046 len = decode_int (p, &p, end);
7048 for (i = 0; i < len; ++i) {
7049 f = decode_fieldid (p, &p, end, NULL, &err);
7053 /* Check that the field belongs to the object */
7055 for (k = obj->vtable->klass; k; k = k->parent) {
7056 if (k == f->parent) {
7062 return ERR_INVALID_FIELDID;
7064 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
7068 if (mono_class_field_is_special_static (f))
7069 return ERR_INVALID_FIELDID;
7071 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
7072 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
7074 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7075 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
7080 mono_field_static_set_value (vtable, f, val);
7083 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
7089 case CMD_OBJECT_REF_GET_ADDRESS:
7090 buffer_add_long (buf, (gssize)obj);
7092 case CMD_OBJECT_REF_GET_DOMAIN:
7093 buffer_add_domainid (buf, obj->vtable->domain);
7096 return ERR_NOT_IMPLEMENTED;
7103 command_set_to_string (CommandSet command_set)
7105 switch (command_set) {
7108 case CMD_SET_OBJECT_REF:
7109 return "OBJECT_REF";
7110 case CMD_SET_STRING_REF:
7111 return "STRING_REF";
7112 case CMD_SET_THREAD:
7114 case CMD_SET_ARRAY_REF:
7116 case CMD_SET_EVENT_REQUEST:
7117 return "EVENT_REQUEST";
7118 case CMD_SET_STACK_FRAME:
7119 return "STACK_FRAME";
7120 case CMD_SET_APPDOMAIN:
7122 case CMD_SET_ASSEMBLY:
7124 case CMD_SET_METHOD:
7128 case CMD_SET_MODULE:
7138 cmd_to_string (CommandSet set, int command)
7143 case CMD_VM_VERSION:
7145 case CMD_VM_ALL_THREADS:
7146 return "ALL_THREADS";
7147 case CMD_VM_SUSPEND:
7153 case CMD_VM_DISPOSE:
7155 case CMD_VM_INVOKE_METHOD:
7156 return "INVOKE_METHOD";
7157 case CMD_VM_SET_PROTOCOL_VERSION:
7158 return "SET_PROTOCOL_VERSION";
7159 case CMD_VM_ABORT_INVOKE:
7160 return "ABORT_INVOKE";
7173 wait_for_attach (void)
7175 if (listen_fd == -1) {
7176 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
7180 /* Block and wait for client connection */
7181 conn_fd = transport_accept (listen_fd);
7182 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
7183 if (conn_fd == -1) {
7184 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
7189 disconnected = !transport_handshake ();
7191 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
7201 * This thread handles communication with the debugger client using a JDWP
7204 static guint32 WINAPI
7205 debugger_thread (void *arg)
7207 int res, len, id, flags, command_set, command;
7208 guint8 header [HEADER_LENGTH];
7209 guint8 *data, *p, *end;
7213 gboolean attach_failed = FALSE;
7215 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
7217 debugger_thread_id = GetCurrentThreadId ();
7219 mono_jit_thread_attach (mono_get_root_domain ());
7221 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
7223 mono_set_is_debugger_attached (TRUE);
7225 if (agent_config.defer) {
7226 if (!wait_for_attach ()) {
7227 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
7228 attach_failed = TRUE; // Don't abort process when we can't listen
7230 /* Send start event to client */
7231 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
7235 while (!attach_failed) {
7236 res = recv_length (conn_fd, header, HEADER_LENGTH, 0);
7238 /* This will break if the socket is closed during shutdown too */
7239 if (res != HEADER_LENGTH)
7243 end = header + HEADER_LENGTH;
7245 len = decode_int (p, &p, end);
7246 id = decode_int (p, &p, end);
7247 flags = decode_byte (p, &p, end);
7248 command_set = decode_byte (p, &p, end);
7249 command = decode_byte (p, &p, end);
7251 g_assert (flags == 0);
7254 const char *cmd_str;
7257 cmd_str = cmd_to_string (command_set, command);
7259 sprintf (cmd_num, "%d", command);
7263 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
7266 data = g_malloc (len - HEADER_LENGTH);
7267 if (len - HEADER_LENGTH > 0)
7269 res = recv_length (conn_fd, data, len - HEADER_LENGTH, 0);
7270 if (res != len - HEADER_LENGTH)
7275 end = data + (len - HEADER_LENGTH);
7277 buffer_init (&buf, 128);
7282 /* Process the request */
7283 switch (command_set) {
7285 err = vm_commands (command, id, p, end, &buf);
7286 if (!err && command == CMD_VM_INVOKE_METHOD)
7287 /* Sent after the invoke is complete */
7290 case CMD_SET_EVENT_REQUEST:
7291 err = event_commands (command, p, end, &buf);
7293 case CMD_SET_APPDOMAIN:
7294 err = domain_commands (command, p, end, &buf);
7296 case CMD_SET_ASSEMBLY:
7297 err = assembly_commands (command, p, end, &buf);
7299 case CMD_SET_MODULE:
7300 err = module_commands (command, p, end, &buf);
7303 err = type_commands (command, p, end, &buf);
7305 case CMD_SET_METHOD:
7306 err = method_commands (command, p, end, &buf);
7308 case CMD_SET_THREAD:
7309 err = thread_commands (command, p, end, &buf);
7311 case CMD_SET_STACK_FRAME:
7312 err = frame_commands (command, p, end, &buf);
7314 case CMD_SET_ARRAY_REF:
7315 err = array_commands (command, p, end, &buf);
7317 case CMD_SET_STRING_REF:
7318 err = string_commands (command, p, end, &buf);
7320 case CMD_SET_OBJECT_REF:
7321 err = object_commands (command, p, end, &buf);
7324 err = ERR_NOT_IMPLEMENTED;
7328 send_reply_packet (id, err, &buf);
7333 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
7337 mono_set_is_debugger_attached (FALSE);
7339 mono_mutex_lock (&debugger_thread_exited_mutex);
7340 debugger_thread_exited = TRUE;
7341 mono_cond_signal (&debugger_thread_exited_cond);
7342 mono_mutex_unlock (&debugger_thread_exited_mutex);
7344 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
7346 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
7347 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
7348 start_debugger_thread ();
7354 #else /* DISABLE_DEBUGGER_AGENT */
7357 mono_debugger_agent_parse_options (char *options)
7359 g_error ("This runtime is configured with the debugger agent disabled.");
7363 mono_debugger_agent_init (void)
7368 mono_debugger_agent_breakpoint_hit (void *sigctx)
7373 mono_debugger_agent_single_step_event (void *sigctx)
7378 mono_debugger_agent_free_domain_info (MonoDomain *domain)
7383 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
7389 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
7390 MonoContext *catch_ctx)
7395 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
7400 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)