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
88 #include <mono/io-layer/mono-mutex.h>
90 /* Definitions to make backporting to 2.6 easier */
91 //#define MonoInternalThread MonoThread
92 //#define mono_thread_internal_current mono_thread_current
93 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
113 guint32 il_offset, native_offset;
117 * If method is gshared, this is the actual instance, otherwise this is equal to
120 MonoMethod *actual_method;
122 MonoDebugMethodJitInfo *jit;
125 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
126 * the frame can become invalid.
131 typedef struct _InvokeData InvokeData;
139 /* This is the context which needs to be restored after the invoke */
143 * If this is set, invoke this method with the arguments given by ARGS.
147 guint32 suspend_count;
149 InvokeData *last_invoke;
156 gboolean has_context;
157 gpointer resume_event;
158 /* This is computed on demand when it is requested using the wire protocol */
159 /* It is freed up when the thread is resumed */
163 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
166 gboolean frames_up_to_date;
168 * Points to data about a pending invoke which needs to be executed after the thread
171 InvokeData *pending_invoke;
173 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
178 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
179 * within a finite amount of time.
183 * Set to TRUE if this thread is suspended in suspend_current ().
185 gboolean really_suspended;
186 /* Used to pass the context to the breakpoint/single step handler */
187 MonoContext handler_ctx;
188 /* Whenever thread_stop () was called for this thread */
191 /* Number of thread interruptions not yet processed */
192 gint32 interrupt_count;
194 /* Whenever to disable breakpoints (used during invokes) */
195 gboolean disable_breakpoints;
198 * Number of times this thread has been resumed using resume_thread ().
200 guint32 resume_count;
202 MonoInternalThread *thread;
205 * Information about the frame which transitioned to native code for running
208 StackFrameInfo async_last_frame;
211 * The context where the stack walk can be started for running threads.
213 MonoContext async_ctx;
215 gboolean has_async_ctx;
217 gboolean has_filter_ctx;
218 MonoContext filter_ctx;
222 * The lmf where the stack walk can be started for running threads.
227 * The callee address of the last mono_runtime_invoke call
229 gpointer invoke_addr;
231 gboolean abort_requested;
234 * The current mono_runtime_invoke invocation.
239 * The context where single stepping should resume while the thread is suspended because
240 * of an EXCEPTION event.
242 MonoContext catch_ctx;
244 gboolean has_catch_ctx;
248 * Wire Protocol definitions
251 #define HEADER_LENGTH 11
253 #define MAJOR_VERSION 2
254 #define MINOR_VERSION 2
258 CMD_SET_OBJECT_REF = 9,
259 CMD_SET_STRING_REF = 10,
261 CMD_SET_ARRAY_REF = 13,
262 CMD_SET_EVENT_REQUEST = 15,
263 CMD_SET_STACK_FRAME = 16,
264 CMD_SET_APPDOMAIN = 20,
265 CMD_SET_ASSEMBLY = 21,
273 EVENT_KIND_VM_START = 0,
274 EVENT_KIND_VM_DEATH = 1,
275 EVENT_KIND_THREAD_START = 2,
276 EVENT_KIND_THREAD_DEATH = 3,
277 EVENT_KIND_APPDOMAIN_CREATE = 4,
278 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
279 EVENT_KIND_METHOD_ENTRY = 6,
280 EVENT_KIND_METHOD_EXIT = 7,
281 EVENT_KIND_ASSEMBLY_LOAD = 8,
282 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
283 EVENT_KIND_BREAKPOINT = 10,
284 EVENT_KIND_STEP = 11,
285 EVENT_KIND_TYPE_LOAD = 12,
286 EVENT_KIND_EXCEPTION = 13
290 SUSPEND_POLICY_NONE = 0,
291 SUSPEND_POLICY_EVENT_THREAD = 1,
292 SUSPEND_POLICY_ALL = 2
297 ERR_INVALID_OBJECT = 20,
298 ERR_INVALID_FIELDID = 25,
299 ERR_INVALID_FRAMEID = 30,
300 ERR_NOT_IMPLEMENTED = 100,
301 ERR_NOT_SUSPENDED = 101,
302 ERR_INVALID_ARGUMENT = 102,
304 ERR_NO_INVOCATION = 104,
305 ERR_ABSENT_INFORMATION = 105,
306 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106
311 MOD_KIND_THREAD_ONLY = 3,
312 MOD_KIND_LOCATION_ONLY = 7,
313 MOD_KIND_EXCEPTION_ONLY = 8,
315 MOD_KIND_ASSEMBLY_ONLY = 11
330 TOKEN_TYPE_STRING = 0,
332 TOKEN_TYPE_FIELD = 2,
333 TOKEN_TYPE_METHOD = 3,
334 TOKEN_TYPE_UNKNOWN = 4
338 VALUE_TYPE_ID_NULL = 0xf0,
339 VALUE_TYPE_ID_TYPE = 0xf1
343 FRAME_FLAG_DEBUGGER_INVOKE = 1
347 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
348 INVOKE_FLAG_SINGLE_THREADED = 2
353 CMD_VM_ALL_THREADS = 2,
358 CMD_VM_INVOKE_METHOD = 7,
359 CMD_VM_SET_PROTOCOL_VERSION = 8,
360 CMD_VM_ABORT_INVOKE = 9
364 CMD_THREAD_GET_FRAME_INFO = 1,
365 CMD_THREAD_GET_NAME = 2,
366 CMD_THREAD_GET_STATE = 3,
367 CMD_THREAD_GET_INFO = 4,
368 CMD_THREAD_GET_ID = 5
372 CMD_EVENT_REQUEST_SET = 1,
373 CMD_EVENT_REQUEST_CLEAR = 2,
374 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
382 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
383 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
384 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
385 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
386 CMD_APPDOMAIN_CREATE_STRING = 5,
387 CMD_APPDOMAIN_GET_CORLIB = 6,
388 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
392 CMD_ASSEMBLY_GET_LOCATION = 1,
393 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
394 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
395 CMD_ASSEMBLY_GET_OBJECT = 4,
396 CMD_ASSEMBLY_GET_TYPE = 5,
397 CMD_ASSEMBLY_GET_NAME = 6
401 CMD_MODULE_GET_INFO = 1,
405 CMD_METHOD_GET_NAME = 1,
406 CMD_METHOD_GET_DECLARING_TYPE = 2,
407 CMD_METHOD_GET_DEBUG_INFO = 3,
408 CMD_METHOD_GET_PARAM_INFO = 4,
409 CMD_METHOD_GET_LOCALS_INFO = 5,
410 CMD_METHOD_GET_INFO = 6,
411 CMD_METHOD_GET_BODY = 7,
412 CMD_METHOD_RESOLVE_TOKEN = 8,
416 CMD_TYPE_GET_INFO = 1,
417 CMD_TYPE_GET_METHODS = 2,
418 CMD_TYPE_GET_FIELDS = 3,
419 CMD_TYPE_GET_VALUES = 4,
420 CMD_TYPE_GET_OBJECT = 5,
421 CMD_TYPE_GET_SOURCE_FILES = 6,
422 CMD_TYPE_SET_VALUES = 7,
423 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
424 CMD_TYPE_GET_PROPERTIES = 9,
425 CMD_TYPE_GET_CATTRS = 10,
426 CMD_TYPE_GET_FIELD_CATTRS = 11,
427 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
428 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
429 CMD_TYPE_GET_VALUES_2 = 14
433 CMD_STACK_FRAME_GET_VALUES = 1,
434 CMD_STACK_FRAME_GET_THIS = 2,
435 CMD_STACK_FRAME_SET_VALUES = 3
439 CMD_ARRAY_REF_GET_LENGTH = 1,
440 CMD_ARRAY_REF_GET_VALUES = 2,
441 CMD_ARRAY_REF_SET_VALUES = 3,
445 CMD_STRING_REF_GET_VALUE = 1,
449 CMD_OBJECT_REF_GET_TYPE = 1,
450 CMD_OBJECT_REF_GET_VALUES = 2,
451 CMD_OBJECT_REF_IS_COLLECTED = 3,
452 CMD_OBJECT_REF_GET_ADDRESS = 4,
453 CMD_OBJECT_REF_GET_DOMAIN = 5,
454 CMD_OBJECT_REF_SET_VALUES = 6
460 int count; /* For kind == MOD_KIND_COUNT */
461 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
462 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
463 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
465 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
474 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
478 * Describes a single step request.
482 MonoInternalThread *thread;
487 MonoMethod *last_method;
489 /* Whenever single stepping is performed using start/stop_single_stepping () */
491 /* The list of breakpoints used to implement step-over */
496 * Contains additional information for an event
499 /* For EVENT_KIND_EXCEPTION */
501 MonoContext catch_ctx;
505 /* Dummy structure used for the profiler callbacks */
510 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
516 static AgentConfig agent_config;
519 * Whenever the agent is fully initialized.
520 * When using the onuncaught or onthrow options, only some parts of the agent are
521 * initialized on startup, and the full initialization which includes connection
522 * establishment and the startup of the agent thread is only done in response to
525 static gint32 inited;
529 static int packet_id = 0;
531 static int objref_id = 0;
533 static int event_request_id = 0;
535 static int frame_id = 0;
537 static GPtrArray *event_requests;
539 static guint32 debugger_tls_id;
541 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
543 /* Maps MonoInternalThread -> DebuggerTlsData */
544 static MonoGHashTable *thread_to_tls;
546 /* Maps tid -> MonoInternalThread */
547 static MonoGHashTable *tid_to_thread;
549 /* Maps tid -> MonoThread (not MonoInternalThread) */
550 static MonoGHashTable *tid_to_thread_obj;
552 static gsize debugger_thread_id;
554 static HANDLE debugger_thread_handle;
556 static int log_level;
558 static gboolean embedding;
560 static FILE *log_file;
562 /* Classes whose class load event has been sent */
563 static GHashTable *loaded_classes;
565 /* Assemblies whose assembly load event has no been sent yet */
566 static GPtrArray *pending_assembly_loads;
568 /* Types whose type load event has no been sent yet */
569 static GPtrArray *pending_type_loads;
571 /* Whenever the debugger thread has exited */
572 static gboolean debugger_thread_exited;
574 /* Cond variable used to wait for debugger_thread_exited becoming true */
575 static mono_cond_t debugger_thread_exited_cond;
577 /* Mutex for the cond var above */
578 static mono_mutex_t debugger_thread_exited_mutex;
580 static DebuggerProfiler debugger_profiler;
582 /* The single step request instance */
583 static SingleStepReq *ss_req = NULL;
584 static gpointer ss_invoke_addr = NULL;
586 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
587 /* Number of single stepping operations in progress */
591 /* The protocol version of the client */
592 static int major_version, minor_version;
594 /* Whenever the variables above are set by the client */
595 static gboolean protocol_version_set;
597 /* A hash table containing all active domains */
598 static GHashTable *domains;
600 static void transport_connect (const char *host, int port);
602 static guint32 WINAPI debugger_thread (void *arg);
604 static void runtime_initialized (MonoProfiler *prof);
606 static void runtime_shutdown (MonoProfiler *prof);
608 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
610 static void thread_end (MonoProfiler *prof, uintptr_t tid);
612 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
614 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
616 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
618 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
620 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
622 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
624 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
626 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
628 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
630 static void start_single_stepping (void);
632 static void stop_single_stepping (void);
634 static void suspend_current (void);
636 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
638 static void clear_breakpoints_for_domain (MonoDomain *domain);
640 static void clear_types_for_assembly (MonoAssembly *assembly);
642 /* Submodule init/cleanup */
643 static void breakpoints_init (void);
644 static void breakpoints_cleanup (void);
646 static void objrefs_init (void);
647 static void objrefs_cleanup (void);
649 static void ids_init (void);
650 static void ids_cleanup (void);
652 static void suspend_init (void);
654 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
655 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
656 static void ss_destroy (SingleStepReq *req);
658 static void start_debugger_thread (void);
660 static void finish_agent_init (gboolean on_startup);
663 parse_address (char *address, char **host, int *port)
665 char *pos = strchr (address, ':');
667 if (pos == NULL || pos == address)
670 *host = g_malloc (pos - address + 1);
671 strncpy (*host, address, pos - address);
672 (*host) [pos - address] = '\0';
674 *port = atoi (pos + 1);
682 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
683 fprintf (stderr, "Available options:\n");
684 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
685 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
686 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
687 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
688 fprintf (stderr, " suspend=y/n\t\t\tWhenever to suspend after startup.\n");
689 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
690 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
694 parse_flag (const char *option, char *flag)
696 if (!strcmp (flag, "y"))
698 else if (!strcmp (flag, "n"))
701 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
708 mono_debugger_agent_parse_options (char *options)
714 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
715 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
719 agent_config.enabled = TRUE;
720 agent_config.suspend = TRUE;
721 agent_config.server = FALSE;
723 args = g_strsplit (options, ",", -1);
724 for (ptr = args; ptr && *ptr; ptr ++) {
727 if (strncmp (arg, "transport=", 10) == 0) {
728 agent_config.transport = g_strdup (arg + 10);
729 } else if (strncmp (arg, "address=", 8) == 0) {
730 agent_config.address = g_strdup (arg + 8);
731 } else if (strncmp (arg, "loglevel=", 9) == 0) {
732 agent_config.log_level = atoi (arg + 9);
733 } else if (strncmp (arg, "logfile=", 8) == 0) {
734 agent_config.log_file = g_strdup (arg + 8);
735 } else if (strncmp (arg, "suspend=", 8) == 0) {
736 agent_config.suspend = parse_flag ("suspend", arg + 8);
737 } else if (strncmp (arg, "server=", 7) == 0) {
738 agent_config.server = parse_flag ("server", arg + 7);
739 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
740 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
741 } else if (strncmp (arg, "onthrow=", 8) == 0) {
742 /* We support multiple onthrow= options */
743 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
744 } else if (strncmp (arg, "onthrow", 7) == 0) {
745 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
746 } else if (strncmp (arg, "help", 4) == 0) {
749 } else if (strncmp (arg, "timeout=", 8) == 0) {
750 agent_config.timeout = atoi (arg + 8);
751 } else if (strncmp (arg, "launch=", 7) == 0) {
752 agent_config.launch = g_strdup (arg + 7);
753 } else if (strncmp (arg, "embedding=", 10) == 0) {
754 agent_config.embedding = atoi (arg + 10) == 1;
761 if (agent_config.transport == NULL) {
762 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
765 if (strcmp (agent_config.transport, "dt_socket") != 0) {
766 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
770 if (agent_config.address == NULL && !agent_config.server) {
771 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
775 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
776 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
782 mono_debugger_agent_init (void)
784 if (!agent_config.enabled)
787 /* Need to know whenever a thread has acquired the loader mutex */
788 mono_loader_lock_track_ownership (TRUE);
790 event_requests = g_ptr_array_new ();
792 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
793 mono_cond_init (&debugger_thread_exited_cond, NULL);
795 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
796 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
797 mono_profiler_install_runtime_initialized (runtime_initialized);
798 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
799 mono_profiler_install_thread (thread_startup, thread_end);
800 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
801 mono_profiler_install_jit_end (jit_end);
802 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
804 debugger_tls_id = TlsAlloc ();
806 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
807 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
809 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
810 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
812 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
813 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
815 loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
816 pending_assembly_loads = g_ptr_array_new ();
817 pending_type_loads = g_ptr_array_new ();
818 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
820 log_level = agent_config.log_level;
822 embedding = agent_config.embedding;
824 if (agent_config.log_file) {
825 log_file = fopen (agent_config.log_file, "w+");
827 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
839 mini_get_debug_options ()->gen_seq_points = TRUE;
841 * This is needed because currently we don't handle liveness info.
843 mini_get_debug_options ()->mdb_optimizations = TRUE;
845 /* This is needed because we can't set local variables in registers yet */
846 mono_disable_optimizations (MONO_OPT_LINEARS);
848 if (!agent_config.onuncaught && !agent_config.onthrow)
849 finish_agent_init (TRUE);
855 * Finish the initialization of the agent. This involves connecting the transport
856 * and starting the agent thread. This is either done at startup, or
857 * in response to some event like an unhandled exception.
860 finish_agent_init (gboolean on_startup)
866 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
869 if (agent_config.launch) {
872 // FIXME: Generated address
873 // FIXME: Races with transport_connect ()
875 argv [0] = agent_config.launch;
876 argv [1] = agent_config.transport;
877 argv [2] = agent_config.address;
880 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
882 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
887 if (agent_config.address) {
888 res = parse_address (agent_config.address, &host, &port);
895 transport_connect (host, port);
898 /* Do some which is usually done after sending the VMStart () event */
899 vm_start_event_sent = TRUE;
900 start_debugger_thread ();
905 mono_debugger_agent_cleanup (void)
910 /* This will interrupt the agent thread */
911 /* Close the read part only so it can still send back replies */
913 shutdown (conn_fd, SD_RECEIVE);
915 shutdown (conn_fd, SHUT_RD);
919 * Wait for the thread to exit.
921 * If we continue with the shutdown without waiting for it, then the client might
922 * not receive an answer to its last command like a resume.
923 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
926 //WaitForSingleObject (debugger_thread_handle, INFINITE);
927 if (GetCurrentThreadId () != debugger_thread_id) {
928 mono_mutex_lock (&debugger_thread_exited_mutex);
929 while (!debugger_thread_exited) {
931 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
932 mono_mutex_unlock (&debugger_thread_exited_mutex);
934 mono_mutex_lock (&debugger_thread_exited_mutex);
937 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
940 mono_mutex_unlock (&debugger_thread_exited_mutex);
943 breakpoints_cleanup ();
948 shutdown (conn_fd, SD_BOTH);
950 shutdown (conn_fd, SHUT_RDWR);
953 mono_mutex_destroy (&debugger_thread_exited_mutex);
954 mono_cond_destroy (&debugger_thread_exited_cond);
960 * recv() + handle incomplete reads and EINTR
963 recv_length (int fd, void *buf, int len, int flags)
969 res = recv (fd, (char *) buf + total, len - total, flags);
972 } while ((res > 0 && total < len) || (res == -1 && errno == EINTR));
977 #define HAVE_GETADDRINFO 1
983 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
986 transport_connect (const char *host, int port)
988 #ifdef HAVE_GETADDRINFO
989 struct addrinfo hints;
990 struct addrinfo *result, *rp;
992 struct hostent *result;
995 char port_string [128];
996 char handshake_msg [128];
1002 sprintf (port_string, "%d", port);
1004 mono_network_init ();
1006 /* Obtain address(es) matching host/port */
1007 #ifdef HAVE_GETADDRINFO
1008 memset (&hints, 0, sizeof (struct addrinfo));
1009 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1010 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1012 hints.ai_protocol = 0; /* Any protocol */
1014 s = getaddrinfo (host, port_string, &hints, &result);
1016 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1020 /* The PS3 doesn't even have _r or hstrerror () */
1021 result = gethostbyname (host);
1023 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1028 if (agent_config.server) {
1029 #ifdef HAVE_GETADDRINFO
1030 /* Wait for a connection */
1032 struct sockaddr_in addr;
1035 /* No address, generate one */
1036 sfd = socket (AF_INET, SOCK_STREAM, 0);
1039 /* This will bind the socket to a random port */
1040 res = listen (sfd, 16);
1042 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
1046 addrlen = sizeof (addr);
1047 memset (&addr, 0, sizeof (addr));
1048 res = getsockname (sfd, &addr, &addrlen);
1049 g_assert (res == 0);
1052 port = ntohs (addr.sin_port);
1054 /* Emit the address to stdout */
1055 /* FIXME: Should print another interface, not localhost */
1056 printf ("%s:%d\n", host, port);
1058 /* Listen on the provided address */
1059 for (rp = result; rp != NULL; rp = rp->ai_next) {
1060 sfd = socket (rp->ai_family, rp->ai_socktype,
1065 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1069 res = listen (sfd, 16);
1077 * this function is not present on win2000 which we still support, and the
1078 * workaround described here:
1079 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1080 * only works with MSVC.
1082 #ifdef HAVE_GETADDRINFO
1083 freeaddrinfo (result);
1088 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1090 if (agent_config.timeout) {
1095 tv.tv_usec = agent_config.timeout * 1000;
1097 FD_SET (sfd, &readfds);
1098 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1100 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1105 conn_fd = accept (sfd, NULL, NULL);
1106 if (conn_fd == -1) {
1107 fprintf (stderr, "debugger-agent: Unable to listen on %s:%d\n", host, port);
1111 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1114 #endif /* HAVE_GETADDRINFO */
1116 /* Connect to the specified address */
1117 #ifdef HAVE_GETADDRINFO
1118 /* FIXME: Respect the timeout */
1119 for (rp = result; rp != NULL; rp = rp->ai_next) {
1120 sfd = socket (rp->ai_family, rp->ai_socktype,
1125 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1126 break; /* Success */
1132 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1136 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1138 g_assert_not_reached ();
1139 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1141 g_assert_not_reached ();
1147 /* See the comment above */
1148 #ifdef HAVE_GETADDRINFO
1149 freeaddrinfo (result);
1154 /* Write handshake message */
1155 sprintf (handshake_msg, "DWP-Handshake");
1157 res = send (conn_fd, handshake_msg, strlen (handshake_msg), 0);
1158 } while (res == -1 && errno == EINTR);
1159 g_assert (res != -1);
1162 res = recv_length (conn_fd, buf, strlen (handshake_msg), 0);
1163 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1164 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1169 * To support older clients, the client sends its protocol version after connecting
1170 * using a command. Until that is received, default to our protocol version.
1172 major_version = MAJOR_VERSION;
1173 minor_version = MINOR_VERSION;
1174 protocol_version_set = FALSE;
1177 * Set TCP_NODELAY on the socket so the client receives events/command
1178 * results immediately.
1182 int result = setsockopt(conn_fd,
1187 g_assert (result >= 0);
1192 transport_send (guint8 *data, int len)
1197 res = send (conn_fd, data, len, 0);
1198 } while (res == -1 && errno == EINTR);
1206 start_debugger_thread (void)
1210 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1211 g_assert (debugger_thread_handle);
1215 * Functions to decode protocol data
1219 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1222 g_assert (*endbuf <= limit);
1227 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1230 g_assert (*endbuf <= limit);
1232 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1235 static inline gint64
1236 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1238 guint32 high = decode_int (buf, &buf, limit);
1239 guint32 low = decode_int (buf, &buf, limit);
1243 return ((((guint64)high) << 32) | ((guint64)low));
1247 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1249 return decode_int (buf, endbuf, limit);
1253 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1255 int len = decode_int (buf, &buf, limit);
1258 s = g_malloc (len + 1);
1261 memcpy (s, buf, len);
1270 * Functions to encode protocol data
1274 guint8 *buf, *p, *end;
1278 buffer_init (Buffer *buf, int size)
1280 buf->buf = g_malloc (size);
1282 buf->end = buf->buf + size;
1286 buffer_make_room (Buffer *buf, int size)
1288 if (buf->end - buf->p < size) {
1289 int new_size = buf->end - buf->buf + size + 32;
1290 guint8 *p = g_realloc (buf->buf, new_size);
1291 size = buf->p - buf->buf;
1294 buf->end = buf->buf + new_size;
1299 buffer_add_byte (Buffer *buf, guint8 val)
1301 buffer_make_room (buf, 1);
1307 buffer_add_int (Buffer *buf, guint32 val)
1309 buffer_make_room (buf, 4);
1310 buf->p [0] = (val >> 24) & 0xff;
1311 buf->p [1] = (val >> 16) & 0xff;
1312 buf->p [2] = (val >> 8) & 0xff;
1313 buf->p [3] = (val >> 0) & 0xff;
1318 buffer_add_long (Buffer *buf, guint64 l)
1320 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1321 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1325 buffer_add_id (Buffer *buf, int id)
1327 buffer_add_int (buf, (guint64)id);
1331 buffer_add_data (Buffer *buf, guint8 *data, int len)
1333 buffer_make_room (buf, len);
1334 memcpy (buf->p, data, len);
1339 buffer_add_string (Buffer *buf, const char *str)
1344 buffer_add_int (buf, 0);
1347 buffer_add_int (buf, len);
1348 buffer_add_data (buf, (guint8*)str, len);
1353 buffer_free (Buffer *buf)
1359 send_packet (int command_set, int command, Buffer *data)
1365 id = InterlockedIncrement (&packet_id);
1367 len = data->p - data->buf + 11;
1368 buffer_init (&buf, len);
1369 buffer_add_int (&buf, len);
1370 buffer_add_int (&buf, id);
1371 buffer_add_byte (&buf, 0); /* flags */
1372 buffer_add_byte (&buf, command_set);
1373 buffer_add_byte (&buf, command);
1374 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1376 res = transport_send (buf.buf, len);
1384 send_reply_packet (int id, int error, Buffer *data)
1390 len = data->p - data->buf + 11;
1391 buffer_init (&buf, len);
1392 buffer_add_int (&buf, len);
1393 buffer_add_int (&buf, id);
1394 buffer_add_byte (&buf, 0x80); /* flags */
1395 buffer_add_byte (&buf, (error >> 8) & 0xff);
1396 buffer_add_byte (&buf, error);
1397 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1399 res = transport_send (buf.buf, len);
1411 * Represents an object accessible by the debugger client.
1414 /* Unique id used in the wire protocol to refer to objects */
1417 * A weakref gc handle pointing to the object. The gc handle is used to
1418 * detect if the object was garbage collected.
1423 /* Maps objid -> ObjRef */
1424 static GHashTable *objrefs;
1427 free_objref (gpointer value)
1431 mono_gchandle_free (o->handle);
1439 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1443 objrefs_cleanup (void)
1445 g_hash_table_destroy (objrefs);
1449 static GHashTable *obj_to_objref;
1452 * Return an ObjRef for OBJ.
1455 get_objref (MonoObject *obj)
1458 GSList *reflist = NULL, *l;
1464 mono_loader_lock ();
1467 obj_to_objref = g_hash_table_new (NULL, NULL);
1469 /* FIXME: The tables can grow indefinitely */
1471 if (mono_gc_is_moving ()) {
1473 * Objects can move, so use a hash table mapping hash codes to lists of
1474 * ObjRef structures.
1476 hash = mono_object_hash (obj);
1478 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1479 for (l = reflist; l; l = l->next) {
1481 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1482 mono_loader_unlock ();
1487 /* Use a hash table with masked pointers to internalize object references */
1488 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1489 /* ref might refer to a different object with the same addr which was GCd */
1490 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1491 mono_loader_unlock ();
1496 ref = g_new0 (ObjRef, 1);
1497 ref->id = InterlockedIncrement (&objref_id);
1498 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1500 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1502 if (mono_gc_is_moving ()) {
1503 reflist = g_slist_append (reflist, ref);
1504 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1506 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1509 mono_loader_unlock ();
1515 get_objid (MonoObject *obj)
1517 return get_objref (obj)->id;
1521 * Set OBJ to the object identified by OBJID.
1522 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1526 get_object_allow_null (int objid, MonoObject **obj)
1536 return ERR_INVALID_OBJECT;
1538 mono_loader_lock ();
1540 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1543 *obj = mono_gchandle_get_target (ref->handle);
1544 mono_loader_unlock ();
1546 return ERR_INVALID_OBJECT;
1549 mono_loader_unlock ();
1550 return ERR_INVALID_OBJECT;
1555 get_object (int objid, MonoObject **obj)
1557 int err = get_object_allow_null (objid, obj);
1562 return ERR_INVALID_OBJECT;
1567 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1569 return decode_id (buf, endbuf, limit);
1573 buffer_add_objid (Buffer *buf, MonoObject *o)
1575 buffer_add_id (buf, get_objid (o));
1594 * Represents a runtime structure accessible to the debugger client
1597 /* Unique id used in the wire protocol */
1599 /* Domain of the runtime structure, NULL if the domain was unloaded */
1606 MonoAssembly *assembly;
1607 MonoClassField *field;
1609 MonoProperty *property;
1614 /* Maps runtime structure -> Id */
1615 GHashTable *val_to_id [ID_NUM];
1619 static GPtrArray *ids [ID_NUM];
1626 for (i = 0; i < ID_NUM; ++i)
1627 ids [i] = g_ptr_array_new ();
1635 for (i = 0; i < ID_NUM; ++i) {
1637 for (j = 0; j < ids [i]->len; ++j)
1638 g_free (g_ptr_array_index (ids [i], j));
1639 g_ptr_array_free (ids [i], TRUE);
1646 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1648 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1652 for (i = 0; i < ID_NUM; ++i)
1653 if (info->val_to_id [i])
1654 g_hash_table_destroy (info->val_to_id [i]);
1658 domain_jit_info (domain)->agent_info = NULL;
1660 /* Clear ids referencing structures in the domain */
1661 for (i = 0; i < ID_NUM; ++i) {
1663 for (j = 0; j < ids [i]->len; ++j) {
1664 Id *id = g_ptr_array_index (ids [i], j);
1665 if (id->domain == domain)
1671 mono_loader_lock ();
1672 g_hash_table_remove (domains, domain);
1673 mono_loader_unlock ();
1677 get_id (MonoDomain *domain, IdType type, gpointer val)
1680 AgentDomainInfo *info;
1685 mono_loader_lock ();
1687 mono_domain_lock (domain);
1689 if (!domain_jit_info (domain)->agent_info)
1690 domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1691 info = domain_jit_info (domain)->agent_info;
1692 if (info->val_to_id [type] == NULL)
1693 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1695 id = g_hash_table_lookup (info->val_to_id [type], val);
1697 mono_domain_unlock (domain);
1698 mono_loader_unlock ();
1702 id = g_new0 (Id, 1);
1704 id->id = ids [type]->len + 1;
1705 id->domain = domain;
1708 g_hash_table_insert (info->val_to_id [type], val, id);
1710 mono_domain_unlock (domain);
1712 g_ptr_array_add (ids [type], id);
1714 mono_loader_unlock ();
1719 static inline gpointer
1720 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1724 int id = decode_id (buf, endbuf, limit);
1733 // FIXME: error handling
1734 mono_loader_lock ();
1735 g_assert (id > 0 && id <= ids [type]->len);
1737 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1738 mono_loader_unlock ();
1740 if (res->domain == NULL) {
1741 *err = ERR_UNLOADED;
1746 *domain = res->domain;
1748 return res->data.val;
1752 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1754 buffer_add_id (buf, get_id (domain, type, val));
1757 static inline MonoClass*
1758 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1760 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1763 static inline MonoAssembly*
1764 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1766 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1769 static inline MonoImage*
1770 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1772 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1775 static inline MonoMethod*
1776 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1778 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1781 static inline MonoClassField*
1782 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1784 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1787 static inline MonoDomain*
1788 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1790 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1793 static inline MonoProperty*
1794 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1796 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1800 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1802 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1806 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1808 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1812 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1814 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1818 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1820 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1824 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1826 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1830 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1832 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1836 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1838 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1841 static void invoke_method (void);
1848 * save_thread_context:
1850 * Set CTX as the current threads context which is used for computing stack traces.
1851 * This function is signal-safe.
1854 save_thread_context (MonoContext *ctx)
1856 DebuggerTlsData *tls;
1858 tls = TlsGetValue (debugger_tls_id);
1862 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1864 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1865 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1867 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1871 tls->lmf = mono_get_lmf ();
1872 tls->domain = mono_domain_get ();
1873 tls->has_context = TRUE;
1876 /* The number of times the runtime is suspended */
1877 static gint32 suspend_count;
1879 /* Number of threads suspended */
1881 * If this is equal to the size of thread_to_tls, the runtime is considered
1884 static gint32 threads_suspend_count;
1886 static mono_mutex_t suspend_mutex;
1888 /* Cond variable used to wait for suspend_count becoming 0 */
1889 static mono_cond_t suspend_cond;
1891 /* Semaphore used to wait for a thread becoming suspended */
1892 static MonoSemType suspend_sem;
1897 mono_mutex_init (&suspend_mutex, NULL);
1898 mono_cond_init (&suspend_cond, NULL);
1899 MONO_SEM_INIT (&suspend_sem, 0);
1904 StackFrameInfo last_frame;
1905 gboolean last_frame_set;
1908 } GetLastFrameUserData;
1911 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
1913 GetLastFrameUserData *data = user_data;
1915 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
1918 if (!data->last_frame_set) {
1919 /* Store the last frame */
1920 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
1921 data->last_frame_set = TRUE;
1924 /* Store the context/lmf for the frame above the last frame */
1925 memcpy (&data->ctx, ctx, sizeof (MonoContext));
1926 data->lmf = info->lmf;
1933 * mono_debugger_agent_thread_interrupt:
1935 * Called by the abort signal handler.
1936 * Should be signal safe.
1939 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
1941 DebuggerTlsData *tls;
1946 tls = TlsGetValue (debugger_tls_id);
1951 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
1952 * guarantee the signal handler will be called that many times. Instead of tracking
1953 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
1954 * has been requested that hasn't been handled yet, otherwise we can have threads
1955 * refuse to die when VM_EXIT is called
1957 #if defined(__APPLE__)
1958 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
1962 * We use interrupt_count to determine whenever this interrupt should be processed
1963 * by us or the normal interrupt processing code in the signal handler.
1964 * There is no race here with notify_thread (), since the signal is sent after
1965 * incrementing interrupt_count.
1967 if (tls->interrupt_count == 0)
1970 InterlockedDecrement (&tls->interrupt_count);
1973 // FIXME: Races when the thread leaves managed code before hitting a single step
1977 /* Running managed code, will be suspended by the single step code */
1978 DEBUG (1, printf ("[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)GetCurrentThreadId (), ji->method->name, mono_arch_ip_from_context (sigctx)));
1982 * Running native code, will be suspended when it returns to/enters
1983 * managed code. Treat it as already suspended.
1984 * This might interrupt the code in process_single_step_inner (), we use the
1985 * tls->suspending flag to avoid races when that happens.
1987 if (!tls->suspended && !tls->suspending) {
1989 GetLastFrameUserData data;
1991 // FIXME: printf is not signal safe, but this is only used during
1992 // debugger debugging
1994 DEBUG (1, printf ("[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)GetCurrentThreadId (), mono_arch_ip_from_context (sigctx)));
1995 //save_thread_context (&ctx);
1998 /* Already terminated */
2002 * We are in a difficult position: we want to be able to provide stack
2003 * traces for this thread, but we can't use the current ctx+lmf, since
2004 * the thread is still running, so it might return to managed code,
2005 * making these invalid.
2006 * So we start a stack walk and save the first frame, along with the
2007 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2008 * suspended when it returns to managed code, so the parent's ctx should
2011 data.last_frame_set = FALSE;
2013 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2014 mono_walk_stack (get_last_frame, mono_domain_get (), &ctx, FALSE, tls->thread, mono_get_lmf (), &data);
2016 if (data.last_frame_set) {
2017 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2018 memcpy (&tls->async_ctx, &data.ctx, sizeof (MonoContext));
2019 tls->async_lmf = data.lmf;
2020 tls->has_async_ctx = TRUE;
2021 tls->domain = mono_domain_get ();
2022 memcpy (&tls->ctx, &ctx, sizeof (MonoContext));
2024 tls->has_async_ctx = FALSE;
2027 mono_memory_barrier ();
2029 tls->suspended = TRUE;
2030 MONO_SEM_POST (&suspend_sem);
2037 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2040 mono_debugger_agent_thread_interrupt (NULL, NULL);
2042 #endif /* HOST_WIN32 */
2045 * reset_native_thread_suspend_state:
2047 * Reset the suspended flag on native threads
2050 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2052 DebuggerTlsData *tls = value;
2054 if (!tls->really_suspended && tls->suspended)
2055 tls->suspended = FALSE;
2061 * Notify a thread that it needs to suspend.
2064 notify_thread (gpointer key, gpointer value, gpointer user_data)
2066 MonoInternalThread *thread = key;
2067 DebuggerTlsData *tls = value;
2068 gsize tid = thread->tid;
2070 if (GetCurrentThreadId () == tid || tls->terminated)
2073 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2076 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2077 * guarantee the signal handler will be called that many times. Instead of tracking
2078 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2079 * has been requested that hasn't been handled yet, otherwise we can have threads
2080 * refuse to die when VM_EXIT is called
2082 #if defined(__APPLE__)
2083 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2087 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2088 * of things like breaking waits etc. which we don't want.
2090 InterlockedIncrement (&tls->interrupt_count);
2093 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2095 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2097 mono_thread_kill (thread, mono_thread_get_abort_signal ());
2102 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2104 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2107 if (debugger_thread_id == GetCurrentThreadId ())
2110 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2111 if (suspend_count - tls->resume_count > 0)
2112 tls->suspending = TRUE;
2114 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2116 if (suspend_count - tls->resume_count == 0) {
2118 * We are executing a single threaded invoke but the single step for
2119 * suspending is still active.
2120 * FIXME: This slows down single threaded invokes.
2122 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2126 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2128 /* Can't suspend in these methods */
2129 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2132 save_thread_context (ctx);
2140 * Increase the suspend count of the VM. While the suspend count is greater
2141 * than 0, runtime threads are suspended at certain points during execution.
2146 mono_loader_lock ();
2148 mono_mutex_lock (&suspend_mutex);
2152 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2154 if (suspend_count == 1) {
2155 // FIXME: Is it safe to call this inside the lock ?
2156 start_single_stepping ();
2157 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2160 mono_mutex_unlock (&suspend_mutex);
2162 mono_loader_unlock ();
2168 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2176 g_assert (debugger_thread_id == GetCurrentThreadId ());
2178 mono_loader_lock ();
2180 mono_mutex_lock (&suspend_mutex);
2182 g_assert (suspend_count > 0);
2185 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2187 if (suspend_count == 0) {
2188 // FIXME: Is it safe to call this inside the lock ?
2189 stop_single_stepping ();
2190 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2193 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2194 err = mono_cond_broadcast (&suspend_cond);
2195 g_assert (err == 0);
2197 mono_mutex_unlock (&suspend_mutex);
2198 //g_assert (err == 0);
2200 mono_loader_unlock ();
2206 * Resume just one thread.
2209 resume_thread (MonoInternalThread *thread)
2212 DebuggerTlsData *tls;
2214 g_assert (debugger_thread_id == GetCurrentThreadId ());
2216 mono_loader_lock ();
2218 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2221 mono_mutex_lock (&suspend_mutex);
2223 g_assert (suspend_count > 0);
2225 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2227 tls->resume_count += suspend_count;
2230 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2231 * but only the one whose resume_count field is > 0 will be resumed.
2233 err = mono_cond_broadcast (&suspend_cond);
2234 g_assert (err == 0);
2236 mono_mutex_unlock (&suspend_mutex);
2237 //g_assert (err == 0);
2239 mono_loader_unlock ();
2243 invalidate_frames (DebuggerTlsData *tls)
2248 tls = TlsGetValue (debugger_tls_id);
2251 for (i = 0; i < tls->frame_count; ++i) {
2252 if (tls->frames [i]->jit)
2253 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2254 g_free (tls->frames [i]);
2256 g_free (tls->frames);
2257 tls->frame_count = 0;
2264 * Suspend the current thread until the runtime is resumed. If the thread has a
2265 * pending invoke, then the invoke is executed before this function returns.
2268 suspend_current (void)
2271 DebuggerTlsData *tls;
2273 g_assert (debugger_thread_id != GetCurrentThreadId ());
2275 if (mono_loader_lock_is_owned_by_self ()) {
2277 * If we own the loader mutex, can't suspend until we release it, since the
2278 * whole runtime can deadlock otherwise.
2283 tls = TlsGetValue (debugger_tls_id);
2286 mono_mutex_lock (&suspend_mutex);
2288 tls->suspending = FALSE;
2289 tls->really_suspended = TRUE;
2291 if (!tls->suspended) {
2292 tls->suspended = TRUE;
2293 MONO_SEM_POST (&suspend_sem);
2296 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2298 while (suspend_count - tls->resume_count > 0) {
2300 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2302 mono_mutex_unlock (&suspend_mutex);
2304 mono_mutex_lock (&suspend_mutex);
2310 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2311 g_assert (err == 0);
2315 tls->suspended = FALSE;
2316 tls->really_suspended = FALSE;
2318 threads_suspend_count --;
2320 mono_mutex_unlock (&suspend_mutex);
2322 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2324 if (tls->pending_invoke) {
2325 /* Save the original context */
2326 tls->pending_invoke->has_ctx = TRUE;
2327 memcpy (&tls->pending_invoke->ctx, &tls->ctx, sizeof (MonoContext));
2332 /* The frame info becomes invalid after a resume */
2333 tls->has_context = FALSE;
2334 tls->has_async_ctx = FALSE;
2335 invalidate_frames (NULL);
2339 count_thread (gpointer key, gpointer value, gpointer user_data)
2341 DebuggerTlsData *tls = value;
2343 if (!tls->suspended && !tls->terminated)
2344 *(int*)user_data = *(int*)user_data + 1;
2348 count_threads_to_wait_for (void)
2352 mono_loader_lock ();
2353 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2354 mono_loader_unlock ();
2362 * Wait until the runtime is completely suspended.
2365 wait_for_suspend (void)
2367 int nthreads, nwait, err;
2368 gboolean waited = FALSE;
2370 // FIXME: Threads starting/stopping ?
2371 mono_loader_lock ();
2372 nthreads = mono_g_hash_table_size (thread_to_tls);
2373 mono_loader_unlock ();
2376 nwait = count_threads_to_wait_for ();
2378 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2379 err = MONO_SEM_WAIT (&suspend_sem);
2380 g_assert (err == 0);
2388 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2394 * Return whenever the runtime is suspended.
2399 return count_threads_to_wait_for () == 0;
2403 * find_seq_point_for_native_offset:
2405 * Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2406 * should be the location of a sequence point.
2409 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2411 MonoSeqPointInfo *seq_points;
2414 mono_domain_lock (domain);
2415 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2416 mono_domain_unlock (domain);
2417 g_assert (seq_points);
2421 for (i = 0; i < seq_points->len; ++i) {
2422 if (seq_points->seq_points [i].native_offset == native_offset)
2423 return &seq_points->seq_points [i];
2430 * find_next_seq_point_for_native_offset:
2432 * Find the first sequence point after NATIVE_OFFSET.
2435 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2437 MonoSeqPointInfo *seq_points;
2440 mono_domain_lock (domain);
2441 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2442 mono_domain_unlock (domain);
2443 g_assert (seq_points);
2447 for (i = 0; i < seq_points->len; ++i) {
2448 if (seq_points->seq_points [i].native_offset >= native_offset)
2449 return &seq_points->seq_points [i];
2456 * find_prev_seq_point_for_native_offset:
2458 * Find the first sequence point before NATIVE_OFFSET.
2461 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2463 MonoSeqPointInfo *seq_points;
2466 mono_domain_lock (domain);
2467 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2468 mono_domain_unlock (domain);
2469 g_assert (seq_points);
2473 for (i = seq_points->len - 1; i >= 0; --i) {
2474 if (seq_points->seq_points [i].native_offset <= native_offset)
2475 return &seq_points->seq_points [i];
2484 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2485 * should be the location of a sequence point.
2488 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2490 MonoSeqPointInfo *seq_points;
2493 mono_domain_lock (domain);
2494 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2495 mono_domain_unlock (domain);
2496 g_assert (seq_points);
2500 for (i = 0; i < seq_points->len; ++i) {
2501 if (seq_points->seq_points [i].il_offset == il_offset)
2502 return &seq_points->seq_points [i];
2509 * compute_il_offset:
2511 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2512 * a location of a sequence point.
2513 * We use this function instead of mono_debug_il_offset_from_address () etc,
2514 * which doesn't seem to work in a lot of cases.
2517 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2519 MonoSeqPointInfo *seq_points;
2520 int i, last_il_offset, seq_il_offset, seq_native_offset;
2522 mono_domain_lock (domain);
2523 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2524 mono_domain_unlock (domain);
2525 g_assert (seq_points);
2527 last_il_offset = -1;
2529 /* Find the sequence point */
2530 for (i = 0; i < seq_points->len; ++i) {
2531 seq_il_offset = seq_points->seq_points [i].il_offset;
2532 seq_native_offset = seq_points->seq_points [i].native_offset;
2534 if (seq_native_offset > native_offset)
2536 last_il_offset = seq_il_offset;
2539 return last_il_offset;
2543 DebuggerTlsData *tls;
2545 } ComputeFramesUserData;
2548 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2550 ComputeFramesUserData *ud = user_data;
2552 MonoMethod *method, *actual_method;
2554 if (info->type != FRAME_TYPE_MANAGED) {
2555 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2556 /* Mark the last frame as an invoke frame */
2558 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2564 method = info->ji->method;
2566 method = info->method;
2567 actual_method = info->actual_method;
2569 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2572 if (info->il_offset == -1) {
2573 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2574 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2577 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));
2579 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2581 * mono_arch_find_jit_info () returns the context stored in the LMF for
2582 * native frames, but it should unwind once. This is why we have duplicate
2583 * frames on the stack sometimes.
2584 * !managed also seems to be set for dynamic methods.
2589 frame = g_new0 (StackFrame, 1);
2590 frame->method = method;
2591 frame->actual_method = actual_method;
2592 frame->il_offset = info->il_offset;
2593 frame->native_offset = info->native_offset;
2596 frame->has_ctx = TRUE;
2598 frame->domain = info->domain;
2600 ud->frames = g_slist_append (ud->frames, frame);
2606 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2608 ComputeFramesUserData *ud = user_data;
2611 * 'tls->filter_ctx' is the location of the throw site.
2613 * mono_walk_stack() will never actually hit the throw site, but unwind
2614 * directly from the filter to the call site; we abort stack unwinding here
2615 * once this happens and resume from the throw site.
2618 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_ctx))
2621 return process_frame (info, ctx, user_data);
2625 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2627 ComputeFramesUserData user_data;
2629 int i, findex, new_frame_count;
2630 StackFrame **new_frames, *f;
2632 // FIXME: Locking on tls
2633 if (tls->frames && tls->frames_up_to_date)
2636 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2638 user_data.tls = tls;
2639 user_data.frames = NULL;
2640 if (tls->terminated) {
2641 tls->frame_count = 0;
2643 } if (!tls->really_suspended && tls->has_async_ctx) {
2644 /* Have to use the state saved by the signal handler */
2645 process_frame (&tls->async_last_frame, NULL, &user_data);
2646 mono_walk_stack (process_frame, tls->domain, &tls->async_ctx, FALSE, thread, tls->async_lmf, &user_data);
2647 } else if (tls->has_filter_ctx) {
2649 * We are inside an exception filter.
2651 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
2653 if (tls->has_context)
2654 mono_walk_stack (process_filter_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
2656 * After that, we resume unwinding from the location where the exception has been thrown.
2658 mono_walk_stack (process_frame, tls->domain, &tls->filter_ctx, FALSE, thread, tls->filter_lmf, &user_data);
2659 } else if (tls->has_context) {
2660 mono_walk_stack (process_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
2663 tls->frame_count = 0;
2667 new_frame_count = g_slist_length (user_data.frames);
2668 new_frames = g_new0 (StackFrame*, new_frame_count);
2670 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2674 * Reuse the id for already existing stack frames, so invokes don't invalidate
2675 * the still valid stack frames.
2677 for (i = 0; i < tls->frame_count; ++i) {
2678 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2679 f->id = tls->frames [i]->id;
2684 if (i >= tls->frame_count)
2685 f->id = InterlockedIncrement (&frame_id);
2687 new_frames [findex ++] = f;
2690 g_slist_free (user_data.frames);
2692 invalidate_frames (tls);
2694 tls->frames = new_frames;
2695 tls->frame_count = new_frame_count;
2696 tls->frames_up_to_date = TRUE;
2704 * create_event_list:
2706 * Return a list of event request ids matching EVENT, starting from REQS, which
2707 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2709 * We return request ids, instead of requests, to simplify threading, since
2710 * requests could be deleted anytime when the loader lock is not held.
2711 * LOCKING: Assumes the loader lock is held.
2714 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
2717 GSList *events = NULL;
2719 *suspend_policy = SUSPEND_POLICY_NONE;
2722 reqs = event_requests;
2727 for (i = 0; i < reqs->len; ++i) {
2728 EventRequest *req = g_ptr_array_index (reqs, i);
2729 if (req->event_kind == event) {
2730 gboolean filtered = FALSE;
2733 for (j = 0; j < req->nmodifiers; ++j) {
2734 Modifier *mod = &req->modifiers [j];
2736 if (mod->kind == MOD_KIND_COUNT) {
2738 if (mod->data.count > 0) {
2739 if (mod->data.count > 0) {
2741 if (mod->data.count == 0)
2745 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2746 if (mod->data.thread != mono_thread_internal_current ())
2748 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
2749 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
2751 if (ei->caught && !mod->caught)
2753 if (!ei->caught && !mod->uncaught)
2755 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2757 gboolean found = FALSE;
2758 MonoAssembly **assemblies = mod->data.assemblies;
2761 for (k = 0; assemblies [k]; ++k)
2762 if (assemblies [k] == ji->method->klass->image->assembly)
2771 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2772 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2777 /* Send a VM START/DEATH event by default */
2778 if (event == EVENT_KIND_VM_START)
2779 events = g_slist_append (events, GINT_TO_POINTER (0));
2780 if (event == EVENT_KIND_VM_DEATH)
2781 events = g_slist_append (events, GINT_TO_POINTER (0));
2786 static G_GNUC_UNUSED const char*
2787 event_to_string (EventKind event)
2790 case EVENT_KIND_VM_START: return "VM_START";
2791 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2792 case EVENT_KIND_THREAD_START: return "THREAD_START";
2793 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2794 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2795 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2796 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2797 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2798 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2799 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2800 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2801 case EVENT_KIND_STEP: return "STEP";
2802 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2803 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2805 g_assert_not_reached ();
2812 * Send an event to the client, suspending the vm if needed.
2813 * LOCKING: Since this can suspend the calling thread, no locks should be held
2815 * The EVENTS list is freed by this function.
2818 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2822 MonoDomain *domain = mono_domain_get ();
2828 if (!vm_start_event_sent && event != EVENT_KIND_VM_START)
2829 // FIXME: We miss those events
2832 if (vm_death_event_sent)
2835 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH)
2844 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
2845 // FIXME: Send these with a NULL thread, don't suspend the current thread
2848 buffer_init (&buf, 128);
2849 buffer_add_byte (&buf, suspend_policy);
2850 buffer_add_int (&buf, g_slist_length (events)); // n of events
2852 for (l = events; l; l = l->next) {
2853 buffer_add_byte (&buf, event); // event kind
2854 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
2856 thread = mono_thread_current ();
2858 if (event == EVENT_KIND_VM_START)
2860 else if (event == EVENT_KIND_THREAD_START)
2861 g_assert (mono_thread_internal_current () == arg);
2863 buffer_add_objid (&buf, (MonoObject*)thread); // thread
2866 case EVENT_KIND_THREAD_START:
2867 case EVENT_KIND_THREAD_DEATH:
2869 case EVENT_KIND_APPDOMAIN_CREATE:
2870 case EVENT_KIND_APPDOMAIN_UNLOAD:
2871 buffer_add_domainid (&buf, arg);
2873 case EVENT_KIND_METHOD_ENTRY:
2874 case EVENT_KIND_METHOD_EXIT:
2875 buffer_add_methodid (&buf, domain, arg);
2877 case EVENT_KIND_ASSEMBLY_LOAD:
2878 case EVENT_KIND_ASSEMBLY_UNLOAD:
2879 buffer_add_assemblyid (&buf, domain, arg);
2881 case EVENT_KIND_TYPE_LOAD:
2882 buffer_add_typeid (&buf, domain, arg);
2884 case EVENT_KIND_BREAKPOINT:
2885 case EVENT_KIND_STEP:
2886 buffer_add_methodid (&buf, domain, arg);
2887 buffer_add_long (&buf, il_offset);
2889 case EVENT_KIND_VM_START:
2890 buffer_add_domainid (&buf, mono_get_root_domain ());
2892 case EVENT_KIND_VM_DEATH:
2894 case EVENT_KIND_EXCEPTION: {
2895 EventInfo *ei = arg;
2896 buffer_add_objid (&buf, ei->exc);
2900 g_assert_not_reached ();
2904 if (event == EVENT_KIND_VM_START) {
2905 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
2906 start_debugger_thread ();
2909 if (event == EVENT_KIND_VM_DEATH) {
2910 vm_death_event_sent = TRUE;
2912 suspend_policy = SUSPEND_POLICY_NONE;
2915 if (mono_runtime_is_shutting_down ())
2916 suspend_policy = SUSPEND_POLICY_NONE;
2918 if (suspend_policy != SUSPEND_POLICY_NONE) {
2920 * Save the thread context and start suspending before sending the packet,
2921 * since we could be receiving the resume request before send_packet ()
2924 save_thread_context (ctx);
2928 send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
2930 g_slist_free (events);
2933 if (event == EVENT_KIND_VM_START)
2934 vm_start_event_sent = TRUE;
2936 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
2940 switch (suspend_policy) {
2941 case SUSPEND_POLICY_NONE:
2943 case SUSPEND_POLICY_ALL:
2946 case SUSPEND_POLICY_EVENT_THREAD:
2950 g_assert_not_reached ();
2955 process_profiler_event (EventKind event, gpointer arg)
2960 mono_loader_lock ();
2961 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
2962 mono_loader_unlock ();
2964 process_event (event, arg, 0, NULL, events, suspend_policy);
2968 runtime_initialized (MonoProfiler *prof)
2970 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
2974 runtime_shutdown (MonoProfiler *prof)
2976 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
2978 mono_debugger_agent_cleanup ();
2982 thread_startup (MonoProfiler *prof, uintptr_t tid)
2984 MonoInternalThread *thread = mono_thread_internal_current ();
2985 MonoInternalThread *old_thread;
2986 DebuggerTlsData *tls;
2988 if (tid == debugger_thread_id)
2991 g_assert (thread->tid == tid);
2993 mono_loader_lock ();
2994 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2995 mono_loader_unlock ();
2997 if (thread == old_thread) {
2999 * For some reason, thread_startup () might be called for the same thread
3000 * multiple times (attach ?).
3002 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3006 * thread_end () might not be called for some threads, and the tid could
3009 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3010 mono_loader_lock ();
3011 mono_g_hash_table_remove (thread_to_tls, old_thread);
3012 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3013 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3014 mono_loader_unlock ();
3018 tls = TlsGetValue (debugger_tls_id);
3020 // FIXME: Free this somewhere
3021 tls = g_new0 (DebuggerTlsData, 1);
3022 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3023 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3024 tls->thread = thread;
3025 TlsSetValue (debugger_tls_id, tls);
3027 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3029 mono_loader_lock ();
3030 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3031 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3032 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3033 mono_loader_unlock ();
3035 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3038 * suspend_vm () could have missed this thread, so wait for a resume.
3044 thread_end (MonoProfiler *prof, uintptr_t tid)
3046 MonoInternalThread *thread;
3047 DebuggerTlsData *tls = NULL;
3049 mono_loader_lock ();
3050 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3052 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3053 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3054 tls->terminated = TRUE;
3055 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3056 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3057 MONO_GC_UNREGISTER_ROOT (tls->thread);
3060 mono_loader_unlock ();
3062 /* We might be called for threads started before we registered the start callback */
3064 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3065 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3070 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3072 mono_loader_lock ();
3073 g_hash_table_insert (domains, domain, domain);
3074 mono_loader_unlock ();
3076 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3080 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3082 /* Invalidate each thread's frame stack */
3083 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3084 clear_breakpoints_for_domain (domain);
3085 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3089 * invalidate_each_thread:
3091 * A GHFunc to invalidate frames.
3092 * value must be a DebuggerTlsData*
3095 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3097 invalidate_frames (value);
3101 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3103 /* Sent later in jit_end () */
3104 mono_loader_lock ();
3105 g_ptr_array_add (pending_assembly_loads, assembly);
3106 mono_loader_unlock ();
3110 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3112 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3114 clear_event_requests_for_assembly (assembly);
3115 clear_types_for_assembly (assembly);
3119 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3121 #if defined(HOST_WIN32) && !defined(__GNUC__)
3122 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3124 gpointer stackptr = __builtin_frame_address (1);
3126 MonoInternalThread *thread = mono_thread_internal_current ();
3127 DebuggerTlsData *tls;
3129 mono_loader_lock ();
3131 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3132 /* Could be the debugger thread with assembly/type load hooks */
3134 tls->invoke_addr = stackptr;
3136 mono_loader_unlock ();
3140 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3143 #if defined(HOST_WIN32) && !defined(__GNUC__)
3144 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3146 gpointer stackptr = __builtin_frame_address (1);
3149 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3153 * We need to stop single stepping when exiting a runtime invoke, since if it is
3154 * a step out, it may return to native code, and thus never end.
3156 mono_loader_lock ();
3157 ss_invoke_addr = NULL;
3159 for (i = 0; i < event_requests->len; ++i) {
3160 EventRequest *req = g_ptr_array_index (event_requests, i);
3162 if (req->event_kind == EVENT_KIND_STEP) {
3163 ss_destroy (req->info);
3164 g_ptr_array_remove_index_fast (event_requests, i);
3169 mono_loader_unlock ();
3173 send_type_load (MonoClass *klass)
3175 gboolean type_load = FALSE;
3177 mono_loader_lock ();
3178 if (!g_hash_table_lookup (loaded_classes, klass)) {
3180 g_hash_table_insert (loaded_classes, klass, klass);
3182 mono_loader_unlock ();
3184 process_profiler_event (EVENT_KIND_TYPE_LOAD, klass);
3188 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3191 * We emit type load events when the first method of the type is JITted,
3192 * since the class load profiler callbacks might be called with the
3193 * loader lock held. They could also occur in the debugger thread.
3194 * Same for assembly load events.
3197 MonoAssembly *assembly = NULL;
3199 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3200 mono_loader_lock ();
3201 if (pending_assembly_loads->len > 0) {
3202 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3203 g_ptr_array_remove_index (pending_assembly_loads, 0);
3205 mono_loader_unlock ();
3208 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3213 if (!vm_start_event_sent) {
3214 /* Save these so they can be sent after the vm start event */
3215 mono_loader_lock ();
3216 g_ptr_array_add (pending_type_loads, method->klass);
3217 mono_loader_unlock ();
3219 /* Send all pending type load events */
3223 mono_loader_lock ();
3224 if (pending_type_loads->len > 0) {
3225 klass = g_ptr_array_index (pending_type_loads, 0);
3226 g_ptr_array_remove_index (pending_type_loads, 0);
3228 mono_loader_unlock ();
3230 send_type_load (klass);
3235 send_type_load (method->klass);
3239 add_pending_breakpoints (method, jinfo);
3243 * BREAKPOINTS/SINGLE STEPPING
3247 * Contains information about an inserted breakpoint.
3250 long il_offset, native_offset;
3254 } BreakpointInstance;
3257 * Contains generic information about a breakpoint.
3261 * The method where the breakpoint is placed. Can be NULL in which case it
3262 * is inserted into every method. This is used to implement method entry/
3263 * exit events. Can be a generic method definition, in which case the
3264 * breakpoint is inserted into every instance.
3270 * A list of BreakpointInstance structures describing where the breakpoint
3271 * was inserted. There could be more than one because of
3272 * generics/appdomains/method entry/exit.
3274 GPtrArray *children;
3277 /* List of breakpoints */
3278 static GPtrArray *breakpoints;
3279 /* Maps breakpoint locations to the number of breakpoints at that location */
3280 static GHashTable *bp_locs;
3283 breakpoints_init (void)
3285 breakpoints = g_ptr_array_new ();
3286 bp_locs = g_hash_table_new (NULL, NULL);
3290 * insert_breakpoint:
3292 * Insert the breakpoint described by BP into the method described by
3296 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3299 gint32 il_offset = -1, native_offset;
3300 BreakpointInstance *inst;
3303 mono_error_init (error);
3306 for (i = 0; i < seq_points->len; ++i) {
3307 il_offset = seq_points->seq_points [i].il_offset;
3308 native_offset = seq_points->seq_points [i].native_offset;
3310 if (il_offset == bp->il_offset)
3314 if (i == seq_points->len) {
3315 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);
3317 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3326 inst = g_new0 (BreakpointInstance, 1);
3327 inst->native_offset = native_offset;
3328 inst->ip = (guint8*)ji->code_start + native_offset;
3330 inst->domain = domain;
3332 mono_loader_lock ();
3334 g_ptr_array_add (bp->children, inst);
3336 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3337 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3338 mono_loader_unlock ();
3341 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3342 mono_arch_set_breakpoint (ji, inst->ip);
3348 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)il_offset));
3352 remove_breakpoint (BreakpointInstance *inst)
3354 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3356 MonoJitInfo *ji = inst->ji;
3357 guint8 *ip = inst->ip;
3359 mono_loader_lock ();
3360 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3361 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3362 mono_loader_unlock ();
3364 g_assert (count > 0);
3367 mono_arch_clear_breakpoint (ji, ip);
3374 static inline gboolean
3375 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3377 return (!bp->method || method == bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method));
3381 * add_pending_breakpoints:
3383 * Insert pending breakpoints into the newly JITted method METHOD.
3386 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3389 MonoSeqPointInfo *seq_points;
3395 domain = mono_domain_get ();
3397 mono_loader_lock ();
3399 for (i = 0; i < breakpoints->len; ++i) {
3400 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3401 gboolean found = FALSE;
3403 if (!bp_matches_method (bp, method))
3406 for (j = 0; j < bp->children->len; ++j) {
3407 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3414 mono_domain_lock (domain);
3415 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3416 mono_domain_unlock (domain);
3418 /* Could be AOT code */
3420 g_assert (seq_points);
3422 insert_breakpoint (seq_points, domain, ji, bp, NULL);
3426 mono_loader_unlock ();
3430 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
3436 mono_error_init (error);
3438 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3440 /* Might be AOTed code */
3441 code = mono_aot_get_method (domain, method);
3443 ji = mono_jit_info_table_find (domain, code);
3448 insert_breakpoint (seq_points, domain, ji, bp, error);
3452 clear_breakpoint (MonoBreakpoint *bp);
3457 * Set a breakpoint at IL_OFFSET in METHOD.
3458 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3459 * METHOD can also be a generic method definition, in which case a breakpoint
3460 * is placed in all instances of the method.
3461 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
3464 static MonoBreakpoint*
3465 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
3468 GHashTableIter iter, iter2;
3471 MonoSeqPointInfo *seq_points;
3474 mono_error_init (error);
3477 // - suspend/resume the vm to prevent code patching problems
3478 // - multiple breakpoints on the same location
3479 // - dynamic methods
3482 bp = g_new0 (MonoBreakpoint, 1);
3483 bp->method = method;
3484 bp->il_offset = il_offset;
3486 bp->children = g_ptr_array_new ();
3488 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));
3490 mono_loader_lock ();
3492 g_hash_table_iter_init (&iter, domains);
3493 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
3494 mono_domain_lock (domain);
3496 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
3497 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
3498 if (bp_matches_method (bp, m))
3499 set_bp_in_method (domain, m, seq_points, bp, error);
3502 mono_domain_unlock (domain);
3505 mono_loader_unlock ();
3507 mono_loader_lock ();
3508 g_ptr_array_add (breakpoints, bp);
3509 mono_loader_unlock ();
3511 if (error && !mono_error_ok (error)) {
3512 clear_breakpoint (bp);
3520 clear_breakpoint (MonoBreakpoint *bp)
3524 // FIXME: locking, races
3525 for (i = 0; i < bp->children->len; ++i) {
3526 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3528 remove_breakpoint (inst);
3533 mono_loader_lock ();
3534 g_ptr_array_remove (breakpoints, bp);
3535 mono_loader_unlock ();
3537 g_ptr_array_free (bp->children, TRUE);
3542 breakpoints_cleanup (void)
3546 mono_loader_lock ();
3548 while (i < event_requests->len) {
3549 EventRequest *req = g_ptr_array_index (event_requests, i);
3551 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
3552 clear_breakpoint (req->info);
3553 g_ptr_array_remove_index_fast (event_requests, i);
3560 for (i = 0; i < breakpoints->len; ++i)
3561 g_free (g_ptr_array_index (breakpoints, i));
3563 g_ptr_array_free (breakpoints, TRUE);
3564 g_hash_table_destroy (bp_locs);
3569 mono_loader_unlock ();
3573 * clear_breakpoints_for_domain:
3575 * Clear breakpoint instances which reference DOMAIN.
3578 clear_breakpoints_for_domain (MonoDomain *domain)
3582 /* This could be called after shutdown */
3586 mono_loader_lock ();
3587 for (i = 0; i < breakpoints->len; ++i) {
3588 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3591 while (j < bp->children->len) {
3592 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3594 if (inst->domain == domain) {
3595 remove_breakpoint (inst);
3599 g_ptr_array_remove_index_fast (bp->children, j);
3605 mono_loader_unlock ();
3609 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
3611 return bp->method && bp->method->klass->image->assembly == assembly;
3615 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
3618 guint8 *orig_ip, *ip;
3619 int i, j, suspend_policy;
3620 guint32 native_offset;
3622 BreakpointInstance *inst;
3623 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3624 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3625 EventKind kind = EVENT_KIND_BREAKPOINT;
3627 // FIXME: Speed this up
3629 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3630 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
3632 g_assert (ji->method);
3634 /* Compute the native offset of the breakpoint from the ip */
3635 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3636 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3637 native_offset = ip - (guint8*)ji->code_start;
3643 * Skip the instruction causing the breakpoint signal.
3645 mono_arch_skip_breakpoint (ctx);
3647 if (ji->method->wrapper_type || tls->disable_breakpoints)
3650 bp_reqs = g_ptr_array_new ();
3651 ss_reqs = g_ptr_array_new ();
3652 ss_reqs_orig = g_ptr_array_new ();
3654 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3656 mono_loader_lock ();
3659 for (i = 0; i < breakpoints->len; ++i) {
3660 bp = g_ptr_array_index (breakpoints, i);
3665 for (j = 0; j < bp->children->len; ++j) {
3666 inst = g_ptr_array_index (bp->children, j);
3667 if (inst->ji == ji && inst->native_offset == native_offset) {
3668 if (bp->req->event_kind == EVENT_KIND_STEP) {
3669 g_ptr_array_add (ss_reqs_orig, bp->req);
3671 g_ptr_array_add (bp_reqs, bp->req);
3676 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3677 MonoSeqPointInfo *seq_points;
3678 int seq_il_offset, seq_native_offset;
3679 MonoDomain *domain = mono_domain_get ();
3681 /* Maybe a method entry/exit event */
3682 mono_domain_lock (domain);
3683 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3684 mono_domain_unlock (domain);
3686 // FIXME: Generic sharing */
3687 mono_loader_unlock ();
3690 g_assert (seq_points);
3692 for (i = 0; i < seq_points->len; ++i) {
3693 seq_il_offset = seq_points->seq_points [i].il_offset;
3694 seq_native_offset = seq_points->seq_points [i].native_offset;
3696 if (native_offset == seq_native_offset) {
3697 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3698 kind = EVENT_KIND_METHOD_ENTRY;
3699 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3700 kind = EVENT_KIND_METHOD_EXIT;
3706 /* Process single step requests */
3707 for (i = 0; i < ss_reqs_orig->len; ++i) {
3708 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3709 SingleStepReq *ss_req = req->info;
3710 gboolean hit = TRUE;
3711 MonoSeqPointInfo *info;
3714 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3717 if (ss_req->size == STEP_SIZE_LINE) {
3718 /* Have to check whenever a different source line was reached */
3719 MonoDebugMethodInfo *minfo;
3720 MonoDebugSourceLocation *loc = NULL;
3722 minfo = mono_debug_lookup_method (ji->method);
3725 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3727 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3728 /* Have to continue single stepping */
3732 ss_req->last_method = ji->method;
3733 ss_req->last_line = loc->row;
3734 mono_debug_free_source_location (loc);
3739 g_ptr_array_add (ss_reqs, req);
3741 /* Start single stepping again from the current sequence point */
3742 ss_start (ss_req, ji->method, sp, info, ctx, NULL, FALSE);
3745 if (ss_reqs->len > 0)
3746 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3747 if (bp_reqs->len > 0)
3748 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3749 if (kind != EVENT_KIND_BREAKPOINT)
3750 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3752 mono_loader_unlock ();
3754 g_ptr_array_free (bp_reqs, TRUE);
3755 g_ptr_array_free (ss_reqs, TRUE);
3758 * FIXME: The first event will suspend, so the second will only be sent after the
3762 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3764 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3765 if (enter_leave_events)
3766 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3770 process_breakpoint (void)
3772 DebuggerTlsData *tls;
3774 static void (*restore_context) (void *);
3776 if (!restore_context)
3777 restore_context = mono_get_restore_context ();
3779 tls = TlsGetValue (debugger_tls_id);
3780 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3782 process_breakpoint_inner (tls, &ctx);
3784 /* This is called when resuming from a signal handler, so it shouldn't return */
3785 restore_context (&ctx);
3786 g_assert_not_reached ();
3790 resume_from_signal_handler (void *sigctx, void *func)
3792 DebuggerTlsData *tls;
3795 /* Save the original context in TLS */
3796 // FIXME: This might not work on an altstack ?
3797 tls = TlsGetValue (debugger_tls_id);
3800 // FIXME: MonoContext usually doesn't include the fp registers, so these are
3801 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3802 // clob:c could be added to op_seq_point.
3804 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3805 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3806 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
3807 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
3809 MONO_CONTEXT_SET_IP (&ctx, func);
3811 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3813 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3814 mono_ppc_set_func_into_sigctx (sigctx, func);
3819 mono_debugger_agent_breakpoint_hit (void *sigctx)
3822 * We are called from a signal handler, and running code there causes all kinds of
3823 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
3824 * So set up the signal context to return to the real breakpoint handler function.
3827 resume_from_signal_handler (sigctx, process_breakpoint);
3831 ss_depth_to_string (StepDepth depth)
3834 case STEP_DEPTH_OVER:
3836 case STEP_DEPTH_OUT:
3838 case STEP_DEPTH_INTO:
3841 g_assert_not_reached ();
3847 process_single_step_inner (DebuggerTlsData *tls, MonoContext *ctx)
3852 int il_offset, suspend_policy;
3856 // FIXME: Speed this up
3858 ip = MONO_CONTEXT_GET_IP (ctx);
3860 /* Skip the instruction causing the single step */
3861 mono_arch_skip_single_step (ctx);
3863 if (suspend_count > 0) {
3864 process_suspend (tls, ctx);
3869 // FIXME: A suspend race
3872 if (mono_thread_internal_current () != ss_req->thread)
3875 if (log_level > 0) {
3876 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
3878 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));
3882 * We implement step over/out by single stepping until we reach the same
3883 * frame/parent frame.
3886 * - stack growing upward
3890 if (ss_req->depth != STEP_DEPTH_INTO) {
3891 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
3893 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
3896 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
3899 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
3901 g_assert (ji->method);
3903 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
3908 * Stopping in memset makes half-initialized vtypes visible.
3909 * Stopping in memcpy makes half-copied vtypes visible.
3911 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
3915 * The ip points to the instruction causing the single step event, convert it
3916 * to the offset stored in seq_points.
3918 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3919 ip = mono_arch_get_ip_for_single_step (ji, ctx);
3921 g_assert_not_reached ();
3925 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
3926 * example, so do things by hand.
3928 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
3930 if (il_offset == -1)
3933 if (ss_req->size == STEP_SIZE_LINE) {
3934 /* Step until a different source line is reached */
3935 MonoDebugMethodInfo *minfo;
3937 minfo = mono_debug_lookup_method (ji->method);
3940 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
3942 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
3943 mono_debug_free_source_location (loc);
3948 * Step until we reach a location with line number info,
3949 * otherwise the client can't show a location.
3950 * This can happen for example with statics initialized inline
3951 * outside of a cctor.
3956 ss_req->last_method = ji->method;
3957 ss_req->last_line = loc->row;
3958 mono_debug_free_source_location (loc);
3963 // FIXME: Has to lock earlier
3965 reqs = g_ptr_array_new ();
3967 mono_loader_lock ();
3969 g_ptr_array_add (reqs, ss_req->req);
3971 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
3973 g_ptr_array_free (reqs, TRUE);
3975 mono_loader_unlock ();
3977 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
3981 process_single_step (void)
3983 DebuggerTlsData *tls;
3985 static void (*restore_context) (void *);
3987 if (!restore_context)
3988 restore_context = mono_get_restore_context ();
3990 tls = TlsGetValue (debugger_tls_id);
3991 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3993 process_single_step_inner (tls, &ctx);
3995 /* This is called when resuming from a signal handler, so it shouldn't return */
3996 restore_context (&ctx);
3997 g_assert_not_reached ();
4001 * mono_debugger_agent_single_step_event:
4003 * Called from a signal handler to handle a single step event.
4006 mono_debugger_agent_single_step_event (void *sigctx)
4008 /* Resume to process_single_step through the signal context */
4010 // FIXME: Since step out/over is implemented using step in, the step in case should
4011 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4014 if (GetCurrentThreadId () == debugger_thread_id) {
4016 * This could happen despite our best effors when the runtime calls
4017 * assembly/type resolve hooks.
4018 * FIXME: Breakpoints too.
4022 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4023 mono_arch_skip_single_step (&ctx);
4024 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4028 resume_from_signal_handler (sigctx, process_single_step);
4032 * start_single_stepping:
4034 * Turn on single stepping. Can be called multiple times, for example,
4035 * by a single step event request + a suspend.
4038 start_single_stepping (void)
4040 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4041 int val = InterlockedIncrement (&ss_count);
4044 mono_arch_start_single_stepping ();
4046 if (ss_req != NULL && ss_invoke_addr == NULL) {
4047 DebuggerTlsData *tls;
4049 mono_loader_lock ();
4051 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4052 ss_invoke_addr = tls->invoke_addr;
4054 mono_loader_unlock ();
4057 g_assert_not_reached ();
4062 stop_single_stepping (void)
4064 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4065 int val = InterlockedDecrement (&ss_count);
4068 mono_arch_stop_single_stepping ();
4070 g_assert_not_reached ();
4077 * Stop the single stepping operation given by SS_REQ.
4080 ss_stop (SingleStepReq *ss_req)
4082 gboolean use_bps = FALSE;
4089 for (l = ss_req->bps; l; l = l->next) {
4090 clear_breakpoint (l->data);
4092 g_slist_free (ss_req->bps);
4096 if (ss_req->global) {
4097 stop_single_stepping ();
4098 ss_req->global = FALSE;
4105 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4108 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4114 /* Stop the previous operation */
4118 * Implement single stepping using breakpoints if possible.
4120 if (step_to_catch) {
4121 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4122 ss_req->bps = g_slist_append (ss_req->bps, bp);
4123 } else if (ss_req->depth == STEP_DEPTH_OVER) {
4126 * Find the first sequence point in the current or in a previous frame which
4127 * is not the last in its method.
4129 while (sp && sp->next_len == 0) {
4131 if (tls && frame_index < tls->frame_count) {
4132 StackFrame *frame = tls->frames [frame_index];
4134 method = frame->method;
4135 if (frame->il_offset != -1) {
4136 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
4142 if (sp && sp->next_len > 0) {
4143 for (i = 0; i < sp->next_len; ++i) {
4144 next_sp = &info->seq_points [sp->next [i]];
4146 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4147 ss_req->bps = g_slist_append (ss_req->bps, bp);
4153 DEBUG (1, printf ("[dbg] Turning on global single stepping.\n"));
4154 ss_req->global = TRUE;
4155 start_single_stepping ();
4157 ss_req->global = FALSE;
4162 * Start single stepping of thread THREAD
4165 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4167 DebuggerTlsData *tls;
4168 MonoSeqPointInfo *info = NULL;
4169 SeqPoint *sp = NULL;
4170 MonoMethod *method = NULL;
4171 MonoDebugMethodInfo *minfo;
4172 gboolean step_to_catch = FALSE;
4174 if (suspend_count == 0)
4175 return ERR_NOT_SUSPENDED;
4177 wait_for_suspend ();
4179 // FIXME: Multiple requests
4181 DEBUG (0, printf ("Received a single step request while the previous one was still active.\n"));
4182 return ERR_NOT_IMPLEMENTED;
4185 DEBUG (1, printf ("[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4187 ss_req = g_new0 (SingleStepReq, 1);
4189 ss_req->thread = thread;
4190 ss_req->size = size;
4191 ss_req->depth = depth;
4194 mono_loader_lock ();
4195 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4196 mono_loader_unlock ();
4198 g_assert (tls->has_context);
4199 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
4201 if (tls->has_catch_ctx) {
4203 StackFrameInfo frame;
4204 MonoContext new_ctx;
4205 MonoLMF *lmf = NULL;
4208 * We are stopped at a throw site. Stepping should go to the catch site.
4211 /* Find the the jit info for the catch context */
4212 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, &frame);
4214 g_assert (frame.type == FRAME_TYPE_MANAGED);
4217 * Find the seq point corresponding to the landing site ip, which is the first seq
4220 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4223 method = frame.method;
4225 step_to_catch = TRUE;
4226 /* This make sure the seq point is not skipped by process_single_step () */
4227 ss_req->last_sp = NULL;
4230 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4233 /* Compute the initial line info */
4234 compute_frame_info (thread, tls);
4236 g_assert (tls->frame_count);
4237 frame = tls->frames [0];
4239 ss_req->last_method = frame->method;
4240 ss_req->last_line = -1;
4242 minfo = mono_debug_lookup_method (frame->method);
4243 if (minfo && frame->il_offset != -1) {
4244 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4247 ss_req->last_line = loc->row;
4253 if (!step_to_catch && ss_req->depth == STEP_DEPTH_OVER) {
4256 compute_frame_info (thread, tls);
4258 g_assert (tls->frame_count);
4259 frame = tls->frames [0];
4261 if (!method && frame->il_offset != -1) {
4262 /* FIXME: Sort the table and use a binary search */
4263 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4265 method = frame->method;
4269 ss_start (ss_req, method, sp, info, NULL, tls, step_to_catch);
4275 ss_destroy (SingleStepReq *req)
4278 g_assert (ss_req == req);
4287 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
4288 MonoContext *catch_ctx)
4294 DebuggerTlsData *tls = NULL;
4296 if (thread_to_tls != NULL) {
4297 MonoInternalThread *thread = mono_thread_internal_current ();
4299 mono_loader_lock ();
4300 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4301 mono_loader_unlock ();
4303 if (tls && tls->abort_requested)
4305 if (tls && tls->disable_breakpoints)
4309 memset (&ei, 0, sizeof (EventInfo));
4311 /* Just-In-Time debugging */
4313 if (agent_config.onuncaught && !inited) {
4314 finish_agent_init (FALSE);
4317 * Send an unsolicited EXCEPTION event with a dummy request id.
4319 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4320 ei.exc = (MonoObject*)exc;
4321 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4324 } else if (agent_config.onthrow && !inited) {
4326 gboolean found = FALSE;
4328 for (l = agent_config.onthrow; l; l = l->next) {
4329 char *ex_type = l->data;
4330 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
4332 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
4339 finish_agent_init (FALSE);
4342 * Send an unsolicited EXCEPTION event with a dummy request id.
4344 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4345 ei.exc = (MonoObject*)exc;
4346 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4354 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
4356 ei.exc = (MonoObject*)exc;
4357 ei.caught = catch_ctx != NULL;
4359 mono_loader_lock ();
4360 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
4361 mono_loader_unlock ();
4363 if (tls && catch_ctx) {
4364 tls->catch_ctx = *catch_ctx;
4365 tls->has_catch_ctx = TRUE;
4368 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
4371 tls->has_catch_ctx = FALSE;
4375 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4377 DebuggerTlsData *tls;
4382 tls = TlsGetValue (debugger_tls_id);
4387 * We're about to invoke an exception filter during the first pass of exception handling.
4389 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
4390 * 'orig_ctx' is the context where the exception has been thrown.
4393 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
4395 * If we're stopped in Filter(), normal stack unwinding would first unwind to
4396 * the call site (line 37) and then continue to Main(), but it would never
4397 * include the throw site (line 32).
4399 * Since exception filters are invoked during the first pass of exception handling,
4400 * the stack frames of the throw site are still intact, so we should include them
4403 * We do this here by saving the context of the throw site in 'tls->filter_ctx'.
4405 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
4406 * but report the location of the 'throw' to the user.
4410 memcpy (&tls->filter_ctx, orig_ctx, sizeof (MonoContext));
4411 tls->has_filter_ctx = TRUE;
4413 tls->filter_lmf = mono_get_lmf ();
4414 tls->domain = mono_domain_get ();
4418 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4420 DebuggerTlsData *tls;
4425 tls = TlsGetValue (debugger_tls_id);
4429 tls->has_filter_ctx = FALSE;
4433 * buffer_add_value_full:
4435 * Add the encoding of the value at ADDR described by T to the buffer.
4436 * AS_VTYPE determines whenever to treat primitive types as primitive types or
4440 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
4446 g_assert (*(void**)addr);
4447 addr = *(void**)addr;
4452 case MONO_TYPE_BOOLEAN:
4455 case MONO_TYPE_CHAR:
4475 case MONO_TYPE_VOID:
4476 buffer_add_byte (buf, t->type);
4478 case MONO_TYPE_BOOLEAN:
4481 buffer_add_byte (buf, t->type);
4482 buffer_add_int (buf, *(gint8*)addr);
4484 case MONO_TYPE_CHAR:
4487 buffer_add_byte (buf, t->type);
4488 buffer_add_int (buf, *(gint16*)addr);
4493 buffer_add_byte (buf, t->type);
4494 buffer_add_int (buf, *(gint32*)addr);
4499 buffer_add_byte (buf, t->type);
4500 buffer_add_long (buf, *(gint64*)addr);
4504 /* Treat it as a vtype */
4506 case MONO_TYPE_PTR: {
4507 gssize val = *(gssize*)addr;
4509 buffer_add_byte (buf, t->type);
4510 buffer_add_long (buf, val);
4514 case MONO_TYPE_STRING:
4515 case MONO_TYPE_SZARRAY:
4516 case MONO_TYPE_OBJECT:
4517 case MONO_TYPE_CLASS:
4518 case MONO_TYPE_ARRAY:
4519 obj = *(MonoObject**)addr;
4522 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4524 if (obj->vtable->klass->valuetype) {
4525 t = &obj->vtable->klass->byval_arg;
4526 addr = mono_object_unbox (obj);
4528 } else if (obj->vtable->klass->rank) {
4529 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4530 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4531 buffer_add_byte (buf, MONO_TYPE_CLASS);
4533 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4535 buffer_add_objid (buf, obj);
4539 case MONO_TYPE_VALUETYPE: {
4543 MonoClass *klass = mono_class_from_mono_type (t);
4545 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4546 buffer_add_byte (buf, klass->enumtype);
4547 buffer_add_typeid (buf, domain, klass);
4551 while ((f = mono_class_get_fields (klass, &iter))) {
4552 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4554 if (mono_field_is_deleted (f))
4558 buffer_add_int (buf, nfields);
4561 while ((f = mono_class_get_fields (klass, &iter))) {
4562 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4564 if (mono_field_is_deleted (f))
4566 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4570 case MONO_TYPE_GENERICINST:
4571 if (mono_type_generic_inst_is_valuetype (t)) {
4583 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4585 buffer_add_value_full (buf, t, addr, domain, FALSE);
4589 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4592 int type = decode_byte (buf, &buf, limit);
4594 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4595 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4596 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4597 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
4598 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
4599 char *name = mono_type_full_name (t);
4600 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
4602 return ERR_INVALID_ARGUMENT;
4606 case MONO_TYPE_BOOLEAN:
4607 *(guint8*)addr = decode_int (buf, &buf, limit);
4609 case MONO_TYPE_CHAR:
4610 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4613 *(gint8*)addr = decode_int (buf, &buf, limit);
4616 *(guint8*)addr = decode_int (buf, &buf, limit);
4619 *(gint16*)addr = decode_int (buf, &buf, limit);
4622 *(guint16*)addr = decode_int (buf, &buf, limit);
4625 *(gint32*)addr = decode_int (buf, &buf, limit);
4628 *(guint32*)addr = decode_int (buf, &buf, limit);
4631 *(gint64*)addr = decode_long (buf, &buf, limit);
4634 *(guint64*)addr = decode_long (buf, &buf, limit);
4637 *(guint32*)addr = decode_int (buf, &buf, limit);
4640 *(guint64*)addr = decode_long (buf, &buf, limit);
4643 /* We send these as I8, so we get them back as such */
4644 g_assert (type == MONO_TYPE_I8);
4645 *(gssize*)addr = decode_long (buf, &buf, limit);
4647 case MONO_TYPE_GENERICINST:
4648 if (MONO_TYPE_ISSTRUCT (t)) {
4649 /* The client sends these as a valuetype */
4657 /* We send these as vtypes, so we get them back as such */
4658 g_assert (type == MONO_TYPE_VALUETYPE);
4661 case MONO_TYPE_VALUETYPE: {
4662 gboolean is_enum = decode_byte (buf, &buf, limit);
4666 gpointer iter = NULL;
4669 /* Enums are sent as a normal vtype */
4671 return ERR_NOT_IMPLEMENTED;
4672 klass = decode_typeid (buf, &buf, limit, &d, &err);
4676 if (klass != mono_class_from_mono_type (t))
4677 return ERR_INVALID_ARGUMENT;
4679 nfields = decode_int (buf, &buf, limit);
4680 while ((f = mono_class_get_fields (klass, &iter))) {
4681 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4683 if (mono_field_is_deleted (f))
4685 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4690 g_assert (nfields == 0);
4695 if (MONO_TYPE_IS_REFERENCE (t)) {
4696 if (type == MONO_TYPE_OBJECT) {
4697 int objid = decode_objid (buf, &buf, limit);
4701 err = get_object (objid, (MonoObject**)&obj);
4705 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4706 return ERR_INVALID_ARGUMENT;
4707 if (obj && obj->vtable->domain != domain)
4708 return ERR_INVALID_ARGUMENT;
4710 mono_gc_wbarrier_generic_store (addr, obj);
4711 } else if (type == VALUE_TYPE_ID_NULL) {
4712 *(MonoObject**)addr = NULL;
4714 return ERR_INVALID_ARGUMENT;
4728 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4735 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4736 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4739 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4740 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4742 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
4744 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4745 addr = mono_arch_context_get_int_reg (ctx, reg);
4746 addr += (gint32)var->offset;
4748 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4750 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4752 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4756 g_assert_not_reached ();
4761 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
4767 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4768 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4770 if (MONO_TYPE_IS_REFERENCE (t))
4771 size = sizeof (gpointer);
4773 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4776 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4777 // FIXME: Can't set registers, so we disable linears
4780 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4781 addr = mono_arch_context_get_int_reg (ctx, reg);
4782 addr += (gint32)var->offset;
4784 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4786 // FIXME: Write barriers
4787 memcpy (addr, val, size);
4789 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4793 g_assert_not_reached ();
4798 clear_event_request (int req_id, int etype)
4802 mono_loader_lock ();
4803 for (i = 0; i < event_requests->len; ++i) {
4804 EventRequest *req = g_ptr_array_index (event_requests, i);
4806 if (req->id == req_id && req->event_kind == etype) {
4807 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4808 clear_breakpoint (req->info);
4809 if (req->event_kind == EVENT_KIND_STEP)
4810 ss_destroy (req->info);
4811 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
4812 clear_breakpoint (req->info);
4813 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
4814 clear_breakpoint (req->info);
4815 g_ptr_array_remove_index_fast (event_requests, i);
4820 mono_loader_unlock ();
4824 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
4826 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4827 return breakpoint_matches_assembly (req->info, assembly);
4831 for (i = 0; i < req->nmodifiers; ++i) {
4832 Modifier *m = &req->modifiers [i];
4834 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
4836 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
4837 for (j = 0; m->data.assemblies [j]; ++j)
4838 if (m->data.assemblies [j] == assembly)
4848 * clear_event_requests_for_assembly:
4850 * Clear all events requests which reference ASSEMBLY.
4853 clear_event_requests_for_assembly (MonoAssembly *assembly)
4858 mono_loader_lock ();
4862 for (i = 0; i < event_requests->len; ++i) {
4863 EventRequest *req = g_ptr_array_index (event_requests, i);
4865 if (event_req_matches_assembly (req, assembly)) {
4866 clear_event_request (req->id, req->event_kind);
4872 mono_loader_unlock ();
4876 * type_comes_from_assembly:
4878 * GHRFunc that returns TRUE if klass comes from assembly
4881 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
4883 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
4887 * clear_types_for_assembly:
4889 * Clears types from loaded_classes for a given assembly
4892 clear_types_for_assembly (MonoAssembly *assembly)
4894 mono_loader_lock ();
4895 g_hash_table_foreach_remove (loaded_classes, type_comes_from_assembly, assembly);
4896 mono_loader_unlock ();
4900 add_thread (gpointer key, gpointer value, gpointer user_data)
4902 MonoInternalThread *thread = value;
4903 Buffer *buf = user_data;
4905 buffer_add_objid (buf, (MonoObject*)thread);
4909 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
4911 guint8 *p = invoke->p;
4912 guint8 *end = invoke->endp;
4915 MonoMethodSignature *sig;
4918 MonoObject *this, *res, *exc;
4921 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4925 if (invoke->method) {
4927 * Invoke this method directly, currently only Environment.Exit () is supported.
4930 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>"));
4931 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
4932 g_assert_not_reached ();
4935 m = decode_methodid (p, &p, end, &domain, &err);
4938 sig = mono_method_signature (m);
4940 if (m->klass->valuetype)
4941 this_buf = g_alloca (mono_class_instance_size (m->klass));
4943 this_buf = g_alloca (sizeof (MonoObject*));
4944 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
4945 /* Should be null */
4946 int type = decode_byte (p, &p, end);
4947 if (type != VALUE_TYPE_ID_NULL)
4948 return ERR_INVALID_ARGUMENT;
4949 memset (this_buf, 0, mono_class_instance_size (m->klass));
4951 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
4956 if (!m->klass->valuetype)
4957 this = *(MonoObject**)this_buf;
4961 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>"));
4963 if (this && this->vtable->domain != domain)
4966 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
4967 if (!strcmp (m->name, ".ctor")) {
4968 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
4969 return ERR_INVALID_ARGUMENT;
4971 this = mono_object_new (domain, m->klass);
4973 return ERR_INVALID_ARGUMENT;
4977 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
4978 return ERR_INVALID_ARGUMENT;
4980 nargs = decode_int (p, &p, end);
4981 if (nargs != sig->param_count)
4982 return ERR_INVALID_ARGUMENT;
4983 /* Use alloca to get gc tracking */
4984 arg_buf = g_alloca (nargs * sizeof (gpointer));
4985 memset (arg_buf, 0, nargs * sizeof (gpointer));
4986 args = g_alloca (nargs * sizeof (gpointer));
4987 for (i = 0; i < nargs; ++i) {
4988 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
4989 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
4993 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
4996 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
4997 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5000 args [i] = arg_buf [i];
5007 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5008 tls->disable_breakpoints = TRUE;
5010 tls->disable_breakpoints = FALSE;
5013 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5015 /* FIXME: Move this to arch specific code */
5016 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5017 if (invoke->has_ctx) {
5020 lmf_addr = mono_get_lmf_addr ();
5023 memset (&ext, 0, sizeof (ext));
5025 ext.lmf.previous_lmf = *(lmf_addr);
5026 /* Mark that this is a MonoLMFExt */
5027 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5028 ext.lmf.rsp = (gssize)&ext;
5029 #elif defined(TARGET_X86)
5030 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5031 /* Mark that this is a MonoLMFExt */
5032 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5033 ext.lmf.ebp = (gssize)&ext;
5034 #elif defined(TARGET_ARM)
5035 ext.lmf.previous_lmf = *(lmf_addr);
5036 /* Mark that this is a MonoLMFExt */
5037 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5038 #elif defined(TARGET_POWERPC)
5039 ext.lmf.previous_lmf = *(lmf_addr);
5040 /* Mark that this is a MonoLMFExt */
5041 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5042 ext.lmf.ebp = (gssize)&ext;
5044 g_assert_not_reached ();
5047 ext.debugger_invoke = TRUE;
5048 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5050 mono_set_lmf ((MonoLMF*)&ext);
5054 if (m->klass->valuetype)
5055 res = mono_runtime_invoke (m, this_buf, args, &exc);
5057 res = mono_runtime_invoke (m, this, args, &exc);
5059 buffer_add_byte (buf, 0);
5060 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5062 buffer_add_byte (buf, 1);
5063 if (sig->ret->type == MONO_TYPE_VOID) {
5064 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5065 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5068 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5069 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5070 buffer_add_value (buf, sig->ret, &res, domain);
5071 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5073 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5079 tls->disable_breakpoints = FALSE;
5081 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5082 if (invoke->has_ctx)
5083 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5086 // FIXME: byref arguments
5094 * Invoke the method given by tls->pending_invoke in the current thread.
5097 invoke_method (void)
5099 DebuggerTlsData *tls;
5104 static void (*restore_context) (void *);
5105 MonoContext restore_ctx;
5107 if (!restore_context)
5108 restore_context = mono_get_restore_context ();
5110 tls = TlsGetValue (debugger_tls_id);
5114 * Store the `InvokeData *' in `tls->invoke' until we're done with
5115 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5118 mono_loader_lock ();
5120 invoke = tls->pending_invoke;
5122 tls->pending_invoke = NULL;
5124 invoke->last_invoke = tls->invoke;
5125 tls->invoke = invoke;
5127 mono_loader_unlock ();
5129 tls->frames_up_to_date = FALSE;
5133 buffer_init (&buf, 128);
5135 err = do_invoke_method (tls, &buf, invoke);
5137 /* Start suspending before sending the reply */
5138 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5141 send_reply_packet (id, err, &buf);
5145 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5147 if (invoke->has_ctx)
5148 save_thread_context (&restore_ctx);
5150 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5151 g_assert (tls->resume_count);
5152 tls->resume_count -= invoke->suspend_count;
5155 DEBUG (1, printf ("[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5158 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5160 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5161 * after the mono_runtime_invoke() already returned, but it doesn't matter
5162 * because we reset the abort here.
5165 mono_loader_lock ();
5167 if (tls->abort_requested)
5168 mono_thread_internal_reset_abort (tls->thread);
5170 tls->invoke = tls->invoke->last_invoke;
5171 tls->abort_requested = FALSE;
5173 mono_loader_unlock ();
5182 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5184 MonoThread *thread = value;
5185 DebuggerTlsData *tls;
5188 mono_loader_lock ();
5189 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5191 res = tls->really_suspended;
5192 mono_loader_unlock ();
5198 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
5201 case CMD_VM_VERSION: {
5202 char *build_info, *version;
5204 build_info = mono_get_runtime_build_info ();
5205 version = g_strdup_printf ("mono %s", build_info);
5207 buffer_add_string (buf, version); /* vm version */
5208 buffer_add_int (buf, MAJOR_VERSION);
5209 buffer_add_int (buf, MINOR_VERSION);
5210 g_free (build_info);
5214 case CMD_VM_SET_PROTOCOL_VERSION: {
5215 major_version = decode_int (p, &p, end);
5216 minor_version = decode_int (p, &p, end);
5217 protocol_version_set = TRUE;
5218 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
5221 case CMD_VM_ALL_THREADS: {
5223 mono_loader_lock ();
5224 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
5225 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
5226 mono_loader_unlock ();
5229 case CMD_VM_SUSPEND:
5231 wait_for_suspend ();
5234 if (suspend_count == 0)
5235 return ERR_NOT_SUSPENDED;
5238 case CMD_VM_DISPOSE:
5239 /* Clear all event requests */
5240 mono_loader_lock ();
5241 while (event_requests->len > 0) {
5242 EventRequest *req = g_ptr_array_index (event_requests, 0);
5244 clear_event_request (req->id, req->event_kind);
5246 mono_loader_unlock ();
5248 // FIXME: Count resumes
5250 disconnected = TRUE;
5253 MonoInternalThread *thread;
5254 DebuggerTlsData *tls;
5255 MonoClass *env_class;
5256 MonoMethod *exit_method;
5260 exit_code = decode_int (p, &p, end);
5262 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
5264 /* Have to send a reply before exiting */
5265 send_reply_packet (id, 0, buf);
5267 /* Clear all event requests */
5268 mono_loader_lock ();
5269 while (event_requests->len > 0) {
5270 EventRequest *req = g_ptr_array_index (event_requests, 0);
5272 clear_event_request (req->id, req->event_kind);
5274 mono_loader_unlock ();
5277 * The JDWP documentation says that the shutdown is not orderly. It doesn't
5278 * specify whenever a VM_DEATH event is sent. We currently do an orderly
5279 * shutdown by hijacking a thread to execute Environment.Exit (). This is
5280 * better than doing the shutdown ourselves, since it avoids various races.
5284 wait_for_suspend ();
5286 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
5287 g_assert (env_class);
5288 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
5289 g_assert (exit_method);
5291 mono_loader_lock ();
5292 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
5293 mono_loader_unlock ();
5296 mono_loader_lock ();
5297 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5298 mono_loader_unlock ();
5300 args = g_new0 (gpointer, 1);
5301 args [0] = g_malloc (sizeof (int));
5302 *(int*)(args [0]) = exit_code;
5304 tls->pending_invoke = g_new0 (InvokeData, 1);
5305 tls->pending_invoke->method = exit_method;
5306 tls->pending_invoke->args = args;
5308 while (suspend_count > 0)
5312 * No thread found, do it ourselves.
5313 * FIXME: This can race with normal shutdown etc.
5315 while (suspend_count > 0)
5318 mono_runtime_set_shutting_down ();
5320 mono_threads_set_shutting_down ();
5322 /* Suspend all managed threads since the runtime is going away */
5323 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
5324 mono_thread_suspend_all_other_threads ();
5325 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
5326 mono_runtime_quit ();
5328 shutdown (conn_fd, SD_BOTH);
5330 shutdown (conn_fd, SHUT_RDWR);
5332 DEBUG(1, fprintf (log_file, "Exiting...\n"));
5338 case CMD_VM_INVOKE_METHOD: {
5339 int objid = decode_objid (p, &p, end);
5341 DebuggerTlsData *tls;
5344 err = get_object (objid, (MonoObject**)&thread);
5348 flags = decode_int (p, &p, end);
5350 // Wait for suspending if it already started
5352 wait_for_suspend ();
5353 if (!is_suspended ())
5354 return ERR_NOT_SUSPENDED;
5356 mono_loader_lock ();
5357 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5358 mono_loader_unlock ();
5361 if (!tls->really_suspended)
5362 /* The thread is still running native code, can't do invokes */
5363 return ERR_NOT_SUSPENDED;
5366 * Store the invoke data into tls, the thread will execute it after it is
5369 if (tls->pending_invoke)
5371 tls->pending_invoke = g_new0 (InvokeData, 1);
5372 tls->pending_invoke->id = id;
5373 tls->pending_invoke->flags = flags;
5374 tls->pending_invoke->p = g_malloc (end - p);
5375 memcpy (tls->pending_invoke->p, p, end - p);
5376 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
5377 tls->pending_invoke->suspend_count = suspend_count;
5379 if (flags & INVOKE_FLAG_SINGLE_THREADED)
5380 resume_thread (THREAD_TO_INTERNAL (thread));
5385 case CMD_VM_ABORT_INVOKE: {
5386 int objid = decode_objid (p, &p, end);
5388 DebuggerTlsData *tls;
5391 err = get_object (objid, (MonoObject**)&thread);
5395 invoke_id = decode_int (p, &p, end);
5397 mono_loader_lock ();
5398 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5401 if (tls->abort_requested) {
5402 mono_loader_unlock ();
5407 * Check whether we're still inside the mono_runtime_invoke() and that it's
5408 * actually the correct invocation.
5410 * Careful, we do not stop the thread that's doing the invocation, so we can't
5411 * inspect its stack. However, invoke_method() also acquires the loader lock
5412 * when it's done, so we're safe here.
5416 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
5417 mono_loader_unlock ();
5418 return ERR_NO_INVOCATION;
5421 tls->abort_requested = TRUE;
5423 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
5424 mono_loader_unlock ();
5429 return ERR_NOT_IMPLEMENTED;
5436 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5442 case CMD_EVENT_REQUEST_SET: {
5444 int i, event_kind, suspend_policy, nmodifiers, mod;
5447 MonoThread *step_thread;
5448 int size = 0, depth = 0, step_thread_id = 0;
5451 event_kind = decode_byte (p, &p, end);
5452 suspend_policy = decode_byte (p, &p, end);
5453 nmodifiers = decode_byte (p, &p, end);
5455 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
5456 req->id = InterlockedIncrement (&event_request_id);
5457 req->event_kind = event_kind;
5458 req->suspend_policy = suspend_policy;
5459 req->nmodifiers = nmodifiers;
5462 for (i = 0; i < nmodifiers; ++i) {
5463 mod = decode_byte (p, &p, end);
5465 req->modifiers [i].kind = mod;
5466 if (mod == MOD_KIND_COUNT) {
5467 req->modifiers [i].data.count = decode_int (p, &p, end);
5468 } else if (mod == MOD_KIND_LOCATION_ONLY) {
5469 method = decode_methodid (p, &p, end, &domain, &err);
5472 location = decode_long (p, &p, end);
5473 } else if (mod == MOD_KIND_STEP) {
5474 step_thread_id = decode_id (p, &p, end);
5475 size = decode_int (p, &p, end);
5476 depth = decode_int (p, &p, end);
5477 } else if (mod == MOD_KIND_THREAD_ONLY) {
5478 int id = decode_id (p, &p, end);
5480 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
5485 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
5486 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
5490 req->modifiers [i].caught = decode_byte (p, &p, end);
5491 req->modifiers [i].uncaught = decode_byte (p, &p, end);
5492 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" : ""));
5494 req->modifiers [i].data.exc_class = exc_class;
5496 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
5498 return ERR_INVALID_ARGUMENT;
5501 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
5502 int n = decode_int (p, &p, end);
5505 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
5506 for (j = 0; j < n; ++j) {
5507 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
5509 g_free (req->modifiers [i].data.assemblies);
5515 return ERR_NOT_IMPLEMENTED;
5519 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5522 req->info = set_breakpoint (method, location, req, &error);
5523 if (!mono_error_ok (&error)) {
5525 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
5526 mono_error_cleanup (&error);
5527 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
5529 } else if (req->event_kind == EVENT_KIND_STEP) {
5530 g_assert (step_thread_id);
5532 err = get_object (step_thread_id, (MonoObject**)&step_thread);
5538 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
5543 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
5544 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
5545 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
5546 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
5547 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
5549 if (req->nmodifiers) {
5551 return ERR_NOT_IMPLEMENTED;
5555 mono_loader_lock ();
5556 g_ptr_array_add (event_requests, req);
5557 mono_loader_unlock ();
5559 buffer_add_int (buf, req->id);
5562 case CMD_EVENT_REQUEST_CLEAR: {
5563 int etype = decode_byte (p, &p, end);
5564 int req_id = decode_int (p, &p, end);
5566 // FIXME: Make a faster mapping from req_id to request
5567 mono_loader_lock ();
5568 clear_event_request (req_id, etype);
5569 mono_loader_unlock ();
5572 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
5575 mono_loader_lock ();
5577 while (i < event_requests->len) {
5578 EventRequest *req = g_ptr_array_index (event_requests, i);
5580 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5581 clear_breakpoint (req->info);
5583 g_ptr_array_remove_index_fast (event_requests, i);
5589 mono_loader_unlock ();
5593 return ERR_NOT_IMPLEMENTED;
5600 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5606 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
5607 buffer_add_domainid (buf, mono_get_root_domain ());
5610 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
5611 domain = decode_domainid (p, &p, end, NULL, &err);
5614 buffer_add_string (buf, domain->friendly_name);
5617 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
5622 domain = decode_domainid (p, &p, end, NULL, &err);
5625 mono_loader_lock ();
5627 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5630 buffer_add_int (buf, count);
5631 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5633 buffer_add_assemblyid (buf, domain, ass);
5635 mono_loader_unlock ();
5638 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
5639 domain = decode_domainid (p, &p, end, NULL, &err);
5643 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
5646 case CMD_APPDOMAIN_GET_CORLIB: {
5647 domain = decode_domainid (p, &p, end, NULL, &err);
5651 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
5654 case CMD_APPDOMAIN_CREATE_STRING: {
5658 domain = decode_domainid (p, &p, end, NULL, &err);
5661 s = decode_string (p, &p, end);
5663 o = mono_string_new (domain, s);
5664 buffer_add_objid (buf, (MonoObject*)o);
5667 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
5669 MonoDomain *domain2;
5672 domain = decode_domainid (p, &p, end, NULL, &err);
5675 klass = decode_typeid (p, &p, end, &domain2, &err);
5680 g_assert (domain == domain2);
5682 o = mono_object_new (domain, klass);
5684 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
5688 buffer_add_objid (buf, o);
5692 return ERR_NOT_IMPLEMENTED;
5699 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5705 ass = decode_assemblyid (p, &p, end, &domain, &err);
5710 case CMD_ASSEMBLY_GET_LOCATION: {
5711 buffer_add_string (buf, mono_image_get_filename (ass->image));
5714 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
5718 if (ass->image->dynamic) {
5719 buffer_add_id (buf, 0);
5721 token = mono_image_get_entry_point (ass->image);
5723 buffer_add_id (buf, 0);
5725 m = mono_get_method (ass->image, token, NULL);
5726 buffer_add_methodid (buf, domain, m);
5731 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5732 buffer_add_moduleid (buf, domain, ass->image);
5735 case CMD_ASSEMBLY_GET_OBJECT: {
5736 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5737 buffer_add_objid (buf, o);
5740 case CMD_ASSEMBLY_GET_TYPE: {
5741 char *s = decode_string (p, &p, end);
5742 gboolean ignorecase = decode_byte (p, &p, end);
5743 MonoTypeNameParse info;
5745 gboolean type_resolve;
5747 if (!mono_reflection_parse_type (s, &info)) {
5750 if (info.assembly.name)
5752 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5754 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5755 mono_reflection_free_type_info (&info);
5760 case CMD_ASSEMBLY_GET_NAME: {
5762 MonoAssembly *mass = ass;
5764 name = g_strdup_printf (
5765 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5767 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5768 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5769 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5770 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5772 buffer_add_string (buf, name);
5777 return ERR_NOT_IMPLEMENTED;
5784 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5790 case CMD_MODULE_GET_INFO: {
5791 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
5794 basename = g_path_get_basename (image->name);
5795 buffer_add_string (buf, basename); // name
5796 buffer_add_string (buf, image->module_name); // scopename
5797 buffer_add_string (buf, image->name); // fqname
5798 buffer_add_string (buf, mono_image_get_guid (image)); // guid
5799 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
5804 return ERR_NOT_IMPLEMENTED;
5811 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
5813 if (val && val->vtable->klass == mono_defaults.monotype_class) {
5814 /* Special case these so the client doesn't have to handle Type objects */
5816 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
5817 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
5818 } else if (MONO_TYPE_IS_REFERENCE (t))
5819 buffer_add_value (buf, t, &val, domain);
5821 buffer_add_value (buf, t, mono_object_unbox (val), domain);
5825 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
5831 buffer_add_int (buf, 0);
5835 for (i = 0; i < cinfo->num_attrs; ++i) {
5836 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
5839 buffer_add_int (buf, nattrs);
5841 for (i = 0; i < cinfo->num_attrs; ++i) {
5842 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
5843 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
5844 MonoArray *typed_args, *named_args;
5846 CattrNamedArg *arginfo;
5848 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
5850 buffer_add_methodid (buf, domain, attr->ctor);
5854 buffer_add_int (buf, mono_array_length (typed_args));
5855 for (j = 0; j < mono_array_length (typed_args); ++j) {
5856 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
5858 t = mono_method_signature (attr->ctor)->params [j];
5860 buffer_add_cattr_arg (buf, t, domain, val);
5863 buffer_add_int (buf, 0);
5868 buffer_add_int (buf, mono_array_length (named_args));
5870 for (j = 0; j < mono_array_length (named_args); ++j) {
5871 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
5873 if (arginfo [j].prop) {
5874 buffer_add_byte (buf, 0x54);
5875 buffer_add_propertyid (buf, domain, arginfo [j].prop);
5876 } else if (arginfo [j].field) {
5877 buffer_add_byte (buf, 0x53);
5879 g_assert_not_reached ();
5882 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
5885 buffer_add_int (buf, 0);
5892 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
5902 case CMD_TYPE_GET_INFO: {
5903 buffer_add_string (buf, klass->name_space);
5904 buffer_add_string (buf, klass->name);
5906 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
5907 buffer_add_string (buf, name);
5909 buffer_add_assemblyid (buf, domain, klass->image->assembly);
5910 buffer_add_moduleid (buf, domain, klass->image);
5911 buffer_add_typeid (buf, domain, klass->parent);
5912 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
5913 buffer_add_typeid (buf, domain, klass->element_class);
5915 buffer_add_id (buf, 0);
5916 buffer_add_int (buf, klass->type_token);
5917 buffer_add_byte (buf, klass->rank);
5918 buffer_add_int (buf, klass->flags);
5920 type = &klass->byval_arg;
5921 // FIXME: Can't decide whenever a class represents a byref type
5924 if (type->type == MONO_TYPE_PTR)
5926 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
5928 if (type->type == MONO_TYPE_VALUETYPE)
5930 if (klass->enumtype)
5932 buffer_add_byte (buf, b);
5935 while ((nested = mono_class_get_nested_types (klass, &iter)))
5937 buffer_add_int (buf, nnested);
5939 while ((nested = mono_class_get_nested_types (klass, &iter)))
5940 buffer_add_typeid (buf, domain, nested);
5943 case CMD_TYPE_GET_METHODS: {
5946 gpointer iter = NULL;
5949 mono_class_setup_methods (klass);
5951 nmethods = mono_class_num_methods (klass);
5953 buffer_add_int (buf, nmethods);
5955 while ((m = mono_class_get_methods (klass, &iter))) {
5956 buffer_add_methodid (buf, domain, m);
5959 g_assert (i == nmethods);
5962 case CMD_TYPE_GET_FIELDS: {
5965 gpointer iter = NULL;
5968 nfields = mono_class_num_fields (klass);
5970 buffer_add_int (buf, nfields);
5972 while ((f = mono_class_get_fields (klass, &iter))) {
5973 buffer_add_fieldid (buf, domain, f);
5974 buffer_add_string (buf, f->name);
5975 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
5976 buffer_add_int (buf, f->type->attrs);
5979 g_assert (i == nfields);
5982 case CMD_TYPE_GET_PROPERTIES: {
5985 gpointer iter = NULL;
5988 nprops = mono_class_num_properties (klass);
5990 buffer_add_int (buf, nprops);
5992 while ((p = mono_class_get_properties (klass, &iter))) {
5993 buffer_add_propertyid (buf, domain, p);
5994 buffer_add_string (buf, p->name);
5995 buffer_add_methodid (buf, domain, p->get);
5996 buffer_add_methodid (buf, domain, p->set);
5997 buffer_add_int (buf, p->attrs);
6000 g_assert (i == nprops);
6003 case CMD_TYPE_GET_CATTRS: {
6004 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
6005 MonoCustomAttrInfo *cinfo;
6007 cinfo = mono_custom_attrs_from_class (klass);
6009 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6012 case CMD_TYPE_GET_FIELD_CATTRS: {
6013 MonoClass *attr_klass;
6014 MonoCustomAttrInfo *cinfo;
6015 MonoClassField *field;
6017 field = decode_fieldid (p, &p, end, NULL, &err);
6020 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6024 cinfo = mono_custom_attrs_from_field (klass, field);
6026 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6029 case CMD_TYPE_GET_PROPERTY_CATTRS: {
6030 MonoClass *attr_klass;
6031 MonoCustomAttrInfo *cinfo;
6034 prop = decode_propertyid (p, &p, end, NULL, &err);
6037 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6041 cinfo = mono_custom_attrs_from_property (klass, prop);
6043 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6046 case CMD_TYPE_GET_VALUES:
6047 case CMD_TYPE_GET_VALUES_2: {
6054 MonoThread *thread_obj;
6055 MonoInternalThread *thread = NULL;
6056 guint32 special_static_type;
6058 if (command == CMD_TYPE_GET_VALUES_2) {
6059 int objid = decode_objid (p, &p, end);
6062 err = get_object (objid, (MonoObject**)&thread_obj);
6066 thread = THREAD_TO_INTERNAL (thread_obj);
6069 len = decode_int (p, &p, end);
6070 for (i = 0; i < len; ++i) {
6071 f = decode_fieldid (p, &p, end, NULL, &err);
6075 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6076 return ERR_INVALID_FIELDID;
6077 special_static_type = mono_class_field_get_special_static_type (f);
6078 if (special_static_type != SPECIAL_STATIC_NONE) {
6079 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
6080 return ERR_INVALID_FIELDID;
6083 /* Check that the field belongs to the object */
6085 for (k = klass; k; k = k->parent) {
6086 if (k == f->parent) {
6092 return ERR_INVALID_FIELDID;
6094 vtable = mono_class_vtable (domain, f->parent);
6095 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6096 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
6097 buffer_add_value (buf, f->type, val, domain);
6102 case CMD_TYPE_SET_VALUES: {
6110 len = decode_int (p, &p, end);
6111 for (i = 0; i < len; ++i) {
6112 f = decode_fieldid (p, &p, end, NULL, &err);
6116 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6117 return ERR_INVALID_FIELDID;
6118 if (mono_class_field_is_special_static (f))
6119 return ERR_INVALID_FIELDID;
6121 /* Check that the field belongs to the object */
6123 for (k = klass; k; k = k->parent) {
6124 if (k == f->parent) {
6130 return ERR_INVALID_FIELDID;
6132 // FIXME: Check for literal/const
6134 vtable = mono_class_vtable (domain, f->parent);
6135 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6136 err = decode_value (f->type, domain, val, p, &p, end);
6141 if (MONO_TYPE_IS_REFERENCE (f->type))
6142 mono_field_static_set_value (vtable, f, *(gpointer*)val);
6144 mono_field_static_set_value (vtable, f, val);
6149 case CMD_TYPE_GET_OBJECT: {
6150 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
6151 buffer_add_objid (buf, o);
6154 case CMD_TYPE_GET_SOURCE_FILES:
6155 case CMD_TYPE_GET_SOURCE_FILES_2: {
6156 gpointer iter = NULL;
6158 char *source_file, *base;
6162 files = g_ptr_array_new ();
6164 while ((method = mono_class_get_methods (klass, &iter))) {
6165 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6168 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
6172 for (i = 0; i < files->len; ++i)
6173 if (!strcmp (g_ptr_array_index (files, i), source_file))
6175 if (i == files->len)
6176 g_ptr_array_add (files, g_strdup (source_file));
6177 g_free (source_file);
6181 buffer_add_int (buf, files->len);
6182 for (i = 0; i < files->len; ++i) {
6183 source_file = g_ptr_array_index (files, i);
6184 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
6185 buffer_add_string (buf, source_file);
6187 base = g_path_get_basename (source_file);
6188 buffer_add_string (buf, base);
6191 g_free (source_file);
6193 g_ptr_array_free (files, TRUE);
6196 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
6197 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
6201 if (mono_class_is_assignable_from (klass, oklass))
6202 buffer_add_byte (buf, 1);
6204 buffer_add_byte (buf, 0);
6208 return ERR_NOT_IMPLEMENTED;
6215 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6218 MonoDomain *old_domain;
6222 klass = decode_typeid (p, &p, end, &domain, &err);
6226 old_domain = mono_domain_get ();
6228 mono_domain_set (domain, TRUE);
6230 err = type_commands_internal (command, klass, domain, p, end, buf);
6232 mono_domain_set (old_domain, TRUE);
6238 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6240 MonoMethodHeader *header;
6243 case CMD_METHOD_GET_NAME: {
6244 buffer_add_string (buf, method->name);
6247 case CMD_METHOD_GET_DECLARING_TYPE: {
6248 buffer_add_typeid (buf, domain, method->klass);
6251 case CMD_METHOD_GET_DEBUG_INFO: {
6252 MonoDebugMethodInfo *minfo;
6254 int i, n_il_offsets;
6258 header = mono_method_get_header (method);
6260 buffer_add_int (buf, 0);
6261 buffer_add_string (buf, "");
6262 buffer_add_int (buf, 0);
6266 minfo = mono_debug_lookup_method (method);
6268 buffer_add_int (buf, header->code_size);
6269 buffer_add_string (buf, "");
6270 buffer_add_int (buf, 0);
6271 mono_metadata_free_mh (header);
6275 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
6276 buffer_add_int (buf, header->code_size);
6277 buffer_add_string (buf, source_file);
6278 buffer_add_int (buf, n_il_offsets);
6279 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
6280 for (i = 0; i < n_il_offsets; ++i) {
6281 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
6282 buffer_add_int (buf, il_offsets [i]);
6283 buffer_add_int (buf, line_numbers [i]);
6285 g_free (source_file);
6286 g_free (il_offsets);
6287 g_free (line_numbers);
6288 mono_metadata_free_mh (header);
6291 case CMD_METHOD_GET_PARAM_INFO: {
6292 MonoMethodSignature *sig = mono_method_signature (method);
6296 /* FIXME: mono_class_from_mono_type () and byrefs */
6298 /* FIXME: Use a smaller encoding */
6299 buffer_add_int (buf, sig->call_convention);
6300 buffer_add_int (buf, sig->param_count);
6301 buffer_add_int (buf, sig->generic_param_count);
6302 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
6303 for (i = 0; i < sig->param_count; ++i) {
6305 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
6308 /* Emit parameter names */
6309 names = g_new (char *, sig->param_count);
6310 mono_method_get_param_names (method, (const char **) names);
6311 for (i = 0; i < sig->param_count; ++i)
6312 buffer_add_string (buf, names [i]);
6317 case CMD_METHOD_GET_LOCALS_INFO: {
6318 int i, j, num_locals;
6319 MonoDebugLocalsInfo *locals;
6321 header = mono_method_get_header (method);
6324 buffer_add_int (buf, header->num_locals);
6327 for (i = 0; i < header->num_locals; ++i)
6328 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
6331 locals = mono_debug_lookup_locals (method);
6333 num_locals = locals->num_locals;
6336 for (i = 0; i < header->num_locals; ++i) {
6337 for (j = 0; j < num_locals; ++j)
6338 if (locals->locals [j].index == i)
6341 buffer_add_string (buf, locals->locals [j].name);
6343 buffer_add_string (buf, "");
6347 for (i = 0; i < header->num_locals; ++i) {
6348 for (j = 0; j < num_locals; ++j)
6349 if (locals->locals [j].index == i)
6351 if (j < num_locals && locals->locals [j].block) {
6352 buffer_add_int (buf, locals->locals [j].block->start_offset);
6353 buffer_add_int (buf, locals->locals [j].block->end_offset);
6355 buffer_add_int (buf, 0);
6356 buffer_add_int (buf, header->code_size);
6359 mono_metadata_free_mh (header);
6362 mono_debug_symfile_free_locals (locals);
6366 case CMD_METHOD_GET_INFO:
6367 buffer_add_int (buf, method->flags);
6368 buffer_add_int (buf, method->iflags);
6369 buffer_add_int (buf, method->token);
6371 case CMD_METHOD_GET_BODY: {
6374 header = mono_method_get_header (method);
6376 buffer_add_int (buf, 0);
6378 buffer_add_int (buf, header->code_size);
6379 for (i = 0; i < header->code_size; ++i)
6380 buffer_add_byte (buf, header->code [i]);
6382 mono_metadata_free_mh (header);
6385 case CMD_METHOD_RESOLVE_TOKEN: {
6386 guint32 token = decode_int (p, &p, end);
6389 switch (mono_metadata_token_code (token)) {
6390 case MONO_TOKEN_STRING: {
6394 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
6397 s2 = mono_string_to_utf8 (s);
6399 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6400 buffer_add_string (buf, s2);
6406 MonoClass *handle_class;
6408 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6409 val = mono_method_get_wrapper_data (method, token);
6410 handle_class = mono_method_get_wrapper_data (method, token + 1);
6412 if (handle_class == NULL) {
6413 // Can't figure out the token type
6414 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
6418 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
6422 if (handle_class == mono_defaults.typehandle_class) {
6423 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
6424 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
6425 } else if (handle_class == mono_defaults.fieldhandle_class) {
6426 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
6427 buffer_add_fieldid (buf, domain, val);
6428 } else if (handle_class == mono_defaults.methodhandle_class) {
6429 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
6430 buffer_add_methodid (buf, domain, val);
6431 } else if (handle_class == mono_defaults.string_class) {
6434 s = mono_string_to_utf8 (val);
6435 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6436 buffer_add_string (buf, s);
6439 g_assert_not_reached ();
6447 return ERR_NOT_IMPLEMENTED;
6454 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6457 MonoDomain *old_domain;
6461 method = decode_methodid (p, &p, end, &domain, &err);
6465 old_domain = mono_domain_get ();
6467 mono_domain_set (domain, TRUE);
6469 err = method_commands_internal (command, method, domain, p, end, buf);
6471 mono_domain_set (old_domain, TRUE);
6477 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6479 int objid = decode_objid (p, &p, end);
6481 MonoThread *thread_obj;
6482 MonoInternalThread *thread;
6484 err = get_object (objid, (MonoObject**)&thread_obj);
6488 thread = THREAD_TO_INTERNAL (thread_obj);
6491 case CMD_THREAD_GET_NAME: {
6493 gunichar2 *s = mono_thread_get_name (thread, &name_len);
6496 buffer_add_int (buf, 0);
6501 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
6503 buffer_add_int (buf, len);
6504 buffer_add_data (buf, (guint8*)name, len);
6509 case CMD_THREAD_GET_FRAME_INFO: {
6510 DebuggerTlsData *tls;
6511 int i, start_frame, length;
6513 // Wait for suspending if it already started
6515 wait_for_suspend ();
6516 if (!is_suspended ())
6517 return ERR_NOT_SUSPENDED;
6519 start_frame = decode_int (p, &p, end);
6520 length = decode_int (p, &p, end);
6522 if (start_frame != 0 || length != -1)
6523 return ERR_NOT_IMPLEMENTED;
6525 mono_loader_lock ();
6526 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6527 mono_loader_unlock ();
6530 compute_frame_info (thread, tls);
6532 buffer_add_int (buf, tls->frame_count);
6533 for (i = 0; i < tls->frame_count; ++i) {
6534 buffer_add_int (buf, tls->frames [i]->id);
6535 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
6536 buffer_add_int (buf, tls->frames [i]->il_offset);
6538 * Instead of passing the frame type directly to the client, we associate
6539 * it with the previous frame using a set of flags. This avoids lots of
6540 * conditional code in the client, since a frame whose type isn't
6541 * FRAME_TYPE_MANAGED has no method, location, etc.
6543 buffer_add_byte (buf, tls->frames [i]->flags);
6548 case CMD_THREAD_GET_STATE:
6549 buffer_add_int (buf, thread->state);
6551 case CMD_THREAD_GET_INFO:
6552 buffer_add_byte (buf, thread->threadpool_thread);
6554 case CMD_THREAD_GET_ID:
6555 buffer_add_long (buf, (guint64)(gsize)thread);
6558 return ERR_NOT_IMPLEMENTED;
6565 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6569 MonoThread *thread_obj;
6570 MonoInternalThread *thread;
6572 DebuggerTlsData *tls;
6574 MonoDebugMethodJitInfo *jit;
6575 MonoDebugVarInfo *var;
6576 MonoMethodSignature *sig;
6578 MonoMethodHeader *header;
6580 objid = decode_objid (p, &p, end);
6581 err = get_object (objid, (MonoObject**)&thread_obj);
6585 thread = THREAD_TO_INTERNAL (thread_obj);
6587 id = decode_id (p, &p, end);
6589 mono_loader_lock ();
6590 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6591 mono_loader_unlock ();
6594 for (i = 0; i < tls->frame_count; ++i) {
6595 if (tls->frames [i]->id == id)
6598 if (i == tls->frame_count)
6599 return ERR_INVALID_FRAMEID;
6601 frame = tls->frames [i];
6603 if (!frame->has_ctx)
6605 return ERR_INVALID_FRAMEID;
6608 frame->jit = mono_debug_find_method (frame->method, frame->domain);
6610 /* This could happen for aot images with no jit debug info */
6611 return ERR_ABSENT_INFORMATION;
6615 sig = mono_method_signature (frame->actual_method);
6618 case CMD_STACK_FRAME_GET_VALUES: {
6619 len = decode_int (p, &p, end);
6620 header = mono_method_get_header (frame->actual_method);
6622 for (i = 0; i < len; ++i) {
6623 pos = decode_int (p, &p, end);
6628 g_assert (pos >= 0 && pos < jit->num_params);
6630 var = &jit->params [pos];
6632 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
6634 g_assert (pos >= 0 && pos < jit->num_locals);
6636 var = &jit->locals [pos];
6638 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
6641 mono_metadata_free_mh (header);
6644 case CMD_STACK_FRAME_GET_THIS: {
6645 if (frame->method->klass->valuetype) {
6646 if (!sig->hasthis) {
6647 MonoObject *p = NULL;
6648 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
6650 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6653 if (!sig->hasthis) {
6654 MonoObject *p = NULL;
6655 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
6657 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6662 case CMD_STACK_FRAME_SET_VALUES: {
6665 MonoDebugVarInfo *var;
6667 len = decode_int (p, &p, end);
6668 header = mono_method_get_header (frame->actual_method);
6670 for (i = 0; i < len; ++i) {
6671 pos = decode_int (p, &p, end);
6676 g_assert (pos >= 0 && pos < jit->num_params);
6678 t = sig->params [pos];
6679 var = &jit->params [pos];
6681 g_assert (pos >= 0 && pos < jit->num_locals);
6683 t = header->locals [pos];
6684 var = &jit->locals [pos];
6687 if (MONO_TYPE_IS_REFERENCE (t))
6688 val_buf = g_alloca (sizeof (MonoObject*));
6690 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
6691 err = decode_value (t, frame->domain, val_buf, p, &p, end);
6695 set_var (t, var, &frame->ctx, frame->domain, val_buf);
6697 mono_metadata_free_mh (header);
6701 return ERR_NOT_IMPLEMENTED;
6708 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6711 int objid, err, index, len, i, esize;
6714 objid = decode_objid (p, &p, end);
6715 err = get_object (objid, (MonoObject**)&arr);
6720 case CMD_ARRAY_REF_GET_LENGTH:
6721 buffer_add_int (buf, arr->obj.vtable->klass->rank);
6723 buffer_add_int (buf, arr->max_length);
6724 buffer_add_int (buf, 0);
6726 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
6727 buffer_add_int (buf, arr->bounds [i].length);
6728 buffer_add_int (buf, arr->bounds [i].lower_bound);
6732 case CMD_ARRAY_REF_GET_VALUES:
6733 index = decode_int (p, &p, end);
6734 len = decode_int (p, &p, end);
6736 g_assert (index >= 0 && len >= 0);
6737 // Reordered to avoid integer overflow
6738 g_assert (!(index > arr->max_length - len));
6740 esize = mono_array_element_size (arr->obj.vtable->klass);
6741 for (i = index; i < index + len; ++i) {
6742 elem = (gpointer*)((char*)arr->vector + (i * esize));
6743 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
6746 case CMD_ARRAY_REF_SET_VALUES:
6747 index = decode_int (p, &p, end);
6748 len = decode_int (p, &p, end);
6750 g_assert (index >= 0 && len >= 0);
6751 // Reordered to avoid integer overflow
6752 g_assert (!(index > arr->max_length - len));
6754 esize = mono_array_element_size (arr->obj.vtable->klass);
6755 for (i = index; i < index + len; ++i) {
6756 elem = (gpointer*)((char*)arr->vector + (i * esize));
6758 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
6762 return ERR_NOT_IMPLEMENTED;
6769 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6775 objid = decode_objid (p, &p, end);
6776 err = get_object (objid, (MonoObject**)&str);
6781 case CMD_STRING_REF_GET_VALUE:
6782 s = mono_string_to_utf8 (str);
6783 buffer_add_string (buf, s);
6787 return ERR_NOT_IMPLEMENTED;
6794 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6803 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
6804 objid = decode_objid (p, &p, end);
6805 err = get_object (objid, &obj);
6807 buffer_add_int (buf, 1);
6809 buffer_add_int (buf, 0);
6813 objid = decode_objid (p, &p, end);
6814 err = get_object (objid, &obj);
6819 case CMD_OBJECT_REF_GET_TYPE:
6820 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
6822 case CMD_OBJECT_REF_GET_VALUES:
6823 len = decode_int (p, &p, end);
6825 for (i = 0; i < len; ++i) {
6826 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
6830 /* Check that the field belongs to the object */
6832 for (k = obj->vtable->klass; k; k = k->parent) {
6833 if (k == f->parent) {
6839 return ERR_INVALID_FIELDID;
6841 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6845 if (mono_class_field_is_special_static (f))
6846 return ERR_INVALID_FIELDID;
6848 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6849 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6850 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6851 mono_field_static_get_value (vtable, f, val);
6852 buffer_add_value (buf, f->type, val, obj->vtable->domain);
6855 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
6859 case CMD_OBJECT_REF_SET_VALUES:
6860 len = decode_int (p, &p, end);
6862 for (i = 0; i < len; ++i) {
6863 f = decode_fieldid (p, &p, end, NULL, &err);
6867 /* Check that the field belongs to the object */
6869 for (k = obj->vtable->klass; k; k = k->parent) {
6870 if (k == f->parent) {
6876 return ERR_INVALID_FIELDID;
6878 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6882 if (mono_class_field_is_special_static (f))
6883 return ERR_INVALID_FIELDID;
6885 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6886 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6888 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6889 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
6894 mono_field_static_set_value (vtable, f, val);
6897 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
6903 case CMD_OBJECT_REF_GET_ADDRESS:
6904 buffer_add_long (buf, (gssize)obj);
6906 case CMD_OBJECT_REF_GET_DOMAIN:
6907 buffer_add_domainid (buf, obj->vtable->domain);
6910 return ERR_NOT_IMPLEMENTED;
6917 command_set_to_string (CommandSet command_set)
6919 switch (command_set) {
6922 case CMD_SET_OBJECT_REF:
6923 return "OBJECT_REF";
6924 case CMD_SET_STRING_REF:
6925 return "STRING_REF";
6926 case CMD_SET_THREAD:
6928 case CMD_SET_ARRAY_REF:
6930 case CMD_SET_EVENT_REQUEST:
6931 return "EVENT_REQUEST";
6932 case CMD_SET_STACK_FRAME:
6933 return "STACK_FRAME";
6934 case CMD_SET_APPDOMAIN:
6936 case CMD_SET_ASSEMBLY:
6938 case CMD_SET_METHOD:
6942 case CMD_SET_MODULE:
6952 cmd_to_string (CommandSet set, int command)
6957 case CMD_VM_VERSION:
6959 case CMD_VM_ALL_THREADS:
6960 return "ALL_THREADS";
6961 case CMD_VM_SUSPEND:
6967 case CMD_VM_DISPOSE:
6969 case CMD_VM_INVOKE_METHOD:
6970 return "INVOKE_METHOD";
6971 case CMD_VM_SET_PROTOCOL_VERSION:
6972 return "SET_PROTOCOL_VERSION";
6973 case CMD_VM_ABORT_INVOKE:
6974 return "ABORT_INVOKE";
6989 * This thread handles communication with the debugger client using a JDWP
6992 static guint32 WINAPI
6993 debugger_thread (void *arg)
6995 int res, len, id, flags, command_set, command;
6996 guint8 header [HEADER_LENGTH];
6997 guint8 *data, *p, *end;
7002 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
7004 debugger_thread_id = GetCurrentThreadId ();
7006 mono_jit_thread_attach (mono_get_root_domain ());
7008 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
7010 mono_set_is_debugger_attached (TRUE);
7013 res = recv_length (conn_fd, header, HEADER_LENGTH, 0);
7015 /* This will break if the socket is closed during shutdown too */
7016 if (res != HEADER_LENGTH)
7020 end = header + HEADER_LENGTH;
7022 len = decode_int (p, &p, end);
7023 id = decode_int (p, &p, end);
7024 flags = decode_byte (p, &p, end);
7025 command_set = decode_byte (p, &p, end);
7026 command = decode_byte (p, &p, end);
7028 g_assert (flags == 0);
7031 const char *cmd_str;
7034 cmd_str = cmd_to_string (command_set, command);
7036 sprintf (cmd_num, "%d", command);
7040 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
7043 data = g_malloc (len - HEADER_LENGTH);
7044 if (len - HEADER_LENGTH > 0)
7046 res = recv_length (conn_fd, data, len - HEADER_LENGTH, 0);
7047 if (res != len - HEADER_LENGTH)
7052 end = data + (len - HEADER_LENGTH);
7054 buffer_init (&buf, 128);
7059 /* Process the request */
7060 switch (command_set) {
7062 err = vm_commands (command, id, p, end, &buf);
7063 if (!err && command == CMD_VM_INVOKE_METHOD)
7064 /* Sent after the invoke is complete */
7067 case CMD_SET_EVENT_REQUEST:
7068 err = event_commands (command, p, end, &buf);
7070 case CMD_SET_APPDOMAIN:
7071 err = domain_commands (command, p, end, &buf);
7073 case CMD_SET_ASSEMBLY:
7074 err = assembly_commands (command, p, end, &buf);
7076 case CMD_SET_MODULE:
7077 err = module_commands (command, p, end, &buf);
7080 err = type_commands (command, p, end, &buf);
7082 case CMD_SET_METHOD:
7083 err = method_commands (command, p, end, &buf);
7085 case CMD_SET_THREAD:
7086 err = thread_commands (command, p, end, &buf);
7088 case CMD_SET_STACK_FRAME:
7089 err = frame_commands (command, p, end, &buf);
7091 case CMD_SET_ARRAY_REF:
7092 err = array_commands (command, p, end, &buf);
7094 case CMD_SET_STRING_REF:
7095 err = string_commands (command, p, end, &buf);
7097 case CMD_SET_OBJECT_REF:
7098 err = object_commands (command, p, end, &buf);
7101 err = ERR_NOT_IMPLEMENTED;
7105 send_reply_packet (id, err, &buf);
7110 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
7114 mono_set_is_debugger_attached (FALSE);
7116 mono_mutex_lock (&debugger_thread_exited_mutex);
7117 debugger_thread_exited = TRUE;
7118 mono_cond_signal (&debugger_thread_exited_cond);
7119 mono_mutex_unlock (&debugger_thread_exited_mutex);
7121 DEBUG (1, printf ("[dbg] Debugger thread exited.\n"));
7126 #else /* DISABLE_DEBUGGER_AGENT */
7129 mono_debugger_agent_parse_options (char *options)
7131 g_error ("This runtime is configured with the debugger agent disabled.");
7135 mono_debugger_agent_init (void)
7140 mono_debugger_agent_breakpoint_hit (void *sigctx)
7145 mono_debugger_agent_single_step_event (void *sigctx)
7150 mono_debugger_agent_free_domain_info (MonoDomain *domain)
7155 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
7161 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
7162 MonoContext *catch_ctx)