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
114 guint32 il_offset, native_offset;
118 * If method is gshared, this is the actual instance, otherwise this is equal to
121 MonoMethod *actual_method;
123 MonoDebugMethodJitInfo *jit;
126 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
127 * the frame can become invalid.
132 typedef struct _InvokeData InvokeData;
140 /* This is the context which needs to be restored after the invoke */
144 * If this is set, invoke this method with the arguments given by ARGS.
148 guint32 suspend_count;
150 InvokeData *last_invoke;
157 gboolean has_context;
158 gpointer resume_event;
159 /* This is computed on demand when it is requested using the wire protocol */
160 /* It is freed up when the thread is resumed */
164 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
167 gboolean frames_up_to_date;
169 * Points to data about a pending invoke which needs to be executed after the thread
172 InvokeData *pending_invoke;
174 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
179 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
180 * within a finite amount of time.
184 * Set to TRUE if this thread is suspended in suspend_current ().
186 gboolean really_suspended;
187 /* Used to pass the context to the breakpoint/single step handler */
188 MonoContext handler_ctx;
189 /* Whenever thread_stop () was called for this thread */
192 /* Number of thread interruptions not yet processed */
193 gint32 interrupt_count;
195 /* Whenever to disable breakpoints (used during invokes) */
196 gboolean disable_breakpoints;
199 * Number of times this thread has been resumed using resume_thread ().
201 guint32 resume_count;
203 MonoInternalThread *thread;
206 * Information about the frame which transitioned to native code for running
209 StackFrameInfo async_last_frame;
212 * The context where the stack walk can be started for running threads.
214 MonoContext async_ctx;
216 gboolean has_async_ctx;
218 gboolean has_filter_ctx;
219 MonoContext filter_ctx;
223 * The lmf where the stack walk can be started for running threads.
228 * The callee address of the last mono_runtime_invoke call
230 gpointer invoke_addr;
232 gboolean abort_requested;
235 * The current mono_runtime_invoke invocation.
240 * The context where single stepping should resume while the thread is suspended because
241 * of an EXCEPTION event.
243 MonoContext catch_ctx;
245 gboolean has_catch_ctx;
249 * Wire Protocol definitions
252 #define HEADER_LENGTH 11
254 #define MAJOR_VERSION 2
255 #define MINOR_VERSION 3
259 CMD_SET_OBJECT_REF = 9,
260 CMD_SET_STRING_REF = 10,
262 CMD_SET_ARRAY_REF = 13,
263 CMD_SET_EVENT_REQUEST = 15,
264 CMD_SET_STACK_FRAME = 16,
265 CMD_SET_APPDOMAIN = 20,
266 CMD_SET_ASSEMBLY = 21,
274 EVENT_KIND_VM_START = 0,
275 EVENT_KIND_VM_DEATH = 1,
276 EVENT_KIND_THREAD_START = 2,
277 EVENT_KIND_THREAD_DEATH = 3,
278 EVENT_KIND_APPDOMAIN_CREATE = 4,
279 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
280 EVENT_KIND_METHOD_ENTRY = 6,
281 EVENT_KIND_METHOD_EXIT = 7,
282 EVENT_KIND_ASSEMBLY_LOAD = 8,
283 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
284 EVENT_KIND_BREAKPOINT = 10,
285 EVENT_KIND_STEP = 11,
286 EVENT_KIND_TYPE_LOAD = 12,
287 EVENT_KIND_EXCEPTION = 13
291 SUSPEND_POLICY_NONE = 0,
292 SUSPEND_POLICY_EVENT_THREAD = 1,
293 SUSPEND_POLICY_ALL = 2
298 ERR_INVALID_OBJECT = 20,
299 ERR_INVALID_FIELDID = 25,
300 ERR_INVALID_FRAMEID = 30,
301 ERR_NOT_IMPLEMENTED = 100,
302 ERR_NOT_SUSPENDED = 101,
303 ERR_INVALID_ARGUMENT = 102,
305 ERR_NO_INVOCATION = 104,
306 ERR_ABSENT_INFORMATION = 105,
307 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106
312 MOD_KIND_THREAD_ONLY = 3,
313 MOD_KIND_LOCATION_ONLY = 7,
314 MOD_KIND_EXCEPTION_ONLY = 8,
316 MOD_KIND_ASSEMBLY_ONLY = 11
331 TOKEN_TYPE_STRING = 0,
333 TOKEN_TYPE_FIELD = 2,
334 TOKEN_TYPE_METHOD = 3,
335 TOKEN_TYPE_UNKNOWN = 4
339 VALUE_TYPE_ID_NULL = 0xf0,
340 VALUE_TYPE_ID_TYPE = 0xf1
344 FRAME_FLAG_DEBUGGER_INVOKE = 1
348 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
349 INVOKE_FLAG_SINGLE_THREADED = 2
354 CMD_VM_ALL_THREADS = 2,
359 CMD_VM_INVOKE_METHOD = 7,
360 CMD_VM_SET_PROTOCOL_VERSION = 8,
361 CMD_VM_ABORT_INVOKE = 9
365 CMD_THREAD_GET_FRAME_INFO = 1,
366 CMD_THREAD_GET_NAME = 2,
367 CMD_THREAD_GET_STATE = 3,
368 CMD_THREAD_GET_INFO = 4,
369 CMD_THREAD_GET_ID = 5,
370 CMD_THREAD_GET_TID = 6
374 CMD_EVENT_REQUEST_SET = 1,
375 CMD_EVENT_REQUEST_CLEAR = 2,
376 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
384 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
385 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
386 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
387 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
388 CMD_APPDOMAIN_CREATE_STRING = 5,
389 CMD_APPDOMAIN_GET_CORLIB = 6,
390 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
394 CMD_ASSEMBLY_GET_LOCATION = 1,
395 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
396 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
397 CMD_ASSEMBLY_GET_OBJECT = 4,
398 CMD_ASSEMBLY_GET_TYPE = 5,
399 CMD_ASSEMBLY_GET_NAME = 6
403 CMD_MODULE_GET_INFO = 1,
407 CMD_METHOD_GET_NAME = 1,
408 CMD_METHOD_GET_DECLARING_TYPE = 2,
409 CMD_METHOD_GET_DEBUG_INFO = 3,
410 CMD_METHOD_GET_PARAM_INFO = 4,
411 CMD_METHOD_GET_LOCALS_INFO = 5,
412 CMD_METHOD_GET_INFO = 6,
413 CMD_METHOD_GET_BODY = 7,
414 CMD_METHOD_RESOLVE_TOKEN = 8,
418 CMD_TYPE_GET_INFO = 1,
419 CMD_TYPE_GET_METHODS = 2,
420 CMD_TYPE_GET_FIELDS = 3,
421 CMD_TYPE_GET_VALUES = 4,
422 CMD_TYPE_GET_OBJECT = 5,
423 CMD_TYPE_GET_SOURCE_FILES = 6,
424 CMD_TYPE_SET_VALUES = 7,
425 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
426 CMD_TYPE_GET_PROPERTIES = 9,
427 CMD_TYPE_GET_CATTRS = 10,
428 CMD_TYPE_GET_FIELD_CATTRS = 11,
429 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
430 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
431 CMD_TYPE_GET_VALUES_2 = 14
435 CMD_STACK_FRAME_GET_VALUES = 1,
436 CMD_STACK_FRAME_GET_THIS = 2,
437 CMD_STACK_FRAME_SET_VALUES = 3
441 CMD_ARRAY_REF_GET_LENGTH = 1,
442 CMD_ARRAY_REF_GET_VALUES = 2,
443 CMD_ARRAY_REF_SET_VALUES = 3,
447 CMD_STRING_REF_GET_VALUE = 1,
451 CMD_OBJECT_REF_GET_TYPE = 1,
452 CMD_OBJECT_REF_GET_VALUES = 2,
453 CMD_OBJECT_REF_IS_COLLECTED = 3,
454 CMD_OBJECT_REF_GET_ADDRESS = 4,
455 CMD_OBJECT_REF_GET_DOMAIN = 5,
456 CMD_OBJECT_REF_SET_VALUES = 6
462 int count; /* For kind == MOD_KIND_COUNT */
463 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
464 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
465 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
467 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
476 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
480 * Describes a single step request.
484 MonoInternalThread *thread;
489 MonoMethod *last_method;
491 /* Whenever single stepping is performed using start/stop_single_stepping () */
493 /* The list of breakpoints used to implement step-over */
498 * Contains additional information for an event
501 /* For EVENT_KIND_EXCEPTION */
503 MonoContext catch_ctx;
507 /* Dummy structure used for the profiler callbacks */
512 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
518 static AgentConfig agent_config;
521 * Whenever the agent is fully initialized.
522 * When using the onuncaught or onthrow options, only some parts of the agent are
523 * initialized on startup, and the full initialization which includes connection
524 * establishment and the startup of the agent thread is only done in response to
527 static gint32 inited;
530 static int listen_fd;
532 static int packet_id = 0;
534 static int objref_id = 0;
536 static int event_request_id = 0;
538 static int frame_id = 0;
540 static GPtrArray *event_requests;
542 static guint32 debugger_tls_id;
544 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
546 /* Maps MonoInternalThread -> DebuggerTlsData */
547 static MonoGHashTable *thread_to_tls;
549 /* Maps tid -> MonoInternalThread */
550 static MonoGHashTable *tid_to_thread;
552 /* Maps tid -> MonoThread (not MonoInternalThread) */
553 static MonoGHashTable *tid_to_thread_obj;
555 static gsize debugger_thread_id;
557 static HANDLE debugger_thread_handle;
559 static int log_level;
561 static gboolean embedding;
563 static FILE *log_file;
565 /* Classes whose class load event has been sent */
566 static GHashTable *loaded_classes;
568 /* Assemblies whose assembly load event has no been sent yet */
569 static GPtrArray *pending_assembly_loads;
571 /* Types whose type load event has no been sent yet */
572 static GPtrArray *pending_type_loads;
574 /* Whenever the debugger thread has exited */
575 static gboolean debugger_thread_exited;
577 /* Cond variable used to wait for debugger_thread_exited becoming true */
578 static mono_cond_t debugger_thread_exited_cond;
580 /* Mutex for the cond var above */
581 static mono_mutex_t debugger_thread_exited_mutex;
583 static DebuggerProfiler debugger_profiler;
585 /* The single step request instance */
586 static SingleStepReq *ss_req = NULL;
587 static gpointer ss_invoke_addr = NULL;
589 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
590 /* Number of single stepping operations in progress */
594 /* The protocol version of the client */
595 static int major_version, minor_version;
597 /* Whenever the variables above are set by the client */
598 static gboolean protocol_version_set;
600 /* A hash table containing all active domains */
601 static GHashTable *domains;
603 static void transport_connect (const char *host, int port);
605 static guint32 WINAPI debugger_thread (void *arg);
607 static void runtime_initialized (MonoProfiler *prof);
609 static void runtime_shutdown (MonoProfiler *prof);
611 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
613 static void thread_end (MonoProfiler *prof, uintptr_t tid);
615 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
617 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
619 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
621 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
623 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
625 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
627 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
629 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
631 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
633 static void start_single_stepping (void);
635 static void stop_single_stepping (void);
637 static void suspend_current (void);
639 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
641 static void clear_breakpoints_for_domain (MonoDomain *domain);
643 static void clear_types_for_assembly (MonoAssembly *assembly);
645 /* Submodule init/cleanup */
646 static void breakpoints_init (void);
647 static void breakpoints_cleanup (void);
649 static void objrefs_init (void);
650 static void objrefs_cleanup (void);
652 static void ids_init (void);
653 static void ids_cleanup (void);
655 static void suspend_init (void);
657 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
658 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
659 static void ss_destroy (SingleStepReq *req);
661 static void start_debugger_thread (void);
662 static void stop_debugger_thread (void);
664 static void finish_agent_init (gboolean on_startup);
667 parse_address (char *address, char **host, int *port)
669 char *pos = strchr (address, ':');
671 if (pos == NULL || pos == address)
674 *host = g_malloc (pos - address + 1);
675 strncpy (*host, address, pos - address);
676 (*host) [pos - address] = '\0';
678 *port = atoi (pos + 1);
686 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
687 fprintf (stderr, "Available options:\n");
688 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
689 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
690 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
691 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
692 fprintf (stderr, " suspend=y/n\t\t\tWhenever to suspend after startup.\n");
693 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
694 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
698 parse_flag (const char *option, char *flag)
700 if (!strcmp (flag, "y"))
702 else if (!strcmp (flag, "n"))
705 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
712 mono_debugger_agent_parse_options (char *options)
718 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
719 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
723 agent_config.enabled = TRUE;
724 agent_config.suspend = TRUE;
725 agent_config.server = FALSE;
727 args = g_strsplit (options, ",", -1);
728 for (ptr = args; ptr && *ptr; ptr ++) {
731 if (strncmp (arg, "transport=", 10) == 0) {
732 agent_config.transport = g_strdup (arg + 10);
733 } else if (strncmp (arg, "address=", 8) == 0) {
734 agent_config.address = g_strdup (arg + 8);
735 } else if (strncmp (arg, "loglevel=", 9) == 0) {
736 agent_config.log_level = atoi (arg + 9);
737 } else if (strncmp (arg, "logfile=", 8) == 0) {
738 agent_config.log_file = g_strdup (arg + 8);
739 } else if (strncmp (arg, "suspend=", 8) == 0) {
740 agent_config.suspend = parse_flag ("suspend", arg + 8);
741 } else if (strncmp (arg, "server=", 7) == 0) {
742 agent_config.server = parse_flag ("server", arg + 7);
743 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
744 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
745 } else if (strncmp (arg, "onthrow=", 8) == 0) {
746 /* We support multiple onthrow= options */
747 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
748 } else if (strncmp (arg, "onthrow", 7) == 0) {
749 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
750 } else if (strncmp (arg, "help", 4) == 0) {
753 } else if (strncmp (arg, "timeout=", 8) == 0) {
754 agent_config.timeout = atoi (arg + 8);
755 } else if (strncmp (arg, "launch=", 7) == 0) {
756 agent_config.launch = g_strdup (arg + 7);
757 } else if (strncmp (arg, "embedding=", 10) == 0) {
758 agent_config.embedding = atoi (arg + 10) == 1;
765 if (agent_config.transport == NULL) {
766 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
769 if (strcmp (agent_config.transport, "dt_socket") != 0) {
770 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
774 if (agent_config.address == NULL && !agent_config.server) {
775 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
779 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
780 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
786 mono_debugger_agent_init (void)
788 if (!agent_config.enabled)
791 /* Need to know whenever a thread has acquired the loader mutex */
792 mono_loader_lock_track_ownership (TRUE);
794 event_requests = g_ptr_array_new ();
796 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
797 mono_cond_init (&debugger_thread_exited_cond, NULL);
799 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
800 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
801 mono_profiler_install_runtime_initialized (runtime_initialized);
802 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
803 mono_profiler_install_thread (thread_startup, thread_end);
804 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
805 mono_profiler_install_jit_end (jit_end);
806 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
808 debugger_tls_id = TlsAlloc ();
810 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
811 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
813 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
814 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
816 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
817 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
819 loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
820 pending_assembly_loads = g_ptr_array_new ();
821 pending_type_loads = g_ptr_array_new ();
822 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
824 log_level = agent_config.log_level;
826 embedding = agent_config.embedding;
828 if (agent_config.log_file) {
829 log_file = fopen (agent_config.log_file, "w+");
831 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
843 mini_get_debug_options ()->gen_seq_points = TRUE;
845 * This is needed because currently we don't handle liveness info.
847 mini_get_debug_options ()->mdb_optimizations = TRUE;
849 /* This is needed because we can't set local variables in registers yet */
850 mono_disable_optimizations (MONO_OPT_LINEARS);
852 if (!agent_config.onuncaught && !agent_config.onthrow)
853 finish_agent_init (TRUE);
859 * Finish the initialization of the agent. This involves connecting the transport
860 * and starting the agent thread. This is either done at startup, or
861 * in response to some event like an unhandled exception.
864 finish_agent_init (gboolean on_startup)
870 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
873 if (agent_config.launch) {
876 // FIXME: Generated address
877 // FIXME: Races with transport_connect ()
879 argv [0] = agent_config.launch;
880 argv [1] = agent_config.transport;
881 argv [2] = agent_config.address;
884 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
886 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
891 if (agent_config.address) {
892 res = parse_address (agent_config.address, &host, &port);
899 transport_connect (host, port);
902 /* Do some which is usually done after sending the VMStart () event */
903 vm_start_event_sent = TRUE;
904 start_debugger_thread ();
909 mono_debugger_agent_cleanup (void)
914 stop_debugger_thread ();
916 breakpoints_cleanup ();
920 mono_mutex_destroy (&debugger_thread_exited_mutex);
921 mono_cond_destroy (&debugger_thread_exited_cond);
927 * recv() + handle incomplete reads and EINTR
930 recv_length (int fd, void *buf, int len, int flags)
936 res = recv (fd, (char *) buf + total, len - total, flags);
939 } while ((res > 0 && total < len) || (res == -1 && errno == EINTR));
944 #define HAVE_GETADDRINFO 1
948 transport_handshake (void)
950 char handshake_msg [128];
954 /* Write handshake message */
955 sprintf (handshake_msg, "DWP-Handshake");
957 res = send (conn_fd, handshake_msg, strlen (handshake_msg), 0);
958 } while (res == -1 && errno == EINTR);
959 g_assert (res != -1);
962 res = recv_length (conn_fd, buf, strlen (handshake_msg), 0);
963 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
964 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
969 * To support older clients, the client sends its protocol version after connecting
970 * using a command. Until that is received, default to our protocol version.
972 major_version = MAJOR_VERSION;
973 minor_version = MINOR_VERSION;
974 protocol_version_set = FALSE;
977 * Set TCP_NODELAY on the socket so the client receives events/command
978 * results immediately.
982 int result = setsockopt (conn_fd,
987 g_assert (result >= 0);
994 transport_accept (int socket_fd)
996 conn_fd = accept (socket_fd, NULL, NULL);
998 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1000 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1007 * transport_connect:
1009 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1012 transport_connect (const char *host, int port)
1014 #ifdef HAVE_GETADDRINFO
1015 struct addrinfo hints;
1016 struct addrinfo *result, *rp;
1018 struct hostent *result;
1021 char port_string [128];
1027 sprintf (port_string, "%d", port);
1029 mono_network_init ();
1031 /* Obtain address(es) matching host/port */
1032 #ifdef HAVE_GETADDRINFO
1033 memset (&hints, 0, sizeof (struct addrinfo));
1034 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1035 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1037 hints.ai_protocol = 0; /* Any protocol */
1039 s = getaddrinfo (host, port_string, &hints, &result);
1041 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1045 /* The PS3 doesn't even have _r or hstrerror () */
1046 result = gethostbyname (host);
1048 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1053 if (agent_config.server) {
1054 #ifdef HAVE_GETADDRINFO
1055 /* Wait for a connection */
1057 struct sockaddr_in addr;
1060 /* No address, generate one */
1061 sfd = socket (AF_INET, SOCK_STREAM, 0);
1064 /* This will bind the socket to a random port */
1065 res = listen (sfd, 16);
1067 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
1072 addrlen = sizeof (addr);
1073 memset (&addr, 0, sizeof (addr));
1074 res = getsockname (sfd, &addr, &addrlen);
1075 g_assert (res == 0);
1078 port = ntohs (addr.sin_port);
1080 /* Emit the address to stdout */
1081 /* FIXME: Should print another interface, not localhost */
1082 printf ("%s:%d\n", host, port);
1084 /* Listen on the provided address */
1085 for (rp = result; rp != NULL; rp = rp->ai_next) {
1086 sfd = socket (rp->ai_family, rp->ai_socktype,
1091 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1095 res = listen (sfd, 16);
1104 * this function is not present on win2000 which we still support, and the
1105 * workaround described here:
1106 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1107 * only works with MSVC.
1109 #ifdef HAVE_GETADDRINFO
1110 freeaddrinfo (result);
1115 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1117 if (agent_config.timeout) {
1122 tv.tv_usec = agent_config.timeout * 1000;
1124 FD_SET (sfd, &readfds);
1125 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1127 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1132 conn_fd = transport_accept (sfd);
1136 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1139 #endif /* HAVE_GETADDRINFO */
1141 /* Connect to the specified address */
1142 #ifdef HAVE_GETADDRINFO
1143 /* FIXME: Respect the timeout */
1144 for (rp = result; rp != NULL; rp = rp->ai_next) {
1145 sfd = socket (rp->ai_family, rp->ai_socktype,
1150 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1151 break; /* Success */
1157 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1161 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1163 g_assert_not_reached ();
1164 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1166 g_assert_not_reached ();
1172 /* See the comment above */
1173 #ifdef HAVE_GETADDRINFO
1174 freeaddrinfo (result);
1179 if (!transport_handshake ())
1184 transport_send (guint8 *data, int len)
1189 res = send (conn_fd, data, len, 0);
1190 } while (res == -1 && errno == EINTR);
1198 stop_debugger_thread (void)
1203 /* This will interrupt the agent thread */
1204 /* Close the read part only so it can still send back replies */
1205 /* Also shut down the connection listener so that we can exit normally */
1207 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1208 shutdown (conn_fd, SD_BOTH);
1209 shutdown (listen_fd, SD_BOTH);
1210 closesocket (listen_fd);
1212 shutdown (conn_fd, SHUT_RD);
1213 shutdown (listen_fd, SHUT_RDWR);
1218 * Wait for the thread to exit.
1220 * If we continue with the shutdown without waiting for it, then the client might
1221 * not receive an answer to its last command like a resume.
1222 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1225 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1226 if (GetCurrentThreadId () != debugger_thread_id) {
1228 mono_mutex_lock (&debugger_thread_exited_mutex);
1229 if (!debugger_thread_exited) {
1231 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1232 mono_mutex_unlock (&debugger_thread_exited_mutex);
1234 mono_mutex_lock (&debugger_thread_exited_mutex);
1237 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1240 mono_mutex_unlock (&debugger_thread_exited_mutex);
1241 } while (!debugger_thread_exited);
1245 shutdown (conn_fd, SD_BOTH);
1247 shutdown (conn_fd, SHUT_RDWR);
1252 start_debugger_thread (void)
1256 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1257 g_assert (debugger_thread_handle);
1261 * Functions to decode protocol data
1265 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1268 g_assert (*endbuf <= limit);
1273 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1276 g_assert (*endbuf <= limit);
1278 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1281 static inline gint64
1282 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1284 guint32 high = decode_int (buf, &buf, limit);
1285 guint32 low = decode_int (buf, &buf, limit);
1289 return ((((guint64)high) << 32) | ((guint64)low));
1293 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1295 return decode_int (buf, endbuf, limit);
1299 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1301 int len = decode_int (buf, &buf, limit);
1304 s = g_malloc (len + 1);
1307 memcpy (s, buf, len);
1316 * Functions to encode protocol data
1320 guint8 *buf, *p, *end;
1324 buffer_init (Buffer *buf, int size)
1326 buf->buf = g_malloc (size);
1328 buf->end = buf->buf + size;
1332 buffer_make_room (Buffer *buf, int size)
1334 if (buf->end - buf->p < size) {
1335 int new_size = buf->end - buf->buf + size + 32;
1336 guint8 *p = g_realloc (buf->buf, new_size);
1337 size = buf->p - buf->buf;
1340 buf->end = buf->buf + new_size;
1345 buffer_add_byte (Buffer *buf, guint8 val)
1347 buffer_make_room (buf, 1);
1353 buffer_add_int (Buffer *buf, guint32 val)
1355 buffer_make_room (buf, 4);
1356 buf->p [0] = (val >> 24) & 0xff;
1357 buf->p [1] = (val >> 16) & 0xff;
1358 buf->p [2] = (val >> 8) & 0xff;
1359 buf->p [3] = (val >> 0) & 0xff;
1364 buffer_add_long (Buffer *buf, guint64 l)
1366 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1367 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1371 buffer_add_id (Buffer *buf, int id)
1373 buffer_add_int (buf, (guint64)id);
1377 buffer_add_data (Buffer *buf, guint8 *data, int len)
1379 buffer_make_room (buf, len);
1380 memcpy (buf->p, data, len);
1385 buffer_add_string (Buffer *buf, const char *str)
1390 buffer_add_int (buf, 0);
1393 buffer_add_int (buf, len);
1394 buffer_add_data (buf, (guint8*)str, len);
1399 buffer_free (Buffer *buf)
1405 send_packet (int command_set, int command, Buffer *data)
1411 id = InterlockedIncrement (&packet_id);
1413 len = data->p - data->buf + 11;
1414 buffer_init (&buf, len);
1415 buffer_add_int (&buf, len);
1416 buffer_add_int (&buf, id);
1417 buffer_add_byte (&buf, 0); /* flags */
1418 buffer_add_byte (&buf, command_set);
1419 buffer_add_byte (&buf, command);
1420 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1422 res = transport_send (buf.buf, len);
1430 send_reply_packet (int id, int error, Buffer *data)
1436 len = data->p - data->buf + 11;
1437 buffer_init (&buf, len);
1438 buffer_add_int (&buf, len);
1439 buffer_add_int (&buf, id);
1440 buffer_add_byte (&buf, 0x80); /* flags */
1441 buffer_add_byte (&buf, (error >> 8) & 0xff);
1442 buffer_add_byte (&buf, error);
1443 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1445 res = transport_send (buf.buf, len);
1457 * Represents an object accessible by the debugger client.
1460 /* Unique id used in the wire protocol to refer to objects */
1463 * A weakref gc handle pointing to the object. The gc handle is used to
1464 * detect if the object was garbage collected.
1469 /* Maps objid -> ObjRef */
1470 static GHashTable *objrefs;
1473 free_objref (gpointer value)
1477 mono_gchandle_free (o->handle);
1485 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1489 objrefs_cleanup (void)
1491 g_hash_table_destroy (objrefs);
1495 static GHashTable *obj_to_objref;
1498 * Return an ObjRef for OBJ.
1501 get_objref (MonoObject *obj)
1504 GSList *reflist = NULL, *l;
1510 mono_loader_lock ();
1513 obj_to_objref = g_hash_table_new (NULL, NULL);
1515 /* FIXME: The tables can grow indefinitely */
1517 if (mono_gc_is_moving ()) {
1519 * Objects can move, so use a hash table mapping hash codes to lists of
1520 * ObjRef structures.
1522 hash = mono_object_hash (obj);
1524 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1525 for (l = reflist; l; l = l->next) {
1527 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1528 mono_loader_unlock ();
1533 /* Use a hash table with masked pointers to internalize object references */
1534 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1535 /* ref might refer to a different object with the same addr which was GCd */
1536 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1537 mono_loader_unlock ();
1542 ref = g_new0 (ObjRef, 1);
1543 ref->id = InterlockedIncrement (&objref_id);
1544 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1546 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1548 if (mono_gc_is_moving ()) {
1549 reflist = g_slist_append (reflist, ref);
1550 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1552 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1555 mono_loader_unlock ();
1561 get_objid (MonoObject *obj)
1563 return get_objref (obj)->id;
1567 * Set OBJ to the object identified by OBJID.
1568 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1572 get_object_allow_null (int objid, MonoObject **obj)
1582 return ERR_INVALID_OBJECT;
1584 mono_loader_lock ();
1586 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1589 *obj = mono_gchandle_get_target (ref->handle);
1590 mono_loader_unlock ();
1592 return ERR_INVALID_OBJECT;
1595 mono_loader_unlock ();
1596 return ERR_INVALID_OBJECT;
1601 get_object (int objid, MonoObject **obj)
1603 int err = get_object_allow_null (objid, obj);
1608 return ERR_INVALID_OBJECT;
1613 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1615 return decode_id (buf, endbuf, limit);
1619 buffer_add_objid (Buffer *buf, MonoObject *o)
1621 buffer_add_id (buf, get_objid (o));
1640 * Represents a runtime structure accessible to the debugger client
1643 /* Unique id used in the wire protocol */
1645 /* Domain of the runtime structure, NULL if the domain was unloaded */
1652 MonoAssembly *assembly;
1653 MonoClassField *field;
1655 MonoProperty *property;
1660 /* Maps runtime structure -> Id */
1661 GHashTable *val_to_id [ID_NUM];
1665 static GPtrArray *ids [ID_NUM];
1672 for (i = 0; i < ID_NUM; ++i)
1673 ids [i] = g_ptr_array_new ();
1681 for (i = 0; i < ID_NUM; ++i) {
1683 for (j = 0; j < ids [i]->len; ++j)
1684 g_free (g_ptr_array_index (ids [i], j));
1685 g_ptr_array_free (ids [i], TRUE);
1692 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1694 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1698 for (i = 0; i < ID_NUM; ++i)
1699 if (info->val_to_id [i])
1700 g_hash_table_destroy (info->val_to_id [i]);
1704 domain_jit_info (domain)->agent_info = NULL;
1706 /* Clear ids referencing structures in the domain */
1707 for (i = 0; i < ID_NUM; ++i) {
1709 for (j = 0; j < ids [i]->len; ++j) {
1710 Id *id = g_ptr_array_index (ids [i], j);
1711 if (id->domain == domain)
1717 mono_loader_lock ();
1718 g_hash_table_remove (domains, domain);
1719 mono_loader_unlock ();
1723 get_id (MonoDomain *domain, IdType type, gpointer val)
1726 AgentDomainInfo *info;
1731 mono_loader_lock ();
1733 mono_domain_lock (domain);
1735 if (!domain_jit_info (domain)->agent_info)
1736 domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1737 info = domain_jit_info (domain)->agent_info;
1738 if (info->val_to_id [type] == NULL)
1739 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1741 id = g_hash_table_lookup (info->val_to_id [type], val);
1743 mono_domain_unlock (domain);
1744 mono_loader_unlock ();
1748 id = g_new0 (Id, 1);
1750 id->id = ids [type]->len + 1;
1751 id->domain = domain;
1754 g_hash_table_insert (info->val_to_id [type], val, id);
1756 mono_domain_unlock (domain);
1758 g_ptr_array_add (ids [type], id);
1760 mono_loader_unlock ();
1765 static inline gpointer
1766 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1770 int id = decode_id (buf, endbuf, limit);
1779 // FIXME: error handling
1780 mono_loader_lock ();
1781 g_assert (id > 0 && id <= ids [type]->len);
1783 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1784 mono_loader_unlock ();
1786 if (res->domain == NULL) {
1787 *err = ERR_UNLOADED;
1792 *domain = res->domain;
1794 return res->data.val;
1798 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1800 buffer_add_id (buf, get_id (domain, type, val));
1803 static inline MonoClass*
1804 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1806 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1809 static inline MonoAssembly*
1810 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1812 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1815 static inline MonoImage*
1816 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1818 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1821 static inline MonoMethod*
1822 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1824 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1827 static inline MonoClassField*
1828 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1830 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1833 static inline MonoDomain*
1834 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1836 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1839 static inline MonoProperty*
1840 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1842 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1846 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1848 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1852 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1854 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1858 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1860 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1864 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1866 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1870 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1872 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1876 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1878 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1882 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1884 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1887 static void invoke_method (void);
1894 * save_thread_context:
1896 * Set CTX as the current threads context which is used for computing stack traces.
1897 * This function is signal-safe.
1900 save_thread_context (MonoContext *ctx)
1902 DebuggerTlsData *tls;
1904 tls = TlsGetValue (debugger_tls_id);
1908 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1910 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1911 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1913 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1917 tls->lmf = mono_get_lmf ();
1918 tls->domain = mono_domain_get ();
1919 tls->has_context = TRUE;
1922 /* The number of times the runtime is suspended */
1923 static gint32 suspend_count;
1925 /* Number of threads suspended */
1927 * If this is equal to the size of thread_to_tls, the runtime is considered
1930 static gint32 threads_suspend_count;
1932 static mono_mutex_t suspend_mutex;
1934 /* Cond variable used to wait for suspend_count becoming 0 */
1935 static mono_cond_t suspend_cond;
1937 /* Semaphore used to wait for a thread becoming suspended */
1938 static MonoSemType suspend_sem;
1943 mono_mutex_init (&suspend_mutex, NULL);
1944 mono_cond_init (&suspend_cond, NULL);
1945 MONO_SEM_INIT (&suspend_sem, 0);
1950 StackFrameInfo last_frame;
1951 gboolean last_frame_set;
1954 } GetLastFrameUserData;
1957 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
1959 GetLastFrameUserData *data = user_data;
1961 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
1964 if (!data->last_frame_set) {
1965 /* Store the last frame */
1966 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
1967 data->last_frame_set = TRUE;
1970 /* Store the context/lmf for the frame above the last frame */
1971 memcpy (&data->ctx, ctx, sizeof (MonoContext));
1972 data->lmf = info->lmf;
1979 * mono_debugger_agent_thread_interrupt:
1981 * Called by the abort signal handler.
1982 * Should be signal safe.
1985 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
1987 DebuggerTlsData *tls;
1992 tls = TlsGetValue (debugger_tls_id);
1997 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
1998 * guarantee the signal handler will be called that many times. Instead of tracking
1999 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2000 * has been requested that hasn't been handled yet, otherwise we can have threads
2001 * refuse to die when VM_EXIT is called
2003 #if defined(__APPLE__)
2004 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2008 * We use interrupt_count to determine whenever this interrupt should be processed
2009 * by us or the normal interrupt processing code in the signal handler.
2010 * There is no race here with notify_thread (), since the signal is sent after
2011 * incrementing interrupt_count.
2013 if (tls->interrupt_count == 0)
2016 InterlockedDecrement (&tls->interrupt_count);
2019 // FIXME: Races when the thread leaves managed code before hitting a single step
2023 /* Running managed code, will be suspended by the single step code */
2024 DEBUG (1, printf ("[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)GetCurrentThreadId (), ji->method->name, mono_arch_ip_from_context (sigctx)));
2028 * Running native code, will be suspended when it returns to/enters
2029 * managed code. Treat it as already suspended.
2030 * This might interrupt the code in process_single_step_inner (), we use the
2031 * tls->suspending flag to avoid races when that happens.
2033 if (!tls->suspended && !tls->suspending) {
2035 GetLastFrameUserData data;
2037 // FIXME: printf is not signal safe, but this is only used during
2038 // debugger debugging
2040 DEBUG (1, printf ("[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)GetCurrentThreadId (), mono_arch_ip_from_context (sigctx)));
2041 //save_thread_context (&ctx);
2044 /* Already terminated */
2048 * We are in a difficult position: we want to be able to provide stack
2049 * traces for this thread, but we can't use the current ctx+lmf, since
2050 * the thread is still running, so it might return to managed code,
2051 * making these invalid.
2052 * So we start a stack walk and save the first frame, along with the
2053 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2054 * suspended when it returns to managed code, so the parent's ctx should
2057 data.last_frame_set = FALSE;
2059 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2060 mono_walk_stack (get_last_frame, mono_domain_get (), &ctx, MONO_UNWIND_DEFAULT, tls->thread, mono_get_lmf (), &data);
2062 if (data.last_frame_set) {
2063 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2064 memcpy (&tls->async_ctx, &data.ctx, sizeof (MonoContext));
2065 tls->async_lmf = data.lmf;
2066 tls->has_async_ctx = TRUE;
2067 tls->domain = mono_domain_get ();
2068 memcpy (&tls->ctx, &ctx, sizeof (MonoContext));
2070 tls->has_async_ctx = FALSE;
2073 mono_memory_barrier ();
2075 tls->suspended = TRUE;
2076 MONO_SEM_POST (&suspend_sem);
2083 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2086 mono_debugger_agent_thread_interrupt (NULL, NULL);
2088 #endif /* HOST_WIN32 */
2091 * reset_native_thread_suspend_state:
2093 * Reset the suspended flag on native threads
2096 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2098 DebuggerTlsData *tls = value;
2100 if (!tls->really_suspended && tls->suspended)
2101 tls->suspended = FALSE;
2107 * Notify a thread that it needs to suspend.
2110 notify_thread (gpointer key, gpointer value, gpointer user_data)
2112 MonoInternalThread *thread = key;
2113 DebuggerTlsData *tls = value;
2114 gsize tid = thread->tid;
2116 if (GetCurrentThreadId () == tid || tls->terminated)
2119 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2122 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2123 * guarantee the signal handler will be called that many times. Instead of tracking
2124 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2125 * has been requested that hasn't been handled yet, otherwise we can have threads
2126 * refuse to die when VM_EXIT is called
2128 #if defined(__APPLE__)
2129 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2133 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2134 * of things like breaking waits etc. which we don't want.
2136 InterlockedIncrement (&tls->interrupt_count);
2139 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2141 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2143 mono_thread_kill (thread, mono_thread_get_abort_signal ());
2148 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2150 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2153 if (debugger_thread_id == GetCurrentThreadId ())
2156 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2157 if (suspend_count - tls->resume_count > 0)
2158 tls->suspending = TRUE;
2160 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2162 if (suspend_count - tls->resume_count == 0) {
2164 * We are executing a single threaded invoke but the single step for
2165 * suspending is still active.
2166 * FIXME: This slows down single threaded invokes.
2168 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2172 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2174 /* Can't suspend in these methods */
2175 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2178 save_thread_context (ctx);
2186 * Increase the suspend count of the VM. While the suspend count is greater
2187 * than 0, runtime threads are suspended at certain points during execution.
2192 mono_loader_lock ();
2194 mono_mutex_lock (&suspend_mutex);
2198 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2200 if (suspend_count == 1) {
2201 // FIXME: Is it safe to call this inside the lock ?
2202 start_single_stepping ();
2203 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2206 mono_mutex_unlock (&suspend_mutex);
2208 mono_loader_unlock ();
2214 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2222 g_assert (debugger_thread_id == GetCurrentThreadId ());
2224 mono_loader_lock ();
2226 mono_mutex_lock (&suspend_mutex);
2228 g_assert (suspend_count > 0);
2231 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2233 if (suspend_count == 0) {
2234 // FIXME: Is it safe to call this inside the lock ?
2235 stop_single_stepping ();
2236 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2239 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2240 err = mono_cond_broadcast (&suspend_cond);
2241 g_assert (err == 0);
2243 mono_mutex_unlock (&suspend_mutex);
2244 //g_assert (err == 0);
2246 mono_loader_unlock ();
2252 * Resume just one thread.
2255 resume_thread (MonoInternalThread *thread)
2258 DebuggerTlsData *tls;
2260 g_assert (debugger_thread_id == GetCurrentThreadId ());
2262 mono_loader_lock ();
2264 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2267 mono_mutex_lock (&suspend_mutex);
2269 g_assert (suspend_count > 0);
2271 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2273 tls->resume_count += suspend_count;
2276 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2277 * but only the one whose resume_count field is > 0 will be resumed.
2279 err = mono_cond_broadcast (&suspend_cond);
2280 g_assert (err == 0);
2282 mono_mutex_unlock (&suspend_mutex);
2283 //g_assert (err == 0);
2285 mono_loader_unlock ();
2289 invalidate_frames (DebuggerTlsData *tls)
2294 tls = TlsGetValue (debugger_tls_id);
2297 for (i = 0; i < tls->frame_count; ++i) {
2298 if (tls->frames [i]->jit)
2299 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2300 g_free (tls->frames [i]);
2302 g_free (tls->frames);
2303 tls->frame_count = 0;
2310 * Suspend the current thread until the runtime is resumed. If the thread has a
2311 * pending invoke, then the invoke is executed before this function returns.
2314 suspend_current (void)
2317 DebuggerTlsData *tls;
2319 g_assert (debugger_thread_id != GetCurrentThreadId ());
2321 if (mono_loader_lock_is_owned_by_self ()) {
2323 * If we own the loader mutex, can't suspend until we release it, since the
2324 * whole runtime can deadlock otherwise.
2329 tls = TlsGetValue (debugger_tls_id);
2332 mono_mutex_lock (&suspend_mutex);
2334 tls->suspending = FALSE;
2335 tls->really_suspended = TRUE;
2337 if (!tls->suspended) {
2338 tls->suspended = TRUE;
2339 MONO_SEM_POST (&suspend_sem);
2342 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2344 while (suspend_count - tls->resume_count > 0) {
2346 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2348 mono_mutex_unlock (&suspend_mutex);
2350 mono_mutex_lock (&suspend_mutex);
2356 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2357 g_assert (err == 0);
2361 tls->suspended = FALSE;
2362 tls->really_suspended = FALSE;
2364 threads_suspend_count --;
2366 mono_mutex_unlock (&suspend_mutex);
2368 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2370 if (tls->pending_invoke) {
2371 /* Save the original context */
2372 tls->pending_invoke->has_ctx = TRUE;
2373 memcpy (&tls->pending_invoke->ctx, &tls->ctx, sizeof (MonoContext));
2378 /* The frame info becomes invalid after a resume */
2379 tls->has_context = FALSE;
2380 tls->has_async_ctx = FALSE;
2381 invalidate_frames (NULL);
2385 count_thread (gpointer key, gpointer value, gpointer user_data)
2387 DebuggerTlsData *tls = value;
2389 if (!tls->suspended && !tls->terminated)
2390 *(int*)user_data = *(int*)user_data + 1;
2394 count_threads_to_wait_for (void)
2398 mono_loader_lock ();
2399 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2400 mono_loader_unlock ();
2408 * Wait until the runtime is completely suspended.
2411 wait_for_suspend (void)
2413 int nthreads, nwait, err;
2414 gboolean waited = FALSE;
2416 // FIXME: Threads starting/stopping ?
2417 mono_loader_lock ();
2418 nthreads = mono_g_hash_table_size (thread_to_tls);
2419 mono_loader_unlock ();
2422 nwait = count_threads_to_wait_for ();
2424 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2425 err = MONO_SEM_WAIT (&suspend_sem);
2426 g_assert (err == 0);
2434 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2440 * Return whenever the runtime is suspended.
2445 return count_threads_to_wait_for () == 0;
2449 * find_seq_point_for_native_offset:
2451 * Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2452 * should be the location of a sequence point.
2455 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2457 MonoSeqPointInfo *seq_points;
2460 mono_domain_lock (domain);
2461 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2462 mono_domain_unlock (domain);
2463 g_assert (seq_points);
2467 for (i = 0; i < seq_points->len; ++i) {
2468 if (seq_points->seq_points [i].native_offset == native_offset)
2469 return &seq_points->seq_points [i];
2476 * find_next_seq_point_for_native_offset:
2478 * Find the first sequence point after NATIVE_OFFSET.
2481 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2483 MonoSeqPointInfo *seq_points;
2486 mono_domain_lock (domain);
2487 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2488 mono_domain_unlock (domain);
2489 g_assert (seq_points);
2493 for (i = 0; i < seq_points->len; ++i) {
2494 if (seq_points->seq_points [i].native_offset >= native_offset)
2495 return &seq_points->seq_points [i];
2502 * find_prev_seq_point_for_native_offset:
2504 * Find the first sequence point before NATIVE_OFFSET.
2507 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2509 MonoSeqPointInfo *seq_points;
2512 mono_domain_lock (domain);
2513 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2514 mono_domain_unlock (domain);
2515 g_assert (seq_points);
2519 for (i = seq_points->len - 1; i >= 0; --i) {
2520 if (seq_points->seq_points [i].native_offset <= native_offset)
2521 return &seq_points->seq_points [i];
2530 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2531 * should be the location of a sequence point.
2534 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2536 MonoSeqPointInfo *seq_points;
2539 mono_domain_lock (domain);
2540 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2541 mono_domain_unlock (domain);
2542 g_assert (seq_points);
2546 for (i = 0; i < seq_points->len; ++i) {
2547 if (seq_points->seq_points [i].il_offset == il_offset)
2548 return &seq_points->seq_points [i];
2555 * compute_il_offset:
2557 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2558 * a location of a sequence point.
2559 * We use this function instead of mono_debug_il_offset_from_address () etc,
2560 * which doesn't seem to work in a lot of cases.
2563 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2565 MonoSeqPointInfo *seq_points;
2566 int i, last_il_offset, seq_il_offset, seq_native_offset;
2568 mono_domain_lock (domain);
2569 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2570 mono_domain_unlock (domain);
2571 g_assert (seq_points);
2573 last_il_offset = -1;
2575 /* Find the sequence point */
2576 for (i = 0; i < seq_points->len; ++i) {
2577 seq_il_offset = seq_points->seq_points [i].il_offset;
2578 seq_native_offset = seq_points->seq_points [i].native_offset;
2580 if (seq_native_offset > native_offset)
2582 last_il_offset = seq_il_offset;
2585 return last_il_offset;
2589 DebuggerTlsData *tls;
2591 } ComputeFramesUserData;
2594 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2596 ComputeFramesUserData *ud = user_data;
2598 MonoMethod *method, *actual_method;
2600 if (info->type != FRAME_TYPE_MANAGED) {
2601 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2602 /* Mark the last frame as an invoke frame */
2604 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2610 method = info->ji->method;
2612 method = info->method;
2613 actual_method = info->actual_method;
2615 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2618 if (info->il_offset == -1) {
2619 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2620 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2623 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));
2625 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2627 * mono_arch_find_jit_info () returns the context stored in the LMF for
2628 * native frames, but it should unwind once. This is why we have duplicate
2629 * frames on the stack sometimes.
2630 * !managed also seems to be set for dynamic methods.
2635 frame = g_new0 (StackFrame, 1);
2636 frame->method = method;
2637 frame->actual_method = actual_method;
2638 frame->il_offset = info->il_offset;
2639 frame->native_offset = info->native_offset;
2642 frame->has_ctx = TRUE;
2644 frame->domain = info->domain;
2646 ud->frames = g_slist_append (ud->frames, frame);
2652 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2654 ComputeFramesUserData *ud = user_data;
2657 * 'tls->filter_ctx' is the location of the throw site.
2659 * mono_walk_stack() will never actually hit the throw site, but unwind
2660 * directly from the filter to the call site; we abort stack unwinding here
2661 * once this happens and resume from the throw site.
2664 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_ctx))
2667 return process_frame (info, ctx, user_data);
2671 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2673 ComputeFramesUserData user_data;
2675 int i, findex, new_frame_count;
2676 StackFrame **new_frames, *f;
2678 // FIXME: Locking on tls
2679 if (tls->frames && tls->frames_up_to_date)
2682 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2684 user_data.tls = tls;
2685 user_data.frames = NULL;
2686 if (tls->terminated) {
2687 tls->frame_count = 0;
2689 } if (!tls->really_suspended && tls->has_async_ctx) {
2690 /* Have to use the state saved by the signal handler */
2691 process_frame (&tls->async_last_frame, NULL, &user_data);
2692 mono_walk_stack (process_frame, tls->domain, &tls->async_ctx, MONO_UNWIND_DEFAULT, thread, tls->async_lmf, &user_data);
2693 } else if (tls->has_filter_ctx) {
2695 * We are inside an exception filter.
2697 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
2699 if (tls->has_context)
2700 mono_walk_stack (process_filter_frame, tls->domain, &tls->ctx, MONO_UNWIND_DEFAULT, thread, tls->lmf, &user_data);
2702 * After that, we resume unwinding from the location where the exception has been thrown.
2704 mono_walk_stack (process_frame, tls->domain, &tls->filter_ctx, MONO_UNWIND_DEFAULT, thread, tls->filter_lmf, &user_data);
2705 } else if (tls->has_context) {
2706 mono_walk_stack (process_frame, tls->domain, &tls->ctx, MONO_UNWIND_DEFAULT, thread, tls->lmf, &user_data);
2709 tls->frame_count = 0;
2713 new_frame_count = g_slist_length (user_data.frames);
2714 new_frames = g_new0 (StackFrame*, new_frame_count);
2716 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2720 * Reuse the id for already existing stack frames, so invokes don't invalidate
2721 * the still valid stack frames.
2723 for (i = 0; i < tls->frame_count; ++i) {
2724 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2725 f->id = tls->frames [i]->id;
2730 if (i >= tls->frame_count)
2731 f->id = InterlockedIncrement (&frame_id);
2733 new_frames [findex ++] = f;
2736 g_slist_free (user_data.frames);
2738 invalidate_frames (tls);
2740 tls->frames = new_frames;
2741 tls->frame_count = new_frame_count;
2742 tls->frames_up_to_date = TRUE;
2750 * create_event_list:
2752 * Return a list of event request ids matching EVENT, starting from REQS, which
2753 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2755 * We return request ids, instead of requests, to simplify threading, since
2756 * requests could be deleted anytime when the loader lock is not held.
2757 * LOCKING: Assumes the loader lock is held.
2760 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
2763 GSList *events = NULL;
2765 *suspend_policy = SUSPEND_POLICY_NONE;
2768 reqs = event_requests;
2773 for (i = 0; i < reqs->len; ++i) {
2774 EventRequest *req = g_ptr_array_index (reqs, i);
2775 if (req->event_kind == event) {
2776 gboolean filtered = FALSE;
2779 for (j = 0; j < req->nmodifiers; ++j) {
2780 Modifier *mod = &req->modifiers [j];
2782 if (mod->kind == MOD_KIND_COUNT) {
2784 if (mod->data.count > 0) {
2785 if (mod->data.count > 0) {
2787 if (mod->data.count == 0)
2791 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2792 if (mod->data.thread != mono_thread_internal_current ())
2794 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
2795 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
2797 if (ei->caught && !mod->caught)
2799 if (!ei->caught && !mod->uncaught)
2801 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2803 gboolean found = FALSE;
2804 MonoAssembly **assemblies = mod->data.assemblies;
2807 for (k = 0; assemblies [k]; ++k)
2808 if (assemblies [k] == ji->method->klass->image->assembly)
2817 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2818 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2823 /* Send a VM START/DEATH event by default */
2824 if (event == EVENT_KIND_VM_START)
2825 events = g_slist_append (events, GINT_TO_POINTER (0));
2826 if (event == EVENT_KIND_VM_DEATH)
2827 events = g_slist_append (events, GINT_TO_POINTER (0));
2832 static G_GNUC_UNUSED const char*
2833 event_to_string (EventKind event)
2836 case EVENT_KIND_VM_START: return "VM_START";
2837 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2838 case EVENT_KIND_THREAD_START: return "THREAD_START";
2839 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2840 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2841 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2842 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2843 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2844 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2845 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2846 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2847 case EVENT_KIND_STEP: return "STEP";
2848 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2849 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2851 g_assert_not_reached ();
2858 * Send an event to the client, suspending the vm if needed.
2859 * LOCKING: Since this can suspend the calling thread, no locks should be held
2861 * The EVENTS list is freed by this function.
2864 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2868 MonoDomain *domain = mono_domain_get ();
2870 gboolean send_success = FALSE;
2873 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
2877 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
2878 // FIXME: We miss those events
2879 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
2883 if (vm_death_event_sent) {
2884 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
2888 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
2889 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
2894 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
2901 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
2902 // FIXME: Send these with a NULL thread, don't suspend the current thread
2905 buffer_init (&buf, 128);
2906 buffer_add_byte (&buf, suspend_policy);
2907 buffer_add_int (&buf, g_slist_length (events)); // n of events
2909 for (l = events; l; l = l->next) {
2910 buffer_add_byte (&buf, event); // event kind
2911 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
2913 thread = mono_thread_current ();
2915 if (event == EVENT_KIND_VM_START)
2917 else if (event == EVENT_KIND_THREAD_START)
2918 g_assert (mono_thread_internal_current () == arg);
2920 buffer_add_objid (&buf, (MonoObject*)thread); // thread
2923 case EVENT_KIND_THREAD_START:
2924 case EVENT_KIND_THREAD_DEATH:
2926 case EVENT_KIND_APPDOMAIN_CREATE:
2927 case EVENT_KIND_APPDOMAIN_UNLOAD:
2928 buffer_add_domainid (&buf, arg);
2930 case EVENT_KIND_METHOD_ENTRY:
2931 case EVENT_KIND_METHOD_EXIT:
2932 buffer_add_methodid (&buf, domain, arg);
2934 case EVENT_KIND_ASSEMBLY_LOAD:
2935 case EVENT_KIND_ASSEMBLY_UNLOAD:
2936 buffer_add_assemblyid (&buf, domain, arg);
2938 case EVENT_KIND_TYPE_LOAD:
2939 buffer_add_typeid (&buf, domain, arg);
2941 case EVENT_KIND_BREAKPOINT:
2942 case EVENT_KIND_STEP:
2943 buffer_add_methodid (&buf, domain, arg);
2944 buffer_add_long (&buf, il_offset);
2946 case EVENT_KIND_VM_START:
2947 buffer_add_domainid (&buf, mono_get_root_domain ());
2949 case EVENT_KIND_VM_DEATH:
2951 case EVENT_KIND_EXCEPTION: {
2952 EventInfo *ei = arg;
2953 buffer_add_objid (&buf, ei->exc);
2957 g_assert_not_reached ();
2961 if (event == EVENT_KIND_VM_START) {
2962 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
2963 start_debugger_thread ();
2966 if (event == EVENT_KIND_VM_DEATH) {
2967 vm_death_event_sent = TRUE;
2969 suspend_policy = SUSPEND_POLICY_NONE;
2972 if (mono_runtime_is_shutting_down ())
2973 suspend_policy = SUSPEND_POLICY_NONE;
2975 if (suspend_policy != SUSPEND_POLICY_NONE) {
2977 * Save the thread context and start suspending before sending the packet,
2978 * since we could be receiving the resume request before send_packet ()
2981 save_thread_context (ctx);
2985 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
2989 g_slist_free (events);
2992 if (!send_success) {
2993 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
2997 if (event == EVENT_KIND_VM_START)
2998 vm_start_event_sent = TRUE;
3000 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
3003 switch (suspend_policy) {
3004 case SUSPEND_POLICY_NONE:
3006 case SUSPEND_POLICY_ALL:
3009 case SUSPEND_POLICY_EVENT_THREAD:
3013 g_assert_not_reached ();
3018 process_profiler_event (EventKind event, gpointer arg)
3023 mono_loader_lock ();
3024 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
3025 mono_loader_unlock ();
3027 process_event (event, arg, 0, NULL, events, suspend_policy);
3031 runtime_initialized (MonoProfiler *prof)
3033 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3037 runtime_shutdown (MonoProfiler *prof)
3039 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3041 mono_debugger_agent_cleanup ();
3045 thread_startup (MonoProfiler *prof, uintptr_t tid)
3047 MonoInternalThread *thread = mono_thread_internal_current ();
3048 MonoInternalThread *old_thread;
3049 DebuggerTlsData *tls;
3051 if (tid == debugger_thread_id)
3054 g_assert (thread->tid == tid);
3056 mono_loader_lock ();
3057 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3058 mono_loader_unlock ();
3060 if (thread == old_thread) {
3062 * For some reason, thread_startup () might be called for the same thread
3063 * multiple times (attach ?).
3065 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3069 * thread_end () might not be called for some threads, and the tid could
3072 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3073 mono_loader_lock ();
3074 mono_g_hash_table_remove (thread_to_tls, old_thread);
3075 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3076 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3077 mono_loader_unlock ();
3081 tls = TlsGetValue (debugger_tls_id);
3083 // FIXME: Free this somewhere
3084 tls = g_new0 (DebuggerTlsData, 1);
3085 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3086 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3087 tls->thread = thread;
3088 TlsSetValue (debugger_tls_id, tls);
3090 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3092 mono_loader_lock ();
3093 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3094 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3095 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3096 mono_loader_unlock ();
3098 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3101 * suspend_vm () could have missed this thread, so wait for a resume.
3107 thread_end (MonoProfiler *prof, uintptr_t tid)
3109 MonoInternalThread *thread;
3110 DebuggerTlsData *tls = NULL;
3112 mono_loader_lock ();
3113 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3115 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3116 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3117 tls->terminated = TRUE;
3118 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3119 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3120 MONO_GC_UNREGISTER_ROOT (tls->thread);
3123 mono_loader_unlock ();
3125 /* We might be called for threads started before we registered the start callback */
3127 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3128 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3133 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3135 mono_loader_lock ();
3136 g_hash_table_insert (domains, domain, domain);
3137 mono_loader_unlock ();
3139 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3143 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3145 /* Invalidate each thread's frame stack */
3146 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3147 clear_breakpoints_for_domain (domain);
3148 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3152 * invalidate_each_thread:
3154 * A GHFunc to invalidate frames.
3155 * value must be a DebuggerTlsData*
3158 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3160 invalidate_frames (value);
3164 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3166 /* Sent later in jit_end () */
3167 mono_loader_lock ();
3168 g_ptr_array_add (pending_assembly_loads, assembly);
3169 mono_loader_unlock ();
3173 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3175 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3177 clear_event_requests_for_assembly (assembly);
3178 clear_types_for_assembly (assembly);
3182 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3184 #if defined(HOST_WIN32) && !defined(__GNUC__)
3185 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3187 gpointer stackptr = __builtin_frame_address (1);
3189 MonoInternalThread *thread = mono_thread_internal_current ();
3190 DebuggerTlsData *tls;
3192 mono_loader_lock ();
3194 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3195 /* Could be the debugger thread with assembly/type load hooks */
3197 tls->invoke_addr = stackptr;
3199 mono_loader_unlock ();
3203 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3206 #if defined(HOST_WIN32) && !defined(__GNUC__)
3207 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3209 gpointer stackptr = __builtin_frame_address (1);
3212 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3216 * We need to stop single stepping when exiting a runtime invoke, since if it is
3217 * a step out, it may return to native code, and thus never end.
3219 mono_loader_lock ();
3220 ss_invoke_addr = NULL;
3222 for (i = 0; i < event_requests->len; ++i) {
3223 EventRequest *req = g_ptr_array_index (event_requests, i);
3225 if (req->event_kind == EVENT_KIND_STEP) {
3226 ss_destroy (req->info);
3227 g_ptr_array_remove_index_fast (event_requests, i);
3232 mono_loader_unlock ();
3236 send_type_load (MonoClass *klass)
3238 gboolean type_load = FALSE;
3240 mono_loader_lock ();
3241 if (!g_hash_table_lookup (loaded_classes, klass)) {
3243 g_hash_table_insert (loaded_classes, klass, klass);
3245 mono_loader_unlock ();
3247 process_profiler_event (EVENT_KIND_TYPE_LOAD, klass);
3251 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3254 * We emit type load events when the first method of the type is JITted,
3255 * since the class load profiler callbacks might be called with the
3256 * loader lock held. They could also occur in the debugger thread.
3257 * Same for assembly load events.
3260 MonoAssembly *assembly = NULL;
3262 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3263 mono_loader_lock ();
3264 if (pending_assembly_loads->len > 0) {
3265 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3266 g_ptr_array_remove_index (pending_assembly_loads, 0);
3268 mono_loader_unlock ();
3271 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3276 if (!vm_start_event_sent) {
3277 /* Save these so they can be sent after the vm start event */
3278 mono_loader_lock ();
3279 g_ptr_array_add (pending_type_loads, method->klass);
3280 mono_loader_unlock ();
3282 /* Send all pending type load events */
3286 mono_loader_lock ();
3287 if (pending_type_loads->len > 0) {
3288 klass = g_ptr_array_index (pending_type_loads, 0);
3289 g_ptr_array_remove_index (pending_type_loads, 0);
3291 mono_loader_unlock ();
3293 send_type_load (klass);
3298 send_type_load (method->klass);
3302 add_pending_breakpoints (method, jinfo);
3306 * BREAKPOINTS/SINGLE STEPPING
3310 * Contains information about an inserted breakpoint.
3313 long il_offset, native_offset;
3317 } BreakpointInstance;
3320 * Contains generic information about a breakpoint.
3324 * The method where the breakpoint is placed. Can be NULL in which case it
3325 * is inserted into every method. This is used to implement method entry/
3326 * exit events. Can be a generic method definition, in which case the
3327 * breakpoint is inserted into every instance.
3333 * A list of BreakpointInstance structures describing where the breakpoint
3334 * was inserted. There could be more than one because of
3335 * generics/appdomains/method entry/exit.
3337 GPtrArray *children;
3340 /* List of breakpoints */
3341 static GPtrArray *breakpoints;
3342 /* Maps breakpoint locations to the number of breakpoints at that location */
3343 static GHashTable *bp_locs;
3346 breakpoints_init (void)
3348 breakpoints = g_ptr_array_new ();
3349 bp_locs = g_hash_table_new (NULL, NULL);
3353 * insert_breakpoint:
3355 * Insert the breakpoint described by BP into the method described by
3359 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3362 gint32 il_offset = -1, native_offset;
3363 BreakpointInstance *inst;
3366 mono_error_init (error);
3369 for (i = 0; i < seq_points->len; ++i) {
3370 il_offset = seq_points->seq_points [i].il_offset;
3371 native_offset = seq_points->seq_points [i].native_offset;
3373 if (il_offset == bp->il_offset)
3377 if (i == seq_points->len) {
3378 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);
3380 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3389 inst = g_new0 (BreakpointInstance, 1);
3390 inst->native_offset = native_offset;
3391 inst->ip = (guint8*)ji->code_start + native_offset;
3393 inst->domain = domain;
3395 mono_loader_lock ();
3397 g_ptr_array_add (bp->children, inst);
3399 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3400 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3401 mono_loader_unlock ();
3404 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3405 mono_arch_set_breakpoint (ji, inst->ip);
3411 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)il_offset));
3415 remove_breakpoint (BreakpointInstance *inst)
3417 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3419 MonoJitInfo *ji = inst->ji;
3420 guint8 *ip = inst->ip;
3422 mono_loader_lock ();
3423 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3424 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3425 mono_loader_unlock ();
3427 g_assert (count > 0);
3430 mono_arch_clear_breakpoint (ji, ip);
3437 static inline gboolean
3438 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3440 return (!bp->method || method == bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method));
3444 * add_pending_breakpoints:
3446 * Insert pending breakpoints into the newly JITted method METHOD.
3449 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3452 MonoSeqPointInfo *seq_points;
3458 domain = mono_domain_get ();
3460 mono_loader_lock ();
3462 for (i = 0; i < breakpoints->len; ++i) {
3463 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3464 gboolean found = FALSE;
3466 if (!bp_matches_method (bp, method))
3469 for (j = 0; j < bp->children->len; ++j) {
3470 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3477 mono_domain_lock (domain);
3478 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3479 mono_domain_unlock (domain);
3481 /* Could be AOT code */
3483 g_assert (seq_points);
3485 insert_breakpoint (seq_points, domain, ji, bp, NULL);
3489 mono_loader_unlock ();
3493 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
3499 mono_error_init (error);
3501 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3503 /* Might be AOTed code */
3504 code = mono_aot_get_method (domain, method);
3506 ji = mono_jit_info_table_find (domain, code);
3511 insert_breakpoint (seq_points, domain, ji, bp, error);
3515 clear_breakpoint (MonoBreakpoint *bp);
3520 * Set a breakpoint at IL_OFFSET in METHOD.
3521 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3522 * METHOD can also be a generic method definition, in which case a breakpoint
3523 * is placed in all instances of the method.
3524 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
3527 static MonoBreakpoint*
3528 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
3531 GHashTableIter iter, iter2;
3534 MonoSeqPointInfo *seq_points;
3537 mono_error_init (error);
3540 // - suspend/resume the vm to prevent code patching problems
3541 // - multiple breakpoints on the same location
3542 // - dynamic methods
3545 bp = g_new0 (MonoBreakpoint, 1);
3546 bp->method = method;
3547 bp->il_offset = il_offset;
3549 bp->children = g_ptr_array_new ();
3551 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));
3553 mono_loader_lock ();
3555 g_hash_table_iter_init (&iter, domains);
3556 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
3557 mono_domain_lock (domain);
3559 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
3560 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
3561 if (bp_matches_method (bp, m))
3562 set_bp_in_method (domain, m, seq_points, bp, error);
3565 mono_domain_unlock (domain);
3568 mono_loader_unlock ();
3570 mono_loader_lock ();
3571 g_ptr_array_add (breakpoints, bp);
3572 mono_loader_unlock ();
3574 if (error && !mono_error_ok (error)) {
3575 clear_breakpoint (bp);
3583 clear_breakpoint (MonoBreakpoint *bp)
3587 // FIXME: locking, races
3588 for (i = 0; i < bp->children->len; ++i) {
3589 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3591 remove_breakpoint (inst);
3596 mono_loader_lock ();
3597 g_ptr_array_remove (breakpoints, bp);
3598 mono_loader_unlock ();
3600 g_ptr_array_free (bp->children, TRUE);
3605 breakpoints_cleanup (void)
3609 mono_loader_lock ();
3611 while (i < event_requests->len) {
3612 EventRequest *req = g_ptr_array_index (event_requests, i);
3614 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
3615 clear_breakpoint (req->info);
3616 g_ptr_array_remove_index_fast (event_requests, i);
3623 for (i = 0; i < breakpoints->len; ++i)
3624 g_free (g_ptr_array_index (breakpoints, i));
3626 g_ptr_array_free (breakpoints, TRUE);
3627 g_hash_table_destroy (bp_locs);
3632 mono_loader_unlock ();
3636 * clear_breakpoints_for_domain:
3638 * Clear breakpoint instances which reference DOMAIN.
3641 clear_breakpoints_for_domain (MonoDomain *domain)
3645 /* This could be called after shutdown */
3649 mono_loader_lock ();
3650 for (i = 0; i < breakpoints->len; ++i) {
3651 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3654 while (j < bp->children->len) {
3655 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3657 if (inst->domain == domain) {
3658 remove_breakpoint (inst);
3662 g_ptr_array_remove_index_fast (bp->children, j);
3668 mono_loader_unlock ();
3672 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
3674 return bp->method && bp->method->klass->image->assembly == assembly;
3678 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
3681 guint8 *orig_ip, *ip;
3682 int i, j, suspend_policy;
3683 guint32 native_offset;
3685 BreakpointInstance *inst;
3686 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3687 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3688 EventKind kind = EVENT_KIND_BREAKPOINT;
3690 // FIXME: Speed this up
3692 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3693 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
3695 g_assert (ji->method);
3697 /* Compute the native offset of the breakpoint from the ip */
3698 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3699 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3700 native_offset = ip - (guint8*)ji->code_start;
3706 * Skip the instruction causing the breakpoint signal.
3708 mono_arch_skip_breakpoint (ctx);
3710 if (ji->method->wrapper_type || tls->disable_breakpoints)
3713 bp_reqs = g_ptr_array_new ();
3714 ss_reqs = g_ptr_array_new ();
3715 ss_reqs_orig = g_ptr_array_new ();
3717 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3719 mono_loader_lock ();
3722 for (i = 0; i < breakpoints->len; ++i) {
3723 bp = g_ptr_array_index (breakpoints, i);
3728 for (j = 0; j < bp->children->len; ++j) {
3729 inst = g_ptr_array_index (bp->children, j);
3730 if (inst->ji == ji && inst->native_offset == native_offset) {
3731 if (bp->req->event_kind == EVENT_KIND_STEP) {
3732 g_ptr_array_add (ss_reqs_orig, bp->req);
3734 g_ptr_array_add (bp_reqs, bp->req);
3739 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3740 MonoSeqPointInfo *seq_points;
3741 int seq_il_offset, seq_native_offset;
3742 MonoDomain *domain = mono_domain_get ();
3744 /* Maybe a method entry/exit event */
3745 mono_domain_lock (domain);
3746 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3747 mono_domain_unlock (domain);
3749 // FIXME: Generic sharing */
3750 mono_loader_unlock ();
3753 g_assert (seq_points);
3755 for (i = 0; i < seq_points->len; ++i) {
3756 seq_il_offset = seq_points->seq_points [i].il_offset;
3757 seq_native_offset = seq_points->seq_points [i].native_offset;
3759 if (native_offset == seq_native_offset) {
3760 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3761 kind = EVENT_KIND_METHOD_ENTRY;
3762 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3763 kind = EVENT_KIND_METHOD_EXIT;
3769 /* Process single step requests */
3770 for (i = 0; i < ss_reqs_orig->len; ++i) {
3771 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3772 SingleStepReq *ss_req = req->info;
3773 gboolean hit = TRUE;
3774 MonoSeqPointInfo *info;
3777 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3780 if (ss_req->size == STEP_SIZE_LINE) {
3781 /* Have to check whenever a different source line was reached */
3782 MonoDebugMethodInfo *minfo;
3783 MonoDebugSourceLocation *loc = NULL;
3785 minfo = mono_debug_lookup_method (ji->method);
3788 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3790 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3791 /* Have to continue single stepping */
3795 ss_req->last_method = ji->method;
3796 ss_req->last_line = loc->row;
3797 mono_debug_free_source_location (loc);
3802 g_ptr_array_add (ss_reqs, req);
3804 /* Start single stepping again from the current sequence point */
3805 ss_start (ss_req, ji->method, sp, info, ctx, NULL, FALSE);
3808 if (ss_reqs->len > 0)
3809 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3810 if (bp_reqs->len > 0)
3811 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3812 if (kind != EVENT_KIND_BREAKPOINT)
3813 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3815 mono_loader_unlock ();
3817 g_ptr_array_free (bp_reqs, TRUE);
3818 g_ptr_array_free (ss_reqs, TRUE);
3821 * FIXME: The first event will suspend, so the second will only be sent after the
3825 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3827 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3828 if (enter_leave_events)
3829 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3833 process_breakpoint (void)
3835 DebuggerTlsData *tls;
3837 static void (*restore_context) (void *);
3839 if (!restore_context)
3840 restore_context = mono_get_restore_context ();
3842 tls = TlsGetValue (debugger_tls_id);
3843 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3845 process_breakpoint_inner (tls, &ctx);
3847 /* This is called when resuming from a signal handler, so it shouldn't return */
3848 restore_context (&ctx);
3849 g_assert_not_reached ();
3853 resume_from_signal_handler (void *sigctx, void *func)
3855 DebuggerTlsData *tls;
3858 /* Save the original context in TLS */
3859 // FIXME: This might not work on an altstack ?
3860 tls = TlsGetValue (debugger_tls_id);
3863 // FIXME: MonoContext usually doesn't include the fp registers, so these are
3864 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3865 // clob:c could be added to op_seq_point.
3867 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3868 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3869 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
3870 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
3872 MONO_CONTEXT_SET_IP (&ctx, func);
3874 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3876 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3877 mono_ppc_set_func_into_sigctx (sigctx, func);
3882 mono_debugger_agent_breakpoint_hit (void *sigctx)
3885 * We are called from a signal handler, and running code there causes all kinds of
3886 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
3887 * So set up the signal context to return to the real breakpoint handler function.
3890 resume_from_signal_handler (sigctx, process_breakpoint);
3894 ss_depth_to_string (StepDepth depth)
3897 case STEP_DEPTH_OVER:
3899 case STEP_DEPTH_OUT:
3901 case STEP_DEPTH_INTO:
3904 g_assert_not_reached ();
3910 process_single_step_inner (DebuggerTlsData *tls, MonoContext *ctx)
3915 int il_offset, suspend_policy;
3919 // FIXME: Speed this up
3921 ip = MONO_CONTEXT_GET_IP (ctx);
3923 /* Skip the instruction causing the single step */
3924 mono_arch_skip_single_step (ctx);
3926 if (suspend_count > 0) {
3927 process_suspend (tls, ctx);
3932 // FIXME: A suspend race
3935 if (mono_thread_internal_current () != ss_req->thread)
3938 if (log_level > 0) {
3939 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
3941 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));
3945 * We implement step over/out by single stepping until we reach the same
3946 * frame/parent frame.
3949 * - stack growing upward
3953 if (ss_req->depth != STEP_DEPTH_INTO) {
3954 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
3956 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
3959 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
3962 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
3964 g_assert (ji->method);
3966 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
3971 * Stopping in memset makes half-initialized vtypes visible.
3972 * Stopping in memcpy makes half-copied vtypes visible.
3974 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
3978 * The ip points to the instruction causing the single step event, convert it
3979 * to the offset stored in seq_points.
3981 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3982 ip = mono_arch_get_ip_for_single_step (ji, ctx);
3984 g_assert_not_reached ();
3988 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
3989 * example, so do things by hand.
3991 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
3993 if (il_offset == -1)
3996 if (ss_req->size == STEP_SIZE_LINE) {
3997 /* Step until a different source line is reached */
3998 MonoDebugMethodInfo *minfo;
4000 minfo = mono_debug_lookup_method (ji->method);
4003 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4005 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4006 mono_debug_free_source_location (loc);
4011 * Step until we reach a location with line number info,
4012 * otherwise the client can't show a location.
4013 * This can happen for example with statics initialized inline
4014 * outside of a cctor.
4019 ss_req->last_method = ji->method;
4020 ss_req->last_line = loc->row;
4021 mono_debug_free_source_location (loc);
4026 // FIXME: Has to lock earlier
4028 reqs = g_ptr_array_new ();
4030 mono_loader_lock ();
4032 g_ptr_array_add (reqs, ss_req->req);
4034 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4036 g_ptr_array_free (reqs, TRUE);
4038 mono_loader_unlock ();
4040 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4044 process_single_step (void)
4046 DebuggerTlsData *tls;
4048 static void (*restore_context) (void *);
4050 if (!restore_context)
4051 restore_context = mono_get_restore_context ();
4053 tls = TlsGetValue (debugger_tls_id);
4054 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
4056 process_single_step_inner (tls, &ctx);
4058 /* This is called when resuming from a signal handler, so it shouldn't return */
4059 restore_context (&ctx);
4060 g_assert_not_reached ();
4064 * mono_debugger_agent_single_step_event:
4066 * Called from a signal handler to handle a single step event.
4069 mono_debugger_agent_single_step_event (void *sigctx)
4071 /* Resume to process_single_step through the signal context */
4073 // FIXME: Since step out/over is implemented using step in, the step in case should
4074 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4077 if (GetCurrentThreadId () == debugger_thread_id) {
4079 * This could happen despite our best effors when the runtime calls
4080 * assembly/type resolve hooks.
4081 * FIXME: Breakpoints too.
4085 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4086 mono_arch_skip_single_step (&ctx);
4087 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4091 resume_from_signal_handler (sigctx, process_single_step);
4095 * start_single_stepping:
4097 * Turn on single stepping. Can be called multiple times, for example,
4098 * by a single step event request + a suspend.
4101 start_single_stepping (void)
4103 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4104 int val = InterlockedIncrement (&ss_count);
4107 mono_arch_start_single_stepping ();
4109 if (ss_req != NULL && ss_invoke_addr == NULL) {
4110 DebuggerTlsData *tls;
4112 mono_loader_lock ();
4114 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4115 ss_invoke_addr = tls->invoke_addr;
4117 mono_loader_unlock ();
4120 g_assert_not_reached ();
4125 stop_single_stepping (void)
4127 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4128 int val = InterlockedDecrement (&ss_count);
4131 mono_arch_stop_single_stepping ();
4133 g_assert_not_reached ();
4140 * Stop the single stepping operation given by SS_REQ.
4143 ss_stop (SingleStepReq *ss_req)
4145 gboolean use_bps = FALSE;
4152 for (l = ss_req->bps; l; l = l->next) {
4153 clear_breakpoint (l->data);
4155 g_slist_free (ss_req->bps);
4159 if (ss_req->global) {
4160 stop_single_stepping ();
4161 ss_req->global = FALSE;
4168 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4171 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4177 /* Stop the previous operation */
4181 * Implement single stepping using breakpoints if possible.
4183 if (step_to_catch) {
4184 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4185 ss_req->bps = g_slist_append (ss_req->bps, bp);
4186 } else if (ss_req->depth == STEP_DEPTH_OVER) {
4189 * Find the first sequence point in the current or in a previous frame which
4190 * is not the last in its method.
4192 while (sp && sp->next_len == 0) {
4194 if (tls && frame_index < tls->frame_count) {
4195 StackFrame *frame = tls->frames [frame_index];
4197 method = frame->method;
4198 if (frame->il_offset != -1) {
4199 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
4205 if (sp && sp->next_len > 0) {
4206 for (i = 0; i < sp->next_len; ++i) {
4207 next_sp = &info->seq_points [sp->next [i]];
4209 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4210 ss_req->bps = g_slist_append (ss_req->bps, bp);
4216 DEBUG (1, printf ("[dbg] Turning on global single stepping.\n"));
4217 ss_req->global = TRUE;
4218 start_single_stepping ();
4220 ss_req->global = FALSE;
4225 * Start single stepping of thread THREAD
4228 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4230 DebuggerTlsData *tls;
4231 MonoSeqPointInfo *info = NULL;
4232 SeqPoint *sp = NULL;
4233 MonoMethod *method = NULL;
4234 MonoDebugMethodInfo *minfo;
4235 gboolean step_to_catch = FALSE;
4237 if (suspend_count == 0)
4238 return ERR_NOT_SUSPENDED;
4240 wait_for_suspend ();
4242 // FIXME: Multiple requests
4244 DEBUG (0, printf ("Received a single step request while the previous one was still active.\n"));
4245 return ERR_NOT_IMPLEMENTED;
4248 DEBUG (1, printf ("[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4250 ss_req = g_new0 (SingleStepReq, 1);
4252 ss_req->thread = thread;
4253 ss_req->size = size;
4254 ss_req->depth = depth;
4257 mono_loader_lock ();
4258 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4259 mono_loader_unlock ();
4261 g_assert (tls->has_context);
4262 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
4264 if (tls->has_catch_ctx) {
4266 StackFrameInfo frame;
4267 MonoContext new_ctx;
4268 MonoLMF *lmf = NULL;
4271 * We are stopped at a throw site. Stepping should go to the catch site.
4274 /* Find the the jit info for the catch context */
4275 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4277 g_assert (frame.type == FRAME_TYPE_MANAGED);
4280 * Find the seq point corresponding to the landing site ip, which is the first seq
4283 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4286 method = frame.method;
4288 step_to_catch = TRUE;
4289 /* This make sure the seq point is not skipped by process_single_step () */
4290 ss_req->last_sp = NULL;
4293 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4296 /* Compute the initial line info */
4297 compute_frame_info (thread, tls);
4299 g_assert (tls->frame_count);
4300 frame = tls->frames [0];
4302 ss_req->last_method = frame->method;
4303 ss_req->last_line = -1;
4305 minfo = mono_debug_lookup_method (frame->method);
4306 if (minfo && frame->il_offset != -1) {
4307 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4310 ss_req->last_line = loc->row;
4316 if (!step_to_catch && ss_req->depth == STEP_DEPTH_OVER) {
4319 compute_frame_info (thread, tls);
4321 g_assert (tls->frame_count);
4322 frame = tls->frames [0];
4324 if (!method && frame->il_offset != -1) {
4325 /* FIXME: Sort the table and use a binary search */
4326 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4328 method = frame->method;
4332 ss_start (ss_req, method, sp, info, NULL, tls, step_to_catch);
4338 ss_destroy (SingleStepReq *req)
4341 g_assert (ss_req == req);
4350 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
4351 MonoContext *catch_ctx)
4357 DebuggerTlsData *tls = NULL;
4359 if (thread_to_tls != NULL) {
4360 MonoInternalThread *thread = mono_thread_internal_current ();
4362 mono_loader_lock ();
4363 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4364 mono_loader_unlock ();
4366 if (tls && tls->abort_requested)
4368 if (tls && tls->disable_breakpoints)
4372 memset (&ei, 0, sizeof (EventInfo));
4374 /* Just-In-Time debugging */
4376 if (agent_config.onuncaught && !inited) {
4377 finish_agent_init (FALSE);
4380 * Send an unsolicited EXCEPTION event with a dummy request id.
4382 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4383 ei.exc = (MonoObject*)exc;
4384 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4387 } else if (agent_config.onthrow && !inited) {
4389 gboolean found = FALSE;
4391 for (l = agent_config.onthrow; l; l = l->next) {
4392 char *ex_type = l->data;
4393 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
4395 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
4402 finish_agent_init (FALSE);
4405 * Send an unsolicited EXCEPTION event with a dummy request id.
4407 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4408 ei.exc = (MonoObject*)exc;
4409 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4417 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
4419 ei.exc = (MonoObject*)exc;
4420 ei.caught = catch_ctx != NULL;
4422 mono_loader_lock ();
4423 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
4424 mono_loader_unlock ();
4426 if (tls && catch_ctx) {
4427 tls->catch_ctx = *catch_ctx;
4428 tls->has_catch_ctx = TRUE;
4431 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
4434 tls->has_catch_ctx = FALSE;
4438 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4440 DebuggerTlsData *tls;
4445 tls = TlsGetValue (debugger_tls_id);
4450 * We're about to invoke an exception filter during the first pass of exception handling.
4452 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
4453 * 'orig_ctx' is the context where the exception has been thrown.
4456 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
4458 * If we're stopped in Filter(), normal stack unwinding would first unwind to
4459 * the call site (line 37) and then continue to Main(), but it would never
4460 * include the throw site (line 32).
4462 * Since exception filters are invoked during the first pass of exception handling,
4463 * the stack frames of the throw site are still intact, so we should include them
4466 * We do this here by saving the context of the throw site in 'tls->filter_ctx'.
4468 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
4469 * but report the location of the 'throw' to the user.
4473 memcpy (&tls->filter_ctx, orig_ctx, sizeof (MonoContext));
4474 tls->has_filter_ctx = TRUE;
4476 tls->filter_lmf = mono_get_lmf ();
4477 tls->domain = mono_domain_get ();
4481 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4483 DebuggerTlsData *tls;
4488 tls = TlsGetValue (debugger_tls_id);
4492 tls->has_filter_ctx = FALSE;
4496 * buffer_add_value_full:
4498 * Add the encoding of the value at ADDR described by T to the buffer.
4499 * AS_VTYPE determines whenever to treat primitive types as primitive types or
4503 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
4509 g_assert (*(void**)addr);
4510 addr = *(void**)addr;
4515 case MONO_TYPE_BOOLEAN:
4518 case MONO_TYPE_CHAR:
4538 case MONO_TYPE_VOID:
4539 buffer_add_byte (buf, t->type);
4541 case MONO_TYPE_BOOLEAN:
4544 buffer_add_byte (buf, t->type);
4545 buffer_add_int (buf, *(gint8*)addr);
4547 case MONO_TYPE_CHAR:
4550 buffer_add_byte (buf, t->type);
4551 buffer_add_int (buf, *(gint16*)addr);
4556 buffer_add_byte (buf, t->type);
4557 buffer_add_int (buf, *(gint32*)addr);
4562 buffer_add_byte (buf, t->type);
4563 buffer_add_long (buf, *(gint64*)addr);
4567 /* Treat it as a vtype */
4569 case MONO_TYPE_PTR: {
4570 gssize val = *(gssize*)addr;
4572 buffer_add_byte (buf, t->type);
4573 buffer_add_long (buf, val);
4577 case MONO_TYPE_STRING:
4578 case MONO_TYPE_SZARRAY:
4579 case MONO_TYPE_OBJECT:
4580 case MONO_TYPE_CLASS:
4581 case MONO_TYPE_ARRAY:
4582 obj = *(MonoObject**)addr;
4585 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4587 if (obj->vtable->klass->valuetype) {
4588 t = &obj->vtable->klass->byval_arg;
4589 addr = mono_object_unbox (obj);
4591 } else if (obj->vtable->klass->rank) {
4592 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4593 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4594 buffer_add_byte (buf, MONO_TYPE_CLASS);
4596 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4598 buffer_add_objid (buf, obj);
4602 case MONO_TYPE_VALUETYPE: {
4606 MonoClass *klass = mono_class_from_mono_type (t);
4608 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4609 buffer_add_byte (buf, klass->enumtype);
4610 buffer_add_typeid (buf, domain, klass);
4614 while ((f = mono_class_get_fields (klass, &iter))) {
4615 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4617 if (mono_field_is_deleted (f))
4621 buffer_add_int (buf, nfields);
4624 while ((f = mono_class_get_fields (klass, &iter))) {
4625 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4627 if (mono_field_is_deleted (f))
4629 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4633 case MONO_TYPE_GENERICINST:
4634 if (mono_type_generic_inst_is_valuetype (t)) {
4646 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4648 buffer_add_value_full (buf, t, addr, domain, FALSE);
4652 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4655 int type = decode_byte (buf, &buf, limit);
4657 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4658 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4659 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4660 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
4661 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
4662 char *name = mono_type_full_name (t);
4663 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
4665 return ERR_INVALID_ARGUMENT;
4669 case MONO_TYPE_BOOLEAN:
4670 *(guint8*)addr = decode_int (buf, &buf, limit);
4672 case MONO_TYPE_CHAR:
4673 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4676 *(gint8*)addr = decode_int (buf, &buf, limit);
4679 *(guint8*)addr = decode_int (buf, &buf, limit);
4682 *(gint16*)addr = decode_int (buf, &buf, limit);
4685 *(guint16*)addr = decode_int (buf, &buf, limit);
4688 *(gint32*)addr = decode_int (buf, &buf, limit);
4691 *(guint32*)addr = decode_int (buf, &buf, limit);
4694 *(gint64*)addr = decode_long (buf, &buf, limit);
4697 *(guint64*)addr = decode_long (buf, &buf, limit);
4700 *(guint32*)addr = decode_int (buf, &buf, limit);
4703 *(guint64*)addr = decode_long (buf, &buf, limit);
4706 /* We send these as I8, so we get them back as such */
4707 g_assert (type == MONO_TYPE_I8);
4708 *(gssize*)addr = decode_long (buf, &buf, limit);
4710 case MONO_TYPE_GENERICINST:
4711 if (MONO_TYPE_ISSTRUCT (t)) {
4712 /* The client sends these as a valuetype */
4720 /* We send these as vtypes, so we get them back as such */
4721 g_assert (type == MONO_TYPE_VALUETYPE);
4724 case MONO_TYPE_VALUETYPE: {
4725 gboolean is_enum = decode_byte (buf, &buf, limit);
4729 gpointer iter = NULL;
4732 /* Enums are sent as a normal vtype */
4734 return ERR_NOT_IMPLEMENTED;
4735 klass = decode_typeid (buf, &buf, limit, &d, &err);
4739 if (klass != mono_class_from_mono_type (t))
4740 return ERR_INVALID_ARGUMENT;
4742 nfields = decode_int (buf, &buf, limit);
4743 while ((f = mono_class_get_fields (klass, &iter))) {
4744 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4746 if (mono_field_is_deleted (f))
4748 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4753 g_assert (nfields == 0);
4758 if (MONO_TYPE_IS_REFERENCE (t)) {
4759 if (type == MONO_TYPE_OBJECT) {
4760 int objid = decode_objid (buf, &buf, limit);
4764 err = get_object (objid, (MonoObject**)&obj);
4768 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4769 return ERR_INVALID_ARGUMENT;
4770 if (obj && obj->vtable->domain != domain)
4771 return ERR_INVALID_ARGUMENT;
4773 mono_gc_wbarrier_generic_store (addr, obj);
4774 } else if (type == VALUE_TYPE_ID_NULL) {
4775 *(MonoObject**)addr = NULL;
4777 return ERR_INVALID_ARGUMENT;
4791 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4798 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4799 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4802 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4803 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4805 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
4807 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4808 addr = mono_arch_context_get_int_reg (ctx, reg);
4809 addr += (gint32)var->offset;
4811 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4813 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4815 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4819 g_assert_not_reached ();
4824 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
4830 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4831 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4833 if (MONO_TYPE_IS_REFERENCE (t))
4834 size = sizeof (gpointer);
4836 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4839 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4840 // FIXME: Can't set registers, so we disable linears
4843 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4844 addr = mono_arch_context_get_int_reg (ctx, reg);
4845 addr += (gint32)var->offset;
4847 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4849 // FIXME: Write barriers
4850 memcpy (addr, val, size);
4852 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4856 g_assert_not_reached ();
4861 clear_event_request (int req_id, int etype)
4865 mono_loader_lock ();
4866 for (i = 0; i < event_requests->len; ++i) {
4867 EventRequest *req = g_ptr_array_index (event_requests, i);
4869 if (req->id == req_id && req->event_kind == etype) {
4870 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4871 clear_breakpoint (req->info);
4872 if (req->event_kind == EVENT_KIND_STEP)
4873 ss_destroy (req->info);
4874 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
4875 clear_breakpoint (req->info);
4876 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
4877 clear_breakpoint (req->info);
4878 g_ptr_array_remove_index_fast (event_requests, i);
4883 mono_loader_unlock ();
4887 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
4889 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4890 return breakpoint_matches_assembly (req->info, assembly);
4894 for (i = 0; i < req->nmodifiers; ++i) {
4895 Modifier *m = &req->modifiers [i];
4897 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
4899 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
4900 for (j = 0; m->data.assemblies [j]; ++j)
4901 if (m->data.assemblies [j] == assembly)
4911 * clear_event_requests_for_assembly:
4913 * Clear all events requests which reference ASSEMBLY.
4916 clear_event_requests_for_assembly (MonoAssembly *assembly)
4921 mono_loader_lock ();
4925 for (i = 0; i < event_requests->len; ++i) {
4926 EventRequest *req = g_ptr_array_index (event_requests, i);
4928 if (event_req_matches_assembly (req, assembly)) {
4929 clear_event_request (req->id, req->event_kind);
4935 mono_loader_unlock ();
4939 * type_comes_from_assembly:
4941 * GHRFunc that returns TRUE if klass comes from assembly
4944 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
4946 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
4950 * clear_types_for_assembly:
4952 * Clears types from loaded_classes for a given assembly
4955 clear_types_for_assembly (MonoAssembly *assembly)
4957 mono_loader_lock ();
4958 g_hash_table_foreach_remove (loaded_classes, type_comes_from_assembly, assembly);
4959 mono_loader_unlock ();
4963 add_thread (gpointer key, gpointer value, gpointer user_data)
4965 MonoInternalThread *thread = value;
4966 Buffer *buf = user_data;
4968 buffer_add_objid (buf, (MonoObject*)thread);
4972 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
4974 guint8 *p = invoke->p;
4975 guint8 *end = invoke->endp;
4978 MonoMethodSignature *sig;
4981 MonoObject *this, *res, *exc;
4984 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4988 if (invoke->method) {
4990 * Invoke this method directly, currently only Environment.Exit () is supported.
4993 DEBUG (1, printf ("[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this ? this->vtable->klass->name : "<null>"));
4994 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
4995 g_assert_not_reached ();
4998 m = decode_methodid (p, &p, end, &domain, &err);
5001 sig = mono_method_signature (m);
5003 if (m->klass->valuetype)
5004 this_buf = g_alloca (mono_class_instance_size (m->klass));
5006 this_buf = g_alloca (sizeof (MonoObject*));
5007 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5008 /* Should be null */
5009 int type = decode_byte (p, &p, end);
5010 if (type != VALUE_TYPE_ID_NULL)
5011 return ERR_INVALID_ARGUMENT;
5012 memset (this_buf, 0, mono_class_instance_size (m->klass));
5014 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5019 if (!m->klass->valuetype)
5020 this = *(MonoObject**)this_buf;
5024 DEBUG (1, printf ("[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this ? this->vtable->klass->name : "<null>"));
5026 if (this && this->vtable->domain != domain)
5029 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5030 if (!strcmp (m->name, ".ctor")) {
5031 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5032 return ERR_INVALID_ARGUMENT;
5034 this = mono_object_new (domain, m->klass);
5036 return ERR_INVALID_ARGUMENT;
5040 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5041 return ERR_INVALID_ARGUMENT;
5043 nargs = decode_int (p, &p, end);
5044 if (nargs != sig->param_count)
5045 return ERR_INVALID_ARGUMENT;
5046 /* Use alloca to get gc tracking */
5047 arg_buf = g_alloca (nargs * sizeof (gpointer));
5048 memset (arg_buf, 0, nargs * sizeof (gpointer));
5049 args = g_alloca (nargs * sizeof (gpointer));
5050 for (i = 0; i < nargs; ++i) {
5051 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5052 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5056 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5059 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5060 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5063 args [i] = arg_buf [i];
5070 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5071 tls->disable_breakpoints = TRUE;
5073 tls->disable_breakpoints = FALSE;
5076 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5078 /* FIXME: Move this to arch specific code */
5079 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5080 if (invoke->has_ctx) {
5083 lmf_addr = mono_get_lmf_addr ();
5086 memset (&ext, 0, sizeof (ext));
5088 ext.lmf.previous_lmf = *(lmf_addr);
5089 /* Mark that this is a MonoLMFExt */
5090 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5091 ext.lmf.rsp = (gssize)&ext;
5092 #elif defined(TARGET_X86)
5093 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5094 /* Mark that this is a MonoLMFExt */
5095 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5096 ext.lmf.ebp = (gssize)&ext;
5097 #elif defined(TARGET_ARM)
5098 ext.lmf.previous_lmf = *(lmf_addr);
5099 /* Mark that this is a MonoLMFExt */
5100 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5101 #elif defined(TARGET_POWERPC)
5102 ext.lmf.previous_lmf = *(lmf_addr);
5103 /* Mark that this is a MonoLMFExt */
5104 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5105 ext.lmf.ebp = (gssize)&ext;
5107 g_assert_not_reached ();
5110 ext.debugger_invoke = TRUE;
5111 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5113 mono_set_lmf ((MonoLMF*)&ext);
5117 if (m->klass->valuetype)
5118 res = mono_runtime_invoke (m, this_buf, args, &exc);
5120 res = mono_runtime_invoke (m, this, args, &exc);
5122 buffer_add_byte (buf, 0);
5123 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5125 buffer_add_byte (buf, 1);
5126 if (sig->ret->type == MONO_TYPE_VOID) {
5127 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5128 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5131 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5132 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5133 buffer_add_value (buf, sig->ret, &res, domain);
5134 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5136 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5142 tls->disable_breakpoints = FALSE;
5144 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5145 if (invoke->has_ctx)
5146 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5149 // FIXME: byref arguments
5157 * Invoke the method given by tls->pending_invoke in the current thread.
5160 invoke_method (void)
5162 DebuggerTlsData *tls;
5167 static void (*restore_context) (void *);
5168 MonoContext restore_ctx;
5170 if (!restore_context)
5171 restore_context = mono_get_restore_context ();
5173 tls = TlsGetValue (debugger_tls_id);
5177 * Store the `InvokeData *' in `tls->invoke' until we're done with
5178 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5181 mono_loader_lock ();
5183 invoke = tls->pending_invoke;
5185 tls->pending_invoke = NULL;
5187 invoke->last_invoke = tls->invoke;
5188 tls->invoke = invoke;
5190 mono_loader_unlock ();
5192 tls->frames_up_to_date = FALSE;
5196 buffer_init (&buf, 128);
5198 err = do_invoke_method (tls, &buf, invoke);
5200 /* Start suspending before sending the reply */
5201 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5204 send_reply_packet (id, err, &buf);
5208 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5210 if (invoke->has_ctx)
5211 save_thread_context (&restore_ctx);
5213 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5214 g_assert (tls->resume_count);
5215 tls->resume_count -= invoke->suspend_count;
5218 DEBUG (1, printf ("[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5221 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5223 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5224 * after the mono_runtime_invoke() already returned, but it doesn't matter
5225 * because we reset the abort here.
5228 mono_loader_lock ();
5230 if (tls->abort_requested)
5231 mono_thread_internal_reset_abort (tls->thread);
5233 tls->invoke = tls->invoke->last_invoke;
5234 tls->abort_requested = FALSE;
5236 mono_loader_unlock ();
5245 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5247 MonoThread *thread = value;
5248 DebuggerTlsData *tls;
5251 mono_loader_lock ();
5252 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5254 res = tls->really_suspended;
5255 mono_loader_unlock ();
5261 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
5264 case CMD_VM_VERSION: {
5265 char *build_info, *version;
5267 build_info = mono_get_runtime_build_info ();
5268 version = g_strdup_printf ("mono %s", build_info);
5270 buffer_add_string (buf, version); /* vm version */
5271 buffer_add_int (buf, MAJOR_VERSION);
5272 buffer_add_int (buf, MINOR_VERSION);
5273 g_free (build_info);
5277 case CMD_VM_SET_PROTOCOL_VERSION: {
5278 major_version = decode_int (p, &p, end);
5279 minor_version = decode_int (p, &p, end);
5280 protocol_version_set = TRUE;
5281 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
5284 case CMD_VM_ALL_THREADS: {
5286 mono_loader_lock ();
5287 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
5288 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
5289 mono_loader_unlock ();
5292 case CMD_VM_SUSPEND:
5294 wait_for_suspend ();
5297 if (suspend_count == 0)
5298 return ERR_NOT_SUSPENDED;
5301 case CMD_VM_DISPOSE:
5302 /* Clear all event requests */
5303 mono_loader_lock ();
5304 while (event_requests->len > 0) {
5305 EventRequest *req = g_ptr_array_index (event_requests, 0);
5307 clear_event_request (req->id, req->event_kind);
5309 mono_loader_unlock ();
5311 // FIXME: Count resumes
5313 disconnected = TRUE;
5316 MonoInternalThread *thread;
5317 DebuggerTlsData *tls;
5318 MonoClass *env_class;
5319 MonoMethod *exit_method;
5323 exit_code = decode_int (p, &p, end);
5325 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
5327 /* Have to send a reply before exiting */
5328 send_reply_packet (id, 0, buf);
5330 /* Clear all event requests */
5331 mono_loader_lock ();
5332 while (event_requests->len > 0) {
5333 EventRequest *req = g_ptr_array_index (event_requests, 0);
5335 clear_event_request (req->id, req->event_kind);
5337 mono_loader_unlock ();
5340 * The JDWP documentation says that the shutdown is not orderly. It doesn't
5341 * specify whenever a VM_DEATH event is sent. We currently do an orderly
5342 * shutdown by hijacking a thread to execute Environment.Exit (). This is
5343 * better than doing the shutdown ourselves, since it avoids various races.
5347 wait_for_suspend ();
5349 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
5350 g_assert (env_class);
5351 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
5352 g_assert (exit_method);
5354 mono_loader_lock ();
5355 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
5356 mono_loader_unlock ();
5359 mono_loader_lock ();
5360 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5361 mono_loader_unlock ();
5363 args = g_new0 (gpointer, 1);
5364 args [0] = g_malloc (sizeof (int));
5365 *(int*)(args [0]) = exit_code;
5367 tls->pending_invoke = g_new0 (InvokeData, 1);
5368 tls->pending_invoke->method = exit_method;
5369 tls->pending_invoke->args = args;
5371 while (suspend_count > 0)
5375 * No thread found, do it ourselves.
5376 * FIXME: This can race with normal shutdown etc.
5378 while (suspend_count > 0)
5381 mono_runtime_set_shutting_down ();
5383 mono_threads_set_shutting_down ();
5385 /* Suspend all managed threads since the runtime is going away */
5386 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
5387 mono_thread_suspend_all_other_threads ();
5388 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
5389 mono_runtime_quit ();
5391 shutdown (conn_fd, SD_BOTH);
5393 shutdown (conn_fd, SHUT_RDWR);
5395 DEBUG(1, fprintf (log_file, "Exiting...\n"));
5401 case CMD_VM_INVOKE_METHOD: {
5402 int objid = decode_objid (p, &p, end);
5404 DebuggerTlsData *tls;
5407 err = get_object (objid, (MonoObject**)&thread);
5411 flags = decode_int (p, &p, end);
5413 // Wait for suspending if it already started
5415 wait_for_suspend ();
5416 if (!is_suspended ())
5417 return ERR_NOT_SUSPENDED;
5419 mono_loader_lock ();
5420 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5421 mono_loader_unlock ();
5424 if (!tls->really_suspended)
5425 /* The thread is still running native code, can't do invokes */
5426 return ERR_NOT_SUSPENDED;
5429 * Store the invoke data into tls, the thread will execute it after it is
5432 if (tls->pending_invoke)
5434 tls->pending_invoke = g_new0 (InvokeData, 1);
5435 tls->pending_invoke->id = id;
5436 tls->pending_invoke->flags = flags;
5437 tls->pending_invoke->p = g_malloc (end - p);
5438 memcpy (tls->pending_invoke->p, p, end - p);
5439 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
5440 tls->pending_invoke->suspend_count = suspend_count;
5442 if (flags & INVOKE_FLAG_SINGLE_THREADED)
5443 resume_thread (THREAD_TO_INTERNAL (thread));
5448 case CMD_VM_ABORT_INVOKE: {
5449 int objid = decode_objid (p, &p, end);
5451 DebuggerTlsData *tls;
5454 err = get_object (objid, (MonoObject**)&thread);
5458 invoke_id = decode_int (p, &p, end);
5460 mono_loader_lock ();
5461 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5464 if (tls->abort_requested) {
5465 mono_loader_unlock ();
5470 * Check whether we're still inside the mono_runtime_invoke() and that it's
5471 * actually the correct invocation.
5473 * Careful, we do not stop the thread that's doing the invocation, so we can't
5474 * inspect its stack. However, invoke_method() also acquires the loader lock
5475 * when it's done, so we're safe here.
5479 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
5480 mono_loader_unlock ();
5481 return ERR_NO_INVOCATION;
5484 tls->abort_requested = TRUE;
5486 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
5487 mono_loader_unlock ();
5492 return ERR_NOT_IMPLEMENTED;
5499 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5505 case CMD_EVENT_REQUEST_SET: {
5507 int i, event_kind, suspend_policy, nmodifiers, mod;
5510 MonoThread *step_thread;
5511 int size = 0, depth = 0, step_thread_id = 0;
5514 event_kind = decode_byte (p, &p, end);
5515 suspend_policy = decode_byte (p, &p, end);
5516 nmodifiers = decode_byte (p, &p, end);
5518 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
5519 req->id = InterlockedIncrement (&event_request_id);
5520 req->event_kind = event_kind;
5521 req->suspend_policy = suspend_policy;
5522 req->nmodifiers = nmodifiers;
5525 for (i = 0; i < nmodifiers; ++i) {
5526 mod = decode_byte (p, &p, end);
5528 req->modifiers [i].kind = mod;
5529 if (mod == MOD_KIND_COUNT) {
5530 req->modifiers [i].data.count = decode_int (p, &p, end);
5531 } else if (mod == MOD_KIND_LOCATION_ONLY) {
5532 method = decode_methodid (p, &p, end, &domain, &err);
5535 location = decode_long (p, &p, end);
5536 } else if (mod == MOD_KIND_STEP) {
5537 step_thread_id = decode_id (p, &p, end);
5538 size = decode_int (p, &p, end);
5539 depth = decode_int (p, &p, end);
5540 } else if (mod == MOD_KIND_THREAD_ONLY) {
5541 int id = decode_id (p, &p, end);
5543 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
5548 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
5549 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
5553 req->modifiers [i].caught = decode_byte (p, &p, end);
5554 req->modifiers [i].uncaught = decode_byte (p, &p, end);
5555 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" : ""));
5557 req->modifiers [i].data.exc_class = exc_class;
5559 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
5561 return ERR_INVALID_ARGUMENT;
5564 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
5565 int n = decode_int (p, &p, end);
5568 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
5569 for (j = 0; j < n; ++j) {
5570 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
5572 g_free (req->modifiers [i].data.assemblies);
5578 return ERR_NOT_IMPLEMENTED;
5582 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5585 req->info = set_breakpoint (method, location, req, &error);
5586 if (!mono_error_ok (&error)) {
5588 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
5589 mono_error_cleanup (&error);
5590 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
5592 } else if (req->event_kind == EVENT_KIND_STEP) {
5593 g_assert (step_thread_id);
5595 err = get_object (step_thread_id, (MonoObject**)&step_thread);
5601 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
5606 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
5607 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
5608 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
5609 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
5610 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
5612 if (req->nmodifiers) {
5614 return ERR_NOT_IMPLEMENTED;
5618 mono_loader_lock ();
5619 g_ptr_array_add (event_requests, req);
5620 mono_loader_unlock ();
5622 buffer_add_int (buf, req->id);
5625 case CMD_EVENT_REQUEST_CLEAR: {
5626 int etype = decode_byte (p, &p, end);
5627 int req_id = decode_int (p, &p, end);
5629 // FIXME: Make a faster mapping from req_id to request
5630 mono_loader_lock ();
5631 clear_event_request (req_id, etype);
5632 mono_loader_unlock ();
5635 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
5638 mono_loader_lock ();
5640 while (i < event_requests->len) {
5641 EventRequest *req = g_ptr_array_index (event_requests, i);
5643 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5644 clear_breakpoint (req->info);
5646 g_ptr_array_remove_index_fast (event_requests, i);
5652 mono_loader_unlock ();
5656 return ERR_NOT_IMPLEMENTED;
5663 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5669 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
5670 buffer_add_domainid (buf, mono_get_root_domain ());
5673 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
5674 domain = decode_domainid (p, &p, end, NULL, &err);
5677 buffer_add_string (buf, domain->friendly_name);
5680 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
5685 domain = decode_domainid (p, &p, end, NULL, &err);
5688 mono_loader_lock ();
5690 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5693 buffer_add_int (buf, count);
5694 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5696 buffer_add_assemblyid (buf, domain, ass);
5698 mono_loader_unlock ();
5701 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
5702 domain = decode_domainid (p, &p, end, NULL, &err);
5706 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
5709 case CMD_APPDOMAIN_GET_CORLIB: {
5710 domain = decode_domainid (p, &p, end, NULL, &err);
5714 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
5717 case CMD_APPDOMAIN_CREATE_STRING: {
5721 domain = decode_domainid (p, &p, end, NULL, &err);
5724 s = decode_string (p, &p, end);
5726 o = mono_string_new (domain, s);
5727 buffer_add_objid (buf, (MonoObject*)o);
5730 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
5732 MonoDomain *domain2;
5735 domain = decode_domainid (p, &p, end, NULL, &err);
5738 klass = decode_typeid (p, &p, end, &domain2, &err);
5743 g_assert (domain == domain2);
5745 o = mono_object_new (domain, klass);
5747 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
5751 buffer_add_objid (buf, o);
5755 return ERR_NOT_IMPLEMENTED;
5762 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5768 ass = decode_assemblyid (p, &p, end, &domain, &err);
5773 case CMD_ASSEMBLY_GET_LOCATION: {
5774 buffer_add_string (buf, mono_image_get_filename (ass->image));
5777 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
5781 if (ass->image->dynamic) {
5782 buffer_add_id (buf, 0);
5784 token = mono_image_get_entry_point (ass->image);
5786 buffer_add_id (buf, 0);
5788 m = mono_get_method (ass->image, token, NULL);
5789 buffer_add_methodid (buf, domain, m);
5794 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5795 buffer_add_moduleid (buf, domain, ass->image);
5798 case CMD_ASSEMBLY_GET_OBJECT: {
5799 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5800 buffer_add_objid (buf, o);
5803 case CMD_ASSEMBLY_GET_TYPE: {
5804 char *s = decode_string (p, &p, end);
5805 gboolean ignorecase = decode_byte (p, &p, end);
5806 MonoTypeNameParse info;
5808 gboolean type_resolve;
5810 if (!mono_reflection_parse_type (s, &info)) {
5813 if (info.assembly.name)
5815 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5817 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5818 mono_reflection_free_type_info (&info);
5823 case CMD_ASSEMBLY_GET_NAME: {
5825 MonoAssembly *mass = ass;
5827 name = g_strdup_printf (
5828 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5830 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5831 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5832 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5833 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5835 buffer_add_string (buf, name);
5840 return ERR_NOT_IMPLEMENTED;
5847 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5853 case CMD_MODULE_GET_INFO: {
5854 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
5857 basename = g_path_get_basename (image->name);
5858 buffer_add_string (buf, basename); // name
5859 buffer_add_string (buf, image->module_name); // scopename
5860 buffer_add_string (buf, image->name); // fqname
5861 buffer_add_string (buf, mono_image_get_guid (image)); // guid
5862 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
5867 return ERR_NOT_IMPLEMENTED;
5874 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
5876 if (val && val->vtable->klass == mono_defaults.monotype_class) {
5877 /* Special case these so the client doesn't have to handle Type objects */
5879 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
5880 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
5881 } else if (MONO_TYPE_IS_REFERENCE (t))
5882 buffer_add_value (buf, t, &val, domain);
5884 buffer_add_value (buf, t, mono_object_unbox (val), domain);
5888 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
5894 buffer_add_int (buf, 0);
5898 for (i = 0; i < cinfo->num_attrs; ++i) {
5899 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
5902 buffer_add_int (buf, nattrs);
5904 for (i = 0; i < cinfo->num_attrs; ++i) {
5905 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
5906 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
5907 MonoArray *typed_args, *named_args;
5909 CattrNamedArg *arginfo;
5911 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
5913 buffer_add_methodid (buf, domain, attr->ctor);
5917 buffer_add_int (buf, mono_array_length (typed_args));
5918 for (j = 0; j < mono_array_length (typed_args); ++j) {
5919 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
5921 t = mono_method_signature (attr->ctor)->params [j];
5923 buffer_add_cattr_arg (buf, t, domain, val);
5926 buffer_add_int (buf, 0);
5931 buffer_add_int (buf, mono_array_length (named_args));
5933 for (j = 0; j < mono_array_length (named_args); ++j) {
5934 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
5936 if (arginfo [j].prop) {
5937 buffer_add_byte (buf, 0x54);
5938 buffer_add_propertyid (buf, domain, arginfo [j].prop);
5939 } else if (arginfo [j].field) {
5940 buffer_add_byte (buf, 0x53);
5942 g_assert_not_reached ();
5945 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
5948 buffer_add_int (buf, 0);
5955 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
5965 case CMD_TYPE_GET_INFO: {
5966 buffer_add_string (buf, klass->name_space);
5967 buffer_add_string (buf, klass->name);
5969 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
5970 buffer_add_string (buf, name);
5972 buffer_add_assemblyid (buf, domain, klass->image->assembly);
5973 buffer_add_moduleid (buf, domain, klass->image);
5974 buffer_add_typeid (buf, domain, klass->parent);
5975 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
5976 buffer_add_typeid (buf, domain, klass->element_class);
5978 buffer_add_id (buf, 0);
5979 buffer_add_int (buf, klass->type_token);
5980 buffer_add_byte (buf, klass->rank);
5981 buffer_add_int (buf, klass->flags);
5983 type = &klass->byval_arg;
5984 // FIXME: Can't decide whenever a class represents a byref type
5987 if (type->type == MONO_TYPE_PTR)
5989 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
5991 if (type->type == MONO_TYPE_VALUETYPE)
5993 if (klass->enumtype)
5995 buffer_add_byte (buf, b);
5998 while ((nested = mono_class_get_nested_types (klass, &iter)))
6000 buffer_add_int (buf, nnested);
6002 while ((nested = mono_class_get_nested_types (klass, &iter)))
6003 buffer_add_typeid (buf, domain, nested);
6006 case CMD_TYPE_GET_METHODS: {
6009 gpointer iter = NULL;
6012 mono_class_setup_methods (klass);
6014 nmethods = mono_class_num_methods (klass);
6016 buffer_add_int (buf, nmethods);
6018 while ((m = mono_class_get_methods (klass, &iter))) {
6019 buffer_add_methodid (buf, domain, m);
6022 g_assert (i == nmethods);
6025 case CMD_TYPE_GET_FIELDS: {
6028 gpointer iter = NULL;
6031 nfields = mono_class_num_fields (klass);
6033 buffer_add_int (buf, nfields);
6035 while ((f = mono_class_get_fields (klass, &iter))) {
6036 buffer_add_fieldid (buf, domain, f);
6037 buffer_add_string (buf, f->name);
6038 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
6039 buffer_add_int (buf, f->type->attrs);
6042 g_assert (i == nfields);
6045 case CMD_TYPE_GET_PROPERTIES: {
6048 gpointer iter = NULL;
6051 nprops = mono_class_num_properties (klass);
6053 buffer_add_int (buf, nprops);
6055 while ((p = mono_class_get_properties (klass, &iter))) {
6056 buffer_add_propertyid (buf, domain, p);
6057 buffer_add_string (buf, p->name);
6058 buffer_add_methodid (buf, domain, p->get);
6059 buffer_add_methodid (buf, domain, p->set);
6060 buffer_add_int (buf, p->attrs);
6063 g_assert (i == nprops);
6066 case CMD_TYPE_GET_CATTRS: {
6067 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
6068 MonoCustomAttrInfo *cinfo;
6070 cinfo = mono_custom_attrs_from_class (klass);
6072 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6075 case CMD_TYPE_GET_FIELD_CATTRS: {
6076 MonoClass *attr_klass;
6077 MonoCustomAttrInfo *cinfo;
6078 MonoClassField *field;
6080 field = decode_fieldid (p, &p, end, NULL, &err);
6083 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6087 cinfo = mono_custom_attrs_from_field (klass, field);
6089 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6092 case CMD_TYPE_GET_PROPERTY_CATTRS: {
6093 MonoClass *attr_klass;
6094 MonoCustomAttrInfo *cinfo;
6097 prop = decode_propertyid (p, &p, end, NULL, &err);
6100 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6104 cinfo = mono_custom_attrs_from_property (klass, prop);
6106 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6109 case CMD_TYPE_GET_VALUES:
6110 case CMD_TYPE_GET_VALUES_2: {
6117 MonoThread *thread_obj;
6118 MonoInternalThread *thread = NULL;
6119 guint32 special_static_type;
6121 if (command == CMD_TYPE_GET_VALUES_2) {
6122 int objid = decode_objid (p, &p, end);
6125 err = get_object (objid, (MonoObject**)&thread_obj);
6129 thread = THREAD_TO_INTERNAL (thread_obj);
6132 len = decode_int (p, &p, end);
6133 for (i = 0; i < len; ++i) {
6134 f = decode_fieldid (p, &p, end, NULL, &err);
6138 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6139 return ERR_INVALID_FIELDID;
6140 special_static_type = mono_class_field_get_special_static_type (f);
6141 if (special_static_type != SPECIAL_STATIC_NONE) {
6142 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
6143 return ERR_INVALID_FIELDID;
6146 /* Check that the field belongs to the object */
6148 for (k = klass; k; k = k->parent) {
6149 if (k == f->parent) {
6155 return ERR_INVALID_FIELDID;
6157 vtable = mono_class_vtable (domain, f->parent);
6158 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6159 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
6160 buffer_add_value (buf, f->type, val, domain);
6165 case CMD_TYPE_SET_VALUES: {
6173 len = decode_int (p, &p, end);
6174 for (i = 0; i < len; ++i) {
6175 f = decode_fieldid (p, &p, end, NULL, &err);
6179 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6180 return ERR_INVALID_FIELDID;
6181 if (mono_class_field_is_special_static (f))
6182 return ERR_INVALID_FIELDID;
6184 /* Check that the field belongs to the object */
6186 for (k = klass; k; k = k->parent) {
6187 if (k == f->parent) {
6193 return ERR_INVALID_FIELDID;
6195 // FIXME: Check for literal/const
6197 vtable = mono_class_vtable (domain, f->parent);
6198 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6199 err = decode_value (f->type, domain, val, p, &p, end);
6204 if (MONO_TYPE_IS_REFERENCE (f->type))
6205 mono_field_static_set_value (vtable, f, *(gpointer*)val);
6207 mono_field_static_set_value (vtable, f, val);
6212 case CMD_TYPE_GET_OBJECT: {
6213 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
6214 buffer_add_objid (buf, o);
6217 case CMD_TYPE_GET_SOURCE_FILES:
6218 case CMD_TYPE_GET_SOURCE_FILES_2: {
6219 gpointer iter = NULL;
6221 char *source_file, *base;
6225 files = g_ptr_array_new ();
6227 while ((method = mono_class_get_methods (klass, &iter))) {
6228 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6231 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
6235 for (i = 0; i < files->len; ++i)
6236 if (!strcmp (g_ptr_array_index (files, i), source_file))
6238 if (i == files->len)
6239 g_ptr_array_add (files, g_strdup (source_file));
6240 g_free (source_file);
6244 buffer_add_int (buf, files->len);
6245 for (i = 0; i < files->len; ++i) {
6246 source_file = g_ptr_array_index (files, i);
6247 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
6248 buffer_add_string (buf, source_file);
6250 base = g_path_get_basename (source_file);
6251 buffer_add_string (buf, base);
6254 g_free (source_file);
6256 g_ptr_array_free (files, TRUE);
6259 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
6260 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
6264 if (mono_class_is_assignable_from (klass, oklass))
6265 buffer_add_byte (buf, 1);
6267 buffer_add_byte (buf, 0);
6271 return ERR_NOT_IMPLEMENTED;
6278 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6281 MonoDomain *old_domain;
6285 klass = decode_typeid (p, &p, end, &domain, &err);
6289 old_domain = mono_domain_get ();
6291 mono_domain_set (domain, TRUE);
6293 err = type_commands_internal (command, klass, domain, p, end, buf);
6295 mono_domain_set (old_domain, TRUE);
6301 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6303 MonoMethodHeader *header;
6306 case CMD_METHOD_GET_NAME: {
6307 buffer_add_string (buf, method->name);
6310 case CMD_METHOD_GET_DECLARING_TYPE: {
6311 buffer_add_typeid (buf, domain, method->klass);
6314 case CMD_METHOD_GET_DEBUG_INFO: {
6315 MonoDebugMethodInfo *minfo;
6317 int i, n_il_offsets;
6321 header = mono_method_get_header (method);
6323 buffer_add_int (buf, 0);
6324 buffer_add_string (buf, "");
6325 buffer_add_int (buf, 0);
6329 minfo = mono_debug_lookup_method (method);
6331 buffer_add_int (buf, header->code_size);
6332 buffer_add_string (buf, "");
6333 buffer_add_int (buf, 0);
6334 mono_metadata_free_mh (header);
6338 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
6339 buffer_add_int (buf, header->code_size);
6340 buffer_add_string (buf, source_file);
6341 buffer_add_int (buf, n_il_offsets);
6342 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
6343 for (i = 0; i < n_il_offsets; ++i) {
6344 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
6345 buffer_add_int (buf, il_offsets [i]);
6346 buffer_add_int (buf, line_numbers [i]);
6348 g_free (source_file);
6349 g_free (il_offsets);
6350 g_free (line_numbers);
6351 mono_metadata_free_mh (header);
6354 case CMD_METHOD_GET_PARAM_INFO: {
6355 MonoMethodSignature *sig = mono_method_signature (method);
6359 /* FIXME: mono_class_from_mono_type () and byrefs */
6361 /* FIXME: Use a smaller encoding */
6362 buffer_add_int (buf, sig->call_convention);
6363 buffer_add_int (buf, sig->param_count);
6364 buffer_add_int (buf, sig->generic_param_count);
6365 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
6366 for (i = 0; i < sig->param_count; ++i) {
6368 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
6371 /* Emit parameter names */
6372 names = g_new (char *, sig->param_count);
6373 mono_method_get_param_names (method, (const char **) names);
6374 for (i = 0; i < sig->param_count; ++i)
6375 buffer_add_string (buf, names [i]);
6380 case CMD_METHOD_GET_LOCALS_INFO: {
6381 int i, j, num_locals;
6382 MonoDebugLocalsInfo *locals;
6384 header = mono_method_get_header (method);
6387 buffer_add_int (buf, header->num_locals);
6390 for (i = 0; i < header->num_locals; ++i)
6391 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
6394 locals = mono_debug_lookup_locals (method);
6396 num_locals = locals->num_locals;
6399 for (i = 0; i < header->num_locals; ++i) {
6400 for (j = 0; j < num_locals; ++j)
6401 if (locals->locals [j].index == i)
6404 buffer_add_string (buf, locals->locals [j].name);
6406 buffer_add_string (buf, "");
6410 for (i = 0; i < header->num_locals; ++i) {
6411 for (j = 0; j < num_locals; ++j)
6412 if (locals->locals [j].index == i)
6414 if (j < num_locals && locals->locals [j].block) {
6415 buffer_add_int (buf, locals->locals [j].block->start_offset);
6416 buffer_add_int (buf, locals->locals [j].block->end_offset);
6418 buffer_add_int (buf, 0);
6419 buffer_add_int (buf, header->code_size);
6422 mono_metadata_free_mh (header);
6425 mono_debug_symfile_free_locals (locals);
6429 case CMD_METHOD_GET_INFO:
6430 buffer_add_int (buf, method->flags);
6431 buffer_add_int (buf, method->iflags);
6432 buffer_add_int (buf, method->token);
6434 case CMD_METHOD_GET_BODY: {
6437 header = mono_method_get_header (method);
6439 buffer_add_int (buf, 0);
6441 buffer_add_int (buf, header->code_size);
6442 for (i = 0; i < header->code_size; ++i)
6443 buffer_add_byte (buf, header->code [i]);
6445 mono_metadata_free_mh (header);
6448 case CMD_METHOD_RESOLVE_TOKEN: {
6449 guint32 token = decode_int (p, &p, end);
6452 switch (mono_metadata_token_code (token)) {
6453 case MONO_TOKEN_STRING: {
6457 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
6460 s2 = mono_string_to_utf8 (s);
6462 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6463 buffer_add_string (buf, s2);
6469 MonoClass *handle_class;
6471 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6472 val = mono_method_get_wrapper_data (method, token);
6473 handle_class = mono_method_get_wrapper_data (method, token + 1);
6475 if (handle_class == NULL) {
6476 // Can't figure out the token type
6477 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
6481 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
6485 if (handle_class == mono_defaults.typehandle_class) {
6486 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
6487 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
6488 buffer_add_typeid (buf, domain, (MonoClass *) val);
6490 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
6491 } else if (handle_class == mono_defaults.fieldhandle_class) {
6492 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
6493 buffer_add_fieldid (buf, domain, val);
6494 } else if (handle_class == mono_defaults.methodhandle_class) {
6495 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
6496 buffer_add_methodid (buf, domain, val);
6497 } else if (handle_class == mono_defaults.string_class) {
6500 s = mono_string_to_utf8 (val);
6501 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6502 buffer_add_string (buf, s);
6505 g_assert_not_reached ();
6513 return ERR_NOT_IMPLEMENTED;
6520 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6523 MonoDomain *old_domain;
6527 method = decode_methodid (p, &p, end, &domain, &err);
6531 old_domain = mono_domain_get ();
6533 mono_domain_set (domain, TRUE);
6535 err = method_commands_internal (command, method, domain, p, end, buf);
6537 mono_domain_set (old_domain, TRUE);
6543 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6545 int objid = decode_objid (p, &p, end);
6547 MonoThread *thread_obj;
6548 MonoInternalThread *thread;
6550 err = get_object (objid, (MonoObject**)&thread_obj);
6554 thread = THREAD_TO_INTERNAL (thread_obj);
6557 case CMD_THREAD_GET_NAME: {
6559 gunichar2 *s = mono_thread_get_name (thread, &name_len);
6562 buffer_add_int (buf, 0);
6567 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
6569 buffer_add_int (buf, len);
6570 buffer_add_data (buf, (guint8*)name, len);
6575 case CMD_THREAD_GET_FRAME_INFO: {
6576 DebuggerTlsData *tls;
6577 int i, start_frame, length;
6579 // Wait for suspending if it already started
6581 wait_for_suspend ();
6582 if (!is_suspended ())
6583 return ERR_NOT_SUSPENDED;
6585 start_frame = decode_int (p, &p, end);
6586 length = decode_int (p, &p, end);
6588 if (start_frame != 0 || length != -1)
6589 return ERR_NOT_IMPLEMENTED;
6591 mono_loader_lock ();
6592 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6593 mono_loader_unlock ();
6596 compute_frame_info (thread, tls);
6598 buffer_add_int (buf, tls->frame_count);
6599 for (i = 0; i < tls->frame_count; ++i) {
6600 buffer_add_int (buf, tls->frames [i]->id);
6601 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
6602 buffer_add_int (buf, tls->frames [i]->il_offset);
6604 * Instead of passing the frame type directly to the client, we associate
6605 * it with the previous frame using a set of flags. This avoids lots of
6606 * conditional code in the client, since a frame whose type isn't
6607 * FRAME_TYPE_MANAGED has no method, location, etc.
6609 buffer_add_byte (buf, tls->frames [i]->flags);
6614 case CMD_THREAD_GET_STATE:
6615 buffer_add_int (buf, thread->state);
6617 case CMD_THREAD_GET_INFO:
6618 buffer_add_byte (buf, thread->threadpool_thread);
6620 case CMD_THREAD_GET_ID:
6621 buffer_add_long (buf, (guint64)(gsize)thread);
6623 case CMD_THREAD_GET_TID:
6624 buffer_add_long (buf, (guint64)thread->tid);
6627 return ERR_NOT_IMPLEMENTED;
6634 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6638 MonoThread *thread_obj;
6639 MonoInternalThread *thread;
6641 DebuggerTlsData *tls;
6643 MonoDebugMethodJitInfo *jit;
6644 MonoDebugVarInfo *var;
6645 MonoMethodSignature *sig;
6647 MonoMethodHeader *header;
6649 objid = decode_objid (p, &p, end);
6650 err = get_object (objid, (MonoObject**)&thread_obj);
6654 thread = THREAD_TO_INTERNAL (thread_obj);
6656 id = decode_id (p, &p, end);
6658 mono_loader_lock ();
6659 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6660 mono_loader_unlock ();
6663 for (i = 0; i < tls->frame_count; ++i) {
6664 if (tls->frames [i]->id == id)
6667 if (i == tls->frame_count)
6668 return ERR_INVALID_FRAMEID;
6670 frame = tls->frames [i];
6672 if (!frame->has_ctx)
6674 return ERR_INVALID_FRAMEID;
6677 frame->jit = mono_debug_find_method (frame->method, frame->domain);
6679 /* This could happen for aot images with no jit debug info */
6680 return ERR_ABSENT_INFORMATION;
6684 sig = mono_method_signature (frame->actual_method);
6687 case CMD_STACK_FRAME_GET_VALUES: {
6688 len = decode_int (p, &p, end);
6689 header = mono_method_get_header (frame->actual_method);
6691 for (i = 0; i < len; ++i) {
6692 pos = decode_int (p, &p, end);
6697 g_assert (pos >= 0 && pos < jit->num_params);
6699 var = &jit->params [pos];
6701 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
6703 g_assert (pos >= 0 && pos < jit->num_locals);
6705 var = &jit->locals [pos];
6707 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
6710 mono_metadata_free_mh (header);
6713 case CMD_STACK_FRAME_GET_THIS: {
6714 if (frame->method->klass->valuetype) {
6715 if (!sig->hasthis) {
6716 MonoObject *p = NULL;
6717 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
6719 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6722 if (!sig->hasthis) {
6723 MonoObject *p = NULL;
6724 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
6726 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6731 case CMD_STACK_FRAME_SET_VALUES: {
6734 MonoDebugVarInfo *var;
6736 len = decode_int (p, &p, end);
6737 header = mono_method_get_header (frame->actual_method);
6739 for (i = 0; i < len; ++i) {
6740 pos = decode_int (p, &p, end);
6745 g_assert (pos >= 0 && pos < jit->num_params);
6747 t = sig->params [pos];
6748 var = &jit->params [pos];
6750 g_assert (pos >= 0 && pos < jit->num_locals);
6752 t = header->locals [pos];
6753 var = &jit->locals [pos];
6756 if (MONO_TYPE_IS_REFERENCE (t))
6757 val_buf = g_alloca (sizeof (MonoObject*));
6759 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
6760 err = decode_value (t, frame->domain, val_buf, p, &p, end);
6764 set_var (t, var, &frame->ctx, frame->domain, val_buf);
6766 mono_metadata_free_mh (header);
6770 return ERR_NOT_IMPLEMENTED;
6777 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6780 int objid, err, index, len, i, esize;
6783 objid = decode_objid (p, &p, end);
6784 err = get_object (objid, (MonoObject**)&arr);
6789 case CMD_ARRAY_REF_GET_LENGTH:
6790 buffer_add_int (buf, arr->obj.vtable->klass->rank);
6792 buffer_add_int (buf, arr->max_length);
6793 buffer_add_int (buf, 0);
6795 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
6796 buffer_add_int (buf, arr->bounds [i].length);
6797 buffer_add_int (buf, arr->bounds [i].lower_bound);
6801 case CMD_ARRAY_REF_GET_VALUES:
6802 index = decode_int (p, &p, end);
6803 len = decode_int (p, &p, end);
6805 g_assert (index >= 0 && len >= 0);
6806 // Reordered to avoid integer overflow
6807 g_assert (!(index > arr->max_length - len));
6809 esize = mono_array_element_size (arr->obj.vtable->klass);
6810 for (i = index; i < index + len; ++i) {
6811 elem = (gpointer*)((char*)arr->vector + (i * esize));
6812 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
6815 case CMD_ARRAY_REF_SET_VALUES:
6816 index = decode_int (p, &p, end);
6817 len = decode_int (p, &p, end);
6819 g_assert (index >= 0 && len >= 0);
6820 // Reordered to avoid integer overflow
6821 g_assert (!(index > arr->max_length - len));
6823 esize = mono_array_element_size (arr->obj.vtable->klass);
6824 for (i = index; i < index + len; ++i) {
6825 elem = (gpointer*)((char*)arr->vector + (i * esize));
6827 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
6831 return ERR_NOT_IMPLEMENTED;
6838 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6844 objid = decode_objid (p, &p, end);
6845 err = get_object (objid, (MonoObject**)&str);
6850 case CMD_STRING_REF_GET_VALUE:
6851 s = mono_string_to_utf8 (str);
6852 buffer_add_string (buf, s);
6856 return ERR_NOT_IMPLEMENTED;
6863 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6872 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
6873 objid = decode_objid (p, &p, end);
6874 err = get_object (objid, &obj);
6876 buffer_add_int (buf, 1);
6878 buffer_add_int (buf, 0);
6882 objid = decode_objid (p, &p, end);
6883 err = get_object (objid, &obj);
6888 case CMD_OBJECT_REF_GET_TYPE:
6889 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
6891 case CMD_OBJECT_REF_GET_VALUES:
6892 len = decode_int (p, &p, end);
6894 for (i = 0; i < len; ++i) {
6895 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
6899 /* Check that the field belongs to the object */
6901 for (k = obj->vtable->klass; k; k = k->parent) {
6902 if (k == f->parent) {
6908 return ERR_INVALID_FIELDID;
6910 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6914 if (mono_class_field_is_special_static (f))
6915 return ERR_INVALID_FIELDID;
6917 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6918 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6919 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6920 mono_field_static_get_value (vtable, f, val);
6921 buffer_add_value (buf, f->type, val, obj->vtable->domain);
6924 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
6928 case CMD_OBJECT_REF_SET_VALUES:
6929 len = decode_int (p, &p, end);
6931 for (i = 0; i < len; ++i) {
6932 f = decode_fieldid (p, &p, end, NULL, &err);
6936 /* Check that the field belongs to the object */
6938 for (k = obj->vtable->klass; k; k = k->parent) {
6939 if (k == f->parent) {
6945 return ERR_INVALID_FIELDID;
6947 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6951 if (mono_class_field_is_special_static (f))
6952 return ERR_INVALID_FIELDID;
6954 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6955 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6957 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6958 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
6963 mono_field_static_set_value (vtable, f, val);
6966 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
6972 case CMD_OBJECT_REF_GET_ADDRESS:
6973 buffer_add_long (buf, (gssize)obj);
6975 case CMD_OBJECT_REF_GET_DOMAIN:
6976 buffer_add_domainid (buf, obj->vtable->domain);
6979 return ERR_NOT_IMPLEMENTED;
6986 command_set_to_string (CommandSet command_set)
6988 switch (command_set) {
6991 case CMD_SET_OBJECT_REF:
6992 return "OBJECT_REF";
6993 case CMD_SET_STRING_REF:
6994 return "STRING_REF";
6995 case CMD_SET_THREAD:
6997 case CMD_SET_ARRAY_REF:
6999 case CMD_SET_EVENT_REQUEST:
7000 return "EVENT_REQUEST";
7001 case CMD_SET_STACK_FRAME:
7002 return "STACK_FRAME";
7003 case CMD_SET_APPDOMAIN:
7005 case CMD_SET_ASSEMBLY:
7007 case CMD_SET_METHOD:
7011 case CMD_SET_MODULE:
7021 cmd_to_string (CommandSet set, int command)
7026 case CMD_VM_VERSION:
7028 case CMD_VM_ALL_THREADS:
7029 return "ALL_THREADS";
7030 case CMD_VM_SUSPEND:
7036 case CMD_VM_DISPOSE:
7038 case CMD_VM_INVOKE_METHOD:
7039 return "INVOKE_METHOD";
7040 case CMD_VM_SET_PROTOCOL_VERSION:
7041 return "SET_PROTOCOL_VERSION";
7042 case CMD_VM_ABORT_INVOKE:
7043 return "ABORT_INVOKE";
7058 * This thread handles communication with the debugger client using a JDWP
7061 static guint32 WINAPI
7062 debugger_thread (void *arg)
7064 int res, len, id, flags, command_set, command;
7065 guint8 header [HEADER_LENGTH];
7066 guint8 *data, *p, *end;
7071 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
7073 debugger_thread_id = GetCurrentThreadId ();
7075 mono_jit_thread_attach (mono_get_root_domain ());
7077 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
7079 mono_set_is_debugger_attached (TRUE);
7082 res = recv_length (conn_fd, header, HEADER_LENGTH, 0);
7084 /* This will break if the socket is closed during shutdown too */
7085 if (res != HEADER_LENGTH)
7089 end = header + HEADER_LENGTH;
7091 len = decode_int (p, &p, end);
7092 id = decode_int (p, &p, end);
7093 flags = decode_byte (p, &p, end);
7094 command_set = decode_byte (p, &p, end);
7095 command = decode_byte (p, &p, end);
7097 g_assert (flags == 0);
7100 const char *cmd_str;
7103 cmd_str = cmd_to_string (command_set, command);
7105 sprintf (cmd_num, "%d", command);
7109 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
7112 data = g_malloc (len - HEADER_LENGTH);
7113 if (len - HEADER_LENGTH > 0)
7115 res = recv_length (conn_fd, data, len - HEADER_LENGTH, 0);
7116 if (res != len - HEADER_LENGTH)
7121 end = data + (len - HEADER_LENGTH);
7123 buffer_init (&buf, 128);
7128 /* Process the request */
7129 switch (command_set) {
7131 err = vm_commands (command, id, p, end, &buf);
7132 if (!err && command == CMD_VM_INVOKE_METHOD)
7133 /* Sent after the invoke is complete */
7136 case CMD_SET_EVENT_REQUEST:
7137 err = event_commands (command, p, end, &buf);
7139 case CMD_SET_APPDOMAIN:
7140 err = domain_commands (command, p, end, &buf);
7142 case CMD_SET_ASSEMBLY:
7143 err = assembly_commands (command, p, end, &buf);
7145 case CMD_SET_MODULE:
7146 err = module_commands (command, p, end, &buf);
7149 err = type_commands (command, p, end, &buf);
7151 case CMD_SET_METHOD:
7152 err = method_commands (command, p, end, &buf);
7154 case CMD_SET_THREAD:
7155 err = thread_commands (command, p, end, &buf);
7157 case CMD_SET_STACK_FRAME:
7158 err = frame_commands (command, p, end, &buf);
7160 case CMD_SET_ARRAY_REF:
7161 err = array_commands (command, p, end, &buf);
7163 case CMD_SET_STRING_REF:
7164 err = string_commands (command, p, end, &buf);
7166 case CMD_SET_OBJECT_REF:
7167 err = object_commands (command, p, end, &buf);
7170 err = ERR_NOT_IMPLEMENTED;
7174 send_reply_packet (id, err, &buf);
7179 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
7183 mono_set_is_debugger_attached (FALSE);
7185 mono_mutex_lock (&debugger_thread_exited_mutex);
7186 debugger_thread_exited = TRUE;
7187 mono_cond_signal (&debugger_thread_exited_cond);
7188 mono_mutex_unlock (&debugger_thread_exited_mutex);
7190 DEBUG (1, printf ("[dbg] Debugger thread exited.\n"));
7195 #else /* DISABLE_DEBUGGER_AGENT */
7198 mono_debugger_agent_parse_options (char *options)
7200 g_error ("This runtime is configured with the debugger agent disabled.");
7204 mono_debugger_agent_init (void)
7209 mono_debugger_agent_breakpoint_hit (void *sigctx)
7214 mono_debugger_agent_single_step_event (void *sigctx)
7219 mono_debugger_agent_free_domain_info (MonoDomain *domain)
7224 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
7230 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
7231 MonoContext *catch_ctx)
7236 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
7241 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)