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 "debugger-agent.h"
78 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
79 #define DISABLE_DEBUGGER_AGENT 1
82 #ifdef DISABLE_SOFT_DEBUG
83 #define DISABLE_DEBUGGER_AGENT 1
86 #ifndef DISABLE_DEBUGGER_AGENT
87 #include <mono/io-layer/mono-mutex.h>
89 /* Definitions to make backporting to 2.6 easier */
90 //#define MonoInternalThread MonoThread
91 //#define mono_thread_internal_current mono_thread_current
92 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
112 guint32 il_offset, native_offset;
116 * If method is gshared, this is the actual instance, otherwise this is equal to
119 MonoMethod *actual_method;
121 MonoDebugMethodJitInfo *jit;
124 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
125 * the frame can become invalid.
130 typedef struct _InvokeData InvokeData;
138 /* This is the context which needs to be restored after the invoke */
142 * If this is set, invoke this method with the arguments given by ARGS.
146 guint32 suspend_count;
148 InvokeData *last_invoke;
155 gboolean has_context;
156 gpointer resume_event;
157 /* This is computed on demand when it is requested using the wire protocol */
158 /* It is freed up when the thread is resumed */
162 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
165 gboolean frames_up_to_date;
167 * Points to data about a pending invoke which needs to be executed after the thread
170 InvokeData *pending_invoke;
172 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
177 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
178 * within a finite amount of time.
182 * Set to TRUE if this thread is suspended in suspend_current ().
184 gboolean really_suspended;
185 /* Used to pass the context to the breakpoint/single step handler */
186 MonoContext handler_ctx;
187 /* Whenever thread_stop () was called for this thread */
190 /* Number of thread interruptions not yet processed */
191 gint32 interrupt_count;
193 /* Whenever to disable breakpoints (used during invokes) */
194 gboolean disable_breakpoints;
197 * Number of times this thread has been resumed using resume_thread ().
199 guint32 resume_count;
201 MonoInternalThread *thread;
204 * Information about the frame which transitioned to native code for running
207 StackFrameInfo async_last_frame;
210 * The context where the stack walk can be started for running threads.
212 MonoContext async_ctx;
214 gboolean has_async_ctx;
216 gboolean has_filter_ctx;
217 MonoContext filter_ctx;
221 * The lmf where the stack walk can be started for running threads.
226 * The callee address of the last mono_runtime_invoke call
228 gpointer invoke_addr;
230 gboolean abort_requested;
233 * The current mono_runtime_invoke invocation.
238 * The context where single stepping should resume while the thread is suspended because
239 * of an EXCEPTION event.
241 MonoContext catch_ctx;
243 gboolean has_catch_ctx;
247 * Wire Protocol definitions
250 #define HEADER_LENGTH 11
252 #define MAJOR_VERSION 2
253 #define MINOR_VERSION 2
257 CMD_SET_OBJECT_REF = 9,
258 CMD_SET_STRING_REF = 10,
260 CMD_SET_ARRAY_REF = 13,
261 CMD_SET_EVENT_REQUEST = 15,
262 CMD_SET_STACK_FRAME = 16,
263 CMD_SET_APPDOMAIN = 20,
264 CMD_SET_ASSEMBLY = 21,
272 EVENT_KIND_VM_START = 0,
273 EVENT_KIND_VM_DEATH = 1,
274 EVENT_KIND_THREAD_START = 2,
275 EVENT_KIND_THREAD_DEATH = 3,
276 EVENT_KIND_APPDOMAIN_CREATE = 4,
277 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
278 EVENT_KIND_METHOD_ENTRY = 6,
279 EVENT_KIND_METHOD_EXIT = 7,
280 EVENT_KIND_ASSEMBLY_LOAD = 8,
281 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
282 EVENT_KIND_BREAKPOINT = 10,
283 EVENT_KIND_STEP = 11,
284 EVENT_KIND_TYPE_LOAD = 12,
285 EVENT_KIND_EXCEPTION = 13
289 SUSPEND_POLICY_NONE = 0,
290 SUSPEND_POLICY_EVENT_THREAD = 1,
291 SUSPEND_POLICY_ALL = 2
296 ERR_INVALID_OBJECT = 20,
297 ERR_INVALID_FIELDID = 25,
298 ERR_INVALID_FRAMEID = 30,
299 ERR_NOT_IMPLEMENTED = 100,
300 ERR_NOT_SUSPENDED = 101,
301 ERR_INVALID_ARGUMENT = 102,
303 ERR_NO_INVOCATION = 104,
304 ERR_ABSENT_INFORMATION = 105
309 MOD_KIND_THREAD_ONLY = 3,
310 MOD_KIND_LOCATION_ONLY = 7,
311 MOD_KIND_EXCEPTION_ONLY = 8,
313 MOD_KIND_ASSEMBLY_ONLY = 11
328 TOKEN_TYPE_STRING = 0,
330 TOKEN_TYPE_FIELD = 2,
331 TOKEN_TYPE_METHOD = 3,
332 TOKEN_TYPE_UNKNOWN = 4
336 VALUE_TYPE_ID_NULL = 0xf0,
337 VALUE_TYPE_ID_TYPE = 0xf1
341 FRAME_FLAG_DEBUGGER_INVOKE = 1
345 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
346 INVOKE_FLAG_SINGLE_THREADED = 2
351 CMD_VM_ALL_THREADS = 2,
356 CMD_VM_INVOKE_METHOD = 7,
357 CMD_VM_SET_PROTOCOL_VERSION = 8,
358 CMD_VM_ABORT_INVOKE = 9
362 CMD_THREAD_GET_FRAME_INFO = 1,
363 CMD_THREAD_GET_NAME = 2,
364 CMD_THREAD_GET_STATE = 3,
365 CMD_THREAD_GET_INFO = 4,
366 CMD_THREAD_GET_ID = 5
370 CMD_EVENT_REQUEST_SET = 1,
371 CMD_EVENT_REQUEST_CLEAR = 2,
372 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
380 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
381 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
382 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
383 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
384 CMD_APPDOMAIN_CREATE_STRING = 5,
385 CMD_APPDOMAIN_GET_CORLIB = 6,
386 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
390 CMD_ASSEMBLY_GET_LOCATION = 1,
391 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
392 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
393 CMD_ASSEMBLY_GET_OBJECT = 4,
394 CMD_ASSEMBLY_GET_TYPE = 5,
395 CMD_ASSEMBLY_GET_NAME = 6
399 CMD_MODULE_GET_INFO = 1,
403 CMD_METHOD_GET_NAME = 1,
404 CMD_METHOD_GET_DECLARING_TYPE = 2,
405 CMD_METHOD_GET_DEBUG_INFO = 3,
406 CMD_METHOD_GET_PARAM_INFO = 4,
407 CMD_METHOD_GET_LOCALS_INFO = 5,
408 CMD_METHOD_GET_INFO = 6,
409 CMD_METHOD_GET_BODY = 7,
410 CMD_METHOD_RESOLVE_TOKEN = 8,
414 CMD_TYPE_GET_INFO = 1,
415 CMD_TYPE_GET_METHODS = 2,
416 CMD_TYPE_GET_FIELDS = 3,
417 CMD_TYPE_GET_VALUES = 4,
418 CMD_TYPE_GET_OBJECT = 5,
419 CMD_TYPE_GET_SOURCE_FILES = 6,
420 CMD_TYPE_SET_VALUES = 7,
421 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
422 CMD_TYPE_GET_PROPERTIES = 9,
423 CMD_TYPE_GET_CATTRS = 10,
424 CMD_TYPE_GET_FIELD_CATTRS = 11,
425 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
426 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
430 CMD_STACK_FRAME_GET_VALUES = 1,
431 CMD_STACK_FRAME_GET_THIS = 2,
432 CMD_STACK_FRAME_SET_VALUES = 3
436 CMD_ARRAY_REF_GET_LENGTH = 1,
437 CMD_ARRAY_REF_GET_VALUES = 2,
438 CMD_ARRAY_REF_SET_VALUES = 3,
442 CMD_STRING_REF_GET_VALUE = 1,
446 CMD_OBJECT_REF_GET_TYPE = 1,
447 CMD_OBJECT_REF_GET_VALUES = 2,
448 CMD_OBJECT_REF_IS_COLLECTED = 3,
449 CMD_OBJECT_REF_GET_ADDRESS = 4,
450 CMD_OBJECT_REF_GET_DOMAIN = 5,
451 CMD_OBJECT_REF_SET_VALUES = 6
457 int count; /* For kind == MOD_KIND_COUNT */
458 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
459 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
460 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
462 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
471 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
475 * Describes a single step request.
479 MonoInternalThread *thread;
484 MonoMethod *last_method;
486 /* Whenever single stepping is performed using start/stop_single_stepping () */
488 /* The list of breakpoints used to implement step-over */
493 * Contains additional information for an event
496 /* For EVENT_KIND_EXCEPTION */
498 MonoContext catch_ctx;
502 /* Dummy structure used for the profiler callbacks */
507 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
513 static AgentConfig agent_config;
516 * Whenever the agent is fully initialized.
517 * When using the onuncaught or onthrow options, only some parts of the agent are
518 * initialized on startup, and the full initialization which includes connection
519 * establishment and the startup of the agent thread is only done in response to
522 static gint32 inited;
526 static int packet_id = 0;
528 static int objref_id = 0;
530 static int event_request_id = 0;
532 static int frame_id = 0;
534 static GPtrArray *event_requests;
536 static guint32 debugger_tls_id;
538 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
540 /* Maps MonoInternalThread -> DebuggerTlsData */
541 static MonoGHashTable *thread_to_tls;
543 /* Maps tid -> MonoInternalThread */
544 static MonoGHashTable *tid_to_thread;
546 /* Maps tid -> MonoThread (not MonoInternalThread) */
547 static MonoGHashTable *tid_to_thread_obj;
549 static gsize debugger_thread_id;
551 static HANDLE debugger_thread_handle;
553 static int log_level;
555 static gboolean embedding;
557 static FILE *log_file;
559 /* Classes whose class load event has been sent */
560 static GHashTable *loaded_classes;
562 /* Assemblies whose assembly load event has no been sent yet */
563 static GPtrArray *pending_assembly_loads;
565 /* Types whose type load event has no been sent yet */
566 static GPtrArray *pending_type_loads;
568 /* Whenever the debugger thread has exited */
569 static gboolean debugger_thread_exited;
571 /* Cond variable used to wait for debugger_thread_exited becoming true */
572 static mono_cond_t debugger_thread_exited_cond;
574 /* Mutex for the cond var above */
575 static mono_mutex_t debugger_thread_exited_mutex;
577 static DebuggerProfiler debugger_profiler;
579 /* The single step request instance */
580 static SingleStepReq *ss_req = NULL;
581 static gpointer ss_invoke_addr = NULL;
583 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
584 /* Number of single stepping operations in progress */
588 /* The protocol version of the client */
589 static int major_version, minor_version;
591 /* Whenever the variables above are set by the client */
592 static gboolean protocol_version_set;
594 /* A hash table containing all active domains */
595 static GHashTable *domains;
597 static void transport_connect (const char *host, int port);
599 static guint32 WINAPI debugger_thread (void *arg);
601 static void runtime_initialized (MonoProfiler *prof);
603 static void runtime_shutdown (MonoProfiler *prof);
605 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
607 static void thread_end (MonoProfiler *prof, uintptr_t tid);
609 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
611 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
613 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
615 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
617 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
619 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
621 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
623 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
625 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
627 static void start_single_stepping (void);
629 static void stop_single_stepping (void);
631 static void suspend_current (void);
633 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
635 static void clear_breakpoints_for_domain (MonoDomain *domain);
637 static void clear_types_for_assembly (MonoAssembly *assembly);
639 /* Submodule init/cleanup */
640 static void breakpoints_init (void);
641 static void breakpoints_cleanup (void);
643 static void objrefs_init (void);
644 static void objrefs_cleanup (void);
646 static void ids_init (void);
647 static void ids_cleanup (void);
649 static void suspend_init (void);
651 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
652 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
653 static void ss_destroy (SingleStepReq *req);
655 static void start_debugger_thread (void);
657 static void finish_agent_init (gboolean on_startup);
660 parse_address (char *address, char **host, int *port)
662 char *pos = strchr (address, ':');
664 if (pos == NULL || pos == address)
667 *host = g_malloc (pos - address + 1);
668 strncpy (*host, address, pos - address);
669 (*host) [pos - address] = '\0';
671 *port = atoi (pos + 1);
679 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
680 fprintf (stderr, "Available options:\n");
681 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
682 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
683 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
684 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
685 fprintf (stderr, " suspend=y/n\t\t\tWhenever to suspend after startup.\n");
686 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
687 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
691 parse_flag (const char *option, char *flag)
693 if (!strcmp (flag, "y"))
695 else if (!strcmp (flag, "n"))
698 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
705 mono_debugger_agent_parse_options (char *options)
711 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
712 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
716 agent_config.enabled = TRUE;
717 agent_config.suspend = TRUE;
718 agent_config.server = FALSE;
720 args = g_strsplit (options, ",", -1);
721 for (ptr = args; ptr && *ptr; ptr ++) {
724 if (strncmp (arg, "transport=", 10) == 0) {
725 agent_config.transport = g_strdup (arg + 10);
726 } else if (strncmp (arg, "address=", 8) == 0) {
727 agent_config.address = g_strdup (arg + 8);
728 } else if (strncmp (arg, "loglevel=", 9) == 0) {
729 agent_config.log_level = atoi (arg + 9);
730 } else if (strncmp (arg, "logfile=", 8) == 0) {
731 agent_config.log_file = g_strdup (arg + 8);
732 } else if (strncmp (arg, "suspend=", 8) == 0) {
733 agent_config.suspend = parse_flag ("suspend", arg + 8);
734 } else if (strncmp (arg, "server=", 7) == 0) {
735 agent_config.server = parse_flag ("server", arg + 7);
736 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
737 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
738 } else if (strncmp (arg, "onthrow=", 8) == 0) {
739 /* We support multiple onthrow= options */
740 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
741 } else if (strncmp (arg, "onthrow", 7) == 0) {
742 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
743 } else if (strncmp (arg, "help", 4) == 0) {
746 } else if (strncmp (arg, "timeout=", 8) == 0) {
747 agent_config.timeout = atoi (arg + 8);
748 } else if (strncmp (arg, "launch=", 7) == 0) {
749 agent_config.launch = g_strdup (arg + 7);
750 } else if (strncmp (arg, "embedding=", 10) == 0) {
751 agent_config.embedding = atoi (arg + 10) == 1;
758 if (agent_config.transport == NULL) {
759 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
762 if (strcmp (agent_config.transport, "dt_socket") != 0) {
763 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
767 if (agent_config.address == NULL && !agent_config.server) {
768 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
772 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
773 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
779 mono_debugger_agent_init (void)
781 if (!agent_config.enabled)
784 /* Need to know whenever a thread has acquired the loader mutex */
785 mono_loader_lock_track_ownership (TRUE);
787 event_requests = g_ptr_array_new ();
789 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
790 mono_cond_init (&debugger_thread_exited_cond, NULL);
792 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
793 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
794 mono_profiler_install_runtime_initialized (runtime_initialized);
795 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
796 mono_profiler_install_thread (thread_startup, thread_end);
797 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
798 mono_profiler_install_jit_end (jit_end);
799 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
801 debugger_tls_id = TlsAlloc ();
803 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
804 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
806 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
807 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
809 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
810 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
812 loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
813 pending_assembly_loads = g_ptr_array_new ();
814 pending_type_loads = g_ptr_array_new ();
815 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
817 log_level = agent_config.log_level;
819 embedding = agent_config.embedding;
821 if (agent_config.log_file) {
822 log_file = fopen (agent_config.log_file, "w+");
824 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
836 mini_get_debug_options ()->gen_seq_points = TRUE;
838 * This is needed because currently we don't handle liveness info.
840 mini_get_debug_options ()->mdb_optimizations = TRUE;
842 /* This is needed because we can't set local variables in registers yet */
843 mono_disable_optimizations (MONO_OPT_LINEARS);
845 if (!agent_config.onuncaught && !agent_config.onthrow)
846 finish_agent_init (TRUE);
852 * Finish the initialization of the agent. This involves connecting the transport
853 * and starting the agent thread. This is either done at startup, or
854 * in response to some event like an unhandled exception.
857 finish_agent_init (gboolean on_startup)
863 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
866 if (agent_config.launch) {
869 // FIXME: Generated address
870 // FIXME: Races with transport_connect ()
872 argv [0] = agent_config.launch;
873 argv [1] = agent_config.transport;
874 argv [2] = agent_config.address;
877 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
879 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
884 if (agent_config.address) {
885 res = parse_address (agent_config.address, &host, &port);
892 transport_connect (host, port);
895 /* Do some which is usually done after sending the VMStart () event */
896 vm_start_event_sent = TRUE;
897 start_debugger_thread ();
902 mono_debugger_agent_cleanup (void)
907 /* This will interrupt the agent thread */
908 /* Close the read part only so it can still send back replies */
910 shutdown (conn_fd, SD_RECEIVE);
912 shutdown (conn_fd, SHUT_RD);
916 * Wait for the thread to exit.
918 * If we continue with the shutdown without waiting for it, then the client might
919 * not receive an answer to its last command like a resume.
920 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
923 //WaitForSingleObject (debugger_thread_handle, INFINITE);
924 if (GetCurrentThreadId () != debugger_thread_id) {
925 mono_mutex_lock (&debugger_thread_exited_mutex);
926 while (!debugger_thread_exited) {
928 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
929 mono_mutex_unlock (&debugger_thread_exited_mutex);
931 mono_mutex_lock (&debugger_thread_exited_mutex);
934 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
937 mono_mutex_unlock (&debugger_thread_exited_mutex);
940 breakpoints_cleanup ();
945 shutdown (conn_fd, SD_BOTH);
947 shutdown (conn_fd, SHUT_RDWR);
950 mono_mutex_destroy (&debugger_thread_exited_mutex);
951 mono_cond_destroy (&debugger_thread_exited_cond);
957 * recv() + handle incomplete reads and EINTR
960 recv_length (int fd, void *buf, int len, int flags)
966 res = recv (fd, (char *) buf + total, len - total, flags);
969 } while ((res > 0 && total < len) || (res == -1 && errno == EINTR));
974 #define HAVE_GETADDRINFO 1
980 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
983 transport_connect (const char *host, int port)
985 #ifdef HAVE_GETADDRINFO
986 struct addrinfo hints;
987 struct addrinfo *result, *rp;
989 struct hostent *result;
992 char port_string [128];
993 char handshake_msg [128];
999 sprintf (port_string, "%d", port);
1001 mono_network_init ();
1003 /* Obtain address(es) matching host/port */
1004 #ifdef HAVE_GETADDRINFO
1005 memset (&hints, 0, sizeof (struct addrinfo));
1006 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1007 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1009 hints.ai_protocol = 0; /* Any protocol */
1011 s = getaddrinfo (host, port_string, &hints, &result);
1013 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1017 /* The PS3 doesn't even have _r or hstrerror () */
1018 result = gethostbyname (host);
1020 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1025 if (agent_config.server) {
1026 #ifdef HAVE_GETADDRINFO
1027 /* Wait for a connection */
1029 struct sockaddr_in addr;
1032 /* No address, generate one */
1033 sfd = socket (AF_INET, SOCK_STREAM, 0);
1036 /* This will bind the socket to a random port */
1037 res = listen (sfd, 16);
1039 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
1043 addrlen = sizeof (addr);
1044 memset (&addr, 0, sizeof (addr));
1045 res = getsockname (sfd, &addr, &addrlen);
1046 g_assert (res == 0);
1049 port = ntohs (addr.sin_port);
1051 /* Emit the address to stdout */
1052 /* FIXME: Should print another interface, not localhost */
1053 printf ("%s:%d\n", host, port);
1055 /* Listen on the provided address */
1056 for (rp = result; rp != NULL; rp = rp->ai_next) {
1057 sfd = socket (rp->ai_family, rp->ai_socktype,
1062 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1066 res = listen (sfd, 16);
1074 * this function is not present on win2000 which we still support, and the
1075 * workaround described here:
1076 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1077 * only works with MSVC.
1079 #ifdef HAVE_GETADDRINFO
1080 freeaddrinfo (result);
1085 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1087 if (agent_config.timeout) {
1092 tv.tv_usec = agent_config.timeout * 1000;
1094 FD_SET (sfd, &readfds);
1095 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1097 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1102 conn_fd = accept (sfd, NULL, NULL);
1103 if (conn_fd == -1) {
1104 fprintf (stderr, "debugger-agent: Unable to listen on %s:%d\n", host, port);
1108 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1111 #endif /* HAVE_GETADDRINFO */
1113 /* Connect to the specified address */
1114 #ifdef HAVE_GETADDRINFO
1115 /* FIXME: Respect the timeout */
1116 for (rp = result; rp != NULL; rp = rp->ai_next) {
1117 sfd = socket (rp->ai_family, rp->ai_socktype,
1122 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1123 break; /* Success */
1129 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1133 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1135 g_assert_not_reached ();
1136 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1138 g_assert_not_reached ();
1144 /* See the comment above */
1145 #ifdef HAVE_GETADDRINFO
1146 freeaddrinfo (result);
1151 /* Write handshake message */
1152 sprintf (handshake_msg, "DWP-Handshake");
1154 res = send (conn_fd, handshake_msg, strlen (handshake_msg), 0);
1155 } while (res == -1 && errno == EINTR);
1156 g_assert (res != -1);
1159 res = recv_length (conn_fd, buf, strlen (handshake_msg), 0);
1160 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1161 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1166 * To support older clients, the client sends its protocol version after connecting
1167 * using a command. Until that is received, default to our protocol version.
1169 major_version = MAJOR_VERSION;
1170 minor_version = MINOR_VERSION;
1171 protocol_version_set = FALSE;
1174 * Set TCP_NODELAY on the socket so the client receives events/command
1175 * results immediately.
1179 int result = setsockopt(conn_fd,
1184 g_assert (result >= 0);
1189 transport_send (guint8 *data, int len)
1194 res = send (conn_fd, data, len, 0);
1195 } while (res == -1 && errno == EINTR);
1203 start_debugger_thread (void)
1207 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1208 g_assert (debugger_thread_handle);
1212 * Functions to decode protocol data
1216 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1219 g_assert (*endbuf <= limit);
1224 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1227 g_assert (*endbuf <= limit);
1229 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1232 static inline gint64
1233 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1235 guint32 high = decode_int (buf, &buf, limit);
1236 guint32 low = decode_int (buf, &buf, limit);
1240 return ((((guint64)high) << 32) | ((guint64)low));
1244 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1246 return decode_int (buf, endbuf, limit);
1250 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1252 int len = decode_int (buf, &buf, limit);
1255 s = g_malloc (len + 1);
1258 memcpy (s, buf, len);
1267 * Functions to encode protocol data
1271 guint8 *buf, *p, *end;
1275 buffer_init (Buffer *buf, int size)
1277 buf->buf = g_malloc (size);
1279 buf->end = buf->buf + size;
1283 buffer_make_room (Buffer *buf, int size)
1285 if (buf->end - buf->p < size) {
1286 int new_size = buf->end - buf->buf + size + 32;
1287 guint8 *p = g_realloc (buf->buf, new_size);
1288 size = buf->p - buf->buf;
1291 buf->end = buf->buf + new_size;
1296 buffer_add_byte (Buffer *buf, guint8 val)
1298 buffer_make_room (buf, 1);
1304 buffer_add_int (Buffer *buf, guint32 val)
1306 buffer_make_room (buf, 4);
1307 buf->p [0] = (val >> 24) & 0xff;
1308 buf->p [1] = (val >> 16) & 0xff;
1309 buf->p [2] = (val >> 8) & 0xff;
1310 buf->p [3] = (val >> 0) & 0xff;
1315 buffer_add_long (Buffer *buf, guint64 l)
1317 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1318 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1322 buffer_add_id (Buffer *buf, int id)
1324 buffer_add_int (buf, (guint64)id);
1328 buffer_add_data (Buffer *buf, guint8 *data, int len)
1330 buffer_make_room (buf, len);
1331 memcpy (buf->p, data, len);
1336 buffer_add_string (Buffer *buf, const char *str)
1341 buffer_add_int (buf, 0);
1344 buffer_add_int (buf, len);
1345 buffer_add_data (buf, (guint8*)str, len);
1350 buffer_free (Buffer *buf)
1356 send_packet (int command_set, int command, Buffer *data)
1362 id = InterlockedIncrement (&packet_id);
1364 len = data->p - data->buf + 11;
1365 buffer_init (&buf, len);
1366 buffer_add_int (&buf, len);
1367 buffer_add_int (&buf, id);
1368 buffer_add_byte (&buf, 0); /* flags */
1369 buffer_add_byte (&buf, command_set);
1370 buffer_add_byte (&buf, command);
1371 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1373 res = transport_send (buf.buf, len);
1381 send_reply_packet (int id, int error, Buffer *data)
1387 len = data->p - data->buf + 11;
1388 buffer_init (&buf, len);
1389 buffer_add_int (&buf, len);
1390 buffer_add_int (&buf, id);
1391 buffer_add_byte (&buf, 0x80); /* flags */
1392 buffer_add_byte (&buf, (error >> 8) & 0xff);
1393 buffer_add_byte (&buf, error);
1394 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1396 res = transport_send (buf.buf, len);
1408 * Represents an object accessible by the debugger client.
1411 /* Unique id used in the wire protocol to refer to objects */
1414 * A weakref gc handle pointing to the object. The gc handle is used to
1415 * detect if the object was garbage collected.
1420 /* Maps objid -> ObjRef */
1421 static GHashTable *objrefs;
1424 free_objref (gpointer value)
1428 mono_gchandle_free (o->handle);
1436 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1440 objrefs_cleanup (void)
1442 g_hash_table_destroy (objrefs);
1446 static GHashTable *obj_to_objref;
1449 * Return an ObjRef for OBJ.
1452 get_objref (MonoObject *obj)
1455 GSList *reflist = NULL, *l;
1461 mono_loader_lock ();
1464 obj_to_objref = g_hash_table_new (NULL, NULL);
1466 /* FIXME: The tables can grow indefinitely */
1468 if (mono_gc_is_moving ()) {
1470 * Objects can move, so use a hash table mapping hash codes to lists of
1471 * ObjRef structures.
1473 hash = mono_object_hash (obj);
1475 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1476 for (l = reflist; l; l = l->next) {
1478 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1479 mono_loader_unlock ();
1484 /* Use a hash table with masked pointers to internalize object references */
1485 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1486 /* ref might refer to a different object with the same addr which was GCd */
1487 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1488 mono_loader_unlock ();
1493 ref = g_new0 (ObjRef, 1);
1494 ref->id = InterlockedIncrement (&objref_id);
1495 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1497 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1499 if (mono_gc_is_moving ()) {
1500 reflist = g_slist_append (reflist, ref);
1501 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1503 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1506 mono_loader_unlock ();
1512 get_objid (MonoObject *obj)
1514 return get_objref (obj)->id;
1518 * Set OBJ to the object identified by OBJID.
1519 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1523 get_object_allow_null (int objid, MonoObject **obj)
1533 return ERR_INVALID_OBJECT;
1535 mono_loader_lock ();
1537 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1540 *obj = mono_gchandle_get_target (ref->handle);
1541 mono_loader_unlock ();
1543 return ERR_INVALID_OBJECT;
1546 mono_loader_unlock ();
1547 return ERR_INVALID_OBJECT;
1552 get_object (int objid, MonoObject **obj)
1554 int err = get_object_allow_null (objid, obj);
1559 return ERR_INVALID_OBJECT;
1564 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1566 return decode_id (buf, endbuf, limit);
1570 buffer_add_objid (Buffer *buf, MonoObject *o)
1572 buffer_add_id (buf, get_objid (o));
1591 * Represents a runtime structure accessible to the debugger client
1594 /* Unique id used in the wire protocol */
1596 /* Domain of the runtime structure, NULL if the domain was unloaded */
1603 MonoAssembly *assembly;
1604 MonoClassField *field;
1606 MonoProperty *property;
1611 /* Maps runtime structure -> Id */
1612 GHashTable *val_to_id [ID_NUM];
1616 static GPtrArray *ids [ID_NUM];
1623 for (i = 0; i < ID_NUM; ++i)
1624 ids [i] = g_ptr_array_new ();
1632 for (i = 0; i < ID_NUM; ++i) {
1634 for (j = 0; j < ids [i]->len; ++j)
1635 g_free (g_ptr_array_index (ids [i], j));
1636 g_ptr_array_free (ids [i], TRUE);
1643 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1645 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1649 for (i = 0; i < ID_NUM; ++i)
1650 if (info->val_to_id [i])
1651 g_hash_table_destroy (info->val_to_id [i]);
1655 domain_jit_info (domain)->agent_info = NULL;
1657 /* Clear ids referencing structures in the domain */
1658 for (i = 0; i < ID_NUM; ++i) {
1660 for (j = 0; j < ids [i]->len; ++j) {
1661 Id *id = g_ptr_array_index (ids [i], j);
1662 if (id->domain == domain)
1668 mono_loader_lock ();
1669 g_hash_table_remove (domains, domain);
1670 mono_loader_unlock ();
1674 get_id (MonoDomain *domain, IdType type, gpointer val)
1677 AgentDomainInfo *info;
1682 mono_loader_lock ();
1684 mono_domain_lock (domain);
1686 if (!domain_jit_info (domain)->agent_info)
1687 domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1688 info = domain_jit_info (domain)->agent_info;
1689 if (info->val_to_id [type] == NULL)
1690 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1692 id = g_hash_table_lookup (info->val_to_id [type], val);
1694 mono_domain_unlock (domain);
1695 mono_loader_unlock ();
1699 id = g_new0 (Id, 1);
1701 id->id = ids [type]->len + 1;
1702 id->domain = domain;
1705 g_hash_table_insert (info->val_to_id [type], val, id);
1707 mono_domain_unlock (domain);
1709 g_ptr_array_add (ids [type], id);
1711 mono_loader_unlock ();
1716 static inline gpointer
1717 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1721 int id = decode_id (buf, endbuf, limit);
1730 // FIXME: error handling
1731 mono_loader_lock ();
1732 g_assert (id > 0 && id <= ids [type]->len);
1734 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1735 mono_loader_unlock ();
1737 if (res->domain == NULL) {
1738 *err = ERR_UNLOADED;
1743 *domain = res->domain;
1745 return res->data.val;
1749 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1751 buffer_add_id (buf, get_id (domain, type, val));
1754 static inline MonoClass*
1755 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1757 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1760 static inline MonoAssembly*
1761 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1763 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1766 static inline MonoImage*
1767 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1769 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1772 static inline MonoMethod*
1773 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1775 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1778 static inline MonoClassField*
1779 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1781 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1784 static inline MonoDomain*
1785 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1787 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1790 static inline MonoProperty*
1791 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1793 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1797 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1799 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1803 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1805 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1809 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1811 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1815 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1817 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1821 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1823 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1827 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1829 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1833 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1835 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1838 static void invoke_method (void);
1845 * save_thread_context:
1847 * Set CTX as the current threads context which is used for computing stack traces.
1848 * This function is signal-safe.
1851 save_thread_context (MonoContext *ctx)
1853 DebuggerTlsData *tls;
1855 tls = TlsGetValue (debugger_tls_id);
1859 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1861 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1862 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1864 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1868 tls->lmf = mono_get_lmf ();
1869 tls->domain = mono_domain_get ();
1870 tls->has_context = TRUE;
1873 /* The number of times the runtime is suspended */
1874 static gint32 suspend_count;
1876 /* Number of threads suspended */
1878 * If this is equal to the size of thread_to_tls, the runtime is considered
1881 static gint32 threads_suspend_count;
1883 static mono_mutex_t suspend_mutex;
1885 /* Cond variable used to wait for suspend_count becoming 0 */
1886 static mono_cond_t suspend_cond;
1888 /* Semaphore used to wait for a thread becoming suspended */
1889 static MonoSemType suspend_sem;
1894 mono_mutex_init (&suspend_mutex, NULL);
1895 mono_cond_init (&suspend_cond, NULL);
1896 MONO_SEM_INIT (&suspend_sem, 0);
1901 StackFrameInfo last_frame;
1902 gboolean last_frame_set;
1905 } GetLastFrameUserData;
1908 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
1910 GetLastFrameUserData *data = user_data;
1912 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
1915 if (!data->last_frame_set) {
1916 /* Store the last frame */
1917 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
1918 data->last_frame_set = TRUE;
1921 /* Store the context/lmf for the frame above the last frame */
1922 memcpy (&data->ctx, ctx, sizeof (MonoContext));
1923 data->lmf = info->lmf;
1930 * mono_debugger_agent_thread_interrupt:
1932 * Called by the abort signal handler.
1933 * Should be signal safe.
1936 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
1938 DebuggerTlsData *tls;
1943 tls = TlsGetValue (debugger_tls_id);
1948 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
1949 * guarantee the signal handler will be called that many times. Instead of tracking
1950 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
1951 * has been requested that hasn't been handled yet, otherwise we can have threads
1952 * refuse to die when VM_EXIT is called
1954 #if defined(__APPLE__)
1955 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
1959 * We use interrupt_count to determine whenever this interrupt should be processed
1960 * by us or the normal interrupt processing code in the signal handler.
1961 * There is no race here with notify_thread (), since the signal is sent after
1962 * incrementing interrupt_count.
1964 if (tls->interrupt_count == 0)
1967 InterlockedDecrement (&tls->interrupt_count);
1970 // FIXME: Races when the thread leaves managed code before hitting a single step
1974 /* Running managed code, will be suspended by the single step code */
1975 DEBUG (1, printf ("[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)GetCurrentThreadId (), ji->method->name, mono_arch_ip_from_context (sigctx)));
1979 * Running native code, will be suspended when it returns to/enters
1980 * managed code. Treat it as already suspended.
1981 * This might interrupt the code in process_single_step_inner (), we use the
1982 * tls->suspending flag to avoid races when that happens.
1984 if (!tls->suspended && !tls->suspending) {
1986 GetLastFrameUserData data;
1988 // FIXME: printf is not signal safe, but this is only used during
1989 // debugger debugging
1991 DEBUG (1, printf ("[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)GetCurrentThreadId (), mono_arch_ip_from_context (sigctx)));
1992 //save_thread_context (&ctx);
1995 /* Already terminated */
1999 * We are in a difficult position: we want to be able to provide stack
2000 * traces for this thread, but we can't use the current ctx+lmf, since
2001 * the thread is still running, so it might return to managed code,
2002 * making these invalid.
2003 * So we start a stack walk and save the first frame, along with the
2004 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2005 * suspended when it returns to managed code, so the parent's ctx should
2008 data.last_frame_set = FALSE;
2010 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2011 mono_walk_stack (get_last_frame, mono_domain_get (), &ctx, FALSE, tls->thread, mono_get_lmf (), &data);
2013 if (data.last_frame_set) {
2014 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2015 memcpy (&tls->async_ctx, &data.ctx, sizeof (MonoContext));
2016 tls->async_lmf = data.lmf;
2017 tls->has_async_ctx = TRUE;
2018 tls->domain = mono_domain_get ();
2019 memcpy (&tls->ctx, &ctx, sizeof (MonoContext));
2021 tls->has_async_ctx = FALSE;
2024 mono_memory_barrier ();
2026 tls->suspended = TRUE;
2027 MONO_SEM_POST (&suspend_sem);
2034 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2037 mono_debugger_agent_thread_interrupt (NULL, NULL);
2039 #endif /* HOST_WIN32 */
2042 * reset_native_thread_suspend_state:
2044 * Reset the suspended flag on native threads
2047 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2049 DebuggerTlsData *tls = value;
2051 if (!tls->really_suspended && tls->suspended)
2052 tls->suspended = FALSE;
2058 * Notify a thread that it needs to suspend.
2061 notify_thread (gpointer key, gpointer value, gpointer user_data)
2063 MonoInternalThread *thread = key;
2064 DebuggerTlsData *tls = value;
2065 gsize tid = thread->tid;
2067 if (GetCurrentThreadId () == tid || tls->terminated)
2070 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2073 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2074 * guarantee the signal handler will be called that many times. Instead of tracking
2075 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2076 * has been requested that hasn't been handled yet, otherwise we can have threads
2077 * refuse to die when VM_EXIT is called
2079 #if defined(__APPLE__)
2080 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2084 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2085 * of things like breaking waits etc. which we don't want.
2087 InterlockedIncrement (&tls->interrupt_count);
2090 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2092 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2094 mono_thread_kill (thread, mono_thread_get_abort_signal ());
2099 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2101 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2104 if (debugger_thread_id == GetCurrentThreadId ())
2107 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2108 if (suspend_count - tls->resume_count > 0)
2109 tls->suspending = TRUE;
2111 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2113 if (suspend_count - tls->resume_count == 0) {
2115 * We are executing a single threaded invoke but the single step for
2116 * suspending is still active.
2117 * FIXME: This slows down single threaded invokes.
2119 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2123 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2125 /* Can't suspend in these methods */
2126 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2129 save_thread_context (ctx);
2137 * Increase the suspend count of the VM. While the suspend count is greater
2138 * than 0, runtime threads are suspended at certain points during execution.
2143 mono_loader_lock ();
2145 mono_mutex_lock (&suspend_mutex);
2149 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2151 if (suspend_count == 1) {
2152 // FIXME: Is it safe to call this inside the lock ?
2153 start_single_stepping ();
2154 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2157 mono_mutex_unlock (&suspend_mutex);
2159 mono_loader_unlock ();
2165 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2173 g_assert (debugger_thread_id == GetCurrentThreadId ());
2175 mono_loader_lock ();
2177 mono_mutex_lock (&suspend_mutex);
2179 g_assert (suspend_count > 0);
2182 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2184 if (suspend_count == 0) {
2185 // FIXME: Is it safe to call this inside the lock ?
2186 stop_single_stepping ();
2187 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2190 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2191 err = mono_cond_broadcast (&suspend_cond);
2192 g_assert (err == 0);
2194 mono_mutex_unlock (&suspend_mutex);
2195 //g_assert (err == 0);
2197 mono_loader_unlock ();
2203 * Resume just one thread.
2206 resume_thread (MonoInternalThread *thread)
2209 DebuggerTlsData *tls;
2211 g_assert (debugger_thread_id == GetCurrentThreadId ());
2213 mono_loader_lock ();
2215 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2218 mono_mutex_lock (&suspend_mutex);
2220 g_assert (suspend_count > 0);
2222 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2224 tls->resume_count += suspend_count;
2227 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2228 * but only the one whose resume_count field is > 0 will be resumed.
2230 err = mono_cond_broadcast (&suspend_cond);
2231 g_assert (err == 0);
2233 mono_mutex_unlock (&suspend_mutex);
2234 //g_assert (err == 0);
2236 mono_loader_unlock ();
2240 invalidate_frames (DebuggerTlsData *tls)
2245 tls = TlsGetValue (debugger_tls_id);
2248 for (i = 0; i < tls->frame_count; ++i) {
2249 if (tls->frames [i]->jit)
2250 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2251 g_free (tls->frames [i]);
2253 g_free (tls->frames);
2254 tls->frame_count = 0;
2261 * Suspend the current thread until the runtime is resumed. If the thread has a
2262 * pending invoke, then the invoke is executed before this function returns.
2265 suspend_current (void)
2268 DebuggerTlsData *tls;
2270 g_assert (debugger_thread_id != GetCurrentThreadId ());
2272 if (mono_loader_lock_is_owned_by_self ()) {
2274 * If we own the loader mutex, can't suspend until we release it, since the
2275 * whole runtime can deadlock otherwise.
2280 tls = TlsGetValue (debugger_tls_id);
2283 mono_mutex_lock (&suspend_mutex);
2285 tls->suspending = FALSE;
2286 tls->really_suspended = TRUE;
2288 if (!tls->suspended) {
2289 tls->suspended = TRUE;
2290 MONO_SEM_POST (&suspend_sem);
2293 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2295 while (suspend_count - tls->resume_count > 0) {
2297 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2299 mono_mutex_unlock (&suspend_mutex);
2301 mono_mutex_lock (&suspend_mutex);
2307 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2308 g_assert (err == 0);
2312 tls->suspended = FALSE;
2313 tls->really_suspended = FALSE;
2315 threads_suspend_count --;
2317 mono_mutex_unlock (&suspend_mutex);
2319 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2321 if (tls->pending_invoke) {
2322 /* Save the original context */
2323 tls->pending_invoke->has_ctx = TRUE;
2324 memcpy (&tls->pending_invoke->ctx, &tls->ctx, sizeof (MonoContext));
2329 /* The frame info becomes invalid after a resume */
2330 tls->has_context = FALSE;
2331 tls->has_async_ctx = FALSE;
2332 invalidate_frames (NULL);
2336 count_thread (gpointer key, gpointer value, gpointer user_data)
2338 DebuggerTlsData *tls = value;
2340 if (!tls->suspended && !tls->terminated)
2341 *(int*)user_data = *(int*)user_data + 1;
2345 count_threads_to_wait_for (void)
2349 mono_loader_lock ();
2350 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2351 mono_loader_unlock ();
2359 * Wait until the runtime is completely suspended.
2362 wait_for_suspend (void)
2364 int nthreads, nwait, err;
2365 gboolean waited = FALSE;
2367 // FIXME: Threads starting/stopping ?
2368 mono_loader_lock ();
2369 nthreads = mono_g_hash_table_size (thread_to_tls);
2370 mono_loader_unlock ();
2373 nwait = count_threads_to_wait_for ();
2375 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2376 err = MONO_SEM_WAIT (&suspend_sem);
2377 g_assert (err == 0);
2385 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2391 * Return whenever the runtime is suspended.
2396 return count_threads_to_wait_for () == 0;
2400 * find_seq_point_for_native_offset:
2402 * Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2403 * should be the location of a sequence point.
2406 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2408 MonoSeqPointInfo *seq_points;
2411 mono_domain_lock (domain);
2412 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2413 mono_domain_unlock (domain);
2414 g_assert (seq_points);
2418 for (i = 0; i < seq_points->len; ++i) {
2419 if (seq_points->seq_points [i].native_offset == native_offset)
2420 return &seq_points->seq_points [i];
2427 * find_next_seq_point_for_native_offset:
2429 * Find the first sequence point after NATIVE_OFFSET.
2432 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2434 MonoSeqPointInfo *seq_points;
2437 mono_domain_lock (domain);
2438 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2439 mono_domain_unlock (domain);
2440 g_assert (seq_points);
2444 for (i = 0; i < seq_points->len; ++i) {
2445 if (seq_points->seq_points [i].native_offset >= native_offset)
2446 return &seq_points->seq_points [i];
2453 * find_prev_seq_point_for_native_offset:
2455 * Find the first sequence point before NATIVE_OFFSET.
2458 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2460 MonoSeqPointInfo *seq_points;
2463 mono_domain_lock (domain);
2464 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2465 mono_domain_unlock (domain);
2466 g_assert (seq_points);
2470 for (i = seq_points->len - 1; i >= 0; --i) {
2471 if (seq_points->seq_points [i].native_offset <= native_offset)
2472 return &seq_points->seq_points [i];
2481 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2482 * should be the location of a sequence point.
2485 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2487 MonoSeqPointInfo *seq_points;
2490 mono_domain_lock (domain);
2491 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2492 mono_domain_unlock (domain);
2493 g_assert (seq_points);
2497 for (i = 0; i < seq_points->len; ++i) {
2498 if (seq_points->seq_points [i].il_offset == il_offset)
2499 return &seq_points->seq_points [i];
2506 * compute_il_offset:
2508 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2509 * a location of a sequence point.
2510 * We use this function instead of mono_debug_il_offset_from_address () etc,
2511 * which doesn't seem to work in a lot of cases.
2514 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2516 MonoSeqPointInfo *seq_points;
2517 int i, last_il_offset, seq_il_offset, seq_native_offset;
2519 mono_domain_lock (domain);
2520 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2521 mono_domain_unlock (domain);
2522 g_assert (seq_points);
2524 last_il_offset = -1;
2526 /* Find the sequence point */
2527 for (i = 0; i < seq_points->len; ++i) {
2528 seq_il_offset = seq_points->seq_points [i].il_offset;
2529 seq_native_offset = seq_points->seq_points [i].native_offset;
2531 if (seq_native_offset > native_offset)
2533 last_il_offset = seq_il_offset;
2536 return last_il_offset;
2540 DebuggerTlsData *tls;
2542 } ComputeFramesUserData;
2545 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2547 ComputeFramesUserData *ud = user_data;
2549 MonoMethod *method, *actual_method;
2551 if (info->type != FRAME_TYPE_MANAGED) {
2552 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2553 /* Mark the last frame as an invoke frame */
2555 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2561 method = info->ji->method;
2563 method = info->method;
2564 actual_method = info->actual_method;
2566 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2569 if (info->il_offset == -1) {
2570 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2571 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2574 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));
2576 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2578 * mono_arch_find_jit_info () returns the context stored in the LMF for
2579 * native frames, but it should unwind once. This is why we have duplicate
2580 * frames on the stack sometimes.
2581 * !managed also seems to be set for dynamic methods.
2586 frame = g_new0 (StackFrame, 1);
2587 frame->method = method;
2588 frame->actual_method = actual_method;
2589 frame->il_offset = info->il_offset;
2590 frame->native_offset = info->native_offset;
2593 frame->has_ctx = TRUE;
2595 frame->domain = info->domain;
2597 ud->frames = g_slist_append (ud->frames, frame);
2603 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2605 ComputeFramesUserData *ud = user_data;
2608 * 'tls->filter_ctx' is the location of the throw site.
2610 * mono_walk_stack() will never actually hit the throw site, but unwind
2611 * directly from the filter to the call site; we abort stack unwinding here
2612 * once this happens and resume from the throw site.
2615 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_ctx))
2618 return process_frame (info, ctx, user_data);
2622 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2624 ComputeFramesUserData user_data;
2626 int i, findex, new_frame_count;
2627 StackFrame **new_frames, *f;
2629 // FIXME: Locking on tls
2630 if (tls->frames && tls->frames_up_to_date)
2633 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2635 user_data.tls = tls;
2636 user_data.frames = NULL;
2637 if (tls->terminated) {
2638 tls->frame_count = 0;
2640 } if (!tls->really_suspended && tls->has_async_ctx) {
2641 /* Have to use the state saved by the signal handler */
2642 process_frame (&tls->async_last_frame, NULL, &user_data);
2643 mono_walk_stack (process_frame, tls->domain, &tls->async_ctx, FALSE, thread, tls->async_lmf, &user_data);
2644 } else if (tls->has_filter_ctx) {
2646 * We are inside an exception filter.
2648 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
2650 if (tls->has_context)
2651 mono_walk_stack (process_filter_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
2653 * After that, we resume unwinding from the location where the exception has been thrown.
2655 mono_walk_stack (process_frame, tls->domain, &tls->filter_ctx, FALSE, thread, tls->filter_lmf, &user_data);
2656 } else if (tls->has_context) {
2657 mono_walk_stack (process_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
2660 tls->frame_count = 0;
2664 new_frame_count = g_slist_length (user_data.frames);
2665 new_frames = g_new0 (StackFrame*, new_frame_count);
2667 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2671 * Reuse the id for already existing stack frames, so invokes don't invalidate
2672 * the still valid stack frames.
2674 for (i = 0; i < tls->frame_count; ++i) {
2675 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2676 f->id = tls->frames [i]->id;
2681 if (i >= tls->frame_count)
2682 f->id = InterlockedIncrement (&frame_id);
2684 new_frames [findex ++] = f;
2687 g_slist_free (user_data.frames);
2689 invalidate_frames (tls);
2691 tls->frames = new_frames;
2692 tls->frame_count = new_frame_count;
2693 tls->frames_up_to_date = TRUE;
2701 * create_event_list:
2703 * Return a list of event request ids matching EVENT, starting from REQS, which
2704 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2706 * We return request ids, instead of requests, to simplify threading, since
2707 * requests could be deleted anytime when the loader lock is not held.
2708 * LOCKING: Assumes the loader lock is held.
2711 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
2714 GSList *events = NULL;
2716 *suspend_policy = SUSPEND_POLICY_NONE;
2719 reqs = event_requests;
2724 for (i = 0; i < reqs->len; ++i) {
2725 EventRequest *req = g_ptr_array_index (reqs, i);
2726 if (req->event_kind == event) {
2727 gboolean filtered = FALSE;
2730 for (j = 0; j < req->nmodifiers; ++j) {
2731 Modifier *mod = &req->modifiers [j];
2733 if (mod->kind == MOD_KIND_COUNT) {
2735 if (mod->data.count > 0) {
2736 if (mod->data.count > 0) {
2738 if (mod->data.count == 0)
2742 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2743 if (mod->data.thread != mono_thread_internal_current ())
2745 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
2746 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
2748 if (ei->caught && !mod->caught)
2750 if (!ei->caught && !mod->uncaught)
2752 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2754 gboolean found = FALSE;
2755 MonoAssembly **assemblies = mod->data.assemblies;
2758 for (k = 0; assemblies [k]; ++k)
2759 if (assemblies [k] == ji->method->klass->image->assembly)
2768 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2769 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2774 /* Send a VM START/DEATH event by default */
2775 if (event == EVENT_KIND_VM_START)
2776 events = g_slist_append (events, GINT_TO_POINTER (0));
2777 if (event == EVENT_KIND_VM_DEATH)
2778 events = g_slist_append (events, GINT_TO_POINTER (0));
2783 static G_GNUC_UNUSED const char*
2784 event_to_string (EventKind event)
2787 case EVENT_KIND_VM_START: return "VM_START";
2788 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2789 case EVENT_KIND_THREAD_START: return "THREAD_START";
2790 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2791 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2792 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2793 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2794 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2795 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2796 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2797 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2798 case EVENT_KIND_STEP: return "STEP";
2799 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2800 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2802 g_assert_not_reached ();
2809 * Send an event to the client, suspending the vm if needed.
2810 * LOCKING: Since this can suspend the calling thread, no locks should be held
2812 * The EVENTS list is freed by this function.
2815 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2819 MonoDomain *domain = mono_domain_get ();
2825 if (!vm_start_event_sent && event != EVENT_KIND_VM_START)
2826 // FIXME: We miss those events
2829 if (vm_death_event_sent)
2832 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH)
2841 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
2842 // FIXME: Send these with a NULL thread, don't suspend the current thread
2845 buffer_init (&buf, 128);
2846 buffer_add_byte (&buf, suspend_policy);
2847 buffer_add_int (&buf, g_slist_length (events)); // n of events
2849 for (l = events; l; l = l->next) {
2850 buffer_add_byte (&buf, event); // event kind
2851 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
2853 thread = mono_thread_current ();
2855 if (event == EVENT_KIND_VM_START)
2857 else if (event == EVENT_KIND_THREAD_START)
2858 g_assert (mono_thread_internal_current () == arg);
2860 buffer_add_objid (&buf, (MonoObject*)thread); // thread
2863 case EVENT_KIND_THREAD_START:
2864 case EVENT_KIND_THREAD_DEATH:
2866 case EVENT_KIND_APPDOMAIN_CREATE:
2867 case EVENT_KIND_APPDOMAIN_UNLOAD:
2868 buffer_add_domainid (&buf, arg);
2870 case EVENT_KIND_METHOD_ENTRY:
2871 case EVENT_KIND_METHOD_EXIT:
2872 buffer_add_methodid (&buf, domain, arg);
2874 case EVENT_KIND_ASSEMBLY_LOAD:
2875 case EVENT_KIND_ASSEMBLY_UNLOAD:
2876 buffer_add_assemblyid (&buf, domain, arg);
2878 case EVENT_KIND_TYPE_LOAD:
2879 buffer_add_typeid (&buf, domain, arg);
2881 case EVENT_KIND_BREAKPOINT:
2882 case EVENT_KIND_STEP:
2883 buffer_add_methodid (&buf, domain, arg);
2884 buffer_add_long (&buf, il_offset);
2886 case EVENT_KIND_VM_START:
2887 buffer_add_domainid (&buf, mono_get_root_domain ());
2889 case EVENT_KIND_VM_DEATH:
2891 case EVENT_KIND_EXCEPTION: {
2892 EventInfo *ei = arg;
2893 buffer_add_objid (&buf, ei->exc);
2897 g_assert_not_reached ();
2901 if (event == EVENT_KIND_VM_START) {
2902 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
2903 start_debugger_thread ();
2906 if (event == EVENT_KIND_VM_DEATH) {
2907 vm_death_event_sent = TRUE;
2909 suspend_policy = SUSPEND_POLICY_NONE;
2912 if (mono_runtime_is_shutting_down ())
2913 suspend_policy = SUSPEND_POLICY_NONE;
2915 if (suspend_policy != SUSPEND_POLICY_NONE) {
2917 * Save the thread context and start suspending before sending the packet,
2918 * since we could be receiving the resume request before send_packet ()
2921 save_thread_context (ctx);
2925 send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
2927 g_slist_free (events);
2930 if (event == EVENT_KIND_VM_START)
2931 vm_start_event_sent = TRUE;
2933 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
2937 switch (suspend_policy) {
2938 case SUSPEND_POLICY_NONE:
2940 case SUSPEND_POLICY_ALL:
2943 case SUSPEND_POLICY_EVENT_THREAD:
2947 g_assert_not_reached ();
2952 process_profiler_event (EventKind event, gpointer arg)
2957 mono_loader_lock ();
2958 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
2959 mono_loader_unlock ();
2961 process_event (event, arg, 0, NULL, events, suspend_policy);
2965 runtime_initialized (MonoProfiler *prof)
2967 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
2971 runtime_shutdown (MonoProfiler *prof)
2973 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
2975 mono_debugger_agent_cleanup ();
2979 thread_startup (MonoProfiler *prof, uintptr_t tid)
2981 MonoInternalThread *thread = mono_thread_internal_current ();
2982 MonoInternalThread *old_thread;
2983 DebuggerTlsData *tls;
2985 if (tid == debugger_thread_id)
2988 g_assert (thread->tid == tid);
2990 mono_loader_lock ();
2991 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2992 mono_loader_unlock ();
2994 if (thread == old_thread) {
2996 * For some reason, thread_startup () might be called for the same thread
2997 * multiple times (attach ?).
2999 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3003 * thread_end () might not be called for some threads, and the tid could
3006 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3007 mono_loader_lock ();
3008 mono_g_hash_table_remove (thread_to_tls, old_thread);
3009 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3010 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3011 mono_loader_unlock ();
3015 tls = TlsGetValue (debugger_tls_id);
3017 // FIXME: Free this somewhere
3018 tls = g_new0 (DebuggerTlsData, 1);
3019 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3020 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3021 tls->thread = thread;
3022 TlsSetValue (debugger_tls_id, tls);
3024 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3026 mono_loader_lock ();
3027 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3028 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3029 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3030 mono_loader_unlock ();
3032 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3035 * suspend_vm () could have missed this thread, so wait for a resume.
3041 thread_end (MonoProfiler *prof, uintptr_t tid)
3043 MonoInternalThread *thread;
3044 DebuggerTlsData *tls = NULL;
3046 mono_loader_lock ();
3047 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3049 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3050 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3051 tls->terminated = TRUE;
3052 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3053 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3054 MONO_GC_UNREGISTER_ROOT (tls->thread);
3057 mono_loader_unlock ();
3059 /* We might be called for threads started before we registered the start callback */
3061 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3062 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3067 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3069 mono_loader_lock ();
3070 g_hash_table_insert (domains, domain, domain);
3071 mono_loader_unlock ();
3073 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3077 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3079 /* Invalidate each thread's frame stack */
3080 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3081 clear_breakpoints_for_domain (domain);
3082 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3086 * invalidate_each_thread:
3088 * A GHFunc to invalidate frames.
3089 * value must be a DebuggerTlsData*
3092 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3094 invalidate_frames (value);
3098 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3100 /* Sent later in jit_end () */
3101 mono_loader_lock ();
3102 g_ptr_array_add (pending_assembly_loads, assembly);
3103 mono_loader_unlock ();
3107 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3109 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3111 clear_event_requests_for_assembly (assembly);
3112 clear_types_for_assembly (assembly);
3116 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3118 #if defined(HOST_WIN32) && !defined(__GNUC__)
3119 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3121 gpointer stackptr = __builtin_frame_address (1);
3123 MonoInternalThread *thread = mono_thread_internal_current ();
3124 DebuggerTlsData *tls;
3126 mono_loader_lock ();
3128 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3129 /* Could be the debugger thread with assembly/type load hooks */
3131 tls->invoke_addr = stackptr;
3133 mono_loader_unlock ();
3137 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3140 #if defined(HOST_WIN32) && !defined(__GNUC__)
3141 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3143 gpointer stackptr = __builtin_frame_address (1);
3146 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3150 * We need to stop single stepping when exiting a runtime invoke, since if it is
3151 * a step out, it may return to native code, and thus never end.
3153 mono_loader_lock ();
3154 ss_invoke_addr = NULL;
3156 for (i = 0; i < event_requests->len; ++i) {
3157 EventRequest *req = g_ptr_array_index (event_requests, i);
3159 if (req->event_kind == EVENT_KIND_STEP) {
3160 ss_destroy (req->info);
3161 g_ptr_array_remove_index_fast (event_requests, i);
3166 mono_loader_unlock ();
3170 send_type_load (MonoClass *klass)
3172 gboolean type_load = FALSE;
3174 mono_loader_lock ();
3175 if (!g_hash_table_lookup (loaded_classes, klass)) {
3177 g_hash_table_insert (loaded_classes, klass, klass);
3179 mono_loader_unlock ();
3181 process_profiler_event (EVENT_KIND_TYPE_LOAD, klass);
3185 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3188 * We emit type load events when the first method of the type is JITted,
3189 * since the class load profiler callbacks might be called with the
3190 * loader lock held. They could also occur in the debugger thread.
3191 * Same for assembly load events.
3194 MonoAssembly *assembly = NULL;
3196 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3197 mono_loader_lock ();
3198 if (pending_assembly_loads->len > 0) {
3199 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3200 g_ptr_array_remove_index (pending_assembly_loads, 0);
3202 mono_loader_unlock ();
3205 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3210 if (!vm_start_event_sent) {
3211 /* Save these so they can be sent after the vm start event */
3212 mono_loader_lock ();
3213 g_ptr_array_add (pending_type_loads, method->klass);
3214 mono_loader_unlock ();
3216 /* Send all pending type load events */
3220 mono_loader_lock ();
3221 if (pending_type_loads->len > 0) {
3222 klass = g_ptr_array_index (pending_type_loads, 0);
3223 g_ptr_array_remove_index (pending_type_loads, 0);
3225 mono_loader_unlock ();
3227 send_type_load (klass);
3232 send_type_load (method->klass);
3236 add_pending_breakpoints (method, jinfo);
3240 * BREAKPOINTS/SINGLE STEPPING
3244 * Contains information about an inserted breakpoint.
3247 long il_offset, native_offset;
3251 } BreakpointInstance;
3254 * Contains generic information about a breakpoint.
3258 * The method where the breakpoint is placed. Can be NULL in which case it
3259 * is inserted into every method. This is used to implement method entry/
3260 * exit events. Can be a generic method definition, in which case the
3261 * breakpoint is inserted into every instance.
3267 * A list of BreakpointInstance structures describing where the breakpoint
3268 * was inserted. There could be more than one because of
3269 * generics/appdomains/method entry/exit.
3271 GPtrArray *children;
3274 /* List of breakpoints */
3275 static GPtrArray *breakpoints;
3276 /* Maps breakpoint locations to the number of breakpoints at that location */
3277 static GHashTable *bp_locs;
3280 breakpoints_init (void)
3282 breakpoints = g_ptr_array_new ();
3283 bp_locs = g_hash_table_new (NULL, NULL);
3287 * insert_breakpoint:
3289 * Insert the breakpoint described by BP into the method described by
3293 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp)
3296 gint32 il_offset = -1, native_offset;
3297 BreakpointInstance *inst;
3300 for (i = 0; i < seq_points->len; ++i) {
3301 il_offset = seq_points->seq_points [i].il_offset;
3302 native_offset = seq_points->seq_points [i].native_offset;
3304 if (il_offset == bp->il_offset)
3308 if (i == seq_points->len) {
3309 /* Have to handle this somehow */
3310 g_error ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (ji->method, TRUE), bp->il_offset, seq_points->len);
3313 inst = g_new0 (BreakpointInstance, 1);
3314 inst->native_offset = native_offset;
3315 inst->ip = (guint8*)ji->code_start + native_offset;
3317 inst->domain = domain;
3319 mono_loader_lock ();
3321 g_ptr_array_add (bp->children, inst);
3323 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3324 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3325 mono_loader_unlock ();
3328 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3329 mono_arch_set_breakpoint (ji, inst->ip);
3335 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)il_offset));
3339 remove_breakpoint (BreakpointInstance *inst)
3341 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3343 MonoJitInfo *ji = inst->ji;
3344 guint8 *ip = inst->ip;
3346 mono_loader_lock ();
3347 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3348 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3349 mono_loader_unlock ();
3351 g_assert (count > 0);
3354 mono_arch_clear_breakpoint (ji, ip);
3361 static inline gboolean
3362 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3364 return (!bp->method || method == bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method));
3368 * add_pending_breakpoints:
3370 * Insert pending breakpoints into the newly JITted method METHOD.
3373 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3376 MonoSeqPointInfo *seq_points;
3382 domain = mono_domain_get ();
3384 mono_loader_lock ();
3386 for (i = 0; i < breakpoints->len; ++i) {
3387 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3388 gboolean found = FALSE;
3390 if (!bp_matches_method (bp, method))
3393 for (j = 0; j < bp->children->len; ++j) {
3394 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3401 mono_domain_lock (domain);
3402 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3403 mono_domain_unlock (domain);
3405 /* Could be AOT code */
3407 g_assert (seq_points);
3409 insert_breakpoint (seq_points, domain, ji, bp);
3413 mono_loader_unlock ();
3417 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp)
3422 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3424 /* Might be AOTed code */
3425 code = mono_aot_get_method (domain, method);
3427 ji = mono_jit_info_table_find (domain, code);
3432 insert_breakpoint (seq_points, domain, ji, bp);
3442 set_bp_in_method_cb (gpointer key, gpointer value, gpointer user_data)
3444 MonoMethod *method = key;
3445 MonoSeqPointInfo *seq_points = value;
3446 SetBpUserData *ud = user_data;
3447 MonoBreakpoint *bp = ud->bp;
3448 MonoDomain *domain = ud->domain;
3450 if (bp_matches_method (bp, method))
3451 set_bp_in_method (domain, method, seq_points, bp);
3455 set_bp_in_domain (gpointer key, gpointer value, gpointer user_data)
3457 MonoDomain *domain = key;
3458 MonoBreakpoint *bp = user_data;
3464 mono_domain_lock (domain);
3465 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, &ud);
3466 mono_domain_unlock (domain);
3472 * Set a breakpoint at IL_OFFSET in METHOD.
3473 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3474 * METHOD can also be a generic method definition, in which case a breakpoint
3475 * is placed in all instances of the method.
3477 static MonoBreakpoint*
3478 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req)
3483 // - suspend/resume the vm to prevent code patching problems
3484 // - multiple breakpoints on the same location
3485 // - dynamic methods
3488 bp = g_new0 (MonoBreakpoint, 1);
3489 bp->method = method;
3490 bp->il_offset = il_offset;
3492 bp->children = g_ptr_array_new ();
3494 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));
3496 mono_loader_lock ();
3498 g_hash_table_foreach (domains, set_bp_in_domain, bp);
3500 mono_loader_unlock ();
3502 mono_loader_lock ();
3503 g_ptr_array_add (breakpoints, bp);
3504 mono_loader_unlock ();
3510 clear_breakpoint (MonoBreakpoint *bp)
3514 // FIXME: locking, races
3515 for (i = 0; i < bp->children->len; ++i) {
3516 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3518 remove_breakpoint (inst);
3523 mono_loader_lock ();
3524 g_ptr_array_remove (breakpoints, bp);
3525 mono_loader_unlock ();
3527 g_ptr_array_free (bp->children, TRUE);
3532 breakpoints_cleanup (void)
3536 mono_loader_lock ();
3538 while (i < event_requests->len) {
3539 EventRequest *req = g_ptr_array_index (event_requests, i);
3541 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
3542 clear_breakpoint (req->info);
3543 g_ptr_array_remove_index_fast (event_requests, i);
3550 for (i = 0; i < breakpoints->len; ++i)
3551 g_free (g_ptr_array_index (breakpoints, i));
3553 g_ptr_array_free (breakpoints, TRUE);
3554 g_hash_table_destroy (bp_locs);
3559 mono_loader_unlock ();
3563 * clear_breakpoints_for_domain:
3565 * Clear breakpoint instances which reference DOMAIN.
3568 clear_breakpoints_for_domain (MonoDomain *domain)
3572 /* This could be called after shutdown */
3576 mono_loader_lock ();
3577 for (i = 0; i < breakpoints->len; ++i) {
3578 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3581 while (j < bp->children->len) {
3582 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3584 if (inst->domain == domain) {
3585 remove_breakpoint (inst);
3589 g_ptr_array_remove_index_fast (bp->children, j);
3595 mono_loader_unlock ();
3599 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
3601 return bp->method && bp->method->klass->image->assembly == assembly;
3605 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
3608 guint8 *orig_ip, *ip;
3609 int i, j, suspend_policy;
3610 guint32 native_offset;
3612 BreakpointInstance *inst;
3613 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3614 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3615 EventKind kind = EVENT_KIND_BREAKPOINT;
3617 // FIXME: Speed this up
3619 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3620 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
3622 g_assert (ji->method);
3624 /* Compute the native offset of the breakpoint from the ip */
3625 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3626 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3627 native_offset = ip - (guint8*)ji->code_start;
3633 * Skip the instruction causing the breakpoint signal.
3635 mono_arch_skip_breakpoint (ctx);
3637 if (ji->method->wrapper_type || tls->disable_breakpoints)
3640 bp_reqs = g_ptr_array_new ();
3641 ss_reqs = g_ptr_array_new ();
3642 ss_reqs_orig = g_ptr_array_new ();
3644 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3646 mono_loader_lock ();
3649 for (i = 0; i < breakpoints->len; ++i) {
3650 bp = g_ptr_array_index (breakpoints, i);
3655 for (j = 0; j < bp->children->len; ++j) {
3656 inst = g_ptr_array_index (bp->children, j);
3657 if (inst->ji == ji && inst->native_offset == native_offset) {
3658 if (bp->req->event_kind == EVENT_KIND_STEP) {
3659 g_ptr_array_add (ss_reqs_orig, bp->req);
3661 g_ptr_array_add (bp_reqs, bp->req);
3666 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3667 MonoSeqPointInfo *seq_points;
3668 int seq_il_offset, seq_native_offset;
3669 MonoDomain *domain = mono_domain_get ();
3671 /* Maybe a method entry/exit event */
3672 mono_domain_lock (domain);
3673 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3674 mono_domain_unlock (domain);
3676 // FIXME: Generic sharing */
3677 mono_loader_unlock ();
3680 g_assert (seq_points);
3682 for (i = 0; i < seq_points->len; ++i) {
3683 seq_il_offset = seq_points->seq_points [i].il_offset;
3684 seq_native_offset = seq_points->seq_points [i].native_offset;
3686 if (native_offset == seq_native_offset) {
3687 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3688 kind = EVENT_KIND_METHOD_ENTRY;
3689 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3690 kind = EVENT_KIND_METHOD_EXIT;
3696 /* Process single step requests */
3697 for (i = 0; i < ss_reqs_orig->len; ++i) {
3698 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3699 SingleStepReq *ss_req = req->info;
3700 gboolean hit = TRUE;
3701 MonoSeqPointInfo *info;
3704 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3707 if (ss_req->size == STEP_SIZE_LINE) {
3708 /* Have to check whenever a different source line was reached */
3709 MonoDebugMethodInfo *minfo;
3710 MonoDebugSourceLocation *loc = NULL;
3712 minfo = mono_debug_lookup_method (ji->method);
3715 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3717 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3718 /* Have to continue single stepping */
3722 ss_req->last_method = ji->method;
3723 ss_req->last_line = loc->row;
3724 mono_debug_free_source_location (loc);
3729 g_ptr_array_add (ss_reqs, req);
3731 /* Start single stepping again from the current sequence point */
3732 ss_start (ss_req, ji->method, sp, info, ctx, NULL, FALSE);
3735 if (ss_reqs->len > 0)
3736 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3737 if (bp_reqs->len > 0)
3738 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3739 if (kind != EVENT_KIND_BREAKPOINT)
3740 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3742 mono_loader_unlock ();
3744 g_ptr_array_free (bp_reqs, TRUE);
3745 g_ptr_array_free (ss_reqs, TRUE);
3748 * FIXME: The first event will suspend, so the second will only be sent after the
3752 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3754 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3755 if (enter_leave_events)
3756 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3760 process_breakpoint (void)
3762 DebuggerTlsData *tls;
3764 static void (*restore_context) (void *);
3766 if (!restore_context)
3767 restore_context = mono_get_restore_context ();
3769 tls = TlsGetValue (debugger_tls_id);
3770 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3772 process_breakpoint_inner (tls, &ctx);
3774 /* This is called when resuming from a signal handler, so it shouldn't return */
3775 restore_context (&ctx);
3776 g_assert_not_reached ();
3780 resume_from_signal_handler (void *sigctx, void *func)
3782 DebuggerTlsData *tls;
3785 /* Save the original context in TLS */
3786 // FIXME: This might not work on an altstack ?
3787 tls = TlsGetValue (debugger_tls_id);
3790 // FIXME: MonoContext usually doesn't include the fp registers, so these are
3791 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3792 // clob:c could be added to op_seq_point.
3794 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3795 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3796 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
3797 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
3799 MONO_CONTEXT_SET_IP (&ctx, func);
3801 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3803 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3804 mono_ppc_set_func_into_sigctx (sigctx, func);
3809 mono_debugger_agent_breakpoint_hit (void *sigctx)
3812 * We are called from a signal handler, and running code there causes all kinds of
3813 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
3814 * So set up the signal context to return to the real breakpoint handler function.
3817 resume_from_signal_handler (sigctx, process_breakpoint);
3821 ss_depth_to_string (StepDepth depth)
3824 case STEP_DEPTH_OVER:
3826 case STEP_DEPTH_OUT:
3828 case STEP_DEPTH_INTO:
3831 g_assert_not_reached ();
3837 process_single_step_inner (DebuggerTlsData *tls, MonoContext *ctx)
3842 int il_offset, suspend_policy;
3846 // FIXME: Speed this up
3848 ip = MONO_CONTEXT_GET_IP (ctx);
3850 /* Skip the instruction causing the single step */
3851 mono_arch_skip_single_step (ctx);
3853 if (suspend_count > 0) {
3854 process_suspend (tls, ctx);
3859 // FIXME: A suspend race
3862 if (mono_thread_internal_current () != ss_req->thread)
3865 if (log_level > 0) {
3866 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
3868 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));
3872 * We implement step over/out by single stepping until we reach the same
3873 * frame/parent frame.
3876 * - stack growing upward
3880 if (ss_req->depth != STEP_DEPTH_INTO) {
3881 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
3883 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
3886 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
3889 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
3891 g_assert (ji->method);
3893 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
3898 * Stopping in memset makes half-initialized vtypes visible.
3899 * Stopping in memcpy makes half-copied vtypes visible.
3901 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
3905 * The ip points to the instruction causing the single step event, convert it
3906 * to the offset stored in seq_points.
3908 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3909 ip = mono_arch_get_ip_for_single_step (ji, ctx);
3911 g_assert_not_reached ();
3915 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
3916 * example, so do things by hand.
3918 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
3920 if (il_offset == -1)
3923 if (ss_req->size == STEP_SIZE_LINE) {
3924 /* Step until a different source line is reached */
3925 MonoDebugMethodInfo *minfo;
3927 minfo = mono_debug_lookup_method (ji->method);
3930 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
3932 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
3933 mono_debug_free_source_location (loc);
3938 * Step until we reach a location with line number info,
3939 * otherwise the client can't show a location.
3940 * This can happen for example with statics initialized inline
3941 * outside of a cctor.
3946 ss_req->last_method = ji->method;
3947 ss_req->last_line = loc->row;
3948 mono_debug_free_source_location (loc);
3953 // FIXME: Has to lock earlier
3955 reqs = g_ptr_array_new ();
3957 mono_loader_lock ();
3959 g_ptr_array_add (reqs, ss_req->req);
3961 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
3963 g_ptr_array_free (reqs, TRUE);
3965 mono_loader_unlock ();
3967 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
3971 process_single_step (void)
3973 DebuggerTlsData *tls;
3975 static void (*restore_context) (void *);
3977 if (!restore_context)
3978 restore_context = mono_get_restore_context ();
3980 tls = TlsGetValue (debugger_tls_id);
3981 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3983 process_single_step_inner (tls, &ctx);
3985 /* This is called when resuming from a signal handler, so it shouldn't return */
3986 restore_context (&ctx);
3987 g_assert_not_reached ();
3991 * mono_debugger_agent_single_step_event:
3993 * Called from a signal handler to handle a single step event.
3996 mono_debugger_agent_single_step_event (void *sigctx)
3998 /* Resume to process_single_step through the signal context */
4000 // FIXME: Since step out/over is implemented using step in, the step in case should
4001 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4004 if (GetCurrentThreadId () == debugger_thread_id) {
4006 * This could happen despite our best effors when the runtime calls
4007 * assembly/type resolve hooks.
4008 * FIXME: Breakpoints too.
4012 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4013 mono_arch_skip_single_step (&ctx);
4014 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4018 resume_from_signal_handler (sigctx, process_single_step);
4022 * start_single_stepping:
4024 * Turn on single stepping. Can be called multiple times, for example,
4025 * by a single step event request + a suspend.
4028 start_single_stepping (void)
4030 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4031 int val = InterlockedIncrement (&ss_count);
4034 mono_arch_start_single_stepping ();
4036 if (ss_req != NULL && ss_invoke_addr == NULL) {
4037 DebuggerTlsData *tls;
4039 mono_loader_lock ();
4041 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4042 ss_invoke_addr = tls->invoke_addr;
4044 mono_loader_unlock ();
4047 g_assert_not_reached ();
4052 stop_single_stepping (void)
4054 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4055 int val = InterlockedDecrement (&ss_count);
4058 mono_arch_stop_single_stepping ();
4060 g_assert_not_reached ();
4067 * Stop the single stepping operation given by SS_REQ.
4070 ss_stop (SingleStepReq *ss_req)
4072 gboolean use_bps = FALSE;
4079 for (l = ss_req->bps; l; l = l->next) {
4080 clear_breakpoint (l->data);
4082 g_slist_free (ss_req->bps);
4086 if (ss_req->global) {
4087 stop_single_stepping ();
4088 ss_req->global = FALSE;
4095 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4098 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4104 /* Stop the previous operation */
4108 * Implement single stepping using breakpoints if possible.
4110 if (step_to_catch) {
4111 bp = set_breakpoint (method, sp->il_offset, ss_req->req);
4112 ss_req->bps = g_slist_append (ss_req->bps, bp);
4113 } else if (ss_req->depth == STEP_DEPTH_OVER) {
4116 * Find the first sequence point in the current or in a previous frame which
4117 * is not the last in its method.
4119 while (sp && sp->next_len == 0) {
4121 if (tls && frame_index < tls->frame_count) {
4122 StackFrame *frame = tls->frames [frame_index];
4124 method = frame->method;
4125 if (frame->il_offset != -1) {
4126 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
4132 if (sp && sp->next_len > 0) {
4133 for (i = 0; i < sp->next_len; ++i) {
4134 next_sp = &info->seq_points [sp->next [i]];
4136 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req);
4137 ss_req->bps = g_slist_append (ss_req->bps, bp);
4143 DEBUG (1, printf ("[dbg] Turning on global single stepping.\n"));
4144 ss_req->global = TRUE;
4145 start_single_stepping ();
4147 ss_req->global = FALSE;
4152 * Start single stepping of thread THREAD
4155 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4157 DebuggerTlsData *tls;
4158 MonoSeqPointInfo *info = NULL;
4159 SeqPoint *sp = NULL;
4160 MonoMethod *method = NULL;
4161 MonoDebugMethodInfo *minfo;
4162 gboolean step_to_catch = FALSE;
4164 if (suspend_count == 0)
4165 return ERR_NOT_SUSPENDED;
4167 wait_for_suspend ();
4169 // FIXME: Multiple requests
4171 DEBUG (0, printf ("Received a single step request while the previous one was still active.\n"));
4172 return ERR_NOT_IMPLEMENTED;
4175 DEBUG (1, printf ("[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4177 ss_req = g_new0 (SingleStepReq, 1);
4179 ss_req->thread = thread;
4180 ss_req->size = size;
4181 ss_req->depth = depth;
4184 mono_loader_lock ();
4185 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4186 mono_loader_unlock ();
4188 g_assert (tls->has_context);
4189 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
4191 if (tls->has_catch_ctx) {
4193 StackFrameInfo frame;
4194 MonoContext new_ctx;
4195 MonoLMF *lmf = NULL;
4198 * We are stopped at a throw site. Stepping should go to the catch site.
4201 /* Find the the jit info for the catch context */
4202 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, &frame);
4204 g_assert (frame.type == FRAME_TYPE_MANAGED);
4207 * Find the seq point corresponding to the landing site ip, which is the first seq
4210 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4213 method = frame.method;
4215 step_to_catch = TRUE;
4216 /* This make sure the seq point is not skipped by process_single_step () */
4217 ss_req->last_sp = NULL;
4220 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4223 /* Compute the initial line info */
4224 compute_frame_info (thread, tls);
4226 g_assert (tls->frame_count);
4227 frame = tls->frames [0];
4229 ss_req->last_method = frame->method;
4230 ss_req->last_line = -1;
4232 minfo = mono_debug_lookup_method (frame->method);
4233 if (minfo && frame->il_offset != -1) {
4234 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4237 ss_req->last_line = loc->row;
4243 if (!step_to_catch && ss_req->depth == STEP_DEPTH_OVER) {
4246 compute_frame_info (thread, tls);
4248 g_assert (tls->frame_count);
4249 frame = tls->frames [0];
4251 if (!method && frame->il_offset != -1) {
4252 /* FIXME: Sort the table and use a binary search */
4253 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4255 method = frame->method;
4259 ss_start (ss_req, method, sp, info, NULL, tls, step_to_catch);
4265 ss_destroy (SingleStepReq *req)
4268 g_assert (ss_req == req);
4277 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
4278 MonoContext *catch_ctx)
4284 DebuggerTlsData *tls = NULL;
4286 if (thread_to_tls != NULL) {
4287 MonoInternalThread *thread = mono_thread_internal_current ();
4289 mono_loader_lock ();
4290 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4291 mono_loader_unlock ();
4293 if (tls && tls->abort_requested)
4295 if (tls && tls->disable_breakpoints)
4299 memset (&ei, 0, sizeof (EventInfo));
4301 /* Just-In-Time debugging */
4303 if (agent_config.onuncaught && !inited) {
4304 finish_agent_init (FALSE);
4307 * Send an unsolicited EXCEPTION event with a dummy request id.
4309 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4310 ei.exc = (MonoObject*)exc;
4311 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4314 } else if (agent_config.onthrow && !inited) {
4316 gboolean found = FALSE;
4318 for (l = agent_config.onthrow; l; l = l->next) {
4319 char *ex_type = l->data;
4320 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
4322 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
4329 finish_agent_init (FALSE);
4332 * Send an unsolicited EXCEPTION event with a dummy request id.
4334 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4335 ei.exc = (MonoObject*)exc;
4336 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4344 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
4346 ei.exc = (MonoObject*)exc;
4347 ei.caught = catch_ctx != NULL;
4349 mono_loader_lock ();
4350 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
4351 mono_loader_unlock ();
4353 if (tls && catch_ctx) {
4354 tls->catch_ctx = *catch_ctx;
4355 tls->has_catch_ctx = TRUE;
4358 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
4361 tls->has_catch_ctx = FALSE;
4365 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4367 DebuggerTlsData *tls;
4372 tls = TlsGetValue (debugger_tls_id);
4377 * We're about to invoke an exception filter during the first pass of exception handling.
4379 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
4380 * 'orig_ctx' is the context where the exception has been thrown.
4383 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
4385 * If we're stopped in Filter(), normal stack unwinding would first unwind to
4386 * the call site (line 37) and then continue to Main(), but it would never
4387 * include the throw site (line 32).
4389 * Since exception filters are invoked during the first pass of exception handling,
4390 * the stack frames of the throw site are still intact, so we should include them
4393 * We do this here by saving the context of the throw site in 'tls->filter_ctx'.
4395 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
4396 * but report the location of the 'throw' to the user.
4400 memcpy (&tls->filter_ctx, orig_ctx, sizeof (MonoContext));
4401 tls->has_filter_ctx = TRUE;
4403 tls->filter_lmf = mono_get_lmf ();
4404 tls->domain = mono_domain_get ();
4408 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4410 DebuggerTlsData *tls;
4415 tls = TlsGetValue (debugger_tls_id);
4419 tls->has_filter_ctx = FALSE;
4423 * buffer_add_value_full:
4425 * Add the encoding of the value at ADDR described by T to the buffer.
4426 * AS_VTYPE determines whenever to treat primitive types as primitive types or
4430 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
4436 g_assert (*(void**)addr);
4437 addr = *(void**)addr;
4442 case MONO_TYPE_BOOLEAN:
4445 case MONO_TYPE_CHAR:
4465 case MONO_TYPE_VOID:
4466 buffer_add_byte (buf, t->type);
4468 case MONO_TYPE_BOOLEAN:
4471 buffer_add_byte (buf, t->type);
4472 buffer_add_int (buf, *(gint8*)addr);
4474 case MONO_TYPE_CHAR:
4477 buffer_add_byte (buf, t->type);
4478 buffer_add_int (buf, *(gint16*)addr);
4483 buffer_add_byte (buf, t->type);
4484 buffer_add_int (buf, *(gint32*)addr);
4489 buffer_add_byte (buf, t->type);
4490 buffer_add_long (buf, *(gint64*)addr);
4494 /* Treat it as a vtype */
4496 case MONO_TYPE_PTR: {
4497 gssize val = *(gssize*)addr;
4499 buffer_add_byte (buf, t->type);
4500 buffer_add_long (buf, val);
4504 case MONO_TYPE_STRING:
4505 case MONO_TYPE_SZARRAY:
4506 case MONO_TYPE_OBJECT:
4507 case MONO_TYPE_CLASS:
4508 case MONO_TYPE_ARRAY:
4509 obj = *(MonoObject**)addr;
4512 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4514 if (obj->vtable->klass->valuetype) {
4515 t = &obj->vtable->klass->byval_arg;
4516 addr = mono_object_unbox (obj);
4518 } else if (obj->vtable->klass->rank) {
4519 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4520 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4521 buffer_add_byte (buf, MONO_TYPE_CLASS);
4523 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4525 buffer_add_objid (buf, obj);
4529 case MONO_TYPE_VALUETYPE: {
4533 MonoClass *klass = mono_class_from_mono_type (t);
4535 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4536 buffer_add_byte (buf, klass->enumtype);
4537 buffer_add_typeid (buf, domain, klass);
4541 while ((f = mono_class_get_fields (klass, &iter))) {
4542 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4544 if (mono_field_is_deleted (f))
4548 buffer_add_int (buf, nfields);
4551 while ((f = mono_class_get_fields (klass, &iter))) {
4552 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4554 if (mono_field_is_deleted (f))
4556 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4560 case MONO_TYPE_GENERICINST:
4561 if (mono_type_generic_inst_is_valuetype (t)) {
4573 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4575 buffer_add_value_full (buf, t, addr, domain, FALSE);
4579 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4582 int type = decode_byte (buf, &buf, limit);
4584 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4585 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4586 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4587 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
4588 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
4589 char *name = mono_type_full_name (t);
4590 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
4592 return ERR_INVALID_ARGUMENT;
4596 case MONO_TYPE_BOOLEAN:
4597 *(guint8*)addr = decode_int (buf, &buf, limit);
4599 case MONO_TYPE_CHAR:
4600 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4603 *(gint8*)addr = decode_int (buf, &buf, limit);
4606 *(guint8*)addr = decode_int (buf, &buf, limit);
4609 *(gint16*)addr = decode_int (buf, &buf, limit);
4612 *(guint16*)addr = decode_int (buf, &buf, limit);
4615 *(gint32*)addr = decode_int (buf, &buf, limit);
4618 *(guint32*)addr = decode_int (buf, &buf, limit);
4621 *(gint64*)addr = decode_long (buf, &buf, limit);
4624 *(guint64*)addr = decode_long (buf, &buf, limit);
4627 *(guint32*)addr = decode_int (buf, &buf, limit);
4630 *(guint64*)addr = decode_long (buf, &buf, limit);
4633 /* We send these as I8, so we get them back as such */
4634 g_assert (type == MONO_TYPE_I8);
4635 *(gssize*)addr = decode_long (buf, &buf, limit);
4637 case MONO_TYPE_GENERICINST:
4638 if (MONO_TYPE_ISSTRUCT (t)) {
4639 /* The client sends these as a valuetype */
4647 /* We send these as vtypes, so we get them back as such */
4648 g_assert (type == MONO_TYPE_VALUETYPE);
4651 case MONO_TYPE_VALUETYPE: {
4652 gboolean is_enum = decode_byte (buf, &buf, limit);
4656 gpointer iter = NULL;
4659 /* Enums are sent as a normal vtype */
4661 return ERR_NOT_IMPLEMENTED;
4662 klass = decode_typeid (buf, &buf, limit, &d, &err);
4666 if (klass != mono_class_from_mono_type (t))
4667 return ERR_INVALID_ARGUMENT;
4669 nfields = decode_int (buf, &buf, limit);
4670 while ((f = mono_class_get_fields (klass, &iter))) {
4671 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4673 if (mono_field_is_deleted (f))
4675 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4680 g_assert (nfields == 0);
4685 if (MONO_TYPE_IS_REFERENCE (t)) {
4686 if (type == MONO_TYPE_OBJECT) {
4687 int objid = decode_objid (buf, &buf, limit);
4691 err = get_object (objid, (MonoObject**)&obj);
4695 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4696 return ERR_INVALID_ARGUMENT;
4697 if (obj && obj->vtable->domain != domain)
4698 return ERR_INVALID_ARGUMENT;
4700 mono_gc_wbarrier_generic_store (addr, obj);
4701 } else if (type == VALUE_TYPE_ID_NULL) {
4702 *(MonoObject**)addr = NULL;
4704 return ERR_INVALID_ARGUMENT;
4718 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4725 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4726 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4729 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4730 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4732 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
4734 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4735 addr = mono_arch_context_get_int_reg (ctx, reg);
4736 addr += (gint32)var->offset;
4738 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4740 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4742 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4746 g_assert_not_reached ();
4751 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
4757 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4758 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4760 if (MONO_TYPE_IS_REFERENCE (t))
4761 size = sizeof (gpointer);
4763 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4766 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4767 // FIXME: Can't set registers, so we disable linears
4770 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4771 addr = mono_arch_context_get_int_reg (ctx, reg);
4772 addr += (gint32)var->offset;
4774 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4776 // FIXME: Write barriers
4777 memcpy (addr, val, size);
4779 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4783 g_assert_not_reached ();
4788 clear_event_request (int req_id, int etype)
4792 mono_loader_lock ();
4793 for (i = 0; i < event_requests->len; ++i) {
4794 EventRequest *req = g_ptr_array_index (event_requests, i);
4796 if (req->id == req_id && req->event_kind == etype) {
4797 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4798 clear_breakpoint (req->info);
4799 if (req->event_kind == EVENT_KIND_STEP)
4800 ss_destroy (req->info);
4801 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
4802 clear_breakpoint (req->info);
4803 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
4804 clear_breakpoint (req->info);
4805 g_ptr_array_remove_index_fast (event_requests, i);
4810 mono_loader_unlock ();
4814 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
4816 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4817 return breakpoint_matches_assembly (req->info, assembly);
4821 for (i = 0; i < req->nmodifiers; ++i) {
4822 Modifier *m = &req->modifiers [i];
4824 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
4826 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
4827 for (j = 0; m->data.assemblies [j]; ++j)
4828 if (m->data.assemblies [j] == assembly)
4838 * clear_event_requests_for_assembly:
4840 * Clear all events requests which reference ASSEMBLY.
4843 clear_event_requests_for_assembly (MonoAssembly *assembly)
4848 mono_loader_lock ();
4852 for (i = 0; i < event_requests->len; ++i) {
4853 EventRequest *req = g_ptr_array_index (event_requests, i);
4855 if (event_req_matches_assembly (req, assembly)) {
4856 clear_event_request (req->id, req->event_kind);
4862 mono_loader_unlock ();
4866 * type_comes_from_assembly:
4868 * GHRFunc that returns TRUE if klass comes from assembly
4871 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
4873 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
4877 * clear_types_for_assembly:
4879 * Clears types from loaded_classes for a given assembly
4882 clear_types_for_assembly (MonoAssembly *assembly)
4884 mono_loader_lock ();
4885 g_hash_table_foreach_remove (loaded_classes, type_comes_from_assembly, assembly);
4886 mono_loader_unlock ();
4890 add_thread (gpointer key, gpointer value, gpointer user_data)
4892 MonoInternalThread *thread = value;
4893 Buffer *buf = user_data;
4895 buffer_add_objid (buf, (MonoObject*)thread);
4899 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
4901 guint8 *p = invoke->p;
4902 guint8 *end = invoke->endp;
4905 MonoMethodSignature *sig;
4908 MonoObject *this, *res, *exc;
4911 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4915 if (invoke->method) {
4917 * Invoke this method directly, currently only Environment.Exit () is supported.
4920 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>"));
4921 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
4922 g_assert_not_reached ();
4925 m = decode_methodid (p, &p, end, &domain, &err);
4928 sig = mono_method_signature (m);
4930 if (m->klass->valuetype)
4931 this_buf = g_alloca (mono_class_instance_size (m->klass));
4933 this_buf = g_alloca (sizeof (MonoObject*));
4934 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
4935 /* Should be null */
4936 int type = decode_byte (p, &p, end);
4937 if (type != VALUE_TYPE_ID_NULL)
4938 return ERR_INVALID_ARGUMENT;
4939 memset (this_buf, 0, mono_class_instance_size (m->klass));
4941 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
4946 if (!m->klass->valuetype)
4947 this = *(MonoObject**)this_buf;
4951 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>"));
4953 if (this && this->vtable->domain != domain)
4956 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
4957 if (!strcmp (m->name, ".ctor")) {
4958 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
4959 return ERR_INVALID_ARGUMENT;
4961 this = mono_object_new (domain, m->klass);
4963 return ERR_INVALID_ARGUMENT;
4967 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
4968 return ERR_INVALID_ARGUMENT;
4970 nargs = decode_int (p, &p, end);
4971 if (nargs != sig->param_count)
4972 return ERR_INVALID_ARGUMENT;
4973 /* Use alloca to get gc tracking */
4974 arg_buf = g_alloca (nargs * sizeof (gpointer));
4975 memset (arg_buf, 0, nargs * sizeof (gpointer));
4976 args = g_alloca (nargs * sizeof (gpointer));
4977 for (i = 0; i < nargs; ++i) {
4978 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
4979 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
4983 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
4986 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
4987 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
4990 args [i] = arg_buf [i];
4997 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
4998 tls->disable_breakpoints = TRUE;
5000 tls->disable_breakpoints = FALSE;
5003 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5005 /* FIXME: Move this to arch specific code */
5006 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5007 if (invoke->has_ctx) {
5010 lmf_addr = mono_get_lmf_addr ();
5013 memset (&ext, 0, sizeof (ext));
5015 ext.lmf.previous_lmf = *(lmf_addr);
5016 /* Mark that this is a MonoLMFExt */
5017 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5018 ext.lmf.rsp = (gssize)&ext;
5019 #elif defined(TARGET_X86)
5020 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5021 /* Mark that this is a MonoLMFExt */
5022 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5023 ext.lmf.ebp = (gssize)&ext;
5024 #elif defined(TARGET_ARM)
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 #elif defined(TARGET_POWERPC)
5029 ext.lmf.previous_lmf = *(lmf_addr);
5030 /* Mark that this is a MonoLMFExt */
5031 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5032 ext.lmf.ebp = (gssize)&ext;
5034 g_assert_not_reached ();
5037 ext.debugger_invoke = TRUE;
5038 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5040 mono_set_lmf ((MonoLMF*)&ext);
5044 if (m->klass->valuetype)
5045 res = mono_runtime_invoke (m, this_buf, args, &exc);
5047 res = mono_runtime_invoke (m, this, args, &exc);
5049 buffer_add_byte (buf, 0);
5050 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5052 buffer_add_byte (buf, 1);
5053 if (sig->ret->type == MONO_TYPE_VOID) {
5054 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5055 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5058 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5059 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5060 buffer_add_value (buf, sig->ret, &res, domain);
5061 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5063 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5069 tls->disable_breakpoints = FALSE;
5071 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5072 if (invoke->has_ctx)
5073 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5076 // FIXME: byref arguments
5084 * Invoke the method given by tls->pending_invoke in the current thread.
5087 invoke_method (void)
5089 DebuggerTlsData *tls;
5094 static void (*restore_context) (void *);
5095 MonoContext restore_ctx;
5097 if (!restore_context)
5098 restore_context = mono_get_restore_context ();
5100 tls = TlsGetValue (debugger_tls_id);
5104 * Store the `InvokeData *' in `tls->invoke' until we're done with
5105 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5108 mono_loader_lock ();
5110 invoke = tls->pending_invoke;
5112 tls->pending_invoke = NULL;
5114 invoke->last_invoke = tls->invoke;
5115 tls->invoke = invoke;
5117 mono_loader_unlock ();
5119 tls->frames_up_to_date = FALSE;
5123 buffer_init (&buf, 128);
5125 err = do_invoke_method (tls, &buf, invoke);
5127 /* Start suspending before sending the reply */
5128 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5131 send_reply_packet (id, err, &buf);
5135 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5137 if (invoke->has_ctx)
5138 save_thread_context (&restore_ctx);
5140 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5141 g_assert (tls->resume_count);
5142 tls->resume_count -= invoke->suspend_count;
5145 DEBUG (1, printf ("[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5148 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5150 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5151 * after the mono_runtime_invoke() already returned, but it doesn't matter
5152 * because we reset the abort here.
5155 mono_loader_lock ();
5157 if (tls->abort_requested)
5158 mono_thread_internal_reset_abort (tls->thread);
5160 tls->invoke = tls->invoke->last_invoke;
5161 tls->abort_requested = FALSE;
5163 mono_loader_unlock ();
5172 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5174 MonoThread *thread = value;
5175 DebuggerTlsData *tls;
5178 mono_loader_lock ();
5179 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5181 res = tls->really_suspended;
5182 mono_loader_unlock ();
5188 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
5191 case CMD_VM_VERSION: {
5192 char *build_info, *version;
5194 build_info = mono_get_runtime_build_info ();
5195 version = g_strdup_printf ("mono %s", build_info);
5197 buffer_add_string (buf, version); /* vm version */
5198 buffer_add_int (buf, MAJOR_VERSION);
5199 buffer_add_int (buf, MINOR_VERSION);
5200 g_free (build_info);
5204 case CMD_VM_SET_PROTOCOL_VERSION: {
5205 major_version = decode_int (p, &p, end);
5206 minor_version = decode_int (p, &p, end);
5207 protocol_version_set = TRUE;
5208 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
5211 case CMD_VM_ALL_THREADS: {
5213 mono_loader_lock ();
5214 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
5215 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
5216 mono_loader_unlock ();
5219 case CMD_VM_SUSPEND:
5221 wait_for_suspend ();
5224 if (suspend_count == 0)
5225 return ERR_NOT_SUSPENDED;
5228 case CMD_VM_DISPOSE:
5229 /* Clear all event requests */
5230 mono_loader_lock ();
5231 while (event_requests->len > 0) {
5232 EventRequest *req = g_ptr_array_index (event_requests, 0);
5234 clear_event_request (req->id, req->event_kind);
5236 mono_loader_unlock ();
5238 // FIXME: Count resumes
5240 disconnected = TRUE;
5243 MonoInternalThread *thread;
5244 DebuggerTlsData *tls;
5245 MonoClass *env_class;
5246 MonoMethod *exit_method;
5250 exit_code = decode_int (p, &p, end);
5252 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
5254 /* Have to send a reply before exiting */
5255 send_reply_packet (id, 0, buf);
5257 /* Clear all event requests */
5258 mono_loader_lock ();
5259 while (event_requests->len > 0) {
5260 EventRequest *req = g_ptr_array_index (event_requests, 0);
5262 clear_event_request (req->id, req->event_kind);
5264 mono_loader_unlock ();
5267 * The JDWP documentation says that the shutdown is not orderly. It doesn't
5268 * specify whenever a VM_DEATH event is sent. We currently do an orderly
5269 * shutdown by hijacking a thread to execute Environment.Exit (). This is
5270 * better than doing the shutdown ourselves, since it avoids various races.
5274 wait_for_suspend ();
5276 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
5277 g_assert (env_class);
5278 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
5279 g_assert (exit_method);
5281 mono_loader_lock ();
5282 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
5283 mono_loader_unlock ();
5286 mono_loader_lock ();
5287 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5288 mono_loader_unlock ();
5290 args = g_new0 (gpointer, 1);
5291 args [0] = g_malloc (sizeof (int));
5292 *(int*)(args [0]) = exit_code;
5294 tls->pending_invoke = g_new0 (InvokeData, 1);
5295 tls->pending_invoke->method = exit_method;
5296 tls->pending_invoke->args = args;
5298 while (suspend_count > 0)
5302 * No thread found, do it ourselves.
5303 * FIXME: This can race with normal shutdown etc.
5305 while (suspend_count > 0)
5308 mono_runtime_set_shutting_down ();
5310 mono_threads_set_shutting_down ();
5312 /* Suspend all managed threads since the runtime is going away */
5313 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
5314 mono_thread_suspend_all_other_threads ();
5315 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
5316 mono_runtime_quit ();
5318 shutdown (conn_fd, SD_BOTH);
5320 shutdown (conn_fd, SHUT_RDWR);
5322 DEBUG(1, fprintf (log_file, "Exiting...\n"));
5328 case CMD_VM_INVOKE_METHOD: {
5329 int objid = decode_objid (p, &p, end);
5331 DebuggerTlsData *tls;
5334 err = get_object (objid, (MonoObject**)&thread);
5338 flags = decode_int (p, &p, end);
5340 // Wait for suspending if it already started
5342 wait_for_suspend ();
5343 if (!is_suspended ())
5344 return ERR_NOT_SUSPENDED;
5346 mono_loader_lock ();
5347 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5348 mono_loader_unlock ();
5351 if (!tls->really_suspended)
5352 /* The thread is still running native code, can't do invokes */
5353 return ERR_NOT_SUSPENDED;
5356 * Store the invoke data into tls, the thread will execute it after it is
5359 if (tls->pending_invoke)
5361 tls->pending_invoke = g_new0 (InvokeData, 1);
5362 tls->pending_invoke->id = id;
5363 tls->pending_invoke->flags = flags;
5364 tls->pending_invoke->p = g_malloc (end - p);
5365 memcpy (tls->pending_invoke->p, p, end - p);
5366 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
5367 tls->pending_invoke->suspend_count = suspend_count;
5369 if (flags & INVOKE_FLAG_SINGLE_THREADED)
5370 resume_thread (THREAD_TO_INTERNAL (thread));
5375 case CMD_VM_ABORT_INVOKE: {
5376 int objid = decode_objid (p, &p, end);
5378 DebuggerTlsData *tls;
5381 err = get_object (objid, (MonoObject**)&thread);
5385 invoke_id = decode_int (p, &p, end);
5387 mono_loader_lock ();
5388 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5391 if (tls->abort_requested) {
5392 mono_loader_unlock ();
5397 * Check whether we're still inside the mono_runtime_invoke() and that it's
5398 * actually the correct invocation.
5400 * Careful, we do not stop the thread that's doing the invocation, so we can't
5401 * inspect its stack. However, invoke_method() also acquires the loader lock
5402 * when it's done, so we're safe here.
5406 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
5407 mono_loader_unlock ();
5408 return ERR_NO_INVOCATION;
5411 tls->abort_requested = TRUE;
5413 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
5414 mono_loader_unlock ();
5419 return ERR_NOT_IMPLEMENTED;
5426 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5431 case CMD_EVENT_REQUEST_SET: {
5433 int i, event_kind, suspend_policy, nmodifiers, mod;
5436 MonoThread *step_thread;
5437 int size = 0, depth = 0, step_thread_id = 0;
5440 event_kind = decode_byte (p, &p, end);
5441 suspend_policy = decode_byte (p, &p, end);
5442 nmodifiers = decode_byte (p, &p, end);
5444 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
5445 req->id = InterlockedIncrement (&event_request_id);
5446 req->event_kind = event_kind;
5447 req->suspend_policy = suspend_policy;
5448 req->nmodifiers = nmodifiers;
5451 for (i = 0; i < nmodifiers; ++i) {
5452 mod = decode_byte (p, &p, end);
5454 req->modifiers [i].kind = mod;
5455 if (mod == MOD_KIND_COUNT) {
5456 req->modifiers [i].data.count = decode_int (p, &p, end);
5457 } else if (mod == MOD_KIND_LOCATION_ONLY) {
5458 method = decode_methodid (p, &p, end, &domain, &err);
5461 location = decode_long (p, &p, end);
5462 } else if (mod == MOD_KIND_STEP) {
5463 step_thread_id = decode_id (p, &p, end);
5464 size = decode_int (p, &p, end);
5465 depth = decode_int (p, &p, end);
5466 } else if (mod == MOD_KIND_THREAD_ONLY) {
5467 int id = decode_id (p, &p, end);
5469 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
5474 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
5475 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
5479 req->modifiers [i].caught = decode_byte (p, &p, end);
5480 req->modifiers [i].uncaught = decode_byte (p, &p, end);
5481 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" : ""));
5483 req->modifiers [i].data.exc_class = exc_class;
5485 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
5487 return ERR_INVALID_ARGUMENT;
5490 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
5491 int n = decode_int (p, &p, end);
5494 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
5495 for (j = 0; j < n; ++j) {
5496 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
5498 g_free (req->modifiers [i].data.assemblies);
5504 return ERR_NOT_IMPLEMENTED;
5508 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5511 req->info = set_breakpoint (method, location, req);
5512 } else if (req->event_kind == EVENT_KIND_STEP) {
5513 g_assert (step_thread_id);
5515 err = get_object (step_thread_id, (MonoObject**)&step_thread);
5521 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
5526 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
5527 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req);
5528 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
5529 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req);
5530 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
5532 if (req->nmodifiers) {
5534 return ERR_NOT_IMPLEMENTED;
5538 mono_loader_lock ();
5539 g_ptr_array_add (event_requests, req);
5540 mono_loader_unlock ();
5542 buffer_add_int (buf, req->id);
5545 case CMD_EVENT_REQUEST_CLEAR: {
5546 int etype = decode_byte (p, &p, end);
5547 int req_id = decode_int (p, &p, end);
5549 // FIXME: Make a faster mapping from req_id to request
5550 mono_loader_lock ();
5551 clear_event_request (req_id, etype);
5552 mono_loader_unlock ();
5555 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
5558 mono_loader_lock ();
5560 while (i < event_requests->len) {
5561 EventRequest *req = g_ptr_array_index (event_requests, i);
5563 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5564 clear_breakpoint (req->info);
5566 g_ptr_array_remove_index_fast (event_requests, i);
5572 mono_loader_unlock ();
5576 return ERR_NOT_IMPLEMENTED;
5583 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5589 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
5590 buffer_add_domainid (buf, mono_get_root_domain ());
5593 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
5594 domain = decode_domainid (p, &p, end, NULL, &err);
5597 buffer_add_string (buf, domain->friendly_name);
5600 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
5605 domain = decode_domainid (p, &p, end, NULL, &err);
5608 mono_loader_lock ();
5610 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5613 buffer_add_int (buf, count);
5614 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5616 buffer_add_assemblyid (buf, domain, ass);
5618 mono_loader_unlock ();
5621 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
5622 domain = decode_domainid (p, &p, end, NULL, &err);
5626 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
5629 case CMD_APPDOMAIN_GET_CORLIB: {
5630 domain = decode_domainid (p, &p, end, NULL, &err);
5634 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
5637 case CMD_APPDOMAIN_CREATE_STRING: {
5641 domain = decode_domainid (p, &p, end, NULL, &err);
5644 s = decode_string (p, &p, end);
5646 o = mono_string_new (domain, s);
5647 buffer_add_objid (buf, (MonoObject*)o);
5650 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
5652 MonoDomain *domain2;
5655 domain = decode_domainid (p, &p, end, NULL, &err);
5658 klass = decode_typeid (p, &p, end, &domain2, &err);
5663 g_assert (domain == domain2);
5665 o = mono_object_new (domain, klass);
5667 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
5671 buffer_add_objid (buf, o);
5675 return ERR_NOT_IMPLEMENTED;
5682 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5688 ass = decode_assemblyid (p, &p, end, &domain, &err);
5693 case CMD_ASSEMBLY_GET_LOCATION: {
5694 buffer_add_string (buf, mono_image_get_filename (ass->image));
5697 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
5701 if (ass->image->dynamic) {
5702 buffer_add_id (buf, 0);
5704 token = mono_image_get_entry_point (ass->image);
5706 buffer_add_id (buf, 0);
5708 m = mono_get_method (ass->image, token, NULL);
5709 buffer_add_methodid (buf, domain, m);
5714 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5715 buffer_add_moduleid (buf, domain, ass->image);
5718 case CMD_ASSEMBLY_GET_OBJECT: {
5719 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5720 buffer_add_objid (buf, o);
5723 case CMD_ASSEMBLY_GET_TYPE: {
5724 char *s = decode_string (p, &p, end);
5725 gboolean ignorecase = decode_byte (p, &p, end);
5726 MonoTypeNameParse info;
5728 gboolean type_resolve;
5730 if (!mono_reflection_parse_type (s, &info)) {
5733 if (info.assembly.name)
5735 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5737 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5738 mono_reflection_free_type_info (&info);
5743 case CMD_ASSEMBLY_GET_NAME: {
5745 MonoAssembly *mass = ass;
5747 name = g_strdup_printf (
5748 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5750 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5751 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5752 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5753 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5755 buffer_add_string (buf, name);
5760 return ERR_NOT_IMPLEMENTED;
5767 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5773 case CMD_MODULE_GET_INFO: {
5774 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
5777 basename = g_path_get_basename (image->name);
5778 buffer_add_string (buf, basename); // name
5779 buffer_add_string (buf, image->module_name); // scopename
5780 buffer_add_string (buf, image->name); // fqname
5781 buffer_add_string (buf, mono_image_get_guid (image)); // guid
5782 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
5787 return ERR_NOT_IMPLEMENTED;
5794 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
5796 if (val && val->vtable->klass == mono_defaults.monotype_class) {
5797 /* Special case these so the client doesn't have to handle Type objects */
5799 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
5800 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
5801 } else if (MONO_TYPE_IS_REFERENCE (t))
5802 buffer_add_value (buf, t, &val, domain);
5804 buffer_add_value (buf, t, mono_object_unbox (val), domain);
5808 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
5814 buffer_add_int (buf, 0);
5818 for (i = 0; i < cinfo->num_attrs; ++i) {
5819 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
5822 buffer_add_int (buf, nattrs);
5824 for (i = 0; i < cinfo->num_attrs; ++i) {
5825 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
5826 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
5827 MonoArray *typed_args, *named_args;
5829 CattrNamedArg *arginfo;
5831 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
5833 buffer_add_methodid (buf, domain, attr->ctor);
5837 buffer_add_int (buf, mono_array_length (typed_args));
5838 for (j = 0; j < mono_array_length (typed_args); ++j) {
5839 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
5841 t = mono_method_signature (attr->ctor)->params [j];
5843 buffer_add_cattr_arg (buf, t, domain, val);
5846 buffer_add_int (buf, 0);
5851 buffer_add_int (buf, mono_array_length (named_args));
5853 for (j = 0; j < mono_array_length (named_args); ++j) {
5854 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
5856 if (arginfo [j].prop) {
5857 buffer_add_byte (buf, 0x54);
5858 buffer_add_propertyid (buf, domain, arginfo [j].prop);
5859 } else if (arginfo [j].field) {
5860 buffer_add_byte (buf, 0x53);
5862 g_assert_not_reached ();
5865 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
5868 buffer_add_int (buf, 0);
5875 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
5885 case CMD_TYPE_GET_INFO: {
5886 buffer_add_string (buf, klass->name_space);
5887 buffer_add_string (buf, klass->name);
5889 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
5890 buffer_add_string (buf, name);
5892 buffer_add_assemblyid (buf, domain, klass->image->assembly);
5893 buffer_add_moduleid (buf, domain, klass->image);
5894 buffer_add_typeid (buf, domain, klass->parent);
5895 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
5896 buffer_add_typeid (buf, domain, klass->element_class);
5898 buffer_add_id (buf, 0);
5899 buffer_add_int (buf, klass->type_token);
5900 buffer_add_byte (buf, klass->rank);
5901 buffer_add_int (buf, klass->flags);
5903 type = &klass->byval_arg;
5904 // FIXME: Can't decide whenever a class represents a byref type
5907 if (type->type == MONO_TYPE_PTR)
5909 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
5911 if (type->type == MONO_TYPE_VALUETYPE)
5913 if (klass->enumtype)
5915 buffer_add_byte (buf, b);
5918 while ((nested = mono_class_get_nested_types (klass, &iter)))
5920 buffer_add_int (buf, nnested);
5922 while ((nested = mono_class_get_nested_types (klass, &iter)))
5923 buffer_add_typeid (buf, domain, nested);
5926 case CMD_TYPE_GET_METHODS: {
5929 gpointer iter = NULL;
5932 mono_class_setup_methods (klass);
5934 nmethods = mono_class_num_methods (klass);
5936 buffer_add_int (buf, nmethods);
5938 while ((m = mono_class_get_methods (klass, &iter))) {
5939 buffer_add_methodid (buf, domain, m);
5942 g_assert (i == nmethods);
5945 case CMD_TYPE_GET_FIELDS: {
5948 gpointer iter = NULL;
5951 nfields = mono_class_num_fields (klass);
5953 buffer_add_int (buf, nfields);
5955 while ((f = mono_class_get_fields (klass, &iter))) {
5956 buffer_add_fieldid (buf, domain, f);
5957 buffer_add_string (buf, f->name);
5958 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
5959 buffer_add_int (buf, f->type->attrs);
5962 g_assert (i == nfields);
5965 case CMD_TYPE_GET_PROPERTIES: {
5968 gpointer iter = NULL;
5971 nprops = mono_class_num_properties (klass);
5973 buffer_add_int (buf, nprops);
5975 while ((p = mono_class_get_properties (klass, &iter))) {
5976 buffer_add_propertyid (buf, domain, p);
5977 buffer_add_string (buf, p->name);
5978 buffer_add_methodid (buf, domain, p->get);
5979 buffer_add_methodid (buf, domain, p->set);
5980 buffer_add_int (buf, p->attrs);
5983 g_assert (i == nprops);
5986 case CMD_TYPE_GET_CATTRS: {
5987 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
5988 MonoCustomAttrInfo *cinfo;
5990 cinfo = mono_custom_attrs_from_class (klass);
5992 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5995 case CMD_TYPE_GET_FIELD_CATTRS: {
5996 MonoClass *attr_klass;
5997 MonoCustomAttrInfo *cinfo;
5998 MonoClassField *field;
6000 field = decode_fieldid (p, &p, end, NULL, &err);
6003 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6007 cinfo = mono_custom_attrs_from_field (klass, field);
6009 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6012 case CMD_TYPE_GET_PROPERTY_CATTRS: {
6013 MonoClass *attr_klass;
6014 MonoCustomAttrInfo *cinfo;
6017 prop = decode_propertyid (p, &p, end, NULL, &err);
6020 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6024 cinfo = mono_custom_attrs_from_property (klass, prop);
6026 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6029 case CMD_TYPE_GET_VALUES: {
6037 len = decode_int (p, &p, end);
6038 for (i = 0; i < len; ++i) {
6039 f = decode_fieldid (p, &p, end, NULL, &err);
6043 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6044 return ERR_INVALID_FIELDID;
6045 if (mono_class_field_is_special_static (f))
6046 return ERR_INVALID_FIELDID;
6048 /* Check that the field belongs to the object */
6050 for (k = klass; k; k = k->parent) {
6051 if (k == f->parent) {
6057 return ERR_INVALID_FIELDID;
6059 vtable = mono_class_vtable (domain, f->parent);
6060 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6061 mono_field_static_get_value (vtable, f, val);
6062 buffer_add_value (buf, f->type, val, domain);
6067 case CMD_TYPE_SET_VALUES: {
6075 len = decode_int (p, &p, end);
6076 for (i = 0; i < len; ++i) {
6077 f = decode_fieldid (p, &p, end, NULL, &err);
6081 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6082 return ERR_INVALID_FIELDID;
6083 if (mono_class_field_is_special_static (f))
6084 return ERR_INVALID_FIELDID;
6086 /* Check that the field belongs to the object */
6088 for (k = klass; k; k = k->parent) {
6089 if (k == f->parent) {
6095 return ERR_INVALID_FIELDID;
6097 // FIXME: Check for literal/const
6099 vtable = mono_class_vtable (domain, f->parent);
6100 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6101 err = decode_value (f->type, domain, val, p, &p, end);
6106 if (MONO_TYPE_IS_REFERENCE (f->type))
6107 mono_field_static_set_value (vtable, f, *(gpointer*)val);
6109 mono_field_static_set_value (vtable, f, val);
6114 case CMD_TYPE_GET_OBJECT: {
6115 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
6116 buffer_add_objid (buf, o);
6119 case CMD_TYPE_GET_SOURCE_FILES:
6120 case CMD_TYPE_GET_SOURCE_FILES_2: {
6121 gpointer iter = NULL;
6123 char *source_file, *base;
6127 files = g_ptr_array_new ();
6129 while ((method = mono_class_get_methods (klass, &iter))) {
6130 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6133 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
6137 for (i = 0; i < files->len; ++i)
6138 if (!strcmp (g_ptr_array_index (files, i), source_file))
6140 if (i == files->len)
6141 g_ptr_array_add (files, g_strdup (source_file));
6142 g_free (source_file);
6146 buffer_add_int (buf, files->len);
6147 for (i = 0; i < files->len; ++i) {
6148 source_file = g_ptr_array_index (files, i);
6149 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
6150 buffer_add_string (buf, source_file);
6152 base = g_path_get_basename (source_file);
6153 buffer_add_string (buf, base);
6156 g_free (source_file);
6158 g_ptr_array_free (files, TRUE);
6161 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
6162 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
6166 if (mono_class_is_assignable_from (klass, oklass))
6167 buffer_add_byte (buf, 1);
6169 buffer_add_byte (buf, 0);
6173 return ERR_NOT_IMPLEMENTED;
6180 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6183 MonoDomain *old_domain;
6187 klass = decode_typeid (p, &p, end, &domain, &err);
6191 old_domain = mono_domain_get ();
6193 mono_domain_set (domain, TRUE);
6195 err = type_commands_internal (command, klass, domain, p, end, buf);
6197 mono_domain_set (old_domain, TRUE);
6203 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6205 MonoMethodHeader *header;
6208 case CMD_METHOD_GET_NAME: {
6209 buffer_add_string (buf, method->name);
6212 case CMD_METHOD_GET_DECLARING_TYPE: {
6213 buffer_add_typeid (buf, domain, method->klass);
6216 case CMD_METHOD_GET_DEBUG_INFO: {
6217 MonoDebugMethodInfo *minfo;
6219 int i, n_il_offsets;
6223 header = mono_method_get_header (method);
6225 buffer_add_int (buf, 0);
6226 buffer_add_string (buf, "");
6227 buffer_add_int (buf, 0);
6231 minfo = mono_debug_lookup_method (method);
6233 buffer_add_int (buf, header->code_size);
6234 buffer_add_string (buf, "");
6235 buffer_add_int (buf, 0);
6236 mono_metadata_free_mh (header);
6240 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
6241 buffer_add_int (buf, header->code_size);
6242 buffer_add_string (buf, source_file);
6243 buffer_add_int (buf, n_il_offsets);
6244 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
6245 for (i = 0; i < n_il_offsets; ++i) {
6246 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
6247 buffer_add_int (buf, il_offsets [i]);
6248 buffer_add_int (buf, line_numbers [i]);
6250 g_free (source_file);
6251 g_free (il_offsets);
6252 g_free (line_numbers);
6253 mono_metadata_free_mh (header);
6256 case CMD_METHOD_GET_PARAM_INFO: {
6257 MonoMethodSignature *sig = mono_method_signature (method);
6261 /* FIXME: mono_class_from_mono_type () and byrefs */
6263 /* FIXME: Use a smaller encoding */
6264 buffer_add_int (buf, sig->call_convention);
6265 buffer_add_int (buf, sig->param_count);
6266 buffer_add_int (buf, sig->generic_param_count);
6267 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
6268 for (i = 0; i < sig->param_count; ++i) {
6270 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
6273 /* Emit parameter names */
6274 names = g_new (char *, sig->param_count);
6275 mono_method_get_param_names (method, (const char **) names);
6276 for (i = 0; i < sig->param_count; ++i)
6277 buffer_add_string (buf, names [i]);
6282 case CMD_METHOD_GET_LOCALS_INFO: {
6283 int i, j, num_locals;
6284 MonoDebugLocalsInfo *locals;
6286 header = mono_method_get_header (method);
6289 buffer_add_int (buf, header->num_locals);
6292 for (i = 0; i < header->num_locals; ++i)
6293 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
6296 locals = mono_debug_lookup_locals (method);
6298 num_locals = locals->num_locals;
6301 for (i = 0; i < header->num_locals; ++i) {
6302 for (j = 0; j < num_locals; ++j)
6303 if (locals->locals [j].index == i)
6306 buffer_add_string (buf, locals->locals [j].name);
6308 buffer_add_string (buf, "");
6312 for (i = 0; i < header->num_locals; ++i) {
6313 for (j = 0; j < num_locals; ++j)
6314 if (locals->locals [j].index == i)
6316 if (j < num_locals && locals->locals [j].block) {
6317 buffer_add_int (buf, locals->locals [j].block->start_offset);
6318 buffer_add_int (buf, locals->locals [j].block->end_offset);
6320 buffer_add_int (buf, 0);
6321 buffer_add_int (buf, header->code_size);
6324 mono_metadata_free_mh (header);
6327 mono_debug_symfile_free_locals (locals);
6331 case CMD_METHOD_GET_INFO:
6332 buffer_add_int (buf, method->flags);
6333 buffer_add_int (buf, method->iflags);
6334 buffer_add_int (buf, method->token);
6336 case CMD_METHOD_GET_BODY: {
6339 header = mono_method_get_header (method);
6341 buffer_add_int (buf, 0);
6343 buffer_add_int (buf, header->code_size);
6344 for (i = 0; i < header->code_size; ++i)
6345 buffer_add_byte (buf, header->code [i]);
6347 mono_metadata_free_mh (header);
6350 case CMD_METHOD_RESOLVE_TOKEN: {
6351 guint32 token = decode_int (p, &p, end);
6354 switch (mono_metadata_token_code (token)) {
6355 case MONO_TOKEN_STRING: {
6359 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
6362 s2 = mono_string_to_utf8 (s);
6364 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6365 buffer_add_string (buf, s2);
6371 MonoClass *handle_class;
6373 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6374 val = mono_method_get_wrapper_data (method, token);
6375 handle_class = mono_method_get_wrapper_data (method, token + 1);
6377 if (handle_class == NULL) {
6378 // Can't figure out the token type
6379 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
6383 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
6387 if (handle_class == mono_defaults.typehandle_class) {
6388 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
6389 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
6390 } else if (handle_class == mono_defaults.fieldhandle_class) {
6391 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
6392 buffer_add_fieldid (buf, domain, val);
6393 } else if (handle_class == mono_defaults.methodhandle_class) {
6394 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
6395 buffer_add_methodid (buf, domain, val);
6396 } else if (handle_class == mono_defaults.string_class) {
6399 s = mono_string_to_utf8 (val);
6400 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6401 buffer_add_string (buf, s);
6404 g_assert_not_reached ();
6412 return ERR_NOT_IMPLEMENTED;
6419 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6422 MonoDomain *old_domain;
6426 method = decode_methodid (p, &p, end, &domain, &err);
6430 old_domain = mono_domain_get ();
6432 mono_domain_set (domain, TRUE);
6434 err = method_commands_internal (command, method, domain, p, end, buf);
6436 mono_domain_set (old_domain, TRUE);
6442 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6444 int objid = decode_objid (p, &p, end);
6446 MonoThread *thread_obj;
6447 MonoInternalThread *thread;
6449 err = get_object (objid, (MonoObject**)&thread_obj);
6453 thread = THREAD_TO_INTERNAL (thread_obj);
6456 case CMD_THREAD_GET_NAME: {
6458 gunichar2 *s = mono_thread_get_name (thread, &name_len);
6461 buffer_add_int (buf, 0);
6466 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
6468 buffer_add_int (buf, len);
6469 buffer_add_data (buf, (guint8*)name, len);
6474 case CMD_THREAD_GET_FRAME_INFO: {
6475 DebuggerTlsData *tls;
6476 int i, start_frame, length;
6478 // Wait for suspending if it already started
6480 wait_for_suspend ();
6481 if (!is_suspended ())
6482 return ERR_NOT_SUSPENDED;
6484 start_frame = decode_int (p, &p, end);
6485 length = decode_int (p, &p, end);
6487 if (start_frame != 0 || length != -1)
6488 return ERR_NOT_IMPLEMENTED;
6490 mono_loader_lock ();
6491 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6492 mono_loader_unlock ();
6495 compute_frame_info (thread, tls);
6497 buffer_add_int (buf, tls->frame_count);
6498 for (i = 0; i < tls->frame_count; ++i) {
6499 buffer_add_int (buf, tls->frames [i]->id);
6500 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
6501 buffer_add_int (buf, tls->frames [i]->il_offset);
6503 * Instead of passing the frame type directly to the client, we associate
6504 * it with the previous frame using a set of flags. This avoids lots of
6505 * conditional code in the client, since a frame whose type isn't
6506 * FRAME_TYPE_MANAGED has no method, location, etc.
6508 buffer_add_byte (buf, tls->frames [i]->flags);
6513 case CMD_THREAD_GET_STATE:
6514 buffer_add_int (buf, thread->state);
6516 case CMD_THREAD_GET_INFO:
6517 buffer_add_byte (buf, thread->threadpool_thread);
6519 case CMD_THREAD_GET_ID:
6520 buffer_add_long (buf, (guint64)(gsize)thread);
6523 return ERR_NOT_IMPLEMENTED;
6530 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6534 MonoThread *thread_obj;
6535 MonoInternalThread *thread;
6537 DebuggerTlsData *tls;
6539 MonoDebugMethodJitInfo *jit;
6540 MonoDebugVarInfo *var;
6541 MonoMethodSignature *sig;
6543 MonoMethodHeader *header;
6545 objid = decode_objid (p, &p, end);
6546 err = get_object (objid, (MonoObject**)&thread_obj);
6550 thread = THREAD_TO_INTERNAL (thread_obj);
6552 id = decode_id (p, &p, end);
6554 mono_loader_lock ();
6555 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6556 mono_loader_unlock ();
6559 for (i = 0; i < tls->frame_count; ++i) {
6560 if (tls->frames [i]->id == id)
6563 if (i == tls->frame_count)
6564 return ERR_INVALID_FRAMEID;
6566 frame = tls->frames [i];
6568 if (!frame->has_ctx)
6570 return ERR_INVALID_FRAMEID;
6573 frame->jit = mono_debug_find_method (frame->method, frame->domain);
6575 /* This could happen for aot images with no jit debug info */
6576 return ERR_ABSENT_INFORMATION;
6580 sig = mono_method_signature (frame->actual_method);
6583 case CMD_STACK_FRAME_GET_VALUES: {
6584 len = decode_int (p, &p, end);
6585 header = mono_method_get_header (frame->actual_method);
6587 for (i = 0; i < len; ++i) {
6588 pos = decode_int (p, &p, end);
6593 g_assert (pos >= 0 && pos < jit->num_params);
6595 var = &jit->params [pos];
6597 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
6599 g_assert (pos >= 0 && pos < jit->num_locals);
6601 var = &jit->locals [pos];
6603 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
6606 mono_metadata_free_mh (header);
6609 case CMD_STACK_FRAME_GET_THIS: {
6610 if (frame->method->klass->valuetype) {
6611 if (!sig->hasthis) {
6612 MonoObject *p = NULL;
6613 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
6615 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6618 if (!sig->hasthis) {
6619 MonoObject *p = NULL;
6620 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
6622 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6627 case CMD_STACK_FRAME_SET_VALUES: {
6630 MonoDebugVarInfo *var;
6632 len = decode_int (p, &p, end);
6633 header = mono_method_get_header (frame->actual_method);
6635 for (i = 0; i < len; ++i) {
6636 pos = decode_int (p, &p, end);
6641 g_assert (pos >= 0 && pos < jit->num_params);
6643 t = sig->params [pos];
6644 var = &jit->params [pos];
6646 g_assert (pos >= 0 && pos < jit->num_locals);
6648 t = header->locals [pos];
6649 var = &jit->locals [pos];
6652 if (MONO_TYPE_IS_REFERENCE (t))
6653 val_buf = g_alloca (sizeof (MonoObject*));
6655 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
6656 err = decode_value (t, frame->domain, val_buf, p, &p, end);
6660 set_var (t, var, &frame->ctx, frame->domain, val_buf);
6662 mono_metadata_free_mh (header);
6666 return ERR_NOT_IMPLEMENTED;
6673 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6676 int objid, err, index, len, i, esize;
6679 objid = decode_objid (p, &p, end);
6680 err = get_object (objid, (MonoObject**)&arr);
6685 case CMD_ARRAY_REF_GET_LENGTH:
6686 buffer_add_int (buf, arr->obj.vtable->klass->rank);
6688 buffer_add_int (buf, arr->max_length);
6689 buffer_add_int (buf, 0);
6691 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
6692 buffer_add_int (buf, arr->bounds [i].length);
6693 buffer_add_int (buf, arr->bounds [i].lower_bound);
6697 case CMD_ARRAY_REF_GET_VALUES:
6698 index = decode_int (p, &p, end);
6699 len = decode_int (p, &p, end);
6701 g_assert (index >= 0 && len >= 0);
6702 // Reordered to avoid integer overflow
6703 g_assert (!(index > arr->max_length - len));
6705 esize = mono_array_element_size (arr->obj.vtable->klass);
6706 for (i = index; i < index + len; ++i) {
6707 elem = (gpointer*)((char*)arr->vector + (i * esize));
6708 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
6711 case CMD_ARRAY_REF_SET_VALUES:
6712 index = decode_int (p, &p, end);
6713 len = decode_int (p, &p, end);
6715 g_assert (index >= 0 && len >= 0);
6716 // Reordered to avoid integer overflow
6717 g_assert (!(index > arr->max_length - len));
6719 esize = mono_array_element_size (arr->obj.vtable->klass);
6720 for (i = index; i < index + len; ++i) {
6721 elem = (gpointer*)((char*)arr->vector + (i * esize));
6723 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
6727 return ERR_NOT_IMPLEMENTED;
6734 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6740 objid = decode_objid (p, &p, end);
6741 err = get_object (objid, (MonoObject**)&str);
6746 case CMD_STRING_REF_GET_VALUE:
6747 s = mono_string_to_utf8 (str);
6748 buffer_add_string (buf, s);
6752 return ERR_NOT_IMPLEMENTED;
6759 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6768 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
6769 objid = decode_objid (p, &p, end);
6770 err = get_object (objid, &obj);
6772 buffer_add_int (buf, 1);
6774 buffer_add_int (buf, 0);
6778 objid = decode_objid (p, &p, end);
6779 err = get_object (objid, &obj);
6784 case CMD_OBJECT_REF_GET_TYPE:
6785 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
6787 case CMD_OBJECT_REF_GET_VALUES:
6788 len = decode_int (p, &p, end);
6790 for (i = 0; i < len; ++i) {
6791 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
6795 /* Check that the field belongs to the object */
6797 for (k = obj->vtable->klass; k; k = k->parent) {
6798 if (k == f->parent) {
6804 return ERR_INVALID_FIELDID;
6806 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6810 if (mono_class_field_is_special_static (f))
6811 return ERR_INVALID_FIELDID;
6813 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6814 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6815 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6816 mono_field_static_get_value (vtable, f, val);
6817 buffer_add_value (buf, f->type, val, obj->vtable->domain);
6820 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
6824 case CMD_OBJECT_REF_SET_VALUES:
6825 len = decode_int (p, &p, end);
6827 for (i = 0; i < len; ++i) {
6828 f = decode_fieldid (p, &p, end, NULL, &err);
6832 /* Check that the field belongs to the object */
6834 for (k = obj->vtable->klass; k; k = k->parent) {
6835 if (k == f->parent) {
6841 return ERR_INVALID_FIELDID;
6843 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6847 if (mono_class_field_is_special_static (f))
6848 return ERR_INVALID_FIELDID;
6850 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6851 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6853 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6854 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
6859 mono_field_static_set_value (vtable, f, val);
6862 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
6868 case CMD_OBJECT_REF_GET_ADDRESS:
6869 buffer_add_long (buf, (gssize)obj);
6871 case CMD_OBJECT_REF_GET_DOMAIN:
6872 buffer_add_domainid (buf, obj->vtable->domain);
6875 return ERR_NOT_IMPLEMENTED;
6882 command_set_to_string (CommandSet command_set)
6884 switch (command_set) {
6887 case CMD_SET_OBJECT_REF:
6888 return "OBJECT_REF";
6889 case CMD_SET_STRING_REF:
6890 return "STRING_REF";
6891 case CMD_SET_THREAD:
6893 case CMD_SET_ARRAY_REF:
6895 case CMD_SET_EVENT_REQUEST:
6896 return "EVENT_REQUEST";
6897 case CMD_SET_STACK_FRAME:
6898 return "STACK_FRAME";
6899 case CMD_SET_APPDOMAIN:
6901 case CMD_SET_ASSEMBLY:
6903 case CMD_SET_METHOD:
6907 case CMD_SET_MODULE:
6917 cmd_to_string (CommandSet set, int command)
6922 case CMD_VM_VERSION:
6924 case CMD_VM_ALL_THREADS:
6925 return "ALL_THREADS";
6926 case CMD_VM_SUSPEND:
6932 case CMD_VM_DISPOSE:
6934 case CMD_VM_INVOKE_METHOD:
6935 return "INVOKE_METHOD";
6936 case CMD_VM_SET_PROTOCOL_VERSION:
6937 return "SET_PROTOCOL_VERSION";
6938 case CMD_VM_ABORT_INVOKE:
6939 return "ABORT_INVOKE";
6954 * This thread handles communication with the debugger client using a JDWP
6957 static guint32 WINAPI
6958 debugger_thread (void *arg)
6960 int res, len, id, flags, command_set, command;
6961 guint8 header [HEADER_LENGTH];
6962 guint8 *data, *p, *end;
6967 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
6969 debugger_thread_id = GetCurrentThreadId ();
6971 mono_jit_thread_attach (mono_get_root_domain ());
6973 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
6975 mono_set_is_debugger_attached (TRUE);
6978 res = recv_length (conn_fd, header, HEADER_LENGTH, 0);
6980 /* This will break if the socket is closed during shutdown too */
6981 if (res != HEADER_LENGTH)
6985 end = header + HEADER_LENGTH;
6987 len = decode_int (p, &p, end);
6988 id = decode_int (p, &p, end);
6989 flags = decode_byte (p, &p, end);
6990 command_set = decode_byte (p, &p, end);
6991 command = decode_byte (p, &p, end);
6993 g_assert (flags == 0);
6996 const char *cmd_str;
6999 cmd_str = cmd_to_string (command_set, command);
7001 sprintf (cmd_num, "%d", command);
7005 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
7008 data = g_malloc (len - HEADER_LENGTH);
7009 if (len - HEADER_LENGTH > 0)
7011 res = recv_length (conn_fd, data, len - HEADER_LENGTH, 0);
7012 if (res != len - HEADER_LENGTH)
7017 end = data + (len - HEADER_LENGTH);
7019 buffer_init (&buf, 128);
7024 /* Process the request */
7025 switch (command_set) {
7027 err = vm_commands (command, id, p, end, &buf);
7028 if (!err && command == CMD_VM_INVOKE_METHOD)
7029 /* Sent after the invoke is complete */
7032 case CMD_SET_EVENT_REQUEST:
7033 err = event_commands (command, p, end, &buf);
7035 case CMD_SET_APPDOMAIN:
7036 err = domain_commands (command, p, end, &buf);
7038 case CMD_SET_ASSEMBLY:
7039 err = assembly_commands (command, p, end, &buf);
7041 case CMD_SET_MODULE:
7042 err = module_commands (command, p, end, &buf);
7045 err = type_commands (command, p, end, &buf);
7047 case CMD_SET_METHOD:
7048 err = method_commands (command, p, end, &buf);
7050 case CMD_SET_THREAD:
7051 err = thread_commands (command, p, end, &buf);
7053 case CMD_SET_STACK_FRAME:
7054 err = frame_commands (command, p, end, &buf);
7056 case CMD_SET_ARRAY_REF:
7057 err = array_commands (command, p, end, &buf);
7059 case CMD_SET_STRING_REF:
7060 err = string_commands (command, p, end, &buf);
7062 case CMD_SET_OBJECT_REF:
7063 err = object_commands (command, p, end, &buf);
7066 err = ERR_NOT_IMPLEMENTED;
7070 send_reply_packet (id, err, &buf);
7075 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
7079 mono_set_is_debugger_attached (FALSE);
7081 mono_mutex_lock (&debugger_thread_exited_mutex);
7082 debugger_thread_exited = TRUE;
7083 mono_cond_signal (&debugger_thread_exited_cond);
7084 mono_mutex_unlock (&debugger_thread_exited_mutex);
7086 DEBUG (1, printf ("[dbg] Debugger thread exited.\n"));
7091 #else /* DISABLE_DEBUGGER_AGENT */
7094 mono_debugger_agent_parse_options (char *options)
7096 g_error ("This runtime is configured with the debugger agent disabled.");
7100 mono_debugger_agent_init (void)
7105 mono_debugger_agent_breakpoint_hit (void *sigctx)
7110 mono_debugger_agent_single_step_event (void *sigctx)
7115 mono_debugger_agent_free_domain_info (MonoDomain *domain)
7120 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
7126 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
7127 MonoContext *catch_ctx)