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
116 MonoDebugMethodJitInfo *jit;
119 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
120 * the frame can become invalid.
125 typedef struct _InvokeData InvokeData;
133 /* This is the context which needs to be restored after the invoke */
137 * If this is set, invoke this method with the arguments given by ARGS.
141 guint32 suspend_count;
143 InvokeData *last_invoke;
150 gboolean has_context;
151 gpointer resume_event;
152 /* This is computed on demand when it is requested using the wire protocol */
153 /* It is freed up when the thread is resumed */
157 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
160 gboolean frames_up_to_date;
162 * Points to data about a pending invoke which needs to be executed after the thread
165 InvokeData *pending_invoke;
167 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
172 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
173 * within a finite amount of time.
177 * Set to TRUE if this thread is suspended in suspend_current ().
179 gboolean really_suspended;
180 /* Used to pass the context to the breakpoint/single step handler */
181 MonoContext handler_ctx;
182 /* Whenever thread_stop () was called for this thread */
185 /* Number of thread interruptions not yet processed */
186 gint32 interrupt_count;
188 /* Whenever to disable breakpoints (used during invokes) */
189 gboolean disable_breakpoints;
192 * Number of times this thread has been resumed using resume_thread ().
194 guint32 resume_count;
196 MonoInternalThread *thread;
199 * Information about the frame which transitioned to native code for running
202 StackFrameInfo async_last_frame;
205 * The context where the stack walk can be started for running threads.
207 MonoContext async_ctx;
209 gboolean has_async_ctx;
212 * The lmf where the stack walk can be started for running threads.
217 * The callee address of the last mono_runtime_invoke call
219 gpointer invoke_addr;
221 gboolean abort_requested;
224 * The current mono_runtime_invoke invocation.
230 * Wire Protocol definitions
233 #define HEADER_LENGTH 11
235 #define MAJOR_VERSION 2
236 #define MINOR_VERSION 2
240 CMD_SET_OBJECT_REF = 9,
241 CMD_SET_STRING_REF = 10,
243 CMD_SET_ARRAY_REF = 13,
244 CMD_SET_EVENT_REQUEST = 15,
245 CMD_SET_STACK_FRAME = 16,
246 CMD_SET_APPDOMAIN = 20,
247 CMD_SET_ASSEMBLY = 21,
255 EVENT_KIND_VM_START = 0,
256 EVENT_KIND_VM_DEATH = 1,
257 EVENT_KIND_THREAD_START = 2,
258 EVENT_KIND_THREAD_DEATH = 3,
259 EVENT_KIND_APPDOMAIN_CREATE = 4,
260 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
261 EVENT_KIND_METHOD_ENTRY = 6,
262 EVENT_KIND_METHOD_EXIT = 7,
263 EVENT_KIND_ASSEMBLY_LOAD = 8,
264 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
265 EVENT_KIND_BREAKPOINT = 10,
266 EVENT_KIND_STEP = 11,
267 EVENT_KIND_TYPE_LOAD = 12,
268 EVENT_KIND_EXCEPTION = 13
272 SUSPEND_POLICY_NONE = 0,
273 SUSPEND_POLICY_EVENT_THREAD = 1,
274 SUSPEND_POLICY_ALL = 2
279 ERR_INVALID_OBJECT = 20,
280 ERR_INVALID_FIELDID = 25,
281 ERR_INVALID_FRAMEID = 30,
282 ERR_NOT_IMPLEMENTED = 100,
283 ERR_NOT_SUSPENDED = 101,
284 ERR_INVALID_ARGUMENT = 102,
286 ERR_NO_INVOCATION = 104,
287 ERR_ABSENT_INFORMATION = 105
292 MOD_KIND_THREAD_ONLY = 3,
293 MOD_KIND_LOCATION_ONLY = 7,
294 MOD_KIND_EXCEPTION_ONLY = 8,
296 MOD_KIND_ASSEMBLY_ONLY = 11
311 TOKEN_TYPE_STRING = 0,
313 TOKEN_TYPE_FIELD = 2,
314 TOKEN_TYPE_METHOD = 3,
315 TOKEN_TYPE_UNKNOWN = 4
319 VALUE_TYPE_ID_NULL = 0xf0,
320 VALUE_TYPE_ID_TYPE = 0xf1
324 FRAME_FLAG_DEBUGGER_INVOKE = 1
328 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
329 INVOKE_FLAG_SINGLE_THREADED = 2
334 CMD_VM_ALL_THREADS = 2,
339 CMD_VM_INVOKE_METHOD = 7,
340 CMD_VM_SET_PROTOCOL_VERSION = 8,
341 CMD_VM_ABORT_INVOKE = 9
345 CMD_THREAD_GET_FRAME_INFO = 1,
346 CMD_THREAD_GET_NAME = 2,
347 CMD_THREAD_GET_STATE = 3,
348 CMD_THREAD_GET_INFO = 4,
349 CMD_THREAD_GET_ID = 5
353 CMD_EVENT_REQUEST_SET = 1,
354 CMD_EVENT_REQUEST_CLEAR = 2,
355 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
363 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
364 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
365 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
366 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
367 CMD_APPDOMAIN_CREATE_STRING = 5,
368 CMD_APPDOMAIN_GET_CORLIB = 6,
369 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
373 CMD_ASSEMBLY_GET_LOCATION = 1,
374 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
375 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
376 CMD_ASSEMBLY_GET_OBJECT = 4,
377 CMD_ASSEMBLY_GET_TYPE = 5,
378 CMD_ASSEMBLY_GET_NAME = 6
382 CMD_MODULE_GET_INFO = 1,
386 CMD_METHOD_GET_NAME = 1,
387 CMD_METHOD_GET_DECLARING_TYPE = 2,
388 CMD_METHOD_GET_DEBUG_INFO = 3,
389 CMD_METHOD_GET_PARAM_INFO = 4,
390 CMD_METHOD_GET_LOCALS_INFO = 5,
391 CMD_METHOD_GET_INFO = 6,
392 CMD_METHOD_GET_BODY = 7,
393 CMD_METHOD_RESOLVE_TOKEN = 8,
397 CMD_TYPE_GET_INFO = 1,
398 CMD_TYPE_GET_METHODS = 2,
399 CMD_TYPE_GET_FIELDS = 3,
400 CMD_TYPE_GET_VALUES = 4,
401 CMD_TYPE_GET_OBJECT = 5,
402 CMD_TYPE_GET_SOURCE_FILES = 6,
403 CMD_TYPE_SET_VALUES = 7,
404 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
405 CMD_TYPE_GET_PROPERTIES = 9,
406 CMD_TYPE_GET_CATTRS = 10,
407 CMD_TYPE_GET_FIELD_CATTRS = 11,
408 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
409 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
413 CMD_STACK_FRAME_GET_VALUES = 1,
414 CMD_STACK_FRAME_GET_THIS = 2,
415 CMD_STACK_FRAME_SET_VALUES = 3
419 CMD_ARRAY_REF_GET_LENGTH = 1,
420 CMD_ARRAY_REF_GET_VALUES = 2,
421 CMD_ARRAY_REF_SET_VALUES = 3,
425 CMD_STRING_REF_GET_VALUE = 1,
429 CMD_OBJECT_REF_GET_TYPE = 1,
430 CMD_OBJECT_REF_GET_VALUES = 2,
431 CMD_OBJECT_REF_IS_COLLECTED = 3,
432 CMD_OBJECT_REF_GET_ADDRESS = 4,
433 CMD_OBJECT_REF_GET_DOMAIN = 5,
434 CMD_OBJECT_REF_SET_VALUES = 6
440 int count; /* For kind == MOD_KIND_COUNT */
441 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
442 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
443 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
445 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
454 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
458 * Describes a single step request.
462 MonoInternalThread *thread;
467 MonoMethod *last_method;
469 /* Whenever single stepping is performed using start/stop_single_stepping () */
471 /* The list of breakpoints used to implement step-over */
476 * Contains additional information for an event
479 /* For EVENT_KIND_EXCEPTION */
481 MonoContext catch_ctx;
485 /* Dummy structure used for the profiler callbacks */
490 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
496 static AgentConfig agent_config;
499 * Whenever the agent is fully initialized.
500 * When using the onuncaught or onthrow options, only some parts of the agent are
501 * initialized on startup, and the full initialization which includes connection
502 * establishment and the startup of the agent thread is only done in response to
505 static gint32 inited;
509 static int packet_id = 0;
511 static int objref_id = 0;
513 static int event_request_id = 0;
515 static int frame_id = 0;
517 static GPtrArray *event_requests;
519 static guint32 debugger_tls_id;
521 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
523 /* Maps MonoInternalThread -> DebuggerTlsData */
524 static MonoGHashTable *thread_to_tls;
526 /* Maps tid -> MonoInternalThread */
527 static MonoGHashTable *tid_to_thread;
529 /* Maps tid -> MonoThread (not MonoInternalThread) */
530 static MonoGHashTable *tid_to_thread_obj;
532 static gsize debugger_thread_id;
534 static HANDLE debugger_thread_handle;
536 static int log_level;
538 static gboolean embedding;
540 static FILE *log_file;
542 /* Classes whose class load event has been sent */
543 static GHashTable *loaded_classes;
545 /* Assemblies whose assembly load event has no been sent yet */
546 static GPtrArray *pending_assembly_loads;
548 /* Types whose type load event has no been sent yet */
549 static GPtrArray *pending_type_loads;
551 /* Whenever the debugger thread has exited */
552 static gboolean debugger_thread_exited;
554 /* Cond variable used to wait for debugger_thread_exited becoming true */
555 static mono_cond_t debugger_thread_exited_cond;
557 /* Mutex for the cond var above */
558 static mono_mutex_t debugger_thread_exited_mutex;
560 static DebuggerProfiler debugger_profiler;
562 /* The single step request instance */
563 static SingleStepReq *ss_req = NULL;
564 static gpointer ss_invoke_addr = NULL;
566 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
567 /* Number of single stepping operations in progress */
571 /* The protocol version of the client */
572 static int major_version, minor_version;
574 /* Whenever the variables above are set by the client */
575 static gboolean protocol_version_set;
577 /* A hash table containing all active domains */
578 static GHashTable *domains;
580 static void transport_connect (const char *host, int port);
582 static guint32 WINAPI debugger_thread (void *arg);
584 static void runtime_initialized (MonoProfiler *prof);
586 static void runtime_shutdown (MonoProfiler *prof);
588 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
590 static void thread_end (MonoProfiler *prof, uintptr_t tid);
592 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
594 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
596 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
598 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
600 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
602 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
604 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
606 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
608 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
610 static void start_single_stepping (void);
612 static void stop_single_stepping (void);
614 static void suspend_current (void);
616 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
618 static void clear_breakpoints_for_domain (MonoDomain *domain);
620 static void clear_types_for_assembly (MonoAssembly *assembly);
622 /* Submodule init/cleanup */
623 static void breakpoints_init (void);
624 static void breakpoints_cleanup (void);
626 static void objrefs_init (void);
627 static void objrefs_cleanup (void);
629 static void ids_init (void);
630 static void ids_cleanup (void);
632 static void suspend_init (void);
634 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls);
635 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
636 static void ss_destroy (SingleStepReq *req);
638 static void start_debugger_thread (void);
640 static void finish_agent_init (gboolean on_startup);
643 parse_address (char *address, char **host, int *port)
645 char *pos = strchr (address, ':');
647 if (pos == NULL || pos == address)
650 *host = g_malloc (pos - address + 1);
651 strncpy (*host, address, pos - address);
652 (*host) [pos - address] = '\0';
654 *port = atoi (pos + 1);
662 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
663 fprintf (stderr, "Available options:\n");
664 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
665 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
666 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
667 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
668 fprintf (stderr, " suspend=y/n\t\t\tWhenever to suspend after startup.\n");
669 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
670 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
674 parse_flag (const char *option, char *flag)
676 if (!strcmp (flag, "y"))
678 else if (!strcmp (flag, "n"))
681 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
688 mono_debugger_agent_parse_options (char *options)
694 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
695 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
699 agent_config.enabled = TRUE;
700 agent_config.suspend = TRUE;
701 agent_config.server = FALSE;
703 args = g_strsplit (options, ",", -1);
704 for (ptr = args; ptr && *ptr; ptr ++) {
707 if (strncmp (arg, "transport=", 10) == 0) {
708 agent_config.transport = g_strdup (arg + 10);
709 } else if (strncmp (arg, "address=", 8) == 0) {
710 agent_config.address = g_strdup (arg + 8);
711 } else if (strncmp (arg, "loglevel=", 9) == 0) {
712 agent_config.log_level = atoi (arg + 9);
713 } else if (strncmp (arg, "logfile=", 8) == 0) {
714 agent_config.log_file = g_strdup (arg + 8);
715 } else if (strncmp (arg, "suspend=", 8) == 0) {
716 agent_config.suspend = parse_flag ("suspend", arg + 8);
717 } else if (strncmp (arg, "server=", 7) == 0) {
718 agent_config.server = parse_flag ("server", arg + 7);
719 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
720 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
721 } else if (strncmp (arg, "onthrow=", 8) == 0) {
722 /* We support multiple onthrow= options */
723 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
724 } else if (strncmp (arg, "onthrow", 7) == 0) {
725 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
726 } else if (strncmp (arg, "help", 4) == 0) {
729 } else if (strncmp (arg, "timeout=", 8) == 0) {
730 agent_config.timeout = atoi (arg + 8);
731 } else if (strncmp (arg, "launch=", 7) == 0) {
732 agent_config.launch = g_strdup (arg + 7);
733 } else if (strncmp (arg, "embedding=", 10) == 0) {
734 agent_config.embedding = atoi (arg + 10) == 1;
741 if (agent_config.transport == NULL) {
742 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
745 if (strcmp (agent_config.transport, "dt_socket") != 0) {
746 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
750 if (agent_config.address == NULL && !agent_config.server) {
751 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
755 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
756 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
762 mono_debugger_agent_init (void)
764 if (!agent_config.enabled)
767 /* Need to know whenever a thread has acquired the loader mutex */
768 mono_loader_lock_track_ownership (TRUE);
770 event_requests = g_ptr_array_new ();
772 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
773 mono_cond_init (&debugger_thread_exited_cond, NULL);
775 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
776 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
777 mono_profiler_install_runtime_initialized (runtime_initialized);
778 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
779 mono_profiler_install_thread (thread_startup, thread_end);
780 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
781 mono_profiler_install_jit_end (jit_end);
782 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
784 debugger_tls_id = TlsAlloc ();
786 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
787 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
789 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
790 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
792 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
793 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
795 loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
796 pending_assembly_loads = g_ptr_array_new ();
797 pending_type_loads = g_ptr_array_new ();
798 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
800 log_level = agent_config.log_level;
802 embedding = agent_config.embedding;
804 if (agent_config.log_file) {
805 log_file = fopen (agent_config.log_file, "w+");
807 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
819 mini_get_debug_options ()->gen_seq_points = TRUE;
821 * This is needed because currently we don't handle liveness info.
823 mini_get_debug_options ()->mdb_optimizations = TRUE;
825 /* This is needed because we can't set local variables in registers yet */
826 mono_disable_optimizations (MONO_OPT_LINEARS);
828 if (!agent_config.onuncaught && !agent_config.onthrow)
829 finish_agent_init (TRUE);
835 * Finish the initialization of the agent. This involves connecting the transport
836 * and starting the agent thread. This is either done at startup, or
837 * in response to some event like an unhandled exception.
840 finish_agent_init (gboolean on_startup)
846 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
849 if (agent_config.launch) {
852 // FIXME: Generated address
853 // FIXME: Races with transport_connect ()
855 argv [0] = agent_config.launch;
856 argv [1] = agent_config.transport;
857 argv [2] = agent_config.address;
860 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
862 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
867 if (agent_config.address) {
868 res = parse_address (agent_config.address, &host, &port);
875 transport_connect (host, port);
878 /* Do some which is usually done after sending the VMStart () event */
879 vm_start_event_sent = TRUE;
880 start_debugger_thread ();
885 mono_debugger_agent_cleanup (void)
890 /* This will interrupt the agent thread */
891 /* Close the read part only so it can still send back replies */
893 shutdown (conn_fd, SD_RECEIVE);
895 shutdown (conn_fd, SHUT_RD);
899 * Wait for the thread to exit.
901 * If we continue with the shutdown without waiting for it, then the client might
902 * not receive an answer to its last command like a resume.
903 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
906 //WaitForSingleObject (debugger_thread_handle, INFINITE);
907 if (GetCurrentThreadId () != debugger_thread_id) {
908 mono_mutex_lock (&debugger_thread_exited_mutex);
909 while (!debugger_thread_exited) {
911 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
912 mono_mutex_unlock (&debugger_thread_exited_mutex);
914 mono_mutex_lock (&debugger_thread_exited_mutex);
917 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
920 mono_mutex_unlock (&debugger_thread_exited_mutex);
923 breakpoints_cleanup ();
928 shutdown (conn_fd, SD_BOTH);
930 shutdown (conn_fd, SHUT_RDWR);
933 mono_mutex_destroy (&debugger_thread_exited_mutex);
934 mono_cond_destroy (&debugger_thread_exited_cond);
940 * recv() + handle incomplete reads and EINTR
943 recv_length (int fd, void *buf, int len, int flags)
949 res = recv (fd, (char *) buf + total, len - total, flags);
952 } while ((res > 0 && total < len) || (res == -1 && errno == EINTR));
958 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
961 transport_connect (const char *host, int port)
963 struct addrinfo hints;
964 struct addrinfo *result, *rp;
966 char port_string [128];
967 char handshake_msg [128];
973 sprintf (port_string, "%d", port);
975 mono_network_init ();
977 /* Obtain address(es) matching host/port */
979 memset (&hints, 0, sizeof (struct addrinfo));
980 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
981 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
983 hints.ai_protocol = 0; /* Any protocol */
985 s = getaddrinfo (host, port_string, &hints, &result);
987 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d: %s\n", host, port, gai_strerror (s));
992 if (agent_config.server) {
993 /* Wait for a connection */
995 struct sockaddr_in addr;
998 /* No address, generate one */
999 sfd = socket (AF_INET, SOCK_STREAM, 0);
1002 /* This will bind the socket to a random port */
1003 res = listen (sfd, 16);
1005 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
1009 addrlen = sizeof (addr);
1010 memset (&addr, 0, sizeof (addr));
1011 res = getsockname (sfd, &addr, &addrlen);
1012 g_assert (res == 0);
1015 port = ntohs (addr.sin_port);
1017 /* Emit the address to stdout */
1018 /* FIXME: Should print another interface, not localhost */
1019 printf ("%s:%d\n", host, port);
1021 /* Listen on the provided address */
1022 for (rp = result; rp != NULL; rp = rp->ai_next) {
1023 sfd = socket (rp->ai_family, rp->ai_socktype,
1028 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1032 res = listen (sfd, 16);
1040 * this function is not present on win2000 which we still support, and the
1041 * workaround described here:
1042 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1043 * only works with MSVC.
1045 freeaddrinfo (result);
1049 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1051 if (agent_config.timeout) {
1056 tv.tv_usec = agent_config.timeout * 1000;
1058 FD_SET (sfd, &readfds);
1059 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1061 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1066 conn_fd = accept (sfd, NULL, NULL);
1067 if (conn_fd == -1) {
1068 fprintf (stderr, "debugger-agent: Unable to listen on %s:%d\n", host, port);
1072 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1074 /* Connect to the specified address */
1075 /* FIXME: Respect the timeout */
1076 for (rp = result; rp != NULL; rp = rp->ai_next) {
1077 sfd = socket (rp->ai_family, rp->ai_socktype,
1082 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1083 break; /* Success */
1091 /* See the comment above */
1092 freeaddrinfo (result);
1096 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1101 /* Write handshake message */
1102 sprintf (handshake_msg, "DWP-Handshake");
1104 res = send (conn_fd, handshake_msg, strlen (handshake_msg), 0);
1105 } while (res == -1 && errno == EINTR);
1106 g_assert (res != -1);
1109 res = recv_length (conn_fd, buf, strlen (handshake_msg), 0);
1110 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1111 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1116 * To support older clients, the client sends its protocol version after connecting
1117 * using a command. Until that is received, default to our protocol version.
1119 major_version = MAJOR_VERSION;
1120 minor_version = MINOR_VERSION;
1121 protocol_version_set = FALSE;
1124 * Set TCP_NODELAY on the socket so the client receives events/command
1125 * results immediately.
1129 int result = setsockopt(conn_fd,
1134 g_assert (result >= 0);
1139 transport_send (guint8 *data, int len)
1144 res = send (conn_fd, data, len, 0);
1145 } while (res == -1 && errno == EINTR);
1153 start_debugger_thread (void)
1157 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1158 g_assert (debugger_thread_handle);
1162 * Functions to decode protocol data
1166 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1169 g_assert (*endbuf <= limit);
1174 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1177 g_assert (*endbuf <= limit);
1179 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1182 static inline gint64
1183 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1185 guint32 high = decode_int (buf, &buf, limit);
1186 guint32 low = decode_int (buf, &buf, limit);
1190 return ((((guint64)high) << 32) | ((guint64)low));
1194 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1196 return decode_int (buf, endbuf, limit);
1200 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1202 int len = decode_int (buf, &buf, limit);
1205 s = g_malloc (len + 1);
1208 memcpy (s, buf, len);
1217 * Functions to encode protocol data
1221 guint8 *buf, *p, *end;
1225 buffer_init (Buffer *buf, int size)
1227 buf->buf = g_malloc (size);
1229 buf->end = buf->buf + size;
1233 buffer_make_room (Buffer *buf, int size)
1235 if (buf->end - buf->p < size) {
1236 int new_size = buf->end - buf->buf + size + 32;
1237 guint8 *p = g_realloc (buf->buf, new_size);
1238 size = buf->p - buf->buf;
1241 buf->end = buf->buf + new_size;
1246 buffer_add_byte (Buffer *buf, guint8 val)
1248 buffer_make_room (buf, 1);
1254 buffer_add_int (Buffer *buf, guint32 val)
1256 buffer_make_room (buf, 4);
1257 buf->p [0] = (val >> 24) & 0xff;
1258 buf->p [1] = (val >> 16) & 0xff;
1259 buf->p [2] = (val >> 8) & 0xff;
1260 buf->p [3] = (val >> 0) & 0xff;
1265 buffer_add_long (Buffer *buf, guint64 l)
1267 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1268 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1272 buffer_add_id (Buffer *buf, int id)
1274 buffer_add_int (buf, (guint64)id);
1278 buffer_add_data (Buffer *buf, guint8 *data, int len)
1280 buffer_make_room (buf, len);
1281 memcpy (buf->p, data, len);
1286 buffer_add_string (Buffer *buf, const char *str)
1291 buffer_add_int (buf, 0);
1294 buffer_add_int (buf, len);
1295 buffer_add_data (buf, (guint8*)str, len);
1300 buffer_free (Buffer *buf)
1306 send_packet (int command_set, int command, Buffer *data)
1312 id = InterlockedIncrement (&packet_id);
1314 len = data->p - data->buf + 11;
1315 buffer_init (&buf, len);
1316 buffer_add_int (&buf, len);
1317 buffer_add_int (&buf, id);
1318 buffer_add_byte (&buf, 0); /* flags */
1319 buffer_add_byte (&buf, command_set);
1320 buffer_add_byte (&buf, command);
1321 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1323 res = transport_send (buf.buf, len);
1331 send_reply_packet (int id, int error, Buffer *data)
1337 len = data->p - data->buf + 11;
1338 buffer_init (&buf, len);
1339 buffer_add_int (&buf, len);
1340 buffer_add_int (&buf, id);
1341 buffer_add_byte (&buf, 0x80); /* flags */
1342 buffer_add_byte (&buf, (error >> 8) & 0xff);
1343 buffer_add_byte (&buf, error);
1344 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1346 res = transport_send (buf.buf, len);
1358 * Represents an object accessible by the debugger client.
1361 /* Unique id used in the wire protocol to refer to objects */
1364 * A weakref gc handle pointing to the object. The gc handle is used to
1365 * detect if the object was garbage collected.
1370 /* Maps objid -> ObjRef */
1371 static GHashTable *objrefs;
1374 free_objref (gpointer value)
1378 mono_gchandle_free (o->handle);
1386 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1390 objrefs_cleanup (void)
1392 g_hash_table_destroy (objrefs);
1396 static GHashTable *obj_to_objref;
1399 * Return an ObjRef for OBJ.
1402 get_objref (MonoObject *obj)
1405 GSList *reflist = NULL, *l;
1411 mono_loader_lock ();
1414 obj_to_objref = g_hash_table_new (NULL, NULL);
1416 /* FIXME: The tables can grow indefinitely */
1418 if (mono_gc_is_moving ()) {
1420 * Objects can move, so use a hash table mapping hash codes to lists of
1421 * ObjRef structures.
1423 hash = mono_object_hash (obj);
1425 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1426 for (l = reflist; l; l = l->next) {
1428 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1429 mono_loader_unlock ();
1434 /* Use a hash table with masked pointers to internalize object references */
1435 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1436 /* ref might refer to a different object with the same addr which was GCd */
1437 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1438 mono_loader_unlock ();
1443 ref = g_new0 (ObjRef, 1);
1444 ref->id = InterlockedIncrement (&objref_id);
1445 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1447 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1449 if (mono_gc_is_moving ()) {
1450 reflist = g_slist_append (reflist, ref);
1451 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1453 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1456 mono_loader_unlock ();
1462 get_objid (MonoObject *obj)
1464 return get_objref (obj)->id;
1468 * Set OBJ to the object identified by OBJID.
1469 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1473 get_object_allow_null (int objid, MonoObject **obj)
1483 return ERR_INVALID_OBJECT;
1485 mono_loader_lock ();
1487 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1490 *obj = mono_gchandle_get_target (ref->handle);
1491 mono_loader_unlock ();
1493 return ERR_INVALID_OBJECT;
1496 mono_loader_unlock ();
1497 return ERR_INVALID_OBJECT;
1502 get_object (int objid, MonoObject **obj)
1504 int err = get_object_allow_null (objid, obj);
1509 return ERR_INVALID_OBJECT;
1514 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1516 return decode_id (buf, endbuf, limit);
1520 buffer_add_objid (Buffer *buf, MonoObject *o)
1522 buffer_add_id (buf, get_objid (o));
1541 * Represents a runtime structure accessible to the debugger client
1544 /* Unique id used in the wire protocol */
1546 /* Domain of the runtime structure, NULL if the domain was unloaded */
1553 MonoAssembly *assembly;
1554 MonoClassField *field;
1556 MonoProperty *property;
1561 /* Maps runtime structure -> Id */
1562 GHashTable *val_to_id [ID_NUM];
1566 static GPtrArray *ids [ID_NUM];
1573 for (i = 0; i < ID_NUM; ++i)
1574 ids [i] = g_ptr_array_new ();
1582 for (i = 0; i < ID_NUM; ++i) {
1584 for (j = 0; j < ids [i]->len; ++j)
1585 g_free (g_ptr_array_index (ids [i], j));
1586 g_ptr_array_free (ids [i], TRUE);
1593 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1595 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1599 for (i = 0; i < ID_NUM; ++i)
1600 if (info->val_to_id [i])
1601 g_hash_table_destroy (info->val_to_id [i]);
1605 domain_jit_info (domain)->agent_info = NULL;
1607 /* Clear ids referencing structures in the domain */
1608 for (i = 0; i < ID_NUM; ++i) {
1610 for (j = 0; j < ids [i]->len; ++j) {
1611 Id *id = g_ptr_array_index (ids [i], j);
1612 if (id->domain == domain)
1618 mono_loader_lock ();
1619 g_hash_table_remove (domains, domain);
1620 mono_loader_unlock ();
1624 get_id (MonoDomain *domain, IdType type, gpointer val)
1627 AgentDomainInfo *info;
1632 mono_loader_lock ();
1634 mono_domain_lock (domain);
1636 if (!domain_jit_info (domain)->agent_info)
1637 domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1638 info = domain_jit_info (domain)->agent_info;
1639 if (info->val_to_id [type] == NULL)
1640 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1642 id = g_hash_table_lookup (info->val_to_id [type], val);
1644 mono_domain_unlock (domain);
1645 mono_loader_unlock ();
1649 id = g_new0 (Id, 1);
1651 id->id = ids [type]->len + 1;
1652 id->domain = domain;
1655 g_hash_table_insert (info->val_to_id [type], val, id);
1657 mono_domain_unlock (domain);
1659 g_ptr_array_add (ids [type], id);
1661 mono_loader_unlock ();
1666 static inline gpointer
1667 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1671 int id = decode_id (buf, endbuf, limit);
1680 // FIXME: error handling
1681 mono_loader_lock ();
1682 g_assert (id > 0 && id <= ids [type]->len);
1684 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1685 mono_loader_unlock ();
1687 if (res->domain == NULL) {
1688 *err = ERR_UNLOADED;
1693 *domain = res->domain;
1695 return res->data.val;
1699 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1701 buffer_add_id (buf, get_id (domain, type, val));
1704 static inline MonoClass*
1705 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1707 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1710 static inline MonoAssembly*
1711 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1713 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1716 static inline MonoImage*
1717 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1719 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1722 static inline MonoMethod*
1723 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1725 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1728 static inline MonoClassField*
1729 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1731 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1734 static inline MonoDomain*
1735 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1737 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1740 static inline MonoProperty*
1741 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1743 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1747 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1749 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1753 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1755 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1759 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1761 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1765 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1767 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1771 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1773 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1777 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1779 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1783 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1785 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1788 static void invoke_method (void);
1795 * save_thread_context:
1797 * Set CTX as the current threads context which is used for computing stack traces.
1798 * This function is signal-safe.
1801 save_thread_context (MonoContext *ctx)
1803 DebuggerTlsData *tls;
1805 tls = TlsGetValue (debugger_tls_id);
1809 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1811 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1812 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1814 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1818 tls->lmf = mono_get_lmf ();
1819 tls->domain = mono_domain_get ();
1820 tls->has_context = TRUE;
1823 /* The number of times the runtime is suspended */
1824 static gint32 suspend_count;
1826 /* Number of threads suspended */
1828 * If this is equal to the size of thread_to_tls, the runtime is considered
1831 static gint32 threads_suspend_count;
1833 static mono_mutex_t suspend_mutex;
1835 /* Cond variable used to wait for suspend_count becoming 0 */
1836 static mono_cond_t suspend_cond;
1838 /* Semaphore used to wait for a thread becoming suspended */
1839 static MonoSemType suspend_sem;
1844 mono_mutex_init (&suspend_mutex, NULL);
1845 mono_cond_init (&suspend_cond, NULL);
1846 MONO_SEM_INIT (&suspend_sem, 0);
1851 StackFrameInfo last_frame;
1852 gboolean last_frame_set;
1855 } GetLastFrameUserData;
1858 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
1860 GetLastFrameUserData *data = user_data;
1862 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
1865 if (!data->last_frame_set) {
1866 /* Store the last frame */
1867 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
1868 data->last_frame_set = TRUE;
1871 /* Store the context/lmf for the frame above the last frame */
1872 memcpy (&data->ctx, ctx, sizeof (MonoContext));
1873 data->lmf = info->lmf;
1880 * mono_debugger_agent_thread_interrupt:
1882 * Called by the abort signal handler.
1883 * Should be signal safe.
1886 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
1888 DebuggerTlsData *tls;
1893 tls = TlsGetValue (debugger_tls_id);
1898 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
1899 * guarantee the signal handler will be called that many times. Instead of tracking
1900 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
1901 * has been requested that hasn't been handled yet, otherwise we can have threads
1902 * refuse to die when VM_EXIT is called
1904 #if defined(__APPLE__)
1905 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
1909 * We use interrupt_count to determine whenever this interrupt should be processed
1910 * by us or the normal interrupt processing code in the signal handler.
1911 * There is no race here with notify_thread (), since the signal is sent after
1912 * incrementing interrupt_count.
1914 if (tls->interrupt_count == 0)
1917 InterlockedDecrement (&tls->interrupt_count);
1920 // FIXME: Races when the thread leaves managed code before hitting a single step
1924 /* Running managed code, will be suspended by the single step code */
1925 DEBUG (1, printf ("[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)GetCurrentThreadId (), ji->method->name, mono_arch_ip_from_context (sigctx)));
1929 * Running native code, will be suspended when it returns to/enters
1930 * managed code. Treat it as already suspended.
1931 * This might interrupt the code in process_single_step_inner (), we use the
1932 * tls->suspending flag to avoid races when that happens.
1934 if (!tls->suspended && !tls->suspending) {
1936 GetLastFrameUserData data;
1938 // FIXME: printf is not signal safe, but this is only used during
1939 // debugger debugging
1941 DEBUG (1, printf ("[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)GetCurrentThreadId (), mono_arch_ip_from_context (sigctx)));
1942 //save_thread_context (&ctx);
1945 /* Already terminated */
1949 * We are in a difficult position: we want to be able to provide stack
1950 * traces for this thread, but we can't use the current ctx+lmf, since
1951 * the thread is still running, so it might return to managed code,
1952 * making these invalid.
1953 * So we start a stack walk and save the first frame, along with the
1954 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
1955 * suspended when it returns to managed code, so the parent's ctx should
1958 data.last_frame_set = FALSE;
1960 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
1961 mono_jit_walk_stack_from_ctx_in_thread (get_last_frame, mono_domain_get (), &ctx, FALSE, tls->thread, mono_get_lmf (), &data);
1963 if (data.last_frame_set) {
1964 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
1965 memcpy (&tls->async_ctx, &data.ctx, sizeof (MonoContext));
1966 tls->async_lmf = data.lmf;
1967 tls->has_async_ctx = TRUE;
1968 tls->domain = mono_domain_get ();
1969 memcpy (&tls->ctx, &ctx, sizeof (MonoContext));
1971 tls->has_async_ctx = FALSE;
1974 mono_memory_barrier ();
1976 tls->suspended = TRUE;
1977 MONO_SEM_POST (&suspend_sem);
1984 static void CALLBACK notify_thread_apc (ULONG_PTR param)
1987 mono_debugger_agent_thread_interrupt (NULL, NULL);
1989 #endif /* HOST_WIN32 */
1992 * reset_native_thread_suspend_state:
1994 * Reset the suspended flag on native threads
1997 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
1999 DebuggerTlsData *tls = value;
2001 if (!tls->really_suspended && tls->suspended)
2002 tls->suspended = FALSE;
2008 * Notify a thread that it needs to suspend.
2011 notify_thread (gpointer key, gpointer value, gpointer user_data)
2013 MonoInternalThread *thread = key;
2014 DebuggerTlsData *tls = value;
2015 gsize tid = thread->tid;
2017 if (GetCurrentThreadId () == tid || tls->terminated)
2020 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2023 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2024 * guarantee the signal handler will be called that many times. Instead of tracking
2025 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2026 * has been requested that hasn't been handled yet, otherwise we can have threads
2027 * refuse to die when VM_EXIT is called
2029 #if defined(__APPLE__)
2030 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2034 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2035 * of things like breaking waits etc. which we don't want.
2037 InterlockedIncrement (&tls->interrupt_count);
2040 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2042 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2044 pthread_kill ((pthread_t) tid, mono_thread_get_abort_signal ());
2049 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2051 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2054 if (debugger_thread_id == GetCurrentThreadId ())
2057 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2058 if (suspend_count - tls->resume_count > 0)
2059 tls->suspending = TRUE;
2061 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2063 if (suspend_count - tls->resume_count == 0) {
2065 * We are executing a single threaded invoke but the single step for
2066 * suspending is still active.
2067 * FIXME: This slows down single threaded invokes.
2069 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2073 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2075 /* Can't suspend in these methods */
2076 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2079 save_thread_context (ctx);
2087 * Increase the suspend count of the VM. While the suspend count is greater
2088 * than 0, runtime threads are suspended at certain points during execution.
2093 mono_loader_lock ();
2095 mono_mutex_lock (&suspend_mutex);
2099 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2101 if (suspend_count == 1) {
2102 // FIXME: Is it safe to call this inside the lock ?
2103 start_single_stepping ();
2104 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2107 mono_mutex_unlock (&suspend_mutex);
2109 mono_loader_unlock ();
2115 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2123 g_assert (debugger_thread_id == GetCurrentThreadId ());
2125 mono_loader_lock ();
2127 mono_mutex_lock (&suspend_mutex);
2129 g_assert (suspend_count > 0);
2132 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2134 if (suspend_count == 0) {
2135 // FIXME: Is it safe to call this inside the lock ?
2136 stop_single_stepping ();
2137 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2140 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2141 err = mono_cond_broadcast (&suspend_cond);
2142 g_assert (err == 0);
2144 mono_mutex_unlock (&suspend_mutex);
2145 //g_assert (err == 0);
2147 mono_loader_unlock ();
2153 * Resume just one thread.
2156 resume_thread (MonoInternalThread *thread)
2159 DebuggerTlsData *tls;
2161 g_assert (debugger_thread_id == GetCurrentThreadId ());
2163 mono_loader_lock ();
2165 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2168 mono_mutex_lock (&suspend_mutex);
2170 g_assert (suspend_count > 0);
2172 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2174 tls->resume_count += suspend_count;
2177 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2178 * but only the one whose resume_count field is > 0 will be resumed.
2180 err = mono_cond_broadcast (&suspend_cond);
2181 g_assert (err == 0);
2183 mono_mutex_unlock (&suspend_mutex);
2184 //g_assert (err == 0);
2186 mono_loader_unlock ();
2190 invalidate_frames (DebuggerTlsData *tls)
2195 tls = TlsGetValue (debugger_tls_id);
2198 for (i = 0; i < tls->frame_count; ++i) {
2199 if (tls->frames [i]->jit)
2200 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2201 g_free (tls->frames [i]);
2203 g_free (tls->frames);
2204 tls->frame_count = 0;
2211 * Suspend the current thread until the runtime is resumed. If the thread has a
2212 * pending invoke, then the invoke is executed before this function returns.
2215 suspend_current (void)
2218 DebuggerTlsData *tls;
2220 g_assert (debugger_thread_id != GetCurrentThreadId ());
2222 if (mono_loader_lock_is_owned_by_self ()) {
2224 * If we own the loader mutex, can't suspend until we release it, since the
2225 * whole runtime can deadlock otherwise.
2230 tls = TlsGetValue (debugger_tls_id);
2233 mono_mutex_lock (&suspend_mutex);
2235 tls->suspending = FALSE;
2236 tls->really_suspended = TRUE;
2238 if (!tls->suspended) {
2239 tls->suspended = TRUE;
2240 MONO_SEM_POST (&suspend_sem);
2243 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2245 while (suspend_count - tls->resume_count > 0) {
2247 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2249 mono_mutex_unlock (&suspend_mutex);
2251 mono_mutex_lock (&suspend_mutex);
2257 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2258 g_assert (err == 0);
2262 tls->suspended = FALSE;
2263 tls->really_suspended = FALSE;
2265 threads_suspend_count --;
2267 mono_mutex_unlock (&suspend_mutex);
2269 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2271 if (tls->pending_invoke) {
2272 /* Save the original context */
2273 tls->pending_invoke->has_ctx = TRUE;
2274 memcpy (&tls->pending_invoke->ctx, &tls->ctx, sizeof (MonoContext));
2279 /* The frame info becomes invalid after a resume */
2280 tls->has_context = FALSE;
2281 tls->has_async_ctx = FALSE;
2282 invalidate_frames (NULL);
2286 count_thread (gpointer key, gpointer value, gpointer user_data)
2288 DebuggerTlsData *tls = value;
2290 if (!tls->suspended && !tls->terminated)
2291 *(int*)user_data = *(int*)user_data + 1;
2295 count_threads_to_wait_for (void)
2299 mono_loader_lock ();
2300 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2301 mono_loader_unlock ();
2309 * Wait until the runtime is completely suspended.
2312 wait_for_suspend (void)
2314 int nthreads, nwait, err;
2315 gboolean waited = FALSE;
2317 // FIXME: Threads starting/stopping ?
2318 mono_loader_lock ();
2319 nthreads = mono_g_hash_table_size (thread_to_tls);
2320 mono_loader_unlock ();
2323 nwait = count_threads_to_wait_for ();
2325 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2326 err = MONO_SEM_WAIT (&suspend_sem);
2327 g_assert (err == 0);
2335 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2341 * Return whenever the runtime is suspended.
2346 return count_threads_to_wait_for () == 0;
2350 * find_seq_point_for_native_offset:
2352 * Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2353 * should be the location of a sequence point.
2356 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2358 MonoSeqPointInfo *seq_points;
2361 mono_domain_lock (domain);
2362 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2363 mono_domain_unlock (domain);
2364 g_assert (seq_points);
2368 for (i = 0; i < seq_points->len; ++i) {
2369 if (seq_points->seq_points [i].native_offset == native_offset)
2370 return &seq_points->seq_points [i];
2379 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2380 * should be the location of a sequence point.
2383 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2385 MonoSeqPointInfo *seq_points;
2388 mono_domain_lock (domain);
2389 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2390 mono_domain_unlock (domain);
2391 g_assert (seq_points);
2395 for (i = 0; i < seq_points->len; ++i) {
2396 if (seq_points->seq_points [i].il_offset == il_offset)
2397 return &seq_points->seq_points [i];
2404 * compute_il_offset:
2406 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2407 * a location of a sequence point.
2408 * We use this function instead of mono_debug_il_offset_from_address () etc,
2409 * which doesn't seem to work in a lot of cases.
2412 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2414 MonoSeqPointInfo *seq_points;
2415 int i, last_il_offset, seq_il_offset, seq_native_offset;
2417 mono_domain_lock (domain);
2418 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2419 mono_domain_unlock (domain);
2420 g_assert (seq_points);
2422 last_il_offset = -1;
2424 /* Find the sequence point */
2425 for (i = 0; i < seq_points->len; ++i) {
2426 seq_il_offset = seq_points->seq_points [i].il_offset;
2427 seq_native_offset = seq_points->seq_points [i].native_offset;
2429 if (seq_native_offset > native_offset)
2431 last_il_offset = seq_il_offset;
2434 return last_il_offset;
2438 DebuggerTlsData *tls;
2440 } ComputeFramesUserData;
2443 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2445 ComputeFramesUserData *ud = user_data;
2449 if (info->type != FRAME_TYPE_MANAGED) {
2450 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2451 /* Mark the last frame as an invoke frame */
2453 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2459 method = info->ji->method;
2461 method = info->method;
2463 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2466 if (info->il_offset == -1) {
2467 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2468 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2471 DEBUG (1, fprintf (log_file, "\tFrame: %s %d %d %d\n", mono_method_full_name (method, TRUE), info->native_offset, info->il_offset, info->managed));
2473 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2475 * mono_arch_find_jit_info () returns the context stored in the LMF for
2476 * native frames, but it should unwind once. This is why we have duplicate
2477 * frames on the stack sometimes.
2478 * !managed also seems to be set for dynamic methods.
2483 frame = g_new0 (StackFrame, 1);
2484 frame->method = method;
2485 frame->il_offset = info->il_offset;
2488 frame->has_ctx = TRUE;
2490 frame->domain = info->domain;
2492 ud->frames = g_slist_append (ud->frames, frame);
2498 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2500 ComputeFramesUserData user_data;
2502 int i, findex, new_frame_count;
2503 StackFrame **new_frames, *f;
2505 // FIXME: Locking on tls
2506 if (tls->frames && tls->frames_up_to_date)
2509 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2511 user_data.tls = tls;
2512 user_data.frames = NULL;
2513 if (tls->terminated) {
2514 tls->frame_count = 0;
2516 } if (!tls->really_suspended && tls->has_async_ctx) {
2517 /* Have to use the state saved by the signal handler */
2518 process_frame (&tls->async_last_frame, NULL, &user_data);
2519 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->async_ctx, FALSE, thread, tls->async_lmf, &user_data);
2520 } else if (tls->has_context) {
2521 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
2524 tls->frame_count = 0;
2528 new_frame_count = g_slist_length (user_data.frames);
2529 new_frames = g_new0 (StackFrame*, new_frame_count);
2531 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2535 * Reuse the id for already existing stack frames, so invokes don't invalidate
2536 * the still valid stack frames.
2538 for (i = 0; i < tls->frame_count; ++i) {
2539 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2540 f->id = tls->frames [i]->id;
2545 if (i >= tls->frame_count)
2546 f->id = InterlockedIncrement (&frame_id);
2548 new_frames [findex ++] = f;
2551 g_slist_free (user_data.frames);
2553 invalidate_frames (tls);
2555 tls->frames = new_frames;
2556 tls->frame_count = new_frame_count;
2557 tls->frames_up_to_date = TRUE;
2565 * create_event_list:
2567 * Return a list of event request ids matching EVENT, starting from REQS, which
2568 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2570 * We return request ids, instead of requests, to simplify threading, since
2571 * requests could be deleted anytime when the loader lock is not held.
2572 * LOCKING: Assumes the loader lock is held.
2575 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
2578 GSList *events = NULL;
2580 *suspend_policy = SUSPEND_POLICY_NONE;
2583 reqs = event_requests;
2588 for (i = 0; i < reqs->len; ++i) {
2589 EventRequest *req = g_ptr_array_index (reqs, i);
2590 if (req->event_kind == event) {
2591 gboolean filtered = FALSE;
2594 for (j = 0; j < req->nmodifiers; ++j) {
2595 Modifier *mod = &req->modifiers [j];
2597 if (mod->kind == MOD_KIND_COUNT) {
2599 if (mod->data.count > 0) {
2600 if (mod->data.count > 0) {
2602 if (mod->data.count == 0)
2606 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2607 if (mod->data.thread != mono_thread_internal_current ())
2609 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
2610 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
2612 if (ei->caught && !mod->caught)
2614 if (!ei->caught && !mod->uncaught)
2616 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2618 gboolean found = FALSE;
2619 MonoAssembly **assemblies = mod->data.assemblies;
2622 for (k = 0; assemblies [k]; ++k)
2623 if (assemblies [k] == ji->method->klass->image->assembly)
2632 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2633 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2638 /* Send a VM START/DEATH event by default */
2639 if (event == EVENT_KIND_VM_START)
2640 events = g_slist_append (events, GINT_TO_POINTER (0));
2641 if (event == EVENT_KIND_VM_DEATH)
2642 events = g_slist_append (events, GINT_TO_POINTER (0));
2647 static G_GNUC_UNUSED const char*
2648 event_to_string (EventKind event)
2651 case EVENT_KIND_VM_START: return "VM_START";
2652 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2653 case EVENT_KIND_THREAD_START: return "THREAD_START";
2654 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2655 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2656 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2657 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2658 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2659 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2660 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2661 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2662 case EVENT_KIND_STEP: return "STEP";
2663 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2664 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2666 g_assert_not_reached ();
2673 * Send an event to the client, suspending the vm if needed.
2674 * LOCKING: Since this can suspend the calling thread, no locks should be held
2676 * The EVENTS list is freed by this function.
2679 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2683 MonoDomain *domain = mono_domain_get ();
2689 if (!vm_start_event_sent && event != EVENT_KIND_VM_START)
2690 // FIXME: We miss those events
2693 if (vm_death_event_sent)
2696 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH)
2705 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
2706 // FIXME: Send these with a NULL thread, don't suspend the current thread
2709 buffer_init (&buf, 128);
2710 buffer_add_byte (&buf, suspend_policy);
2711 buffer_add_int (&buf, g_slist_length (events)); // n of events
2713 for (l = events; l; l = l->next) {
2714 buffer_add_byte (&buf, event); // event kind
2715 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
2717 thread = mono_thread_current ();
2719 if (event == EVENT_KIND_VM_START)
2721 else if (event == EVENT_KIND_THREAD_START)
2722 g_assert (mono_thread_internal_current () == arg);
2724 buffer_add_objid (&buf, (MonoObject*)thread); // thread
2727 case EVENT_KIND_THREAD_START:
2728 case EVENT_KIND_THREAD_DEATH:
2730 case EVENT_KIND_APPDOMAIN_CREATE:
2731 case EVENT_KIND_APPDOMAIN_UNLOAD:
2732 buffer_add_domainid (&buf, arg);
2734 case EVENT_KIND_METHOD_ENTRY:
2735 case EVENT_KIND_METHOD_EXIT:
2736 buffer_add_methodid (&buf, domain, arg);
2738 case EVENT_KIND_ASSEMBLY_LOAD:
2739 case EVENT_KIND_ASSEMBLY_UNLOAD:
2740 buffer_add_assemblyid (&buf, domain, arg);
2742 case EVENT_KIND_TYPE_LOAD:
2743 buffer_add_typeid (&buf, domain, arg);
2745 case EVENT_KIND_BREAKPOINT:
2746 case EVENT_KIND_STEP:
2747 buffer_add_methodid (&buf, domain, arg);
2748 buffer_add_long (&buf, il_offset);
2750 case EVENT_KIND_VM_START:
2751 buffer_add_domainid (&buf, mono_get_root_domain ());
2753 case EVENT_KIND_VM_DEATH:
2755 case EVENT_KIND_EXCEPTION: {
2756 EventInfo *ei = arg;
2757 buffer_add_objid (&buf, ei->exc);
2761 g_assert_not_reached ();
2765 if (event == EVENT_KIND_VM_START) {
2766 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
2767 start_debugger_thread ();
2770 if (event == EVENT_KIND_VM_DEATH) {
2771 vm_death_event_sent = TRUE;
2773 suspend_policy = SUSPEND_POLICY_NONE;
2776 if (mono_runtime_is_shutting_down ())
2777 suspend_policy = SUSPEND_POLICY_NONE;
2779 if (suspend_policy != SUSPEND_POLICY_NONE) {
2781 * Save the thread context and start suspending before sending the packet,
2782 * since we could be receiving the resume request before send_packet ()
2785 save_thread_context (ctx);
2789 send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
2791 g_slist_free (events);
2794 if (event == EVENT_KIND_VM_START)
2795 vm_start_event_sent = TRUE;
2797 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
2801 switch (suspend_policy) {
2802 case SUSPEND_POLICY_NONE:
2804 case SUSPEND_POLICY_ALL:
2807 case SUSPEND_POLICY_EVENT_THREAD:
2811 g_assert_not_reached ();
2816 process_profiler_event (EventKind event, gpointer arg)
2821 mono_loader_lock ();
2822 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
2823 mono_loader_unlock ();
2825 process_event (event, arg, 0, NULL, events, suspend_policy);
2829 runtime_initialized (MonoProfiler *prof)
2831 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
2835 runtime_shutdown (MonoProfiler *prof)
2837 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
2839 mono_debugger_agent_cleanup ();
2843 thread_startup (MonoProfiler *prof, uintptr_t tid)
2845 MonoInternalThread *thread = mono_thread_internal_current ();
2846 MonoInternalThread *old_thread;
2847 DebuggerTlsData *tls;
2849 if (tid == debugger_thread_id)
2852 g_assert (thread->tid == tid);
2854 mono_loader_lock ();
2855 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2856 mono_loader_unlock ();
2858 if (thread == old_thread) {
2860 * For some reason, thread_startup () might be called for the same thread
2861 * multiple times (attach ?).
2863 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
2867 * thread_end () might not be called for some threads, and the tid could
2870 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
2871 mono_loader_lock ();
2872 mono_g_hash_table_remove (thread_to_tls, old_thread);
2873 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
2874 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2875 mono_loader_unlock ();
2879 tls = TlsGetValue (debugger_tls_id);
2881 // FIXME: Free this somewhere
2882 tls = g_new0 (DebuggerTlsData, 1);
2883 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
2884 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
2885 tls->thread = thread;
2886 TlsSetValue (debugger_tls_id, tls);
2888 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2890 mono_loader_lock ();
2891 mono_g_hash_table_insert (thread_to_tls, thread, tls);
2892 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
2893 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
2894 mono_loader_unlock ();
2896 process_profiler_event (EVENT_KIND_THREAD_START, thread);
2899 * suspend_vm () could have missed this thread, so wait for a resume.
2905 thread_end (MonoProfiler *prof, uintptr_t tid)
2907 MonoInternalThread *thread;
2908 DebuggerTlsData *tls = NULL;
2910 mono_loader_lock ();
2911 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2913 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2914 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
2915 tls->terminated = TRUE;
2916 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2917 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
2918 MONO_GC_UNREGISTER_ROOT (tls->thread);
2921 mono_loader_unlock ();
2923 /* We might be called for threads started before we registered the start callback */
2925 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2926 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
2931 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
2933 mono_loader_lock ();
2934 g_hash_table_insert (domains, domain, domain);
2935 mono_loader_unlock ();
2937 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
2941 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
2943 /* Invalidate each thread's frame stack */
2944 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
2945 clear_breakpoints_for_domain (domain);
2946 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
2950 * invalidate_each_thread:
2952 * A GHFunc to invalidate frames.
2953 * value must be a DebuggerTlsData*
2956 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
2958 invalidate_frames (value);
2962 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
2964 /* Sent later in jit_end () */
2965 mono_loader_lock ();
2966 g_ptr_array_add (pending_assembly_loads, assembly);
2967 mono_loader_unlock ();
2971 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
2973 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
2975 clear_event_requests_for_assembly (assembly);
2976 clear_types_for_assembly (assembly);
2980 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2982 #if defined(HOST_WIN32) && !defined(__GNUC__)
2983 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
2985 gpointer stackptr = __builtin_frame_address (1);
2987 MonoInternalThread *thread = mono_thread_internal_current ();
2988 DebuggerTlsData *tls;
2990 mono_loader_lock ();
2992 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2993 /* Could be the debugger thread with assembly/type load hooks */
2995 tls->invoke_addr = stackptr;
2997 mono_loader_unlock ();
3001 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3004 #if defined(HOST_WIN32) && !defined(__GNUC__)
3005 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3007 gpointer stackptr = __builtin_frame_address (1);
3010 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3014 * We need to stop single stepping when exiting a runtime invoke, since if it is
3015 * a step out, it may return to native code, and thus never end.
3017 mono_loader_lock ();
3018 ss_invoke_addr = NULL;
3020 for (i = 0; i < event_requests->len; ++i) {
3021 EventRequest *req = g_ptr_array_index (event_requests, i);
3023 if (req->event_kind == EVENT_KIND_STEP) {
3024 ss_destroy (req->info);
3025 g_ptr_array_remove_index_fast (event_requests, i);
3030 mono_loader_unlock ();
3034 send_type_load (MonoClass *klass)
3036 gboolean type_load = FALSE;
3038 mono_loader_lock ();
3039 if (!g_hash_table_lookup (loaded_classes, klass)) {
3041 g_hash_table_insert (loaded_classes, klass, klass);
3043 mono_loader_unlock ();
3045 process_profiler_event (EVENT_KIND_TYPE_LOAD, klass);
3049 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3052 * We emit type load events when the first method of the type is JITted,
3053 * since the class load profiler callbacks might be called with the
3054 * loader lock held. They could also occur in the debugger thread.
3055 * Same for assembly load events.
3058 MonoAssembly *assembly = NULL;
3060 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3061 mono_loader_lock ();
3062 if (pending_assembly_loads->len > 0) {
3063 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3064 g_ptr_array_remove_index (pending_assembly_loads, 0);
3066 mono_loader_unlock ();
3069 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3074 if (!vm_start_event_sent) {
3075 /* Save these so they can be sent after the vm start event */
3076 mono_loader_lock ();
3077 g_ptr_array_add (pending_type_loads, method->klass);
3078 mono_loader_unlock ();
3080 /* Send all pending type load events */
3084 mono_loader_lock ();
3085 if (pending_type_loads->len > 0) {
3086 klass = g_ptr_array_index (pending_type_loads, 0);
3087 g_ptr_array_remove_index (pending_type_loads, 0);
3089 mono_loader_unlock ();
3091 send_type_load (klass);
3096 send_type_load (method->klass);
3100 add_pending_breakpoints (method, jinfo);
3104 * BREAKPOINTS/SINGLE STEPPING
3108 * Contains information about an inserted breakpoint.
3111 long il_offset, native_offset;
3115 } BreakpointInstance;
3118 * Contains generic information about a breakpoint.
3122 * The method where the breakpoint is placed. Can be NULL in which case it
3123 * is inserted into every method. This is used to implement method entry/
3124 * exit events. Can be a generic method definition, in which case the
3125 * breakpoint is inserted into every instance.
3131 * A list of BreakpointInstance structures describing where the breakpoint
3132 * was inserted. There could be more than one because of
3133 * generics/appdomains/method entry/exit.
3135 GPtrArray *children;
3138 /* List of breakpoints */
3139 static GPtrArray *breakpoints;
3140 /* Maps breakpoint locations to the number of breakpoints at that location */
3141 static GHashTable *bp_locs;
3144 breakpoints_init (void)
3146 breakpoints = g_ptr_array_new ();
3147 bp_locs = g_hash_table_new (NULL, NULL);
3151 * insert_breakpoint:
3153 * Insert the breakpoint described by BP into the method described by
3157 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp)
3160 gint32 il_offset = -1, native_offset;
3161 BreakpointInstance *inst;
3164 for (i = 0; i < seq_points->len; ++i) {
3165 il_offset = seq_points->seq_points [i].il_offset;
3166 native_offset = seq_points->seq_points [i].native_offset;
3168 if (il_offset == bp->il_offset)
3172 if (i == seq_points->len) {
3173 /* Have to handle this somehow */
3174 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);
3177 inst = g_new0 (BreakpointInstance, 1);
3178 inst->native_offset = native_offset;
3179 inst->ip = (guint8*)ji->code_start + native_offset;
3181 inst->domain = domain;
3183 mono_loader_lock ();
3185 g_ptr_array_add (bp->children, inst);
3187 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3188 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3189 mono_loader_unlock ();
3192 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3193 mono_arch_set_breakpoint (ji, inst->ip);
3199 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)il_offset));
3203 remove_breakpoint (BreakpointInstance *inst)
3205 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3207 MonoJitInfo *ji = inst->ji;
3208 guint8 *ip = inst->ip;
3210 mono_loader_lock ();
3211 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3212 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3213 mono_loader_unlock ();
3215 g_assert (count > 0);
3218 mono_arch_clear_breakpoint (ji, ip);
3225 static inline gboolean
3226 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3228 return (!bp->method || method == bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method));
3232 * add_pending_breakpoints:
3234 * Insert pending breakpoints into the newly JITted method METHOD.
3237 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3240 MonoSeqPointInfo *seq_points;
3246 domain = mono_domain_get ();
3248 mono_loader_lock ();
3250 for (i = 0; i < breakpoints->len; ++i) {
3251 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3252 gboolean found = FALSE;
3254 if (!bp_matches_method (bp, method))
3257 for (j = 0; j < bp->children->len; ++j) {
3258 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3265 mono_domain_lock (domain);
3266 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3267 mono_domain_unlock (domain);
3269 /* Could be AOT code */
3271 g_assert (seq_points);
3273 insert_breakpoint (seq_points, domain, ji, bp);
3277 mono_loader_unlock ();
3281 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp)
3286 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3288 /* Might be AOTed code */
3289 code = mono_aot_get_method (domain, method);
3291 ji = mono_jit_info_table_find (domain, code);
3296 insert_breakpoint (seq_points, domain, ji, bp);
3306 set_bp_in_method_cb (gpointer key, gpointer value, gpointer user_data)
3308 MonoMethod *method = key;
3309 MonoSeqPointInfo *seq_points = value;
3310 SetBpUserData *ud = user_data;
3311 MonoBreakpoint *bp = ud->bp;
3312 MonoDomain *domain = ud->domain;
3314 if (bp_matches_method (bp, method))
3315 set_bp_in_method (domain, method, seq_points, bp);
3319 set_bp_in_domain (gpointer key, gpointer value, gpointer user_data)
3321 MonoDomain *domain = key;
3322 MonoBreakpoint *bp = user_data;
3328 mono_domain_lock (domain);
3329 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, &ud);
3330 mono_domain_unlock (domain);
3336 * Set a breakpoint at IL_OFFSET in METHOD.
3337 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3338 * METHOD can also be a generic method definition, in which case a breakpoint
3339 * is placed in all instances of the method.
3341 static MonoBreakpoint*
3342 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req)
3347 // - suspend/resume the vm to prevent code patching problems
3348 // - multiple breakpoints on the same location
3349 // - dynamic methods
3352 bp = g_new0 (MonoBreakpoint, 1);
3353 bp->method = method;
3354 bp->il_offset = il_offset;
3356 bp->children = g_ptr_array_new ();
3358 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));
3360 mono_loader_lock ();
3362 g_hash_table_foreach (domains, set_bp_in_domain, bp);
3364 mono_loader_unlock ();
3366 mono_loader_lock ();
3367 g_ptr_array_add (breakpoints, bp);
3368 mono_loader_unlock ();
3374 clear_breakpoint (MonoBreakpoint *bp)
3378 // FIXME: locking, races
3379 for (i = 0; i < bp->children->len; ++i) {
3380 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3382 remove_breakpoint (inst);
3387 mono_loader_lock ();
3388 g_ptr_array_remove (breakpoints, bp);
3389 mono_loader_unlock ();
3391 g_ptr_array_free (bp->children, TRUE);
3396 breakpoints_cleanup (void)
3400 mono_loader_lock ();
3402 while (i < event_requests->len) {
3403 EventRequest *req = g_ptr_array_index (event_requests, i);
3405 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
3406 clear_breakpoint (req->info);
3407 g_ptr_array_remove_index_fast (event_requests, i);
3414 for (i = 0; i < breakpoints->len; ++i)
3415 g_free (g_ptr_array_index (breakpoints, i));
3417 g_ptr_array_free (breakpoints, TRUE);
3418 g_hash_table_destroy (bp_locs);
3423 mono_loader_unlock ();
3427 * clear_breakpoints_for_domain:
3429 * Clear breakpoint instances which reference DOMAIN.
3432 clear_breakpoints_for_domain (MonoDomain *domain)
3436 /* This could be called after shutdown */
3440 mono_loader_lock ();
3441 for (i = 0; i < breakpoints->len; ++i) {
3442 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3445 while (j < bp->children->len) {
3446 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3448 if (inst->domain == domain) {
3449 remove_breakpoint (inst);
3453 g_ptr_array_remove_index_fast (bp->children, j);
3459 mono_loader_unlock ();
3463 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
3465 return bp->method && bp->method->klass->image->assembly == assembly;
3469 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
3472 guint8 *orig_ip, *ip;
3473 int i, j, suspend_policy;
3474 guint32 native_offset;
3476 BreakpointInstance *inst;
3477 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3478 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3479 EventKind kind = EVENT_KIND_BREAKPOINT;
3481 // FIXME: Speed this up
3483 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3484 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
3486 g_assert (ji->method);
3488 /* Compute the native offset of the breakpoint from the ip */
3489 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3490 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3491 native_offset = ip - (guint8*)ji->code_start;
3497 * Skip the instruction causing the breakpoint signal.
3499 mono_arch_skip_breakpoint (ctx);
3501 if (ji->method->wrapper_type || tls->disable_breakpoints)
3504 bp_reqs = g_ptr_array_new ();
3505 ss_reqs = g_ptr_array_new ();
3506 ss_reqs_orig = g_ptr_array_new ();
3508 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3510 mono_loader_lock ();
3513 for (i = 0; i < breakpoints->len; ++i) {
3514 bp = g_ptr_array_index (breakpoints, i);
3519 for (j = 0; j < bp->children->len; ++j) {
3520 inst = g_ptr_array_index (bp->children, j);
3521 if (inst->ji == ji && inst->native_offset == native_offset) {
3522 if (bp->req->event_kind == EVENT_KIND_STEP) {
3523 g_ptr_array_add (ss_reqs_orig, bp->req);
3525 g_ptr_array_add (bp_reqs, bp->req);
3530 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3531 MonoSeqPointInfo *seq_points;
3532 int seq_il_offset, seq_native_offset;
3533 MonoDomain *domain = mono_domain_get ();
3535 /* Maybe a method entry/exit event */
3536 mono_domain_lock (domain);
3537 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3538 mono_domain_unlock (domain);
3540 // FIXME: Generic sharing */
3541 mono_loader_unlock ();
3544 g_assert (seq_points);
3546 for (i = 0; i < seq_points->len; ++i) {
3547 seq_il_offset = seq_points->seq_points [i].il_offset;
3548 seq_native_offset = seq_points->seq_points [i].native_offset;
3550 if (native_offset == seq_native_offset) {
3551 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3552 kind = EVENT_KIND_METHOD_ENTRY;
3553 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3554 kind = EVENT_KIND_METHOD_EXIT;
3560 /* Process single step requests */
3561 for (i = 0; i < ss_reqs_orig->len; ++i) {
3562 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3563 SingleStepReq *ss_req = bp->req->info;
3564 gboolean hit = TRUE;
3565 MonoSeqPointInfo *info;
3568 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3571 if (ss_req->size == STEP_SIZE_LINE) {
3572 /* Have to check whenever a different source line was reached */
3573 MonoDebugMethodInfo *minfo;
3574 MonoDebugSourceLocation *loc = NULL;
3576 minfo = mono_debug_lookup_method (ji->method);
3579 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3581 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3582 /* Have to continue single stepping */
3586 ss_req->last_method = ji->method;
3587 ss_req->last_line = loc->row;
3588 mono_debug_free_source_location (loc);
3593 g_ptr_array_add (ss_reqs, req);
3595 /* Start single stepping again from the current sequence point */
3596 ss_start (ss_req, ji->method, sp, info, ctx, NULL);
3599 if (ss_reqs->len > 0)
3600 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3601 if (bp_reqs->len > 0)
3602 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3603 if (kind != EVENT_KIND_BREAKPOINT)
3604 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3606 mono_loader_unlock ();
3608 g_ptr_array_free (bp_reqs, TRUE);
3609 g_ptr_array_free (ss_reqs, TRUE);
3612 * FIXME: The first event will suspend, so the second will only be sent after the
3616 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3618 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3619 if (enter_leave_events)
3620 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3624 process_breakpoint (void)
3626 DebuggerTlsData *tls;
3628 static void (*restore_context) (void *);
3630 if (!restore_context)
3631 restore_context = mono_get_restore_context ();
3633 tls = TlsGetValue (debugger_tls_id);
3634 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3636 process_breakpoint_inner (tls, &ctx);
3638 /* This is called when resuming from a signal handler, so it shouldn't return */
3639 restore_context (&ctx);
3640 g_assert_not_reached ();
3644 resume_from_signal_handler (void *sigctx, void *func)
3646 DebuggerTlsData *tls;
3649 /* Save the original context in TLS */
3650 // FIXME: This might not work on an altstack ?
3651 tls = TlsGetValue (debugger_tls_id);
3654 // FIXME: MonoContext usually doesn't include the fp registers, so these are
3655 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3656 // clob:c could be added to op_seq_point.
3658 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3659 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3660 MONO_CONTEXT_SET_IP (&ctx, func);
3661 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3663 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3664 mono_ppc_set_func_into_sigctx (sigctx, func);
3669 mono_debugger_agent_breakpoint_hit (void *sigctx)
3672 * We are called from a signal handler, and running code there causes all kinds of
3673 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
3674 * So set up the signal context to return to the real breakpoint handler function.
3677 resume_from_signal_handler (sigctx, process_breakpoint);
3681 process_single_step_inner (DebuggerTlsData *tls, MonoContext *ctx)
3686 int il_offset, suspend_policy;
3690 // FIXME: Speed this up
3692 ip = MONO_CONTEXT_GET_IP (ctx);
3694 /* Skip the instruction causing the single step */
3695 mono_arch_skip_single_step (ctx);
3697 if (suspend_count > 0) {
3698 process_suspend (tls, ctx);
3703 // FIXME: A suspend race
3706 if (mono_thread_internal_current () != ss_req->thread)
3709 if (log_level > 0) {
3710 const char *depth = NULL;
3712 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
3714 switch (ss_req->depth) {
3715 case STEP_DEPTH_OVER:
3718 case STEP_DEPTH_OUT:
3721 case STEP_DEPTH_INTO:
3725 g_assert_not_reached ();
3728 DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_req->depth == STEP_DEPTH_OVER ? "over" : "out", mono_method_full_name (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
3732 * We implement step over/out by single stepping until we reach the same
3733 * frame/parent frame.
3736 * - stack growing upward
3740 if (ss_req->depth != STEP_DEPTH_INTO) {
3741 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
3743 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
3746 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
3749 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
3751 g_assert (ji->method);
3753 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
3758 * Stopping in memset makes half-initialized vtypes visible.
3759 * Stopping in memcpy makes half-copied vtypes visible.
3761 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
3765 * The ip points to the instruction causing the single step event, convert it
3766 * to the offset stored in seq_points.
3768 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3769 ip = mono_arch_get_ip_for_single_step (ji, ctx);
3771 g_assert_not_reached ();
3775 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
3776 * example, so do things by hand.
3778 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
3780 if (il_offset == -1)
3783 if (ss_req->size == STEP_SIZE_LINE) {
3784 /* Step until a different source line is reached */
3785 MonoDebugMethodInfo *minfo;
3787 minfo = mono_debug_lookup_method (ji->method);
3790 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
3792 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
3793 mono_debug_free_source_location (loc);
3798 * Step until we reach a location with line number info,
3799 * otherwise the client can't show a location.
3800 * This can happen for example with statics initialized inline
3801 * outside of a cctor.
3806 ss_req->last_method = ji->method;
3807 ss_req->last_line = loc->row;
3808 mono_debug_free_source_location (loc);
3813 // FIXME: Has to lock earlier
3815 reqs = g_ptr_array_new ();
3817 mono_loader_lock ();
3819 g_ptr_array_add (reqs, ss_req->req);
3821 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
3823 g_ptr_array_free (reqs, TRUE);
3825 mono_loader_unlock ();
3827 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
3831 process_single_step (void)
3833 DebuggerTlsData *tls;
3835 static void (*restore_context) (void *);
3837 if (!restore_context)
3838 restore_context = mono_get_restore_context ();
3840 tls = TlsGetValue (debugger_tls_id);
3841 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3843 process_single_step_inner (tls, &ctx);
3845 /* This is called when resuming from a signal handler, so it shouldn't return */
3846 restore_context (&ctx);
3847 g_assert_not_reached ();
3851 * mono_debugger_agent_single_step_event:
3853 * Called from a signal handler to handle a single step event.
3856 mono_debugger_agent_single_step_event (void *sigctx)
3858 /* Resume to process_single_step through the signal context */
3860 // FIXME: Since step out/over is implemented using step in, the step in case should
3861 // be as fast as possible. Move the relevant code from process_single_step_inner ()
3864 if (GetCurrentThreadId () == debugger_thread_id) {
3866 * This could happen despite our best effors when the runtime calls
3867 * assembly/type resolve hooks.
3868 * FIXME: Breakpoints too.
3872 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3873 mono_arch_skip_single_step (&ctx);
3874 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3878 resume_from_signal_handler (sigctx, process_single_step);
3882 * start_single_stepping:
3884 * Turn on single stepping. Can be called multiple times, for example,
3885 * by a single step event request + a suspend.
3888 start_single_stepping (void)
3890 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3891 int val = InterlockedIncrement (&ss_count);
3894 mono_arch_start_single_stepping ();
3896 if (ss_req != NULL && ss_invoke_addr == NULL) {
3897 DebuggerTlsData *tls;
3899 mono_loader_lock ();
3901 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
3902 ss_invoke_addr = tls->invoke_addr;
3904 mono_loader_unlock ();
3907 g_assert_not_reached ();
3912 stop_single_stepping (void)
3914 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3915 int val = InterlockedDecrement (&ss_count);
3918 mono_arch_stop_single_stepping ();
3920 g_assert_not_reached ();
3927 * Stop the single stepping operation given by SS_REQ.
3930 ss_stop (SingleStepReq *ss_req)
3932 gboolean use_bps = FALSE;
3939 for (l = ss_req->bps; l; l = l->next) {
3940 clear_breakpoint (l->data);
3942 g_slist_free (ss_req->bps);
3946 if (ss_req->global) {
3947 stop_single_stepping ();
3948 ss_req->global = FALSE;
3955 * Start the single stepping operation given by SS_REQ from the sequence point SP.
3958 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls)
3960 gboolean use_bp = FALSE;
3965 /* Stop the previous operation */
3969 * Implement single stepping using breakpoints if possible.
3971 if (ss_req->depth == STEP_DEPTH_OVER) {
3974 * Find the first sequence point in the current or in a previous frame which
3975 * is not the last in its method.
3977 while (sp && sp->next_len == 0) {
3979 if (tls && frame_index < tls->frame_count) {
3980 StackFrame *frame = tls->frames [frame_index];
3982 method = frame->method;
3983 if (frame->il_offset != -1) {
3984 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
3990 if (sp && sp->next_len > 0) {
3992 for (i = 0; i < sp->next_len; ++i) {
3993 next_sp = &info->seq_points [sp->next [i]];
3995 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req);
3996 ss_req->bps = g_slist_append (ss_req->bps, bp);
4002 ss_req->global = TRUE;
4003 start_single_stepping ();
4005 ss_req->global = FALSE;
4010 * Start single stepping of thread THREAD
4013 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4015 DebuggerTlsData *tls;
4016 MonoSeqPointInfo *info;
4017 SeqPoint *sp = NULL;
4018 MonoMethod *method = NULL;
4020 if (suspend_count == 0)
4021 return ERR_NOT_SUSPENDED;
4023 wait_for_suspend ();
4025 // FIXME: Multiple requests
4027 DEBUG (0, printf ("Received a single step request while the previous one was still active.\n"));
4028 return ERR_NOT_IMPLEMENTED;
4031 ss_req = g_new0 (SingleStepReq, 1);
4033 ss_req->thread = thread;
4034 ss_req->size = size;
4035 ss_req->depth = depth;
4038 mono_loader_lock ();
4039 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4040 mono_loader_unlock ();
4042 g_assert (tls->has_context);
4043 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
4045 if (ss_req->size == STEP_SIZE_LINE) {
4047 MonoDebugMethodInfo *minfo;
4049 /* Compute the initial line info */
4050 compute_frame_info (thread, tls);
4052 g_assert (tls->frame_count);
4053 frame = tls->frames [0];
4055 ss_req->last_method = frame->method;
4056 ss_req->last_line = -1;
4058 minfo = mono_debug_lookup_method (frame->method);
4059 if (minfo && frame->il_offset != -1) {
4060 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4063 ss_req->last_line = loc->row;
4069 if (ss_req->depth == STEP_DEPTH_OVER) {
4072 compute_frame_info (thread, tls);
4074 g_assert (tls->frame_count);
4075 frame = tls->frames [0];
4077 if (frame->il_offset != -1) {
4078 /* FIXME: Sort the table and use a binary search */
4079 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
4081 method = frame->method;
4085 ss_start (ss_req, method, sp, info, NULL, tls);
4091 ss_destroy (SingleStepReq *req)
4094 g_assert (ss_req == req);
4103 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
4104 MonoContext *catch_ctx)
4111 if (thread_to_tls != NULL) {
4112 MonoInternalThread *thread = mono_thread_internal_current ();
4113 DebuggerTlsData *tls;
4115 mono_loader_lock ();
4116 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4117 mono_loader_unlock ();
4119 if (tls && tls->abort_requested)
4123 memset (&ei, 0, sizeof (EventInfo));
4125 /* Just-In-Time debugging */
4127 if (agent_config.onuncaught && !inited) {
4128 finish_agent_init (FALSE);
4131 * Send an unsolicited EXCEPTION event with a dummy request id.
4133 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4134 ei.exc = (MonoObject*)exc;
4135 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4138 } else if (agent_config.onthrow && !inited) {
4140 gboolean found = FALSE;
4142 for (l = agent_config.onthrow; l; l = l->next) {
4143 char *ex_type = l->data;
4144 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
4146 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
4153 finish_agent_init (FALSE);
4156 * Send an unsolicited EXCEPTION event with a dummy request id.
4158 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4159 ei.exc = (MonoObject*)exc;
4160 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4168 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
4170 ei.exc = (MonoObject*)exc;
4171 ei.caught = catch_ctx != NULL;
4173 mono_loader_lock ();
4174 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
4175 mono_loader_unlock ();
4177 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
4181 * buffer_add_value_full:
4183 * Add the encoding of the value at ADDR described by T to the buffer.
4184 * AS_VTYPE determines whenever to treat primitive types as primitive types or
4188 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
4194 g_assert (*(void**)addr);
4195 addr = *(void**)addr;
4200 case MONO_TYPE_BOOLEAN:
4203 case MONO_TYPE_CHAR:
4223 case MONO_TYPE_VOID:
4224 buffer_add_byte (buf, t->type);
4226 case MONO_TYPE_BOOLEAN:
4229 buffer_add_byte (buf, t->type);
4230 buffer_add_int (buf, *(gint8*)addr);
4232 case MONO_TYPE_CHAR:
4235 buffer_add_byte (buf, t->type);
4236 buffer_add_int (buf, *(gint16*)addr);
4241 buffer_add_byte (buf, t->type);
4242 buffer_add_int (buf, *(gint32*)addr);
4247 buffer_add_byte (buf, t->type);
4248 buffer_add_long (buf, *(gint64*)addr);
4252 /* Treat it as a vtype */
4254 case MONO_TYPE_PTR: {
4255 gssize val = *(gssize*)addr;
4257 buffer_add_byte (buf, t->type);
4258 buffer_add_long (buf, val);
4262 case MONO_TYPE_STRING:
4263 case MONO_TYPE_SZARRAY:
4264 case MONO_TYPE_OBJECT:
4265 case MONO_TYPE_CLASS:
4266 case MONO_TYPE_ARRAY:
4267 obj = *(MonoObject**)addr;
4270 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4272 if (obj->vtable->klass->valuetype) {
4273 t = &obj->vtable->klass->byval_arg;
4274 addr = mono_object_unbox (obj);
4276 } else if (obj->vtable->klass->rank) {
4277 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4278 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4279 buffer_add_byte (buf, MONO_TYPE_CLASS);
4281 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4283 buffer_add_objid (buf, obj);
4287 case MONO_TYPE_VALUETYPE: {
4291 MonoClass *klass = mono_class_from_mono_type (t);
4293 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4294 buffer_add_byte (buf, klass->enumtype);
4295 buffer_add_typeid (buf, domain, klass);
4299 while ((f = mono_class_get_fields (klass, &iter))) {
4300 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4302 if (mono_field_is_deleted (f))
4306 buffer_add_int (buf, nfields);
4309 while ((f = mono_class_get_fields (klass, &iter))) {
4310 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4312 if (mono_field_is_deleted (f))
4314 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4318 case MONO_TYPE_GENERICINST:
4319 if (mono_type_generic_inst_is_valuetype (t)) {
4331 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4333 buffer_add_value_full (buf, t, addr, domain, FALSE);
4337 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4340 int type = decode_byte (buf, &buf, limit);
4342 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4343 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4344 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4345 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
4346 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
4347 char *name = mono_type_full_name (t);
4348 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
4350 return ERR_INVALID_ARGUMENT;
4354 case MONO_TYPE_BOOLEAN:
4355 *(guint8*)addr = decode_int (buf, &buf, limit);
4357 case MONO_TYPE_CHAR:
4358 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4361 *(gint8*)addr = decode_int (buf, &buf, limit);
4364 *(guint8*)addr = decode_int (buf, &buf, limit);
4367 *(gint16*)addr = decode_int (buf, &buf, limit);
4370 *(guint16*)addr = decode_int (buf, &buf, limit);
4373 *(gint32*)addr = decode_int (buf, &buf, limit);
4376 *(guint32*)addr = decode_int (buf, &buf, limit);
4379 *(gint64*)addr = decode_long (buf, &buf, limit);
4382 *(guint64*)addr = decode_long (buf, &buf, limit);
4385 *(guint32*)addr = decode_int (buf, &buf, limit);
4388 *(guint64*)addr = decode_long (buf, &buf, limit);
4391 /* We send these as I8, so we get them back as such */
4392 g_assert (type == MONO_TYPE_I8);
4393 *(gssize*)addr = decode_long (buf, &buf, limit);
4395 case MONO_TYPE_GENERICINST:
4396 if (MONO_TYPE_ISSTRUCT (t)) {
4397 /* The client sends these as a valuetype */
4405 /* We send these as vtypes, so we get them back as such */
4406 g_assert (type == MONO_TYPE_VALUETYPE);
4409 case MONO_TYPE_VALUETYPE: {
4410 gboolean is_enum = decode_byte (buf, &buf, limit);
4414 gpointer iter = NULL;
4417 /* Enums are sent as a normal vtype */
4419 return ERR_NOT_IMPLEMENTED;
4420 klass = decode_typeid (buf, &buf, limit, &d, &err);
4424 if (klass != mono_class_from_mono_type (t))
4425 return ERR_INVALID_ARGUMENT;
4427 nfields = decode_int (buf, &buf, limit);
4428 while ((f = mono_class_get_fields (klass, &iter))) {
4429 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4431 if (mono_field_is_deleted (f))
4433 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4438 g_assert (nfields == 0);
4443 if (MONO_TYPE_IS_REFERENCE (t)) {
4444 if (type == MONO_TYPE_OBJECT) {
4445 int objid = decode_objid (buf, &buf, limit);
4449 err = get_object (objid, (MonoObject**)&obj);
4453 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4454 return ERR_INVALID_ARGUMENT;
4455 if (obj && obj->vtable->domain != domain)
4456 return ERR_INVALID_ARGUMENT;
4458 mono_gc_wbarrier_generic_store (addr, obj);
4459 } else if (type == VALUE_TYPE_ID_NULL) {
4460 *(MonoObject**)addr = NULL;
4462 return ERR_INVALID_ARGUMENT;
4476 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4483 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4484 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4487 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4488 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4490 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
4492 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4493 addr = mono_arch_context_get_int_reg (ctx, reg);
4494 addr += (gint32)var->offset;
4496 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4498 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4500 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4504 g_assert_not_reached ();
4509 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
4515 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4516 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4518 if (MONO_TYPE_IS_REFERENCE (t))
4519 size = sizeof (gpointer);
4521 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4524 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4525 // FIXME: Can't set registers, so we disable linears
4528 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4529 addr = mono_arch_context_get_int_reg (ctx, reg);
4530 addr += (gint32)var->offset;
4532 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4534 // FIXME: Write barriers
4535 memcpy (addr, val, size);
4537 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4541 g_assert_not_reached ();
4546 clear_event_request (int req_id, int etype)
4550 mono_loader_lock ();
4551 for (i = 0; i < event_requests->len; ++i) {
4552 EventRequest *req = g_ptr_array_index (event_requests, i);
4554 if (req->id == req_id && req->event_kind == etype) {
4555 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4556 clear_breakpoint (req->info);
4557 if (req->event_kind == EVENT_KIND_STEP)
4558 ss_destroy (req->info);
4559 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
4560 clear_breakpoint (req->info);
4561 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
4562 clear_breakpoint (req->info);
4563 g_ptr_array_remove_index_fast (event_requests, i);
4568 mono_loader_unlock ();
4572 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
4574 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4575 return breakpoint_matches_assembly (req->info, assembly);
4579 for (i = 0; i < req->nmodifiers; ++i) {
4580 Modifier *m = &req->modifiers [i];
4582 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
4584 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
4585 for (j = 0; m->data.assemblies [j]; ++j)
4586 if (m->data.assemblies [j] == assembly)
4596 * clear_event_requests_for_assembly:
4598 * Clear all events requests which reference ASSEMBLY.
4601 clear_event_requests_for_assembly (MonoAssembly *assembly)
4606 mono_loader_lock ();
4610 for (i = 0; i < event_requests->len; ++i) {
4611 EventRequest *req = g_ptr_array_index (event_requests, i);
4613 if (event_req_matches_assembly (req, assembly)) {
4614 clear_event_request (req->id, req->event_kind);
4620 mono_loader_unlock ();
4624 * type_comes_from_assembly:
4626 * GHRFunc that returns TRUE if klass comes from assembly
4629 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
4631 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
4635 * clear_types_for_assembly:
4637 * Clears types from loaded_classes for a given assembly
4640 clear_types_for_assembly (MonoAssembly *assembly)
4642 mono_loader_lock ();
4643 g_hash_table_foreach_remove (loaded_classes, type_comes_from_assembly, assembly);
4644 mono_loader_unlock ();
4648 add_thread (gpointer key, gpointer value, gpointer user_data)
4650 MonoInternalThread *thread = value;
4651 Buffer *buf = user_data;
4653 buffer_add_objid (buf, (MonoObject*)thread);
4657 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
4659 guint8 *p = invoke->p;
4660 guint8 *end = invoke->endp;
4663 MonoMethodSignature *sig;
4666 MonoObject *this, *res, *exc;
4669 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4673 if (invoke->method) {
4675 * Invoke this method directly, currently only Environment.Exit () is supported.
4678 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>"));
4679 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
4680 g_assert_not_reached ();
4683 m = decode_methodid (p, &p, end, &domain, &err);
4686 sig = mono_method_signature (m);
4688 if (m->klass->valuetype)
4689 this_buf = g_alloca (mono_class_instance_size (m->klass));
4691 this_buf = g_alloca (sizeof (MonoObject*));
4692 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
4693 /* Should be null */
4694 int type = decode_byte (p, &p, end);
4695 if (type != VALUE_TYPE_ID_NULL)
4696 return ERR_INVALID_ARGUMENT;
4697 memset (this_buf, 0, mono_class_instance_size (m->klass));
4699 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
4704 if (!m->klass->valuetype)
4705 this = *(MonoObject**)this_buf;
4709 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>"));
4711 if (this && this->vtable->domain != domain)
4714 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
4715 if (!strcmp (m->name, ".ctor")) {
4716 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
4717 return ERR_INVALID_ARGUMENT;
4719 this = mono_object_new (domain, m->klass);
4721 return ERR_INVALID_ARGUMENT;
4725 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
4726 return ERR_INVALID_ARGUMENT;
4728 nargs = decode_int (p, &p, end);
4729 if (nargs != sig->param_count)
4730 return ERR_INVALID_ARGUMENT;
4731 /* Use alloca to get gc tracking */
4732 arg_buf = g_alloca (nargs * sizeof (gpointer));
4733 memset (arg_buf, 0, nargs * sizeof (gpointer));
4734 args = g_alloca (nargs * sizeof (gpointer));
4735 for (i = 0; i < nargs; ++i) {
4736 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
4737 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
4741 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
4744 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
4745 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
4748 args [i] = arg_buf [i];
4755 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
4756 tls->disable_breakpoints = TRUE;
4758 tls->disable_breakpoints = FALSE;
4761 * Add an LMF frame to link the stack frames on the invoke method with our caller.
4763 /* FIXME: Move this to arch specific code */
4764 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4765 if (invoke->has_ctx) {
4768 lmf_addr = mono_get_lmf_addr ();
4771 memset (&ext, 0, sizeof (ext));
4773 ext.lmf.previous_lmf = *(lmf_addr);
4774 /* Mark that this is a MonoLMFExt */
4775 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4776 ext.lmf.rsp = (gssize)&ext;
4777 #elif defined(TARGET_X86)
4778 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
4779 /* Mark that this is a MonoLMFExt */
4780 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4781 ext.lmf.ebp = (gssize)&ext;
4782 #elif defined(TARGET_ARM)
4783 ext.lmf.previous_lmf = *(lmf_addr);
4784 /* Mark that this is a MonoLMFExt */
4785 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4786 ext.lmf.ebp = (gssize)&ext;
4787 #elif defined(TARGET_POWERPC)
4788 ext.lmf.previous_lmf = *(lmf_addr);
4789 /* Mark that this is a MonoLMFExt */
4790 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4791 ext.lmf.ebp = (gssize)&ext;
4793 g_assert_not_reached ();
4796 ext.debugger_invoke = TRUE;
4797 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
4799 mono_set_lmf ((MonoLMF*)&ext);
4803 if (m->klass->valuetype)
4804 res = mono_runtime_invoke (m, this_buf, args, &exc);
4806 res = mono_runtime_invoke (m, this, args, &exc);
4808 buffer_add_byte (buf, 0);
4809 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
4811 buffer_add_byte (buf, 1);
4812 if (sig->ret->type == MONO_TYPE_VOID) {
4813 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
4814 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
4817 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
4818 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
4819 buffer_add_value (buf, sig->ret, &res, domain);
4820 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
4822 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
4828 tls->disable_breakpoints = FALSE;
4830 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4831 if (invoke->has_ctx)
4832 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
4835 // FIXME: byref arguments
4843 * Invoke the method given by tls->pending_invoke in the current thread.
4846 invoke_method (void)
4848 DebuggerTlsData *tls;
4853 static void (*restore_context) (void *);
4854 MonoContext restore_ctx;
4856 if (!restore_context)
4857 restore_context = mono_get_restore_context ();
4859 tls = TlsGetValue (debugger_tls_id);
4863 * Store the `InvokeData *' in `tls->invoke' until we're done with
4864 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
4867 mono_loader_lock ();
4869 invoke = tls->pending_invoke;
4871 tls->pending_invoke = NULL;
4873 invoke->last_invoke = tls->invoke;
4874 tls->invoke = invoke;
4876 mono_loader_unlock ();
4878 tls->frames_up_to_date = FALSE;
4882 buffer_init (&buf, 128);
4884 err = do_invoke_method (tls, &buf, invoke);
4886 /* Start suspending before sending the reply */
4887 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
4890 send_reply_packet (id, err, &buf);
4894 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
4896 if (invoke->has_ctx)
4897 save_thread_context (&restore_ctx);
4899 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
4900 g_assert (tls->resume_count);
4901 tls->resume_count -= invoke->suspend_count;
4904 DEBUG (1, printf ("[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
4907 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
4909 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
4910 * after the mono_runtime_invoke() already returned, but it doesn't matter
4911 * because we reset the abort here.
4914 mono_loader_lock ();
4916 if (tls->abort_requested)
4917 mono_thread_internal_reset_abort (tls->thread);
4919 tls->invoke = tls->invoke->last_invoke;
4920 tls->abort_requested = FALSE;
4922 mono_loader_unlock ();
4931 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
4933 MonoThread *thread = value;
4934 DebuggerTlsData *tls;
4937 mono_loader_lock ();
4938 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4940 res = tls->really_suspended;
4941 mono_loader_unlock ();
4947 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
4950 case CMD_VM_VERSION: {
4951 char *build_info, *version;
4953 build_info = mono_get_runtime_build_info ();
4954 version = g_strdup_printf ("mono %s", build_info);
4956 buffer_add_string (buf, version); /* vm version */
4957 buffer_add_int (buf, MAJOR_VERSION);
4958 buffer_add_int (buf, MINOR_VERSION);
4959 g_free (build_info);
4963 case CMD_VM_SET_PROTOCOL_VERSION: {
4964 major_version = decode_int (p, &p, end);
4965 minor_version = decode_int (p, &p, end);
4966 protocol_version_set = TRUE;
4967 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
4970 case CMD_VM_ALL_THREADS: {
4972 mono_loader_lock ();
4973 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
4974 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
4975 mono_loader_unlock ();
4978 case CMD_VM_SUSPEND:
4980 wait_for_suspend ();
4983 if (suspend_count == 0)
4984 return ERR_NOT_SUSPENDED;
4987 case CMD_VM_DISPOSE:
4988 /* Clear all event requests */
4989 mono_loader_lock ();
4990 while (event_requests->len > 0) {
4991 EventRequest *req = g_ptr_array_index (event_requests, 0);
4993 clear_event_request (req->id, req->event_kind);
4995 mono_loader_unlock ();
4997 // FIXME: Count resumes
4999 disconnected = TRUE;
5002 MonoInternalThread *thread;
5003 DebuggerTlsData *tls;
5004 MonoClass *env_class;
5005 MonoMethod *exit_method;
5009 exit_code = decode_int (p, &p, end);
5011 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
5013 /* Have to send a reply before exiting */
5014 send_reply_packet (id, 0, buf);
5016 /* Clear all event requests */
5017 mono_loader_lock ();
5018 while (event_requests->len > 0) {
5019 EventRequest *req = g_ptr_array_index (event_requests, 0);
5021 clear_event_request (req->id, req->event_kind);
5023 mono_loader_unlock ();
5026 * The JDWP documentation says that the shutdown is not orderly. It doesn't
5027 * specify whenever a VM_DEATH event is sent. We currently do an orderly
5028 * shutdown by hijacking a thread to execute Environment.Exit (). This is
5029 * better than doing the shutdown ourselves, since it avoids various races.
5033 wait_for_suspend ();
5035 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
5036 g_assert (env_class);
5037 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
5038 g_assert (exit_method);
5040 mono_loader_lock ();
5041 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
5042 mono_loader_unlock ();
5045 mono_loader_lock ();
5046 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5047 mono_loader_unlock ();
5049 args = g_new0 (gpointer, 1);
5050 args [0] = g_malloc (sizeof (int));
5051 *(int*)(args [0]) = exit_code;
5053 tls->pending_invoke = g_new0 (InvokeData, 1);
5054 tls->pending_invoke->method = exit_method;
5055 tls->pending_invoke->args = args;
5057 while (suspend_count > 0)
5061 * No thread found, do it ourselves.
5062 * FIXME: This can race with normal shutdown etc.
5064 while (suspend_count > 0)
5067 mono_runtime_set_shutting_down ();
5069 mono_threads_set_shutting_down ();
5071 /* Suspend all managed threads since the runtime is going away */
5072 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
5073 mono_thread_suspend_all_other_threads ();
5074 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
5075 mono_runtime_quit ();
5077 shutdown (conn_fd, SD_BOTH);
5079 shutdown (conn_fd, SHUT_RDWR);
5081 DEBUG(1, fprintf (log_file, "Exiting...\n"));
5087 case CMD_VM_INVOKE_METHOD: {
5088 int objid = decode_objid (p, &p, end);
5090 DebuggerTlsData *tls;
5093 err = get_object (objid, (MonoObject**)&thread);
5097 flags = decode_int (p, &p, end);
5099 // Wait for suspending if it already started
5101 wait_for_suspend ();
5102 if (!is_suspended ())
5103 return ERR_NOT_SUSPENDED;
5105 mono_loader_lock ();
5106 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5107 mono_loader_unlock ();
5110 if (!tls->really_suspended)
5111 /* The thread is still running native code, can't do invokes */
5112 return ERR_NOT_SUSPENDED;
5115 * Store the invoke data into tls, the thread will execute it after it is
5118 if (tls->pending_invoke)
5120 tls->pending_invoke = g_new0 (InvokeData, 1);
5121 tls->pending_invoke->id = id;
5122 tls->pending_invoke->flags = flags;
5123 tls->pending_invoke->p = g_malloc (end - p);
5124 memcpy (tls->pending_invoke->p, p, end - p);
5125 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
5126 tls->pending_invoke->suspend_count = suspend_count;
5128 if (flags & INVOKE_FLAG_SINGLE_THREADED)
5129 resume_thread (THREAD_TO_INTERNAL (thread));
5134 case CMD_VM_ABORT_INVOKE: {
5135 int objid = decode_objid (p, &p, end);
5137 DebuggerTlsData *tls;
5140 err = get_object (objid, (MonoObject**)&thread);
5144 invoke_id = decode_int (p, &p, end);
5146 mono_loader_lock ();
5147 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5150 if (tls->abort_requested) {
5151 mono_loader_unlock ();
5156 * Check whether we're still inside the mono_runtime_invoke() and that it's
5157 * actually the correct invocation.
5159 * Careful, we do not stop the thread that's doing the invocation, so we can't
5160 * inspect its stack. However, invoke_method() also acquires the loader lock
5161 * when it's done, so we're safe here.
5165 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
5166 mono_loader_unlock ();
5167 return ERR_NO_INVOCATION;
5170 tls->abort_requested = TRUE;
5172 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
5173 mono_loader_unlock ();
5178 return ERR_NOT_IMPLEMENTED;
5185 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5190 case CMD_EVENT_REQUEST_SET: {
5192 int i, event_kind, suspend_policy, nmodifiers, mod;
5195 MonoThread *step_thread;
5196 int size = 0, depth = 0, step_thread_id = 0;
5199 event_kind = decode_byte (p, &p, end);
5200 suspend_policy = decode_byte (p, &p, end);
5201 nmodifiers = decode_byte (p, &p, end);
5203 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
5204 req->id = InterlockedIncrement (&event_request_id);
5205 req->event_kind = event_kind;
5206 req->suspend_policy = suspend_policy;
5207 req->nmodifiers = nmodifiers;
5210 for (i = 0; i < nmodifiers; ++i) {
5211 mod = decode_byte (p, &p, end);
5213 req->modifiers [i].kind = mod;
5214 if (mod == MOD_KIND_COUNT) {
5215 req->modifiers [i].data.count = decode_int (p, &p, end);
5216 } else if (mod == MOD_KIND_LOCATION_ONLY) {
5217 method = decode_methodid (p, &p, end, &domain, &err);
5220 location = decode_long (p, &p, end);
5221 } else if (mod == MOD_KIND_STEP) {
5222 step_thread_id = decode_id (p, &p, end);
5223 size = decode_int (p, &p, end);
5224 depth = decode_int (p, &p, end);
5225 } else if (mod == MOD_KIND_THREAD_ONLY) {
5226 int id = decode_id (p, &p, end);
5228 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
5233 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
5234 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
5238 req->modifiers [i].caught = decode_byte (p, &p, end);
5239 req->modifiers [i].uncaught = decode_byte (p, &p, end);
5240 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" : ""));
5242 req->modifiers [i].data.exc_class = exc_class;
5244 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
5246 return ERR_INVALID_ARGUMENT;
5249 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
5250 int n = decode_int (p, &p, end);
5253 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
5254 for (j = 0; j < n; ++j) {
5255 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
5257 g_free (req->modifiers [i].data.assemblies);
5263 return ERR_NOT_IMPLEMENTED;
5267 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5270 req->info = set_breakpoint (method, location, req);
5271 } else if (req->event_kind == EVENT_KIND_STEP) {
5272 g_assert (step_thread_id);
5274 err = get_object (step_thread_id, (MonoObject**)&step_thread);
5280 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
5285 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
5286 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req);
5287 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
5288 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req);
5289 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
5291 if (req->nmodifiers) {
5293 return ERR_NOT_IMPLEMENTED;
5297 mono_loader_lock ();
5298 g_ptr_array_add (event_requests, req);
5299 mono_loader_unlock ();
5301 buffer_add_int (buf, req->id);
5304 case CMD_EVENT_REQUEST_CLEAR: {
5305 int etype = decode_byte (p, &p, end);
5306 int req_id = decode_int (p, &p, end);
5308 // FIXME: Make a faster mapping from req_id to request
5309 mono_loader_lock ();
5310 clear_event_request (req_id, etype);
5311 mono_loader_unlock ();
5314 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
5317 mono_loader_lock ();
5319 while (i < event_requests->len) {
5320 EventRequest *req = g_ptr_array_index (event_requests, i);
5322 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5323 clear_breakpoint (req->info);
5325 g_ptr_array_remove_index_fast (event_requests, i);
5331 mono_loader_unlock ();
5335 return ERR_NOT_IMPLEMENTED;
5342 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5348 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
5349 buffer_add_domainid (buf, mono_get_root_domain ());
5352 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
5353 domain = decode_domainid (p, &p, end, NULL, &err);
5356 buffer_add_string (buf, domain->friendly_name);
5359 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
5364 domain = decode_domainid (p, &p, end, NULL, &err);
5367 mono_loader_lock ();
5369 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5372 buffer_add_int (buf, count);
5373 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5375 buffer_add_assemblyid (buf, domain, ass);
5377 mono_loader_unlock ();
5380 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
5381 domain = decode_domainid (p, &p, end, NULL, &err);
5385 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
5388 case CMD_APPDOMAIN_GET_CORLIB: {
5389 domain = decode_domainid (p, &p, end, NULL, &err);
5393 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
5396 case CMD_APPDOMAIN_CREATE_STRING: {
5400 domain = decode_domainid (p, &p, end, NULL, &err);
5403 s = decode_string (p, &p, end);
5405 o = mono_string_new (domain, s);
5406 buffer_add_objid (buf, (MonoObject*)o);
5409 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
5411 MonoDomain *domain2;
5414 domain = decode_domainid (p, &p, end, NULL, &err);
5417 klass = decode_typeid (p, &p, end, &domain2, &err);
5422 g_assert (domain == domain2);
5424 o = mono_object_new (domain, klass);
5426 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
5430 buffer_add_objid (buf, o);
5434 return ERR_NOT_IMPLEMENTED;
5441 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5447 ass = decode_assemblyid (p, &p, end, &domain, &err);
5452 case CMD_ASSEMBLY_GET_LOCATION: {
5453 buffer_add_string (buf, mono_image_get_filename (ass->image));
5456 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
5460 if (ass->image->dynamic) {
5461 buffer_add_id (buf, 0);
5463 token = mono_image_get_entry_point (ass->image);
5465 buffer_add_id (buf, 0);
5467 m = mono_get_method (ass->image, token, NULL);
5468 buffer_add_methodid (buf, domain, m);
5473 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5474 buffer_add_moduleid (buf, domain, ass->image);
5477 case CMD_ASSEMBLY_GET_OBJECT: {
5478 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5479 buffer_add_objid (buf, o);
5482 case CMD_ASSEMBLY_GET_TYPE: {
5483 char *s = decode_string (p, &p, end);
5484 gboolean ignorecase = decode_byte (p, &p, end);
5485 MonoTypeNameParse info;
5487 gboolean type_resolve;
5489 if (!mono_reflection_parse_type (s, &info)) {
5492 if (info.assembly.name)
5494 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5496 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5497 mono_reflection_free_type_info (&info);
5502 case CMD_ASSEMBLY_GET_NAME: {
5504 MonoAssembly *mass = ass;
5506 name = g_strdup_printf (
5507 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5509 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5510 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5511 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5512 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5514 buffer_add_string (buf, name);
5519 return ERR_NOT_IMPLEMENTED;
5526 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5532 case CMD_MODULE_GET_INFO: {
5533 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
5536 basename = g_path_get_basename (image->name);
5537 buffer_add_string (buf, basename); // name
5538 buffer_add_string (buf, image->module_name); // scopename
5539 buffer_add_string (buf, image->name); // fqname
5540 buffer_add_string (buf, mono_image_get_guid (image)); // guid
5541 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
5546 return ERR_NOT_IMPLEMENTED;
5553 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
5555 if (val && val->vtable->klass == mono_defaults.monotype_class) {
5556 /* Special case these so the client doesn't have to handle Type objects */
5558 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
5559 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
5560 } else if (MONO_TYPE_IS_REFERENCE (t))
5561 buffer_add_value (buf, t, &val, domain);
5563 buffer_add_value (buf, t, mono_object_unbox (val), domain);
5567 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
5573 buffer_add_int (buf, 0);
5577 for (i = 0; i < cinfo->num_attrs; ++i) {
5578 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
5581 buffer_add_int (buf, nattrs);
5583 for (i = 0; i < cinfo->num_attrs; ++i) {
5584 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
5585 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
5586 MonoArray *typed_args, *named_args;
5588 CattrNamedArg *arginfo;
5590 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
5592 buffer_add_methodid (buf, domain, attr->ctor);
5596 buffer_add_int (buf, mono_array_length (typed_args));
5597 for (j = 0; j < mono_array_length (typed_args); ++j) {
5598 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
5600 t = mono_method_signature (attr->ctor)->params [j];
5602 buffer_add_cattr_arg (buf, t, domain, val);
5605 buffer_add_int (buf, 0);
5610 buffer_add_int (buf, mono_array_length (named_args));
5612 for (j = 0; j < mono_array_length (named_args); ++j) {
5613 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
5615 if (arginfo [j].prop) {
5616 buffer_add_byte (buf, 0x54);
5617 buffer_add_propertyid (buf, domain, arginfo [j].prop);
5618 } else if (arginfo [j].field) {
5619 buffer_add_byte (buf, 0x53);
5621 g_assert_not_reached ();
5624 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
5627 buffer_add_int (buf, 0);
5634 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
5644 case CMD_TYPE_GET_INFO: {
5645 buffer_add_string (buf, klass->name_space);
5646 buffer_add_string (buf, klass->name);
5648 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
5649 buffer_add_string (buf, name);
5651 buffer_add_assemblyid (buf, domain, klass->image->assembly);
5652 buffer_add_moduleid (buf, domain, klass->image);
5653 buffer_add_typeid (buf, domain, klass->parent);
5654 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
5655 buffer_add_typeid (buf, domain, klass->element_class);
5657 buffer_add_id (buf, 0);
5658 buffer_add_int (buf, klass->type_token);
5659 buffer_add_byte (buf, klass->rank);
5660 buffer_add_int (buf, klass->flags);
5662 type = &klass->byval_arg;
5663 // FIXME: Can't decide whenever a class represents a byref type
5666 if (type->type == MONO_TYPE_PTR)
5668 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
5670 if (type->type == MONO_TYPE_VALUETYPE)
5672 if (klass->enumtype)
5674 buffer_add_byte (buf, b);
5677 while ((nested = mono_class_get_nested_types (klass, &iter)))
5679 buffer_add_int (buf, nnested);
5681 while ((nested = mono_class_get_nested_types (klass, &iter)))
5682 buffer_add_typeid (buf, domain, nested);
5685 case CMD_TYPE_GET_METHODS: {
5688 gpointer iter = NULL;
5691 mono_class_setup_methods (klass);
5693 nmethods = mono_class_num_methods (klass);
5695 buffer_add_int (buf, nmethods);
5697 while ((m = mono_class_get_methods (klass, &iter))) {
5698 buffer_add_methodid (buf, domain, m);
5701 g_assert (i == nmethods);
5704 case CMD_TYPE_GET_FIELDS: {
5707 gpointer iter = NULL;
5710 nfields = mono_class_num_fields (klass);
5712 buffer_add_int (buf, nfields);
5714 while ((f = mono_class_get_fields (klass, &iter))) {
5715 buffer_add_fieldid (buf, domain, f);
5716 buffer_add_string (buf, f->name);
5717 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
5718 buffer_add_int (buf, f->type->attrs);
5721 g_assert (i == nfields);
5724 case CMD_TYPE_GET_PROPERTIES: {
5727 gpointer iter = NULL;
5730 nprops = mono_class_num_properties (klass);
5732 buffer_add_int (buf, nprops);
5734 while ((p = mono_class_get_properties (klass, &iter))) {
5735 buffer_add_propertyid (buf, domain, p);
5736 buffer_add_string (buf, p->name);
5737 buffer_add_methodid (buf, domain, p->get);
5738 buffer_add_methodid (buf, domain, p->set);
5739 buffer_add_int (buf, p->attrs);
5742 g_assert (i == nprops);
5745 case CMD_TYPE_GET_CATTRS: {
5746 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
5747 MonoCustomAttrInfo *cinfo;
5749 cinfo = mono_custom_attrs_from_class (klass);
5751 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5754 case CMD_TYPE_GET_FIELD_CATTRS: {
5755 MonoClass *attr_klass;
5756 MonoCustomAttrInfo *cinfo;
5757 MonoClassField *field;
5759 field = decode_fieldid (p, &p, end, NULL, &err);
5762 attr_klass = decode_typeid (p, &p, end, NULL, &err);
5766 cinfo = mono_custom_attrs_from_field (klass, field);
5768 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5771 case CMD_TYPE_GET_PROPERTY_CATTRS: {
5772 MonoClass *attr_klass;
5773 MonoCustomAttrInfo *cinfo;
5776 prop = decode_propertyid (p, &p, end, NULL, &err);
5779 attr_klass = decode_typeid (p, &p, end, NULL, &err);
5783 cinfo = mono_custom_attrs_from_property (klass, prop);
5785 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5788 case CMD_TYPE_GET_VALUES: {
5796 len = decode_int (p, &p, end);
5797 for (i = 0; i < len; ++i) {
5798 f = decode_fieldid (p, &p, end, NULL, &err);
5802 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
5803 return ERR_INVALID_FIELDID;
5804 if (mono_class_field_is_special_static (f))
5805 return ERR_INVALID_FIELDID;
5807 /* Check that the field belongs to the object */
5809 for (k = klass; k; k = k->parent) {
5810 if (k == f->parent) {
5816 return ERR_INVALID_FIELDID;
5818 vtable = mono_class_vtable (domain, f->parent);
5819 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5820 mono_field_static_get_value (vtable, f, val);
5821 buffer_add_value (buf, f->type, val, domain);
5826 case CMD_TYPE_SET_VALUES: {
5834 len = decode_int (p, &p, end);
5835 for (i = 0; i < len; ++i) {
5836 f = decode_fieldid (p, &p, end, NULL, &err);
5840 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
5841 return ERR_INVALID_FIELDID;
5842 if (mono_class_field_is_special_static (f))
5843 return ERR_INVALID_FIELDID;
5845 /* Check that the field belongs to the object */
5847 for (k = klass; k; k = k->parent) {
5848 if (k == f->parent) {
5854 return ERR_INVALID_FIELDID;
5856 // FIXME: Check for literal/const
5858 vtable = mono_class_vtable (domain, f->parent);
5859 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5860 err = decode_value (f->type, domain, val, p, &p, end);
5865 if (MONO_TYPE_IS_REFERENCE (f->type))
5866 mono_field_static_set_value (vtable, f, *(gpointer*)val);
5868 mono_field_static_set_value (vtable, f, val);
5873 case CMD_TYPE_GET_OBJECT: {
5874 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
5875 buffer_add_objid (buf, o);
5878 case CMD_TYPE_GET_SOURCE_FILES:
5879 case CMD_TYPE_GET_SOURCE_FILES_2: {
5880 gpointer iter = NULL;
5882 char *source_file, *base;
5886 files = g_ptr_array_new ();
5888 while ((method = mono_class_get_methods (klass, &iter))) {
5889 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
5892 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
5896 for (i = 0; i < files->len; ++i)
5897 if (!strcmp (g_ptr_array_index (files, i), source_file))
5899 if (i == files->len)
5900 g_ptr_array_add (files, g_strdup (source_file));
5901 g_free (source_file);
5905 buffer_add_int (buf, files->len);
5906 for (i = 0; i < files->len; ++i) {
5907 source_file = g_ptr_array_index (files, i);
5908 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
5909 buffer_add_string (buf, source_file);
5911 base = g_path_get_basename (source_file);
5912 buffer_add_string (buf, base);
5915 g_free (source_file);
5917 g_ptr_array_free (files, TRUE);
5920 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
5921 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
5925 if (mono_class_is_assignable_from (klass, oklass))
5926 buffer_add_byte (buf, 1);
5928 buffer_add_byte (buf, 0);
5932 return ERR_NOT_IMPLEMENTED;
5939 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5942 MonoDomain *old_domain;
5946 klass = decode_typeid (p, &p, end, &domain, &err);
5950 old_domain = mono_domain_get ();
5952 mono_domain_set (domain, TRUE);
5954 err = type_commands_internal (command, klass, domain, p, end, buf);
5956 mono_domain_set (old_domain, TRUE);
5962 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
5964 MonoMethodHeader *header;
5967 case CMD_METHOD_GET_NAME: {
5968 buffer_add_string (buf, method->name);
5971 case CMD_METHOD_GET_DECLARING_TYPE: {
5972 buffer_add_typeid (buf, domain, method->klass);
5975 case CMD_METHOD_GET_DEBUG_INFO: {
5976 MonoDebugMethodInfo *minfo;
5978 int i, n_il_offsets;
5982 header = mono_method_get_header (method);
5984 buffer_add_int (buf, 0);
5985 buffer_add_string (buf, "");
5986 buffer_add_int (buf, 0);
5990 minfo = mono_debug_lookup_method (method);
5992 buffer_add_int (buf, header->code_size);
5993 buffer_add_string (buf, "");
5994 buffer_add_int (buf, 0);
5995 mono_metadata_free_mh (header);
5999 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
6000 buffer_add_int (buf, header->code_size);
6001 buffer_add_string (buf, source_file);
6002 buffer_add_int (buf, n_il_offsets);
6003 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
6004 for (i = 0; i < n_il_offsets; ++i) {
6005 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
6006 buffer_add_int (buf, il_offsets [i]);
6007 buffer_add_int (buf, line_numbers [i]);
6009 g_free (source_file);
6010 g_free (il_offsets);
6011 g_free (line_numbers);
6012 mono_metadata_free_mh (header);
6015 case CMD_METHOD_GET_PARAM_INFO: {
6016 MonoMethodSignature *sig = mono_method_signature (method);
6020 /* FIXME: mono_class_from_mono_type () and byrefs */
6022 /* FIXME: Use a smaller encoding */
6023 buffer_add_int (buf, sig->call_convention);
6024 buffer_add_int (buf, sig->param_count);
6025 buffer_add_int (buf, sig->generic_param_count);
6026 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
6027 for (i = 0; i < sig->param_count; ++i) {
6029 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
6032 /* Emit parameter names */
6033 names = g_new (char *, sig->param_count);
6034 mono_method_get_param_names (method, (const char **) names);
6035 for (i = 0; i < sig->param_count; ++i)
6036 buffer_add_string (buf, names [i]);
6041 case CMD_METHOD_GET_LOCALS_INFO: {
6042 int i, j, num_locals;
6043 MonoDebugLocalsInfo *locals;
6045 header = mono_method_get_header (method);
6048 buffer_add_int (buf, header->num_locals);
6051 for (i = 0; i < header->num_locals; ++i)
6052 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
6055 locals = mono_debug_lookup_locals (method);
6057 num_locals = locals->num_locals;
6060 for (i = 0; i < header->num_locals; ++i) {
6061 for (j = 0; j < num_locals; ++j)
6062 if (locals->locals [j].index == i)
6065 buffer_add_string (buf, locals->locals [j].name);
6067 buffer_add_string (buf, "");
6071 for (i = 0; i < header->num_locals; ++i) {
6072 for (j = 0; j < num_locals; ++j)
6073 if (locals->locals [j].index == i)
6075 if (j < num_locals && locals->locals [j].block) {
6076 buffer_add_int (buf, locals->locals [j].block->start_offset);
6077 buffer_add_int (buf, locals->locals [j].block->end_offset);
6079 buffer_add_int (buf, 0);
6080 buffer_add_int (buf, header->code_size);
6083 mono_metadata_free_mh (header);
6086 mono_debug_symfile_free_locals (locals);
6090 case CMD_METHOD_GET_INFO:
6091 buffer_add_int (buf, method->flags);
6092 buffer_add_int (buf, method->iflags);
6093 buffer_add_int (buf, method->token);
6095 case CMD_METHOD_GET_BODY: {
6098 header = mono_method_get_header (method);
6100 buffer_add_int (buf, 0);
6102 buffer_add_int (buf, header->code_size);
6103 for (i = 0; i < header->code_size; ++i)
6104 buffer_add_byte (buf, header->code [i]);
6106 mono_metadata_free_mh (header);
6109 case CMD_METHOD_RESOLVE_TOKEN: {
6110 guint32 token = decode_int (p, &p, end);
6113 switch (mono_metadata_token_code (token)) {
6114 case MONO_TOKEN_STRING: {
6118 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
6121 s2 = mono_string_to_utf8 (s);
6123 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6124 buffer_add_string (buf, s2);
6130 MonoClass *handle_class;
6132 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6133 val = mono_method_get_wrapper_data (method, token);
6134 handle_class = mono_method_get_wrapper_data (method, token + 1);
6136 if (handle_class == NULL) {
6137 // Can't figure out the token type
6138 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
6142 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
6146 if (handle_class == mono_defaults.typehandle_class) {
6147 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
6148 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
6149 } else if (handle_class == mono_defaults.fieldhandle_class) {
6150 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
6151 buffer_add_fieldid (buf, domain, val);
6152 } else if (handle_class == mono_defaults.methodhandle_class) {
6153 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
6154 buffer_add_methodid (buf, domain, val);
6155 } else if (handle_class == mono_defaults.string_class) {
6158 s = mono_string_to_utf8 (val);
6159 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6160 buffer_add_string (buf, s);
6163 g_assert_not_reached ();
6171 return ERR_NOT_IMPLEMENTED;
6178 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6181 MonoDomain *old_domain;
6185 method = decode_methodid (p, &p, end, &domain, &err);
6189 old_domain = mono_domain_get ();
6191 mono_domain_set (domain, TRUE);
6193 err = method_commands_internal (command, method, domain, p, end, buf);
6195 mono_domain_set (old_domain, TRUE);
6201 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6203 int objid = decode_objid (p, &p, end);
6205 MonoThread *thread_obj;
6206 MonoInternalThread *thread;
6208 err = get_object (objid, (MonoObject**)&thread_obj);
6212 thread = THREAD_TO_INTERNAL (thread_obj);
6215 case CMD_THREAD_GET_NAME: {
6217 gunichar2 *s = mono_thread_get_name (thread, &name_len);
6220 buffer_add_int (buf, 0);
6225 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
6227 buffer_add_int (buf, len);
6228 buffer_add_data (buf, (guint8*)name, len);
6233 case CMD_THREAD_GET_FRAME_INFO: {
6234 DebuggerTlsData *tls;
6235 int i, start_frame, length;
6237 // Wait for suspending if it already started
6239 wait_for_suspend ();
6240 if (!is_suspended ())
6241 return ERR_NOT_SUSPENDED;
6243 start_frame = decode_int (p, &p, end);
6244 length = decode_int (p, &p, end);
6246 if (start_frame != 0 || length != -1)
6247 return ERR_NOT_IMPLEMENTED;
6249 mono_loader_lock ();
6250 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6251 mono_loader_unlock ();
6254 compute_frame_info (thread, tls);
6256 buffer_add_int (buf, tls->frame_count);
6257 for (i = 0; i < tls->frame_count; ++i) {
6258 buffer_add_int (buf, tls->frames [i]->id);
6259 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->method);
6260 buffer_add_int (buf, tls->frames [i]->il_offset);
6262 * Instead of passing the frame type directly to the client, we associate
6263 * it with the previous frame using a set of flags. This avoids lots of
6264 * conditional code in the client, since a frame whose type isn't
6265 * FRAME_TYPE_MANAGED has no method, location, etc.
6267 buffer_add_byte (buf, tls->frames [i]->flags);
6272 case CMD_THREAD_GET_STATE:
6273 buffer_add_int (buf, thread->state);
6275 case CMD_THREAD_GET_INFO:
6276 buffer_add_byte (buf, thread->threadpool_thread);
6278 case CMD_THREAD_GET_ID:
6279 buffer_add_long (buf, (guint64)(gsize)thread);
6282 return ERR_NOT_IMPLEMENTED;
6289 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6293 MonoThread *thread_obj;
6294 MonoInternalThread *thread;
6296 DebuggerTlsData *tls;
6298 MonoDebugMethodJitInfo *jit;
6299 MonoDebugVarInfo *var;
6300 MonoMethodSignature *sig;
6302 MonoMethodHeader *header;
6304 objid = decode_objid (p, &p, end);
6305 err = get_object (objid, (MonoObject**)&thread_obj);
6309 thread = THREAD_TO_INTERNAL (thread_obj);
6311 id = decode_id (p, &p, end);
6313 mono_loader_lock ();
6314 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6315 mono_loader_unlock ();
6318 for (i = 0; i < tls->frame_count; ++i) {
6319 if (tls->frames [i]->id == id)
6322 if (i == tls->frame_count)
6323 return ERR_INVALID_FRAMEID;
6325 frame = tls->frames [i];
6327 if (!frame->has_ctx)
6329 return ERR_INVALID_FRAMEID;
6332 frame->jit = mono_debug_find_method (frame->method, frame->domain);
6334 /* This could happen for aot images with no jit debug info */
6335 return ERR_ABSENT_INFORMATION;
6339 sig = mono_method_signature (frame->method);
6342 case CMD_STACK_FRAME_GET_VALUES: {
6343 len = decode_int (p, &p, end);
6344 header = mono_method_get_header (frame->method);
6346 for (i = 0; i < len; ++i) {
6347 pos = decode_int (p, &p, end);
6352 g_assert (pos >= 0 && pos < jit->num_params);
6354 var = &jit->params [pos];
6356 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
6358 g_assert (pos >= 0 && pos < jit->num_locals);
6360 var = &jit->locals [pos];
6362 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
6365 mono_metadata_free_mh (header);
6368 case CMD_STACK_FRAME_GET_THIS: {
6369 if (frame->method->klass->valuetype) {
6370 if (!sig->hasthis) {
6371 MonoObject *p = NULL;
6372 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
6374 add_var (buf, &frame->method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6377 if (!sig->hasthis) {
6378 MonoObject *p = NULL;
6379 buffer_add_value (buf, &frame->method->klass->byval_arg, &p, frame->domain);
6381 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6386 case CMD_STACK_FRAME_SET_VALUES: {
6389 MonoDebugVarInfo *var;
6391 len = decode_int (p, &p, end);
6392 header = mono_method_get_header (frame->method);
6394 for (i = 0; i < len; ++i) {
6395 pos = decode_int (p, &p, end);
6400 g_assert (pos >= 0 && pos < jit->num_params);
6402 t = sig->params [pos];
6403 var = &jit->params [pos];
6405 g_assert (pos >= 0 && pos < jit->num_locals);
6407 t = header->locals [pos];
6408 var = &jit->locals [pos];
6411 if (MONO_TYPE_IS_REFERENCE (t))
6412 val_buf = g_alloca (sizeof (MonoObject*));
6414 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
6415 err = decode_value (t, frame->domain, val_buf, p, &p, end);
6419 set_var (t, var, &frame->ctx, frame->domain, val_buf);
6421 mono_metadata_free_mh (header);
6425 return ERR_NOT_IMPLEMENTED;
6432 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6435 int objid, err, index, len, i, esize;
6438 objid = decode_objid (p, &p, end);
6439 err = get_object (objid, (MonoObject**)&arr);
6444 case CMD_ARRAY_REF_GET_LENGTH:
6445 buffer_add_int (buf, arr->obj.vtable->klass->rank);
6447 buffer_add_int (buf, arr->max_length);
6448 buffer_add_int (buf, 0);
6450 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
6451 buffer_add_int (buf, arr->bounds [i].length);
6452 buffer_add_int (buf, arr->bounds [i].lower_bound);
6456 case CMD_ARRAY_REF_GET_VALUES:
6457 index = decode_int (p, &p, end);
6458 len = decode_int (p, &p, end);
6460 g_assert (index >= 0 && len >= 0);
6461 // Reordered to avoid integer overflow
6462 g_assert (!(index > arr->max_length - len));
6464 esize = mono_array_element_size (arr->obj.vtable->klass);
6465 for (i = index; i < index + len; ++i) {
6466 elem = (gpointer*)((char*)arr->vector + (i * esize));
6467 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
6470 case CMD_ARRAY_REF_SET_VALUES:
6471 index = decode_int (p, &p, end);
6472 len = decode_int (p, &p, end);
6474 g_assert (index >= 0 && len >= 0);
6475 // Reordered to avoid integer overflow
6476 g_assert (!(index > arr->max_length - len));
6478 esize = mono_array_element_size (arr->obj.vtable->klass);
6479 for (i = index; i < index + len; ++i) {
6480 elem = (gpointer*)((char*)arr->vector + (i * esize));
6482 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
6486 return ERR_NOT_IMPLEMENTED;
6493 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6499 objid = decode_objid (p, &p, end);
6500 err = get_object (objid, (MonoObject**)&str);
6505 case CMD_STRING_REF_GET_VALUE:
6506 s = mono_string_to_utf8 (str);
6507 buffer_add_string (buf, s);
6511 return ERR_NOT_IMPLEMENTED;
6518 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6527 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
6528 objid = decode_objid (p, &p, end);
6529 err = get_object (objid, &obj);
6531 buffer_add_int (buf, 1);
6533 buffer_add_int (buf, 0);
6537 objid = decode_objid (p, &p, end);
6538 err = get_object (objid, &obj);
6543 case CMD_OBJECT_REF_GET_TYPE:
6544 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
6546 case CMD_OBJECT_REF_GET_VALUES:
6547 len = decode_int (p, &p, end);
6549 for (i = 0; i < len; ++i) {
6550 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
6554 /* Check that the field belongs to the object */
6556 for (k = obj->vtable->klass; k; k = k->parent) {
6557 if (k == f->parent) {
6563 return ERR_INVALID_FIELDID;
6565 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6569 if (mono_class_field_is_special_static (f))
6570 return ERR_INVALID_FIELDID;
6572 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6573 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6574 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6575 mono_field_static_get_value (vtable, f, val);
6576 buffer_add_value (buf, f->type, val, obj->vtable->domain);
6579 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
6583 case CMD_OBJECT_REF_SET_VALUES:
6584 len = decode_int (p, &p, end);
6586 for (i = 0; i < len; ++i) {
6587 f = decode_fieldid (p, &p, end, NULL, &err);
6591 /* Check that the field belongs to the object */
6593 for (k = obj->vtable->klass; k; k = k->parent) {
6594 if (k == f->parent) {
6600 return ERR_INVALID_FIELDID;
6602 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6606 if (mono_class_field_is_special_static (f))
6607 return ERR_INVALID_FIELDID;
6609 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6610 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6612 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6613 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
6618 mono_field_static_set_value (vtable, f, val);
6621 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
6627 case CMD_OBJECT_REF_GET_ADDRESS:
6628 buffer_add_long (buf, (gssize)obj);
6630 case CMD_OBJECT_REF_GET_DOMAIN:
6631 buffer_add_domainid (buf, obj->vtable->domain);
6634 return ERR_NOT_IMPLEMENTED;
6641 command_set_to_string (CommandSet command_set)
6643 switch (command_set) {
6646 case CMD_SET_OBJECT_REF:
6647 return "OBJECT_REF";
6648 case CMD_SET_STRING_REF:
6649 return "STRING_REF";
6650 case CMD_SET_THREAD:
6652 case CMD_SET_ARRAY_REF:
6654 case CMD_SET_EVENT_REQUEST:
6655 return "EVENT_REQUEST";
6656 case CMD_SET_STACK_FRAME:
6657 return "STACK_FRAME";
6658 case CMD_SET_APPDOMAIN:
6660 case CMD_SET_ASSEMBLY:
6662 case CMD_SET_METHOD:
6666 case CMD_SET_MODULE:
6678 * This thread handles communication with the debugger client using a JDWP
6681 static guint32 WINAPI
6682 debugger_thread (void *arg)
6684 int res, len, id, flags, command_set, command;
6685 guint8 header [HEADER_LENGTH];
6686 guint8 *data, *p, *end;
6691 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
6693 debugger_thread_id = GetCurrentThreadId ();
6695 mono_jit_thread_attach (mono_get_root_domain ());
6697 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
6699 mono_set_is_debugger_attached (TRUE);
6702 res = recv_length (conn_fd, header, HEADER_LENGTH, 0);
6704 /* This will break if the socket is closed during shutdown too */
6705 if (res != HEADER_LENGTH)
6709 end = header + HEADER_LENGTH;
6711 len = decode_int (p, &p, end);
6712 id = decode_int (p, &p, end);
6713 flags = decode_byte (p, &p, end);
6714 command_set = decode_byte (p, &p, end);
6715 command = decode_byte (p, &p, end);
6717 g_assert (flags == 0);
6719 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%d), id=%d.\n", command_set_to_string (command_set), command, id));
6721 data = g_malloc (len - HEADER_LENGTH);
6722 if (len - HEADER_LENGTH > 0)
6724 res = recv_length (conn_fd, data, len - HEADER_LENGTH, 0);
6725 if (res != len - HEADER_LENGTH)
6730 end = data + (len - HEADER_LENGTH);
6732 buffer_init (&buf, 128);
6737 /* Process the request */
6738 switch (command_set) {
6740 err = vm_commands (command, id, p, end, &buf);
6741 if (!err && command == CMD_VM_INVOKE_METHOD)
6742 /* Sent after the invoke is complete */
6745 case CMD_SET_EVENT_REQUEST:
6746 err = event_commands (command, p, end, &buf);
6748 case CMD_SET_APPDOMAIN:
6749 err = domain_commands (command, p, end, &buf);
6751 case CMD_SET_ASSEMBLY:
6752 err = assembly_commands (command, p, end, &buf);
6754 case CMD_SET_MODULE:
6755 err = module_commands (command, p, end, &buf);
6758 err = type_commands (command, p, end, &buf);
6760 case CMD_SET_METHOD:
6761 err = method_commands (command, p, end, &buf);
6763 case CMD_SET_THREAD:
6764 err = thread_commands (command, p, end, &buf);
6766 case CMD_SET_STACK_FRAME:
6767 err = frame_commands (command, p, end, &buf);
6769 case CMD_SET_ARRAY_REF:
6770 err = array_commands (command, p, end, &buf);
6772 case CMD_SET_STRING_REF:
6773 err = string_commands (command, p, end, &buf);
6775 case CMD_SET_OBJECT_REF:
6776 err = object_commands (command, p, end, &buf);
6779 err = ERR_NOT_IMPLEMENTED;
6783 send_reply_packet (id, err, &buf);
6788 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
6792 mono_set_is_debugger_attached (FALSE);
6794 mono_mutex_lock (&debugger_thread_exited_mutex);
6795 debugger_thread_exited = TRUE;
6796 mono_cond_signal (&debugger_thread_exited_cond);
6797 mono_mutex_unlock (&debugger_thread_exited_mutex);
6799 DEBUG (1, printf ("[dbg] Debugger thread exited.\n"));
6804 #else /* DISABLE_DEBUGGER_AGENT */
6807 mono_debugger_agent_parse_options (char *options)
6809 g_error ("This runtime is configure with the debugger agent disabled.");
6813 mono_debugger_agent_init (void)
6818 mono_debugger_agent_breakpoint_hit (void *sigctx)
6823 mono_debugger_agent_single_step_event (void *sigctx)
6828 mono_debugger_agent_free_domain_info (MonoDomain *domain)
6833 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
6839 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
6840 MonoContext *catch_ctx)