2 * debugger-agent.c: Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * (C) 2009 Novell, Inc.
14 #ifdef HAVE_SYS_TYPES_H
15 #include <sys/types.h>
17 #ifdef HAVE_SYS_SOCKET_H
18 #include <sys/socket.h>
20 #ifdef HAVE_NETINET_TCP_H
21 #include <netinet/tcp.h>
23 #ifdef HAVE_NETINET_IN_H
24 #include <netinet/in.h>
39 #include <mono/metadata/mono-debug.h>
40 #include <mono/metadata/mono-debug-debugger.h>
41 #include <mono/metadata/debug-mono-symfile.h>
42 #include <mono/metadata/gc-internal.h>
43 #include <mono/metadata/threads-types.h>
44 #include <mono/utils/mono-semaphore.h>
45 #include "debugger-agent.h"
48 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
49 #define DISABLE_DEBUGGER_AGENT 1
52 #ifndef DISABLE_DEBUGGER_AGENT
53 #include <mono/io-layer/mono-mutex.h>
76 MonoDebugMethodJitInfo *jit;
85 /* This is the context which needs to be restored after the invoke */
95 gpointer resume_event;
96 /* This is computed on demand when it is requested using the wire protocol */
97 /* It is freed up when the thread is resumed */
101 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
104 gboolean frames_up_to_date;
106 * Points to data about a pending invoke which needs to be executed after the thread
111 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
115 /* Used to pass the context to the breakpoint/single step handler */
116 MonoContext handler_ctx;
117 /* Whenever thread_stop () was called for this thread */
120 /* Number of thread interruptions not yet processed */
121 gint32 interrupt_count;
125 * Wire Protocol definitions
128 #define HEADER_LENGTH 11
130 #define MAJOR_VERSION 0
131 #define MINOR_VERSION 2
135 CMD_SET_OBJECT_REF = 9,
136 CMD_SET_STRING_REF = 10,
138 CMD_SET_ARRAY_REF = 13,
139 CMD_SET_EVENT_REQUEST = 15,
140 CMD_SET_STACK_FRAME = 16,
141 CMD_SET_APPDOMAIN = 20,
142 CMD_SET_ASSEMBLY = 21,
150 EVENT_KIND_VM_START = 0,
151 EVENT_KIND_VM_DEATH = 1,
152 EVENT_KIND_THREAD_START = 2,
153 EVENT_KIND_THREAD_DEATH = 3,
154 EVENT_KIND_APPDOMAIN_CREATE = 4,
155 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
156 EVENT_KIND_METHOD_ENTRY = 6,
157 EVENT_KIND_METHOD_EXIT = 7,
158 EVENT_KIND_ASSEMBLY_LOAD = 8,
159 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
160 EVENT_KIND_BREAKPOINT = 10,
161 EVENT_KIND_STEP = 11,
162 EVENT_KIND_TYPE_LOAD = 12,
163 EVENT_KIND_EXCEPTION = 13
167 SUSPEND_POLICY_NONE = 0,
168 SUSPEND_POLICY_EVENT_THREAD = 1,
169 SUSPEND_POLICY_ALL = 2
174 ERR_INVALID_OBJECT = 20,
175 ERR_INVALID_FIELDID = 25,
176 ERR_INVALID_FRAMEID = 30,
177 ERR_NOT_IMPLEMENTED = 100,
178 ERR_NOT_SUSPENDED = 101,
179 ERR_INVALID_ARGUMENT = 102,
185 MOD_KIND_THREAD_ONLY = 3,
186 MOD_KIND_LOCATION_ONLY = 7,
187 MOD_KIND_EXCEPTION_ONLY = 8,
189 MOD_KIND_ASSEMBLY_ONLY = 11
204 TOKEN_TYPE_STRING = 0,
206 TOKEN_TYPE_FIELD = 2,
207 TOKEN_TYPE_METHOD = 3,
208 TOKEN_TYPE_UNKNOWN = 4
212 VALUE_TYPE_ID_NULL = 0xf0,
213 VALUE_TYPE_ID_TYPE = 0xf1
217 FRAME_FLAG_DEBUGGER_INVOKE = 1
222 CMD_VM_ALL_THREADS = 2,
227 CMD_VM_INVOKE_METHOD = 7
231 CMD_THREAD_GET_FRAME_INFO = 1,
232 CMD_THREAD_GET_NAME = 2,
233 CMD_THREAD_GET_STATE = 3,
234 CMD_THREAD_GET_INFO = 4
238 CMD_EVENT_REQUEST_SET = 1,
239 CMD_EVENT_REQUEST_CLEAR = 2,
240 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
248 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
249 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
250 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
251 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
252 CMD_APPDOMAIN_CREATE_STRING = 5,
253 CMD_APPDOMAIN_GET_CORLIB = 6
257 CMD_ASSEMBLY_GET_LOCATION = 1,
258 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
259 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
260 CMD_ASSEMBLY_GET_OBJECT = 4,
261 CMD_ASSEMBLY_GET_TYPE = 5,
265 CMD_MODULE_GET_INFO = 1,
269 CMD_METHOD_GET_NAME = 1,
270 CMD_METHOD_GET_DECLARING_TYPE = 2,
271 CMD_METHOD_GET_DEBUG_INFO = 3,
272 CMD_METHOD_GET_PARAM_INFO = 4,
273 CMD_METHOD_GET_LOCALS_INFO = 5,
274 CMD_METHOD_GET_INFO = 6,
275 CMD_METHOD_GET_BODY = 7,
276 CMD_METHOD_RESOLVE_TOKEN = 8,
280 CMD_TYPE_GET_INFO = 1,
281 CMD_TYPE_GET_METHODS = 2,
282 CMD_TYPE_GET_FIELDS = 3,
283 CMD_TYPE_GET_VALUES = 4,
284 CMD_TYPE_GET_OBJECT = 5,
285 CMD_TYPE_GET_SOURCE_FILES = 6,
286 CMD_TYPE_SET_VALUES = 7,
287 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
288 CMD_TYPE_GET_PROPERTIES = 9,
289 CMD_TYPE_GET_CATTRS = 10,
290 CMD_TYPE_GET_FIELD_CATTRS = 11,
291 CMD_TYPE_GET_PROPERTY_CATTRS = 12
295 CMD_STACK_FRAME_GET_VALUES = 1,
296 CMD_STACK_FRAME_GET_THIS = 2,
297 CMD_STACK_FRAME_SET_VALUES = 3
301 CMD_ARRAY_REF_GET_LENGTH = 1,
302 CMD_ARRAY_REF_GET_VALUES = 2,
303 CMD_ARRAY_REF_SET_VALUES = 3,
307 CMD_STRING_REF_GET_VALUE = 1,
311 CMD_OBJECT_REF_GET_TYPE = 1,
312 CMD_OBJECT_REF_GET_VALUES = 2,
313 CMD_OBJECT_REF_IS_COLLECTED = 3,
314 CMD_OBJECT_REF_GET_ADDRESS = 4,
315 CMD_OBJECT_REF_GET_DOMAIN = 5,
316 CMD_OBJECT_REF_SET_VALUES = 6
322 int count; /* For kind == MOD_KIND_COUNT */
323 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
324 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
325 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
335 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
339 * Describes a single step request.
343 MonoInternalThread *thread;
348 MonoMethod *last_method;
352 /* Dummy structure used for the profiler callbacks */
357 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
363 static AgentConfig agent_config;
366 * Whenever the agent is fully initialized.
367 * When using the onuncaught or onthrow options, only some parts of the agent are
368 * initialized on startup, and the full initialization which includes connection
369 * establishment and the startup of the agent thread is only done in response to
372 static gint32 inited;
376 static int packet_id = 0;
378 static int objref_id = 0;
380 static int event_request_id = 0;
382 static int frame_id = 0;
384 static GPtrArray *event_requests;
386 static guint32 debugger_tls_id;
388 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
390 /* Maps MonoInternalThread -> DebuggerTlsData */
391 static MonoGHashTable *thread_to_tls;
393 /* Maps tid -> MonoInternalThread */
394 static MonoGHashTable *tid_to_thread;
396 /* Maps tid -> MonoThread (not MonoInternalThread) */
397 static MonoGHashTable *tid_to_thread_obj;
399 static gsize debugger_thread_id;
401 static HANDLE debugger_thread_handle;
403 static int log_level;
405 static FILE *log_file;
407 /* Classes whose class load event has been sent */
408 static GHashTable *loaded_classes;
410 /* Assemblies whose assembly load event has no been sent yet */
411 static GPtrArray *pending_assembly_loads;
413 /* Whenever the debugger thread has exited */
414 static gboolean debugger_thread_exited;
416 /* Cond variable used to wait for debugger_thread_exited becoming true */
417 static mono_cond_t debugger_thread_exited_cond = MONO_COND_INITIALIZER;
419 /* Mutex for the cond var above */
420 static mono_mutex_t debugger_thread_exited_mutex = MONO_MUTEX_INITIALIZER;
422 static DebuggerProfiler debugger_profiler;
424 /* The single step request instance */
425 static MonoSingleStepReq *ss_req = NULL;
427 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
428 /* Number of single stepping operations in progress */
432 static void transport_connect (const char *host, int port);
434 static guint32 WINAPI debugger_thread (void *arg);
436 static void runtime_initialized (MonoProfiler *prof);
438 static void runtime_shutdown (MonoProfiler *prof);
440 static void thread_startup (MonoProfiler *prof, gsize tid);
442 static void thread_end (MonoProfiler *prof, gsize tid);
444 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
446 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
448 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
450 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
452 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
454 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
456 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
458 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
460 static void start_single_stepping (void);
462 static void stop_single_stepping (void);
464 static void suspend_current (void);
466 /* Submodule init/cleanup */
467 static void breakpoints_init (void);
468 static void breakpoints_cleanup (void);
470 static void objrefs_init (void);
471 static void objrefs_cleanup (void);
473 static void ids_init (void);
474 static void ids_cleanup (void);
476 static void suspend_init (void);
478 static ErrorCode ss_start (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
479 static void ss_stop (EventRequest *req);
481 static void start_debugger_thread (void);
483 static void finish_agent_init (gboolean on_startup);
486 parse_address (char *address, char **host, int *port)
488 char *pos = strchr (address, ':');
490 if (pos == NULL || pos == address)
493 *host = g_malloc (pos - address + 1);
494 strncpy (*host, address, pos - address);
495 (*host) [pos - address] = '\0';
497 *port = atoi (pos + 1);
505 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
506 fprintf (stderr, "Available options:\n");
507 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
508 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
509 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
510 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
511 fprintf (stderr, " suspend=y/n\t\t\tWhenever to suspend after startup.\n");
512 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
513 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
517 parse_flag (const char *option, char *flag)
519 if (!strcmp (flag, "y"))
521 else if (!strcmp (flag, "n"))
524 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
531 mono_debugger_agent_parse_options (char *options)
537 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
538 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
542 agent_config.enabled = TRUE;
543 agent_config.suspend = TRUE;
544 agent_config.server = FALSE;
546 args = g_strsplit (options, ",", -1);
547 for (ptr = args; ptr && *ptr; ptr ++) {
550 if (strncmp (arg, "transport=", 10) == 0) {
551 agent_config.transport = g_strdup (arg + 10);
552 } else if (strncmp (arg, "address=", 8) == 0) {
553 agent_config.address = g_strdup (arg + 8);
554 } else if (strncmp (arg, "loglevel=", 9) == 0) {
555 agent_config.log_level = atoi (arg + 9);
556 } else if (strncmp (arg, "logfile=", 8) == 0) {
557 agent_config.log_file = g_strdup (arg + 8);
558 } else if (strncmp (arg, "suspend=", 8) == 0) {
559 agent_config.suspend = parse_flag ("suspend", arg + 8);
560 } else if (strncmp (arg, "server=", 7) == 0) {
561 agent_config.server = parse_flag ("server", arg + 7);
562 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
563 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
564 } else if (strncmp (arg, "onthrow=", 8) == 0) {
565 /* We support multiple onthrow= options */
566 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
567 } else if (strncmp (arg, "help", 4) == 0) {
570 } else if (strncmp (arg, "timeout=", 8) == 0) {
571 agent_config.timeout = atoi (arg + 8);
572 } else if (strncmp (arg, "launch=", 7) == 0) {
573 agent_config.launch = g_strdup (arg + 7);
580 if (agent_config.transport == NULL) {
581 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
584 if (strcmp (agent_config.transport, "dt_socket") != 0) {
585 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
589 if (agent_config.address == NULL && !agent_config.server) {
590 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
594 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
595 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
601 mono_debugger_agent_init (void)
603 if (!agent_config.enabled)
606 /* Need to know whenever a thread has acquired the loader mutex */
607 mono_loader_lock_track_ownership (TRUE);
609 event_requests = g_ptr_array_new ();
611 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
612 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
613 mono_profiler_install_runtime_initialized (runtime_initialized);
614 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_unload, NULL);
615 mono_profiler_install_thread (thread_startup, thread_end);
616 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
617 mono_profiler_install_jit_end (jit_end);
618 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
620 debugger_tls_id = TlsAlloc ();
622 thread_to_tls = mono_g_hash_table_new (NULL, NULL);
623 MONO_GC_REGISTER_ROOT (thread_to_tls);
625 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
626 MONO_GC_REGISTER_ROOT (tid_to_thread);
628 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
629 MONO_GC_REGISTER_ROOT (tid_to_thread_obj);
631 loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
632 pending_assembly_loads = g_ptr_array_new ();
634 log_level = agent_config.log_level;
636 if (agent_config.log_file) {
637 log_file = fopen (agent_config.log_file, "w+");
639 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
651 mini_get_debug_options ()->gen_seq_points = TRUE;
653 * This is needed because currently we don't handle liveness info.
655 mini_get_debug_options ()->mdb_optimizations = TRUE;
657 /* This is needed because we can't set local variables in registers yet */
658 mono_disable_optimizations (MONO_OPT_LINEARS);
660 if (!agent_config.onuncaught && !agent_config.onthrow)
661 finish_agent_init (TRUE);
667 * Finish the initialization of the agent. This involves connecting the transport
668 * and starting the agent thread. This is either done at startup, or
669 * in response to some event like an unhandled exception.
672 finish_agent_init (gboolean on_startup)
678 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
681 if (agent_config.launch) {
684 // FIXME: Generated address
685 // FIXME: Races with transport_connect ()
687 argv [0] = agent_config.launch;
688 argv [1] = agent_config.transport;
689 argv [2] = agent_config.address;
692 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
694 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
699 if (agent_config.address) {
700 res = parse_address (agent_config.address, &host, &port);
707 transport_connect (host, port);
710 /* Do some which is usually done after sending the VMStart () event */
711 vm_start_event_sent = TRUE;
712 start_debugger_thread ();
717 mono_debugger_agent_cleanup (void)
722 /* This will interrupt the agent thread */
723 /* Close the read part only so it can still send back replies */
724 #ifdef PLATFORM_WIN32
725 shutdown (conn_fd, SD_RECEIVE);
727 shutdown (conn_fd, SHUT_RD);
731 * Wait for the thread to exit.
733 * If we continue with the shutdown without waiting for it, then the client might
734 * not receive an answer to its last command like a resume.
735 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
738 //WaitForSingleObject (debugger_thread_handle, INFINITE);
739 if (GetCurrentThreadId () != debugger_thread_id) {
740 mono_mutex_lock (&debugger_thread_exited_mutex);
741 if (!debugger_thread_exited)
742 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
743 mono_mutex_unlock (&debugger_thread_exited_mutex);
746 breakpoints_cleanup ();
754 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
757 transport_connect (const char *host, int port)
759 struct addrinfo hints;
760 struct addrinfo *result, *rp;
762 char port_string [128];
763 char handshake_msg [128];
769 sprintf (port_string, "%d", port);
771 /* Obtain address(es) matching host/port */
773 memset (&hints, 0, sizeof (struct addrinfo));
774 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
775 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
777 hints.ai_protocol = 0; /* Any protocol */
779 s = getaddrinfo (host, port_string, &hints, &result);
781 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d: %s\n", host, port, gai_strerror (s));
786 if (agent_config.server) {
787 /* Wait for a connection */
789 struct sockaddr_in addr;
792 /* No address, generate one */
793 sfd = socket (AF_INET, SOCK_STREAM, 0);
796 /* This will bind the socket to a random port */
797 res = listen (sfd, 16);
799 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
803 addrlen = sizeof (addr);
804 memset (&addr, 0, sizeof (addr));
805 res = getsockname (sfd, &addr, &addrlen);
809 port = ntohs (addr.sin_port);
811 /* Emit the address to stdout */
812 /* FIXME: Should print another interface, not localhost */
813 printf ("%s:%d\n", host, port);
815 /* Listen on the provided address */
816 for (rp = result; rp != NULL; rp = rp->ai_next) {
817 sfd = socket (rp->ai_family, rp->ai_socktype,
822 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
826 res = listen (sfd, 16);
832 freeaddrinfo (result);
835 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
837 if (agent_config.timeout) {
842 tv.tv_usec = agent_config.timeout * 1000;
844 FD_SET (sfd, &readfds);
845 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
847 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
852 conn_fd = accept (sfd, NULL, NULL);
854 fprintf (stderr, "debugger-agent: Unable to listen on %s:%d\n", host, port);
858 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
860 /* Connect to the specified address */
861 /* FIXME: Respect the timeout */
862 for (rp = result; rp != NULL; rp = rp->ai_next) {
863 sfd = socket (rp->ai_family, rp->ai_socktype,
868 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
876 freeaddrinfo (result);
879 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
884 /* Write handshake message */
885 sprintf (handshake_msg, "DWP-Handshake");
886 res = write (conn_fd, handshake_msg, strlen (handshake_msg));
887 g_assert (res != -1);
890 res = read (conn_fd, buf, strlen (handshake_msg));
891 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
892 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
897 * Set TCP_NODELAY on the socket so the client receives events/command
898 * results immediately.
902 int result = setsockopt(conn_fd,
907 g_assert (result >= 0);
912 transport_send (guint8 *data, int len)
916 res = write (conn_fd, data, len);
924 start_debugger_thread (void)
928 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
929 g_assert (debugger_thread_handle);
933 * Functions to decode protocol data
937 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
940 g_assert (*endbuf <= limit);
945 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
948 g_assert (*endbuf <= limit);
950 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
954 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
956 guint32 high = decode_int (buf, &buf, limit);
957 guint32 low = decode_int (buf, &buf, limit);
961 return ((((guint64)high) << 32) | ((guint64)low));
965 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
967 return decode_int (buf, endbuf, limit);
971 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
973 int len = decode_int (buf, &buf, limit);
976 s = g_malloc (len + 1);
979 memcpy (s, buf, len);
988 * Functions to encode protocol data
992 guint8 *buf, *p, *end;
996 buffer_init (Buffer *buf, int size)
998 buf->buf = g_malloc (size);
1000 buf->end = buf->buf + size;
1004 buffer_make_room (Buffer *buf, int size)
1006 if (buf->end - buf->p < size) {
1007 int new_size = buf->end - buf->buf + size + 32;
1008 guint8 *p = g_realloc (buf->buf, new_size);
1009 size = buf->p - buf->buf;
1012 buf->end = buf->buf + new_size;
1017 buffer_add_byte (Buffer *buf, guint8 val)
1019 buffer_make_room (buf, 1);
1025 buffer_add_int (Buffer *buf, guint32 val)
1027 buffer_make_room (buf, 4);
1028 buf->p [0] = (val >> 24) & 0xff;
1029 buf->p [1] = (val >> 16) & 0xff;
1030 buf->p [2] = (val >> 8) & 0xff;
1031 buf->p [3] = (val >> 0) & 0xff;
1036 buffer_add_long (Buffer *buf, guint64 l)
1038 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1039 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1043 buffer_add_id (Buffer *buf, int id)
1045 buffer_add_int (buf, (guint64)id);
1049 buffer_add_data (Buffer *buf, guint8 *data, int len)
1051 buffer_make_room (buf, len);
1052 memcpy (buf->p, data, len);
1057 buffer_add_string (Buffer *buf, const char *str)
1062 buffer_add_int (buf, 0);
1065 buffer_add_int (buf, len);
1066 buffer_add_data (buf, (guint8*)str, len);
1071 buffer_free (Buffer *buf)
1077 send_packet (int command_set, int command, Buffer *data)
1083 id = InterlockedIncrement (&packet_id);
1085 len = data->p - data->buf + 11;
1086 buffer_init (&buf, len);
1087 buffer_add_int (&buf, len);
1088 buffer_add_int (&buf, id);
1089 buffer_add_byte (&buf, 0); /* flags */
1090 buffer_add_byte (&buf, command_set);
1091 buffer_add_byte (&buf, command);
1092 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1094 res = transport_send (buf.buf, len);
1102 send_reply_packet (int id, int error, Buffer *data)
1108 len = data->p - data->buf + 11;
1109 buffer_init (&buf, len);
1110 buffer_add_int (&buf, len);
1111 buffer_add_int (&buf, id);
1112 buffer_add_byte (&buf, 0x80); /* flags */
1113 buffer_add_byte (&buf, (error >> 8) & 0xff);
1114 buffer_add_byte (&buf, error);
1115 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1117 res = transport_send (buf.buf, len);
1129 * Represents an object accessible by the debugger client.
1132 /* Unique id used in the wire protocol to refer to objects */
1135 * A weakref gc handle pointing to the object. The gc handle is used to
1136 * detect if the object was garbage collected.
1141 /* Maps objid -> ObjRef */
1142 static GHashTable *objrefs;
1145 free_objref (gpointer value)
1149 mono_gchandle_free (o->handle);
1157 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1161 objrefs_cleanup (void)
1163 g_hash_table_destroy (objrefs);
1167 static GHashTable *obj_to_objref;
1170 * Return an ObjRef for OBJ.
1173 get_objref (MonoObject *obj)
1184 /* Use a hash table with masked pointers to internalize object references */
1185 /* FIXME: This can grow indefinitely */
1186 mono_loader_lock ();
1189 obj_to_objref = g_hash_table_new (NULL, NULL);
1191 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1192 /* ref might refer to a different object with the same addr which was GCd */
1193 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1194 mono_loader_unlock ();
1198 ref = g_new0 (ObjRef, 1);
1199 ref->id = InterlockedIncrement (&objref_id);
1200 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1202 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1203 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1205 mono_loader_unlock ();
1211 get_objid (MonoObject *obj)
1213 return get_objref (obj)->id;
1217 * Set OBJ to the object identified by OBJID.
1218 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1222 get_object_allow_null (int objid, MonoObject **obj)
1232 return ERR_INVALID_OBJECT;
1234 mono_loader_lock ();
1236 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1239 *obj = mono_gchandle_get_target (ref->handle);
1240 mono_loader_unlock ();
1242 return ERR_INVALID_OBJECT;
1245 mono_loader_unlock ();
1246 return ERR_INVALID_OBJECT;
1251 get_object (int objid, MonoObject **obj)
1253 int err = get_object_allow_null (objid, obj);
1258 return ERR_INVALID_OBJECT;
1263 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1265 return decode_id (buf, endbuf, limit);
1269 buffer_add_objid (Buffer *buf, MonoObject *o)
1271 buffer_add_id (buf, get_objid (o));
1290 * Represents a runtime structure accessible to the debugger client
1293 /* Unique id used in the wire protocol */
1295 /* Domain of the runtime structure, NULL if the domain was unloaded */
1302 MonoAssembly *assembly;
1303 MonoClassField *field;
1305 MonoProperty *property;
1310 /* Maps runtime structure -> Id */
1311 GHashTable *val_to_id [ID_NUM];
1315 static GPtrArray *ids [ID_NUM];
1322 for (i = 0; i < ID_NUM; ++i)
1323 ids [i] = g_ptr_array_new ();
1331 for (i = 0; i < ID_NUM; ++i) {
1333 for (j = 0; j < ids [i]->len; ++j)
1334 g_free (g_ptr_array_index (ids [i], j));
1335 g_ptr_array_free (ids [i], TRUE);
1342 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1344 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1348 for (i = 0; i < ID_NUM; ++i)
1349 if (info->val_to_id [i])
1350 g_hash_table_destroy (info->val_to_id [i]);
1354 domain_jit_info (domain)->agent_info = NULL;
1356 /* Clear ids referencing structures in the domain */
1357 for (i = 0; i < ID_NUM; ++i) {
1359 for (j = 0; j < ids [i]->len; ++j) {
1360 Id *id = g_ptr_array_index (ids [i], j);
1361 if (id->domain == domain)
1369 get_id (MonoDomain *domain, IdType type, gpointer val)
1372 AgentDomainInfo *info;
1377 mono_loader_lock ();
1379 mono_domain_lock (domain);
1381 if (!domain_jit_info (domain)->agent_info)
1382 domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1383 info = domain_jit_info (domain)->agent_info;
1384 if (info->val_to_id [type] == NULL)
1385 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1387 id = g_hash_table_lookup (info->val_to_id [type], val);
1389 mono_domain_unlock (domain);
1390 mono_loader_unlock ();
1394 id = g_new0 (Id, 1);
1396 id->id = ids [type]->len + 1;
1397 id->domain = domain;
1400 g_hash_table_insert (info->val_to_id [type], val, id);
1402 mono_domain_unlock (domain);
1404 g_ptr_array_add (ids [type], id);
1406 mono_loader_unlock ();
1411 static inline gpointer
1412 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1416 int id = decode_id (buf, endbuf, limit);
1425 // FIXME: error handling
1426 mono_loader_lock ();
1427 g_assert (id > 0 && id <= ids [type]->len);
1429 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1430 mono_loader_unlock ();
1432 if (res->domain == NULL) {
1433 *err = ERR_UNLOADED;
1438 *domain = res->domain;
1440 return res->data.val;
1444 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1446 buffer_add_id (buf, get_id (domain, type, val));
1449 static inline MonoClass*
1450 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1452 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1455 static inline MonoAssembly*
1456 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1458 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1461 static inline MonoImage*
1462 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1464 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1467 static inline MonoMethod*
1468 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1470 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1473 static inline MonoClassField*
1474 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1476 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1479 static inline MonoDomain*
1480 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1482 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1485 static inline MonoProperty*
1486 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1488 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1492 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1494 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1498 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1500 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1504 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1506 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1510 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1512 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1516 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1518 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1522 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1524 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1528 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1530 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1533 static void invoke_method (void);
1540 save_thread_context (MonoContext *ctx)
1542 DebuggerTlsData *tls;
1544 tls = TlsGetValue (debugger_tls_id);
1548 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1550 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1551 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1553 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1557 tls->lmf = mono_get_lmf ();
1558 tls->domain = mono_domain_get ();
1559 tls->has_context = TRUE;
1562 /* The number of times the runtime is suspended */
1563 static gint32 suspend_count;
1565 /* Number of threads suspended */
1567 * If this is equal to the size of thread_to_tls, the runtime is considered
1570 static gint32 threads_suspend_count;
1572 static mono_mutex_t suspend_mutex = MONO_MUTEX_INITIALIZER;
1574 /* Cond variable used to wait for suspend_count becoming 0 */
1575 static mono_cond_t suspend_cond = MONO_COND_INITIALIZER;
1577 /* Semaphore used to wait for a thread becoming suspended */
1578 static MonoSemType suspend_sem;
1583 MONO_SEM_INIT (&suspend_sem, 0);
1587 * mono_debugger_agent_thread_interrupt:
1589 * Called by the abort signal handler.
1592 mono_debugger_agent_thread_interrupt (MonoJitInfo *ji)
1594 DebuggerTlsData *tls;
1599 tls = TlsGetValue (debugger_tls_id);
1604 * We use interrupt_count to determine whenever this interrupt should be processed
1605 * by us or the normal interrupt processing code in the signal handler.
1606 * There is no race here with notify_thread (), since the signal is sent after
1607 * incrementing interrupt_count.
1609 if (tls->interrupt_count == 0)
1612 InterlockedDecrement (&tls->interrupt_count);
1614 // FIXME: Races when the thread leaves managed code before hitting a single step
1618 /* Running managed code, will be suspended by the single step code */
1619 //printf ("S1: %p\n", GetCurrentThreadId ());
1623 * Running native code, will be suspended when it returns to/enters
1624 * managed code. Treat it as already suspended.
1626 //printf ("S2: %p\n", GetCurrentThreadId ());
1627 if (!tls->suspended) {
1628 tls->suspended = TRUE;
1629 MONO_SEM_POST (&suspend_sem);
1638 * Notify a thread that it needs to suspend.
1641 notify_thread (gpointer key, gpointer value, gpointer user_data)
1643 MonoInternalThread *thread = key;
1644 DebuggerTlsData *tls = value;
1645 gsize tid = thread->tid;
1647 if (GetCurrentThreadId () != tid) {
1648 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
1650 * Maybe we could use the normal interrupt infrastructure, but that does a lot
1651 * of things like breaking waits etc. which we don't want.
1653 InterlockedIncrement (&tls->interrupt_count);
1654 #ifdef PLATFORM_WIN32
1655 /*FIXME: Abort thread */
1657 pthread_kill ((pthread_t) tid, mono_thread_get_abort_signal ());
1665 * Increase the suspend count of the VM. While the suspend count is greater
1666 * than 0, runtime threads are suspended at certain points during execution.
1671 mono_loader_lock ();
1673 mono_mutex_lock (&suspend_mutex);
1677 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
1679 if (suspend_count == 1) {
1680 // FIXME: Is it safe to call this inside the lock ?
1681 start_single_stepping ();
1682 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
1685 mono_mutex_unlock (&suspend_mutex);
1687 mono_loader_unlock ();
1693 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
1701 g_assert (debugger_thread_id == GetCurrentThreadId ());
1703 mono_loader_lock ();
1705 mono_mutex_lock (&suspend_mutex);
1707 g_assert (suspend_count > 0);
1710 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
1712 if (suspend_count == 0) {
1713 // FIXME: Is it safe to call this inside the lock ?
1714 stop_single_stepping ();
1715 err = mono_cond_broadcast (&suspend_cond);
1716 g_assert (err == 0);
1719 err = mono_mutex_unlock (&suspend_mutex);
1720 g_assert (err == 0);
1722 mono_loader_unlock ();
1726 invalidate_frames (DebuggerTlsData *tls)
1731 tls = TlsGetValue (debugger_tls_id);
1734 for (i = 0; i < tls->frame_count; ++i) {
1735 if (tls->frames [i]->jit)
1736 mono_debug_free_method_jit_info (tls->frames [i]->jit);
1737 g_free (tls->frames [i]);
1739 g_free (tls->frames);
1740 tls->frame_count = 0;
1747 * Suspend the current thread until the runtime is resumed. If the thread has a
1748 * pending invoke, then the invoke is executed before this function returns.
1751 suspend_current (void)
1754 DebuggerTlsData *tls;
1756 g_assert (debugger_thread_id != GetCurrentThreadId ());
1758 if (mono_loader_lock_is_owned_by_self ()) {
1760 * If we own the loader mutex, can't suspend until we release it, since the
1761 * whole runtime can deadlock otherwise.
1766 tls = TlsGetValue (debugger_tls_id);
1769 mono_mutex_lock (&suspend_mutex);
1771 if (!tls->suspended) {
1772 tls->suspended = TRUE;
1773 MONO_SEM_POST (&suspend_sem);
1776 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
1778 while (suspend_count > 0) {
1779 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
1780 g_assert (err == 0);
1783 tls->suspended = FALSE;
1785 threads_suspend_count --;
1787 mono_mutex_unlock (&suspend_mutex);
1789 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
1792 /* Save the original context */
1793 tls->invoke->has_ctx = TRUE;
1794 memcpy (&tls->invoke->ctx, &tls->ctx, sizeof (MonoContext));
1799 /* The frame info becomes invalid after a resume */
1800 tls->has_context = FALSE;
1801 invalidate_frames (NULL);
1805 count_thread (gpointer key, gpointer value, gpointer user_data)
1807 DebuggerTlsData *tls = value;
1809 if (!tls->suspended && !tls->terminated)
1810 *(int*)user_data = *(int*)user_data + 1;
1814 count_threads_to_wait_for (void)
1818 mono_loader_lock ();
1819 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
1820 mono_loader_unlock ();
1828 * Wait until the runtime is completely suspended.
1831 wait_for_suspend (void)
1833 int nthreads, nwait, err;
1834 gboolean waited = FALSE;
1836 // FIXME: Threads starting/stopping ?
1837 mono_loader_lock ();
1838 nthreads = mono_g_hash_table_size (thread_to_tls);
1839 mono_loader_unlock ();
1842 nwait = count_threads_to_wait_for ();
1844 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
1845 err = MONO_SEM_WAIT (&suspend_sem);
1846 g_assert (err == 0);
1854 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
1860 * Return whenever the runtime is suspended.
1865 return count_threads_to_wait_for () == 0;
1869 * compute_il_offset:
1871 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
1872 * a location of a sequence point.
1873 * We use this function instead of mono_debug_il_offset_from_address () etc,
1874 * which doesn't seem to work in a lot of cases.
1877 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
1879 GPtrArray *seq_points;
1880 int i, last_il_offset, seq_il_offset, seq_native_offset;
1882 mono_domain_lock (domain);
1883 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
1884 mono_domain_unlock (domain);
1885 g_assert (seq_points);
1887 last_il_offset = -1;
1889 /* Find the sequence point */
1890 for (i = 0; i < seq_points->len; i += 2) {
1891 seq_il_offset = GPOINTER_TO_UINT (g_ptr_array_index (seq_points, i));
1892 seq_native_offset = GPOINTER_TO_UINT (g_ptr_array_index (seq_points, i + 1));
1894 if (seq_native_offset > native_offset)
1896 last_il_offset = seq_il_offset;
1899 return last_il_offset;
1903 DebuggerTlsData *tls;
1905 } ComputeFramesUserData;
1908 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
1910 ComputeFramesUserData *ud = user_data;
1914 if (info->type != FRAME_TYPE_MANAGED) {
1915 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
1916 /* Mark the last frame as an invoke frame */
1918 ((StackFrame*)ud->frames->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
1924 method = info->ji->method;
1926 method = info->method;
1928 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
1931 if (info->il_offset == -1) {
1932 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
1933 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
1936 DEBUG (1, fprintf (stderr, "\tFrame: %s %d %d %d\n", mono_method_full_name (method, TRUE), info->native_offset, info->il_offset, info->managed));
1938 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
1940 * mono_arch_find_jit_info () returns the context stored in the LMF for
1941 * native frames, but it should unwind once. This is why we have duplicate
1942 * frames on the stack sometimes.
1943 * !managed also seems to be set for dynamic methods.
1948 frame = g_new0 (StackFrame, 1);
1949 frame->method = method;
1950 frame->il_offset = info->il_offset;
1952 frame->domain = info->domain;
1954 ud->frames = g_slist_append (ud->frames, frame);
1960 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
1962 ComputeFramesUserData user_data;
1964 int i, findex, new_frame_count;
1965 StackFrame **new_frames, *f;
1967 // FIXME: Locking on tls
1968 if (tls->frames && tls->frames_up_to_date)
1971 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
1973 user_data.tls = tls;
1974 user_data.frames = NULL;
1975 if (tls->has_context) {
1976 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
1979 tls->frame_count = 0;
1983 new_frame_count = g_slist_length (user_data.frames);
1984 new_frames = g_new0 (StackFrame*, new_frame_count);
1986 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
1990 * Reuse the id for already existing stack frames, so invokes don't invalidate
1991 * the still valid stack frames.
1993 for (i = 0; i < tls->frame_count; ++i) {
1994 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
1995 f->id = tls->frames [i]->id;
2000 if (i >= tls->frame_count)
2001 f->id = InterlockedIncrement (&frame_id);
2003 new_frames [findex ++] = f;
2006 g_slist_free (user_data.frames);
2008 invalidate_frames (tls);
2010 tls->frames = new_frames;
2011 tls->frame_count = new_frame_count;
2012 tls->frames_up_to_date = TRUE;
2020 * create_event_list:
2022 * Return a list of event request ids matching EVENT, starting from REQS, which
2023 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2025 * We return request ids, instead of requests, to simplify threading, since
2026 * requests could be deleted anytime when the loader lock is not held.
2027 * LOCKING: Assumes the loader lock is held.
2030 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, MonoException *exc, int *suspend_policy)
2033 GSList *events = NULL;
2035 *suspend_policy = SUSPEND_POLICY_NONE;
2038 reqs = event_requests;
2043 for (i = 0; i < reqs->len; ++i) {
2044 EventRequest *req = g_ptr_array_index (reqs, i);
2045 if (req->event_kind == event) {
2046 gboolean filtered = FALSE;
2049 for (j = 0; j < req->nmodifiers; ++j) {
2050 Modifier *mod = &req->modifiers [j];
2052 if (mod->kind == MOD_KIND_COUNT) {
2054 if (mod->data.count > 0) {
2055 if (mod->data.count > 0) {
2057 if (mod->data.count == 0)
2061 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2062 if (mod->data.thread != mono_thread_internal_current ())
2064 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && exc) {
2065 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, exc->object.vtable->klass))
2067 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2069 gboolean found = FALSE;
2070 MonoAssembly **assemblies = mod->data.assemblies;
2072 for (k = 0; assemblies [k]; ++k)
2073 if (assemblies [k] == ji->method->klass->image->assembly)
2081 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2082 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2087 /* Send a VM START/DEATH event by default */
2088 if (event == EVENT_KIND_VM_START)
2089 events = g_slist_append (events, GINT_TO_POINTER (0));
2090 if (event == EVENT_KIND_VM_DEATH)
2091 events = g_slist_append (events, GINT_TO_POINTER (0));
2096 static G_GNUC_UNUSED const char*
2097 event_to_string (EventKind event)
2100 case EVENT_KIND_VM_START: return "VM_START";
2101 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2102 case EVENT_KIND_THREAD_START: return "THREAD_START";
2103 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2104 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2105 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2106 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2107 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2108 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2109 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2110 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2111 case EVENT_KIND_STEP: return "STEP";
2112 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2113 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2115 g_assert_not_reached ();
2122 * Send an event to the client, suspending the vm if needed.
2123 * LOCKING: Since this can suspend the calling thread, no locks should be held
2125 * The EVENTS list is freed by this function.
2128 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2132 MonoDomain *domain = mono_domain_get ();
2138 if (!vm_start_event_sent && event != EVENT_KIND_VM_START)
2139 // FIXME: We miss those events
2142 if (vm_death_event_sent)
2145 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH)
2154 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
2155 // FIXME: Send these with a NULL thread, don't suspend the current thread
2158 buffer_init (&buf, 128);
2159 buffer_add_byte (&buf, suspend_policy);
2160 buffer_add_int (&buf, g_slist_length (events)); // n of events
2162 for (l = events; l; l = l->next) {
2163 buffer_add_byte (&buf, event); // event kind
2164 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
2166 thread = mono_thread_current ();
2168 if (event == EVENT_KIND_VM_START)
2170 else if (event == EVENT_KIND_THREAD_START)
2171 g_assert (mono_thread_internal_current () == arg);
2173 buffer_add_objid (&buf, (MonoObject*)thread); // thread
2176 case EVENT_KIND_THREAD_START:
2177 case EVENT_KIND_THREAD_DEATH:
2179 case EVENT_KIND_APPDOMAIN_CREATE:
2180 case EVENT_KIND_APPDOMAIN_UNLOAD:
2181 buffer_add_domainid (&buf, arg);
2183 case EVENT_KIND_METHOD_ENTRY:
2184 case EVENT_KIND_METHOD_EXIT:
2185 buffer_add_methodid (&buf, domain, arg);
2187 case EVENT_KIND_ASSEMBLY_LOAD:
2188 case EVENT_KIND_ASSEMBLY_UNLOAD:
2189 buffer_add_assemblyid (&buf, domain, arg);
2191 case EVENT_KIND_TYPE_LOAD:
2192 buffer_add_typeid (&buf, domain, arg);
2194 case EVENT_KIND_BREAKPOINT:
2195 case EVENT_KIND_STEP:
2196 buffer_add_methodid (&buf, domain, arg);
2197 buffer_add_long (&buf, il_offset);
2199 case EVENT_KIND_VM_START:
2200 buffer_add_domainid (&buf, mono_get_root_domain ());
2202 case EVENT_KIND_VM_DEATH:
2204 case EVENT_KIND_EXCEPTION:
2205 buffer_add_objid (&buf, (MonoObject*)arg);
2208 g_assert_not_reached ();
2212 if (event == EVENT_KIND_VM_START) {
2213 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
2214 start_debugger_thread ();
2217 if (event == EVENT_KIND_VM_DEATH) {
2218 vm_death_event_sent = TRUE;
2220 suspend_policy = SUSPEND_POLICY_NONE;
2223 if (mono_runtime_is_shutting_down ())
2224 suspend_policy = SUSPEND_POLICY_NONE;
2226 if (suspend_policy != SUSPEND_POLICY_NONE) {
2228 * Save the thread context and start suspending before sending the packet,
2229 * since we could be receiving the resume request before send_packet ()
2232 save_thread_context (ctx);
2236 send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
2238 g_slist_free (events);
2241 if (event == EVENT_KIND_VM_START)
2242 vm_start_event_sent = TRUE;
2244 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
2248 switch (suspend_policy) {
2249 case SUSPEND_POLICY_NONE:
2251 case SUSPEND_POLICY_ALL:
2254 case SUSPEND_POLICY_EVENT_THREAD:
2258 g_assert_not_reached ();
2263 process_profiler_event (EventKind event, gpointer arg)
2268 mono_loader_lock ();
2269 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
2270 mono_loader_unlock ();
2272 process_event (event, arg, 0, NULL, events, suspend_policy);
2276 runtime_initialized (MonoProfiler *prof)
2278 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
2282 runtime_shutdown (MonoProfiler *prof)
2284 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
2286 mono_debugger_agent_cleanup ();
2290 thread_startup (MonoProfiler *prof, gsize tid)
2292 MonoInternalThread *thread = mono_thread_internal_current ();
2293 MonoInternalThread *old_thread;
2294 DebuggerTlsData *tls;
2296 if (tid == debugger_thread_id)
2299 g_assert (thread->tid == tid);
2301 mono_loader_lock ();
2302 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2303 mono_loader_unlock ();
2305 if (thread == old_thread) {
2307 * For some reason, thread_startup () might be called for the same thread
2308 * multiple times (attach ?).
2310 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
2314 * thread_end () might not be called for some threads, and the tid could
2317 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
2318 mono_loader_lock ();
2319 mono_g_hash_table_remove (thread_to_tls, old_thread);
2320 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
2321 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2322 mono_loader_unlock ();
2326 tls = TlsGetValue (debugger_tls_id);
2328 // FIXME: Free this somewhere
2329 tls = g_new0 (DebuggerTlsData, 1);
2330 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
2331 TlsSetValue (debugger_tls_id, tls);
2333 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2335 mono_loader_lock ();
2336 mono_g_hash_table_insert (thread_to_tls, thread, tls);
2337 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
2338 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
2339 mono_loader_unlock ();
2341 process_profiler_event (EVENT_KIND_THREAD_START, thread);
2344 * suspend_vm () could have missed this thread, so wait for a resume.
2350 thread_end (MonoProfiler *prof, gsize tid)
2352 MonoInternalThread *thread;
2353 DebuggerTlsData *tls = NULL;
2355 mono_loader_lock ();
2356 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2358 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2359 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
2360 tls->terminated = TRUE;
2361 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2362 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
2364 mono_loader_unlock ();
2366 /* We might be called for threads started before we registered the start callback */
2368 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2369 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
2374 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
2376 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
2380 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
2382 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
2386 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
2388 /* Sent later in jit_end () */
2389 mono_loader_lock ();
2390 g_ptr_array_add (pending_assembly_loads, assembly);
2391 mono_loader_unlock ();
2395 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
2397 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
2401 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2406 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2409 #ifdef PLATFORM_WIN32
2410 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
2412 gpointer stackptr = __builtin_frame_address (0);
2415 if (ss_req == NULL || ss_req->start_sp > stackptr || ss_req->thread != mono_thread_internal_current ())
2419 * We need to stop single stepping when exiting a runtime invoke, since if it is
2420 * a step out, it may return to native code, and thus never end.
2422 mono_loader_lock ();
2423 for (i = 0; i < event_requests->len; ++i) {
2424 EventRequest *req = g_ptr_array_index (event_requests, i);
2426 if (req->event_kind == EVENT_KIND_STEP) {
2428 g_ptr_array_remove_index_fast (event_requests, i);
2433 mono_loader_unlock ();
2438 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
2441 * We emit type load events when the first method of the type is JITted,
2442 * since the class load profiler callbacks might be called with the
2443 * loader lock held. They could also occur in the debugger thread.
2444 * Same for assembly load events.
2446 gboolean type_load = FALSE;
2449 MonoAssembly *assembly = NULL;
2451 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
2452 mono_loader_lock ();
2453 if (pending_assembly_loads->len > 0) {
2454 assembly = g_ptr_array_index (pending_assembly_loads, 0);
2455 g_ptr_array_remove_index (pending_assembly_loads, 0);
2457 mono_loader_unlock ();
2460 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
2465 mono_loader_lock ();
2466 if (!g_hash_table_lookup (loaded_classes, method->klass)) {
2468 g_hash_table_insert (loaded_classes, method->klass, method->klass);
2470 mono_loader_unlock ();
2472 process_profiler_event (EVENT_KIND_TYPE_LOAD, method->klass);
2475 add_pending_breakpoints (method, jinfo);
2479 * BREAKPOINTS/SINGLE STEPPING
2483 * Contains information about an inserted breakpoint.
2486 long il_offset, native_offset;
2488 gboolean pending, entry;
2490 } BreakpointInstance;
2493 * Contains generic information about a breakpoint.
2497 * The method where the breakpoint is placed. Can be NULL in which case it
2498 * is inserted into every method. This is used to implement method entry/
2499 * exit events. Can be a generic method definition, in which case the
2500 * breakpoint is inserted into every instance.
2504 gboolean pending, entry;
2507 * A list of BreakpointInstance structures describing where the breakpoint
2508 * was inserted. There could be more than one because of
2509 * generics/appdomains/method entry/exit.
2511 GPtrArray *children;
2514 /* List of breakpoints */
2515 static GPtrArray *breakpoints;
2516 /* Maps breakpoint locations to the number of breakpoints at that location */
2517 static GHashTable *bp_locs;
2520 breakpoints_init (void)
2522 breakpoints = g_ptr_array_new ();
2523 bp_locs = g_hash_table_new (NULL, NULL);
2527 breakpoints_cleanup (void)
2531 mono_loader_lock ();
2533 for (i = 0; i < breakpoints->len; ++i)
2534 g_free (g_ptr_array_index (breakpoints, i));
2536 g_ptr_array_free (breakpoints, TRUE);
2537 g_hash_table_destroy (bp_locs);
2539 mono_loader_unlock ();
2543 * insert_breakpoint:
2545 * Insert the breakpoint described by BP into the method described by
2549 insert_breakpoint (GPtrArray *seq_points, MonoJitInfo *ji, MonoBreakpoint *bp)
2552 gint32 il_offset, native_offset;
2553 BreakpointInstance *inst;
2556 for (i = 0; i < seq_points->len; i += 2) {
2557 il_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i));
2558 native_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i + 1));
2560 if (il_offset == bp->il_offset)
2564 if (i == seq_points->len)
2565 /* Have to handle this somehow */
2568 inst = g_new0 (BreakpointInstance, 1);
2569 inst->native_offset = native_offset;
2570 inst->ip = (guint8*)ji->code_start + native_offset;
2573 mono_loader_lock ();
2575 g_ptr_array_add (bp->children, inst);
2577 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
2578 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
2579 mono_loader_unlock ();
2582 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
2583 mono_arch_set_breakpoint (ji, inst->ip);
2591 remove_breakpoint (BreakpointInstance *inst)
2593 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
2595 MonoJitInfo *ji = inst->ji;
2596 guint8 *ip = inst->ip;
2598 mono_loader_lock ();
2599 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
2600 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
2601 mono_loader_unlock ();
2603 g_assert (count > 0);
2606 mono_arch_clear_breakpoint (ji, ip);
2614 * add_pending_breakpoints:
2616 * Insert pending breakpoints into the newly JITted method METHOD.
2619 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
2622 GPtrArray *seq_points;
2628 domain = mono_domain_get ();
2630 mono_loader_lock ();
2632 for (i = 0; i < breakpoints->len; ++i) {
2633 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
2635 if (bp->pending && (bp->method == method || !bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method))) {
2636 mono_domain_lock (domain);
2637 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
2638 mono_domain_unlock (domain);
2640 /* Could be AOT code */
2642 g_assert (seq_points);
2644 insert_breakpoint (seq_points, ji, bp);
2648 mono_loader_unlock ();
2652 set_bp_in_method (MonoDomain *domain, MonoMethod *method, GPtrArray *seq_points, MonoBreakpoint *bp)
2657 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
2659 /* Might be AOTed code */
2660 code = mono_aot_get_method (domain, method);
2662 ji = mono_jit_info_table_find (domain, code);
2667 insert_breakpoint (seq_points, ji, bp);
2671 set_bp_in_method_cb (gpointer key, gpointer value, gpointer user_data)
2673 MonoMethod *method = key;
2674 GPtrArray *seq_points = value;
2675 MonoBreakpoint *bp = user_data;
2676 MonoDomain *domain = mono_domain_get ();
2679 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method) {
2680 /* Generic instance */
2681 set_bp_in_method (domain, method, seq_points, bp);
2684 /* Method entry/exit */
2685 set_bp_in_method (domain, method, seq_points, bp);
2692 * Set a breakpoint at IL_OFFSET in METHOD.
2693 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
2694 * METHOD can also be a generic method definition, in which case a breakpoint
2695 * is placed in all instances of the method.
2697 static MonoBreakpoint*
2698 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req)
2700 GPtrArray *seq_points;
2705 // - suspend/resume the vm to prevent code patching problems
2707 // - multiple breakpoints on the same location
2708 // - dynamic methods
2711 bp = g_new0 (MonoBreakpoint, 1);
2712 bp->method = method;
2713 bp->il_offset = il_offset;
2715 bp->children = g_ptr_array_new ();
2717 DEBUG(1, fprintf (log_file, "[dbg] Setting breakpoint at %s:0x%x.\n", mono_method_full_name (method, TRUE), (int)il_offset));
2719 domain = mono_domain_get ();
2720 mono_domain_lock (domain);
2722 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2724 set_bp_in_method (domain, method, seq_points, bp);
2726 if (method->is_generic)
2727 /* There might be already JITted instances */
2728 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
2730 /* Not yet JITted */
2734 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
2737 mono_domain_unlock (domain);
2739 mono_loader_lock ();
2740 g_ptr_array_add (breakpoints, bp);
2741 mono_loader_unlock ();
2747 clear_breakpoint (MonoBreakpoint *bp)
2751 // FIXME: locking, races
2752 for (i = 0; i < bp->children->len; ++i) {
2753 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
2755 remove_breakpoint (inst);
2760 mono_loader_lock ();
2761 g_ptr_array_remove (breakpoints, bp);
2762 mono_loader_unlock ();
2764 g_ptr_array_free (bp->children, TRUE);
2769 process_breakpoint_inner (MonoContext *ctx)
2772 guint8 *orig_ip, *ip;
2773 int i, j, suspend_policy;
2774 guint32 native_offset;
2776 BreakpointInstance *inst;
2778 GSList *events = NULL;
2779 EventKind kind = EVENT_KIND_BREAKPOINT;
2781 // FIXME: Speed this up
2783 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
2784 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
2786 g_assert (ji->method);
2788 /* Compute the native offset of the breakpoint from the ip */
2789 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
2790 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
2791 native_offset = ip - (guint8*)ji->code_start;
2797 * Skip the instruction causing the breakpoint signal.
2799 mono_arch_skip_breakpoint (ctx);
2801 if (ji->method->wrapper_type)
2804 reqs = g_ptr_array_new ();
2806 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
2808 mono_loader_lock ();
2811 for (i = 0; i < breakpoints->len; ++i) {
2812 bp = g_ptr_array_index (breakpoints, i);
2817 for (j = 0; j < bp->children->len; ++j) {
2818 inst = g_ptr_array_index (bp->children, j);
2819 if (inst->ji == ji && inst->native_offset == native_offset)
2820 g_ptr_array_add (reqs, bp->req);
2823 if (reqs->len == 0) {
2824 GPtrArray *seq_points;
2825 int seq_il_offset, seq_native_offset;
2826 MonoDomain *domain = mono_domain_get ();
2828 /* Maybe a method entry/exit event */
2829 mono_domain_lock (domain);
2830 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
2831 mono_domain_unlock (domain);
2833 // FIXME: Generic sharing */
2834 mono_loader_unlock ();
2837 g_assert (seq_points);
2839 for (i = 0; i < seq_points->len; i += 2) {
2840 seq_il_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i));
2841 seq_native_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i + 1));
2843 if (native_offset == seq_native_offset) {
2844 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
2845 kind = EVENT_KIND_METHOD_ENTRY;
2846 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
2847 kind = EVENT_KIND_METHOD_EXIT;
2854 events = create_event_list (EVENT_KIND_BREAKPOINT, reqs, ji, NULL, &suspend_policy);
2855 else if (kind != EVENT_KIND_BREAKPOINT)
2856 events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
2858 g_ptr_array_free (reqs, TRUE);
2860 mono_loader_unlock ();
2863 process_event (kind, ji->method, 0, ctx, events, suspend_policy);
2867 process_breakpoint (void)
2869 DebuggerTlsData *tls;
2871 static void (*restore_context) (void *);
2873 if (!restore_context)
2874 restore_context = mono_get_restore_context ();
2876 tls = TlsGetValue (debugger_tls_id);
2877 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
2879 process_breakpoint_inner (&ctx);
2881 /* This is called when resuming from a signal handler, so it shouldn't return */
2882 restore_context (&ctx);
2883 g_assert_not_reached ();
2887 mono_debugger_agent_breakpoint_hit (void *sigctx)
2889 DebuggerTlsData *tls;
2893 * We are called from a signal handler, and running code there causes all kinds of
2894 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
2895 * So set up the signal context to return to the real breakpoint handler function.
2898 // FIXME: This might not work on an altstack ?
2899 tls = TlsGetValue (debugger_tls_id);
2902 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2903 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
2905 MONO_CONTEXT_SET_IP (&ctx, process_breakpoint);
2907 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
2911 process_single_step_inner (MonoContext *ctx)
2916 int il_offset, suspend_policy;
2917 MonoDomain *domain = mono_domain_get ();
2920 // FIXME: Speed this up
2922 ip = MONO_CONTEXT_GET_IP (ctx);
2924 /* Skip the instruction causing the single step */
2925 mono_arch_skip_single_step (ctx);
2927 if (suspend_count > 0) {
2928 if (debugger_thread_id == GetCurrentThreadId ())
2931 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2933 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
2935 /* See the comment below */
2936 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2939 save_thread_context (ctx);
2945 // FIXME: A suspend race
2948 if (mono_thread_internal_current () != ss_req->thread)
2951 if (log_level > 0) {
2952 const char *depth = NULL;
2954 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
2956 switch (ss_req->depth) {
2957 case STEP_DEPTH_OVER:
2960 case STEP_DEPTH_OUT:
2963 case STEP_DEPTH_INTO:
2967 g_assert_not_reached ();
2970 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));
2974 * We implement step over/out by single stepping until we reach the same
2975 * frame/parent frame.
2978 * - stack growing upward
2982 if (ss_req->depth != STEP_DEPTH_INTO) {
2983 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
2985 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
2988 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
2991 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
2993 g_assert (ji->method);
2995 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
3000 * Stopping in memset makes half-initialized vtypes visible.
3001 * Stopping in memcpy makes half-copied vtypes visible.
3003 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
3007 * The ip points to the instruction causing the single step event, convert it
3008 * to the offset stored in seq_points.
3010 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3011 ip = mono_arch_get_ip_for_single_step (ji, ctx);
3013 g_assert_not_reached ();
3017 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
3018 * example, so do things by hand.
3020 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
3022 if (il_offset == -1)
3025 if (ss_req->size == STEP_SIZE_LINE) {
3026 /* Step until a different source line is reached */
3027 MonoDebugMethodInfo *minfo;
3029 minfo = mono_debug_lookup_method (ji->method);
3032 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
3034 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
3035 mono_debug_free_source_location (loc);
3040 * Step until we reach a location with line number info,
3041 * otherwise the client can't show a location.
3042 * This can happen for example with statics initialized inline
3043 * outside of a cctor.
3048 ss_req->last_method = ji->method;
3049 ss_req->last_line = loc->row;
3050 mono_debug_free_source_location (loc);
3055 // FIXME: Has to lock earlier
3057 reqs = g_ptr_array_new ();
3059 mono_loader_lock ();
3061 g_ptr_array_add (reqs, ss_req->req);
3063 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
3065 g_ptr_array_free (reqs, TRUE);
3067 mono_loader_unlock ();
3069 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
3073 process_single_step (void)
3075 DebuggerTlsData *tls;
3077 static void (*restore_context) (void *);
3079 if (!restore_context)
3080 restore_context = mono_get_restore_context ();
3082 tls = TlsGetValue (debugger_tls_id);
3083 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3085 process_single_step_inner (&ctx);
3087 /* This is called when resuming from a signal handler, so it shouldn't return */
3088 restore_context (&ctx);
3089 g_assert_not_reached ();
3093 * mono_debugger_agent_single_step_event:
3095 * Called from a signal handler to handle a single step event.
3098 mono_debugger_agent_single_step_event (void *sigctx)
3100 DebuggerTlsData *tls;
3103 /* Resume to process_single_step through the signal context */
3105 // FIXME: Since step out/over is implemented using step in, the step in case should
3106 // be as fast as possible. Move the relevant code from process_single_step_inner ()
3109 /* Save the original context in TLS */
3110 // FIXME: This might not work on an altstack ?
3111 tls = TlsGetValue (debugger_tls_id);
3113 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3114 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3116 MONO_CONTEXT_SET_IP (&ctx, process_single_step);
3118 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3122 * start_single_stepping:
3124 * Turn on single stepping. Can be called multiple times, for example,
3125 * by a single step event request + a suspend.
3128 start_single_stepping (void)
3130 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3131 int val = InterlockedIncrement (&ss_count);
3134 mono_arch_start_single_stepping ();
3136 g_assert_not_reached ();
3141 stop_single_stepping (void)
3143 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3144 int val = InterlockedDecrement (&ss_count);
3147 mono_arch_stop_single_stepping ();
3149 g_assert_not_reached ();
3154 * Start single stepping of thread THREAD
3157 ss_start (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
3159 DebuggerTlsData *tls;
3161 if (suspend_count == 0)
3162 return ERR_NOT_SUSPENDED;
3164 wait_for_suspend ();
3166 // FIXME: Multiple requests
3168 return ERR_NOT_IMPLEMENTED;
3170 ss_req = g_new0 (MonoSingleStepReq, 1);
3172 ss_req->thread = thread;
3173 ss_req->size = size;
3174 ss_req->depth = depth;
3177 mono_loader_lock ();
3178 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3179 mono_loader_unlock ();
3181 g_assert (tls->has_context);
3182 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
3184 if (ss_req->size == STEP_SIZE_LINE) {
3186 MonoDebugMethodInfo *minfo;
3188 /* Compute the initial line info */
3189 compute_frame_info (thread, tls);
3191 g_assert (tls->frame_count);
3192 frame = tls->frames [0];
3194 ss_req->last_method = frame->method;
3195 ss_req->last_line = -1;
3197 minfo = mono_debug_lookup_method (frame->method);
3198 if (minfo && frame->il_offset != -1) {
3199 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
3202 ss_req->last_line = loc->row;
3208 start_single_stepping ();
3214 ss_stop (EventRequest *req)
3218 g_assert (ss_req->req == req);
3223 stop_single_stepping ();
3227 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *ctx)
3232 /* Just-In-Time debugging */
3233 if (agent_config.onthrow && !inited) {
3235 gboolean found = FALSE;
3237 for (l = agent_config.onthrow; l; l = l->next) {
3238 char *ex_type = l->data;
3239 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
3241 if (!strcmp (ex_type, f))
3248 finish_agent_init (FALSE);
3251 * Send an unsolicited EXCEPTION event with a dummy request id.
3253 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3254 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, SUSPEND_POLICY_ALL);
3262 mono_loader_lock ();
3263 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, exc, &suspend_policy);
3264 mono_loader_unlock ();
3266 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, suspend_policy);
3270 mono_debugger_agent_handle_unhandled_exception (MonoException *exc, MonoContext *ctx)
3274 if (!agent_config.onuncaught)
3277 finish_agent_init (FALSE);
3280 * Send an unsolicited EXCEPTION event with a dummy request id.
3282 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3283 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, SUSPEND_POLICY_ALL);
3289 * Add the encoding of the value at ADDR described by T to the buffer.
3292 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
3297 g_assert (*(void**)addr);
3298 addr = *(void**)addr;
3302 case MONO_TYPE_VOID:
3303 buffer_add_byte (buf, t->type);
3305 case MONO_TYPE_BOOLEAN:
3308 buffer_add_byte (buf, t->type);
3309 buffer_add_int (buf, *(gint8*)addr);
3311 case MONO_TYPE_CHAR:
3314 buffer_add_byte (buf, t->type);
3315 buffer_add_int (buf, *(gint16*)addr);
3320 buffer_add_byte (buf, t->type);
3321 buffer_add_int (buf, *(gint32*)addr);
3326 buffer_add_byte (buf, t->type);
3327 buffer_add_long (buf, *(gint64*)addr);
3331 case MONO_TYPE_PTR: {
3332 gssize val = *(gssize*)addr;
3334 buffer_add_byte (buf, t->type);
3335 buffer_add_long (buf, val);
3339 case MONO_TYPE_STRING:
3340 case MONO_TYPE_SZARRAY:
3341 case MONO_TYPE_OBJECT:
3342 case MONO_TYPE_CLASS:
3343 case MONO_TYPE_ARRAY:
3344 obj = *(MonoObject**)addr;
3347 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
3349 if (obj->vtable->klass->valuetype) {
3350 t = &obj->vtable->klass->byval_arg;
3351 addr = mono_object_unbox (obj);
3353 } else if (obj->vtable->klass->rank) {
3354 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
3355 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
3356 buffer_add_byte (buf, MONO_TYPE_CLASS);
3358 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
3360 buffer_add_objid (buf, obj);
3364 case MONO_TYPE_VALUETYPE: {
3368 MonoClass *klass = mono_class_from_mono_type (t);
3370 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
3371 buffer_add_byte (buf, klass->enumtype);
3372 buffer_add_typeid (buf, domain, klass);
3376 while ((f = mono_class_get_fields (klass, &iter))) {
3377 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
3379 if (mono_field_is_deleted (f))
3383 buffer_add_int (buf, nfields);
3386 while ((f = mono_class_get_fields (klass, &iter))) {
3387 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
3389 if (mono_field_is_deleted (f))
3391 buffer_add_value (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain);
3395 case MONO_TYPE_GENERICINST:
3396 if (mono_type_generic_inst_is_valuetype (t)) {
3408 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
3411 int type = decode_byte (buf, &buf, limit);
3413 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t)) {
3414 DEBUG(1, fprintf (log_file, "Expected value of type %d, got %d.\n", t->type, type));
3415 return ERR_INVALID_ARGUMENT;
3419 case MONO_TYPE_BOOLEAN:
3420 *(guint8*)addr = decode_int (buf, &buf, limit);
3422 case MONO_TYPE_CHAR:
3423 *(gunichar2*)addr = decode_int (buf, &buf, limit);
3426 *(gint8*)addr = decode_int (buf, &buf, limit);
3429 *(guint8*)addr = decode_int (buf, &buf, limit);
3432 *(gint16*)addr = decode_int (buf, &buf, limit);
3435 *(guint16*)addr = decode_int (buf, &buf, limit);
3438 *(gint32*)addr = decode_int (buf, &buf, limit);
3441 *(guint32*)addr = decode_int (buf, &buf, limit);
3444 *(gint64*)addr = decode_long (buf, &buf, limit);
3447 *(guint64*)addr = decode_long (buf, &buf, limit);
3450 *(guint32*)addr = decode_int (buf, &buf, limit);
3453 *(guint64*)addr = decode_long (buf, &buf, limit);
3455 case MONO_TYPE_VALUETYPE: {
3456 gboolean is_enum = decode_byte (buf, &buf, limit);
3460 gpointer iter = NULL;
3463 /* Enums are sent as a normal vtype */
3465 return ERR_NOT_IMPLEMENTED;
3466 klass = decode_typeid (buf, &buf, limit, &d, &err);
3470 if (klass != mono_class_from_mono_type (t))
3471 return ERR_INVALID_ARGUMENT;
3473 nfields = decode_int (buf, &buf, limit);
3474 while ((f = mono_class_get_fields (klass, &iter))) {
3475 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
3477 if (mono_field_is_deleted (f))
3479 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
3484 g_assert (nfields == 0);
3488 if (MONO_TYPE_IS_REFERENCE (t)) {
3489 if (type == MONO_TYPE_OBJECT) {
3490 int objid = decode_objid (buf, &buf, limit);
3494 err = get_object (objid, (MonoObject**)&obj);
3498 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
3499 return ERR_INVALID_ARGUMENT;
3500 if (obj && obj->vtable->domain != domain)
3501 return ERR_INVALID_ARGUMENT;
3503 mono_gc_wbarrier_generic_store (addr, obj);
3504 } else if (type == VALUE_TYPE_ID_NULL) {
3505 *(MonoObject**)addr = NULL;
3507 return ERR_INVALID_ARGUMENT;
3521 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain)
3528 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3529 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3532 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
3533 reg_val = mono_arch_context_get_int_reg (ctx, reg);
3535 buffer_add_value (buf, t, ®_val, domain);
3537 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
3538 addr = mono_arch_context_get_int_reg (ctx, reg);
3539 addr += (gint32)var->offset;
3541 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
3543 buffer_add_value (buf, t, addr, domain);
3545 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
3549 g_assert_not_reached ();
3554 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
3560 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3561 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3563 if (MONO_TYPE_IS_REFERENCE (t))
3564 size = sizeof (gpointer);
3566 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
3569 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
3570 // FIXME: Can't set registers, so we disable linears
3573 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
3574 addr = mono_arch_context_get_int_reg (ctx, reg);
3575 addr += (gint32)var->offset;
3577 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
3579 // FIXME: Write barriers
3580 memcpy (addr, val, size);
3582 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
3586 g_assert_not_reached ();
3591 clear_event_request (int req_id, int etype)
3595 mono_loader_lock ();
3596 for (i = 0; i < event_requests->len; ++i) {
3597 EventRequest *req = g_ptr_array_index (event_requests, i);
3599 if (req->id == req_id && req->event_kind == etype) {
3600 if (req->event_kind == EVENT_KIND_BREAKPOINT)
3601 clear_breakpoint (req->info);
3602 if (req->event_kind == EVENT_KIND_STEP)
3604 g_ptr_array_remove_index_fast (event_requests, i);
3609 mono_loader_unlock ();
3613 add_thread (gpointer key, gpointer value, gpointer user_data)
3615 MonoInternalThread *thread = value;
3616 Buffer *buf = user_data;
3618 buffer_add_objid (buf, (MonoObject*)thread);
3622 do_invoke_method (Buffer *buf, InvokeData *invoke)
3624 guint8 *p = invoke->p;
3625 guint8 *end = invoke->endp;
3628 MonoMethodSignature *sig;
3631 MonoObject *this, *res, *exc;
3634 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
3638 m = decode_methodid (p, &p, end, &domain, &err);
3641 sig = mono_method_signature (m);
3643 if (m->klass->valuetype)
3644 this_buf = g_alloca (mono_class_instance_size (m->klass));
3646 this_buf = g_alloca (sizeof (MonoObject*));
3647 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
3651 if (!m->klass->valuetype)
3652 this = *(MonoObject**)this_buf;
3656 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>"));
3658 if (this && this->vtable->domain != domain)
3661 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
3662 if (!strcmp (m->name, ".ctor")) {
3663 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
3664 return ERR_INVALID_ARGUMENT;
3666 this = mono_object_new (domain, m->klass);
3668 return ERR_INVALID_ARGUMENT;
3672 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
3673 return ERR_INVALID_ARGUMENT;
3675 nargs = decode_int (p, &p, end);
3676 if (nargs != sig->param_count)
3677 return ERR_INVALID_ARGUMENT;
3678 /* Use alloca to get gc tracking */
3679 arg_buf = g_alloca (nargs * sizeof (gpointer));
3680 memset (arg_buf, 0, nargs * sizeof (gpointer));
3681 args = g_alloca (nargs * sizeof (gpointer));
3682 for (i = 0; i < nargs; ++i) {
3683 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
3684 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
3688 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
3691 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
3692 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
3695 args [i] = arg_buf [i];
3703 * Add an LMF frame to link the stack frames on the invoke method with our caller.
3705 /* FIXME: Move this to arch specific code */
3706 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
3707 if (invoke->has_ctx) {
3710 lmf_addr = mono_get_lmf_addr ();
3713 memset (&ext, 0, sizeof (ext));
3715 ext.lmf.previous_lmf = *(lmf_addr);
3716 /* Mark that this is a MonoLMFExt */
3717 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
3718 ext.lmf.rsp = (gssize)&ext;
3719 #elif defined(TARGET_X86)
3720 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
3721 /* Mark that this is a MonoLMFExt */
3722 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
3723 ext.lmf.ebp = (gssize)&ext;
3724 #elif defined(TARGET_ARM)
3725 ext.lmf.previous_lmf = *(lmf_addr);
3726 /* Mark that this is a MonoLMFExt */
3727 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
3728 ext.lmf.ebp = (gssize)&ext;
3730 g_assert_not_reached ();
3733 ext.debugger_invoke = TRUE;
3734 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
3736 mono_set_lmf ((MonoLMF*)&ext);
3740 if (m->klass->valuetype)
3741 res = mono_runtime_invoke (m, this_buf, args, &exc);
3743 res = mono_runtime_invoke (m, this, args, &exc);
3745 buffer_add_byte (buf, 0);
3746 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
3748 buffer_add_byte (buf, 1);
3749 if (sig->ret->type == MONO_TYPE_VOID) {
3750 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
3751 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
3754 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
3755 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
3756 buffer_add_value (buf, sig->ret, &res, domain);
3757 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
3759 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
3765 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
3766 if (invoke->has_ctx)
3767 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
3770 // FIXME: byref arguments
3778 * Invoke the method given by tls->invoke in the current thread.
3781 invoke_method (void)
3783 DebuggerTlsData *tls;
3788 static void (*restore_context) (void *);
3789 MonoContext restore_ctx;
3791 if (!restore_context)
3792 restore_context = mono_get_restore_context ();
3794 tls = TlsGetValue (debugger_tls_id);
3797 invoke = tls->invoke;
3801 tls->frames_up_to_date = FALSE;
3805 buffer_init (&buf, 128);
3807 err = do_invoke_method (&buf, invoke);
3809 /* Start suspending before sending the reply */
3812 send_reply_packet (id, err, &buf);
3816 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
3818 if (invoke->has_ctx)
3819 save_thread_context (&restore_ctx);
3828 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
3831 case CMD_VM_VERSION: {
3832 char *build_info, *version;
3834 build_info = mono_get_runtime_build_info ();
3835 version = g_strdup_printf ("mono %s", build_info);
3837 buffer_add_string (buf, version); /* vm version */
3838 buffer_add_int (buf, MAJOR_VERSION);
3839 buffer_add_int (buf, MINOR_VERSION);
3840 g_free (build_info);
3844 case CMD_VM_ALL_THREADS: {
3846 mono_loader_lock ();
3847 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
3848 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
3849 mono_loader_unlock ();
3852 case CMD_VM_SUSPEND:
3854 wait_for_suspend ();
3857 if (suspend_count == 0)
3858 return ERR_NOT_SUSPENDED;
3861 case CMD_VM_DISPOSE:
3862 /* Clear all event requests */
3863 mono_loader_lock ();
3864 while (event_requests->len > 0) {
3865 EventRequest *req = g_ptr_array_index (event_requests, 0);
3867 clear_event_request (req->id, req->event_kind);
3869 mono_loader_unlock ();
3871 // FIXME: Count resumes
3873 disconnected = TRUE;
3876 int exit_code = decode_int (p, &p, end);
3878 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
3880 /* Have to send a reply before exiting */
3881 send_reply_packet (id, 0, buf);
3883 /* Clear all event requests */
3884 mono_loader_lock ();
3885 while (event_requests->len > 0) {
3886 EventRequest *req = g_ptr_array_index (event_requests, 0);
3888 clear_event_request (req->id, req->event_kind);
3890 mono_loader_unlock ();
3892 /* FIXME: Races with normal shutdown */
3893 while (suspend_count > 0)
3897 * The JDWP documentation says that the shutdown is not orderly. It doesn't
3898 * specify whenever a VM_DEATH event is sent. We currently do an orderly
3899 * shutdown similar to Environment.Exit ().
3901 mono_runtime_set_shutting_down ();
3903 mono_threads_set_shutting_down ();
3905 /* Suspend all managed threads since the runtime is going away */
3906 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
3907 mono_thread_suspend_all_other_threads ();
3908 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
3909 mono_runtime_quit ();
3910 #ifdef PLATFORM_WIN32
3911 shutdown (conn_fd, SD_BOTH);
3913 shutdown (conn_fd, SHUT_RDWR);
3915 DEBUG(1, fprintf (log_file, "Exiting...\n"));
3919 case CMD_VM_INVOKE_METHOD: {
3920 int objid = decode_objid (p, &p, end);
3922 DebuggerTlsData *tls;
3925 err = get_object (objid, (MonoObject**)&thread);
3929 // Wait for suspending if it already started
3931 wait_for_suspend ();
3932 if (!is_suspended ())
3933 return ERR_NOT_SUSPENDED;
3935 mono_loader_lock ();
3936 tls = mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
3937 mono_loader_unlock ();
3941 * Store the invoke data into tls, the thread will execute it after it is
3946 tls->invoke = g_new0 (InvokeData, 1);
3947 tls->invoke->id = id;
3948 tls->invoke->p = g_malloc (end - p);
3949 memcpy (tls->invoke->p, p, end - p);
3950 tls->invoke->endp = tls->invoke->p + (end - p);
3956 return ERR_NOT_IMPLEMENTED;
3963 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
3968 case CMD_EVENT_REQUEST_SET: {
3970 int i, event_kind, suspend_policy, nmodifiers, mod;
3973 MonoThread *step_thread;
3974 int size, depth, step_thread_id;
3977 event_kind = decode_byte (p, &p, end);
3978 suspend_policy = decode_byte (p, &p, end);
3979 nmodifiers = decode_byte (p, &p, end);
3981 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
3982 req->id = InterlockedIncrement (&event_request_id);
3983 req->event_kind = event_kind;
3984 req->suspend_policy = suspend_policy;
3985 req->nmodifiers = nmodifiers;
3988 for (i = 0; i < nmodifiers; ++i) {
3989 mod = decode_byte (p, &p, end);
3991 req->modifiers [i].kind = mod;
3992 if (mod == MOD_KIND_COUNT) {
3993 req->modifiers [i].data.count = decode_int (p, &p, end);
3994 } else if (mod == MOD_KIND_LOCATION_ONLY) {
3995 method = decode_methodid (p, &p, end, &domain, &err);
3998 location = decode_long (p, &p, end);
3999 } else if (mod == MOD_KIND_STEP) {
4000 step_thread_id = decode_id (p, &p, end);
4001 size = decode_int (p, &p, end);
4002 depth = decode_int (p, &p, end);
4003 } else if (mod == MOD_KIND_THREAD_ONLY) {
4004 int id = decode_id (p, &p, end);
4006 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
4011 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
4012 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
4017 req->modifiers [i].data.exc_class = exc_class;
4019 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
4021 return ERR_INVALID_ARGUMENT;
4024 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
4025 int n = decode_int (p, &p, end);
4028 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
4029 for (j = 0; j < n; ++j) {
4030 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
4032 g_free (req->modifiers [i].data.assemblies);
4038 return ERR_NOT_IMPLEMENTED;
4042 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4045 req->info = set_breakpoint (method, location, req);
4046 } else if (req->event_kind == EVENT_KIND_STEP) {
4047 g_assert (step_thread_id);
4049 err = get_object (step_thread_id, (MonoObject**)&step_thread);
4055 err = ss_start (step_thread->internal_thread, size, depth, req);
4060 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
4061 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req);
4062 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
4063 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req);
4064 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
4066 if (req->nmodifiers) {
4068 return ERR_NOT_IMPLEMENTED;
4072 mono_loader_lock ();
4073 g_ptr_array_add (event_requests, req);
4074 mono_loader_unlock ();
4076 buffer_add_int (buf, req->id);
4079 case CMD_EVENT_REQUEST_CLEAR: {
4080 int etype = decode_byte (p, &p, end);
4081 int req_id = decode_int (p, &p, end);
4083 // FIXME: Make a faster mapping from req_id to request
4084 mono_loader_lock ();
4085 clear_event_request (req_id, etype);
4086 mono_loader_unlock ();
4089 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
4092 mono_loader_lock ();
4094 while (i < event_requests->len) {
4095 EventRequest *req = g_ptr_array_index (event_requests, i);
4097 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4098 clear_breakpoint (req->info);
4100 g_ptr_array_remove_index_fast (event_requests, i);
4106 mono_loader_unlock ();
4110 return ERR_NOT_IMPLEMENTED;
4117 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4123 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
4124 buffer_add_domainid (buf, mono_get_root_domain ());
4127 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
4128 domain = decode_domainid (p, &p, end, NULL, &err);
4131 buffer_add_string (buf, domain->friendly_name);
4134 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
4139 domain = decode_domainid (p, &p, end, NULL, &err);
4142 mono_loader_lock ();
4144 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4147 buffer_add_int (buf, count);
4148 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4150 buffer_add_assemblyid (buf, domain, ass);
4152 mono_loader_unlock ();
4155 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
4156 domain = decode_domainid (p, &p, end, NULL, &err);
4160 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
4163 case CMD_APPDOMAIN_GET_CORLIB: {
4164 domain = decode_domainid (p, &p, end, NULL, &err);
4168 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
4171 case CMD_APPDOMAIN_CREATE_STRING: {
4175 domain = decode_domainid (p, &p, end, NULL, &err);
4178 s = decode_string (p, &p, end);
4180 o = mono_string_new (domain, s);
4181 buffer_add_objid (buf, (MonoObject*)o);
4185 return ERR_NOT_IMPLEMENTED;
4192 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4198 ass = decode_assemblyid (p, &p, end, &domain, &err);
4203 case CMD_ASSEMBLY_GET_LOCATION: {
4204 buffer_add_string (buf, mono_image_get_filename (ass->image));
4207 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
4211 if (ass->image->dynamic) {
4212 buffer_add_id (buf, 0);
4214 token = mono_image_get_entry_point (ass->image);
4216 buffer_add_id (buf, 0);
4218 m = mono_get_method (ass->image, token, NULL);
4219 buffer_add_methodid (buf, domain, m);
4224 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
4225 buffer_add_moduleid (buf, domain, ass->image);
4228 case CMD_ASSEMBLY_GET_OBJECT: {
4229 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
4230 buffer_add_objid (buf, o);
4233 case CMD_ASSEMBLY_GET_TYPE: {
4234 char *s = decode_string (p, &p, end);
4235 gboolean ignorecase = decode_byte (p, &p, end);
4236 MonoTypeNameParse info;
4238 gboolean type_resolve;
4240 if (!mono_reflection_parse_type (s, &info)) {
4243 if (info.assembly.name)
4245 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
4247 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
4248 mono_reflection_free_type_info (&info);
4254 return ERR_NOT_IMPLEMENTED;
4261 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4267 case CMD_MODULE_GET_INFO: {
4268 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
4271 basename = g_path_get_basename (image->name);
4272 buffer_add_string (buf, basename); // name
4273 buffer_add_string (buf, image->module_name); // scopename
4274 buffer_add_string (buf, image->name); // fqname
4275 buffer_add_string (buf, mono_image_get_guid (image)); // guid
4276 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
4281 return ERR_NOT_IMPLEMENTED;
4288 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
4290 if (val && val->vtable->klass == mono_defaults.monotype_class) {
4291 /* Special case these so the client doesn't have to handle Type objects */
4293 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
4294 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
4295 } else if (MONO_TYPE_IS_REFERENCE (t))
4296 buffer_add_value (buf, t, &val, domain);
4298 buffer_add_value (buf, t, mono_object_unbox (val), domain);
4302 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
4308 buffer_add_int (buf, 0);
4312 for (i = 0; i < cinfo->num_attrs; ++i) {
4313 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
4316 buffer_add_int (buf, nattrs);
4318 for (i = 0; i < cinfo->num_attrs; ++i) {
4319 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
4320 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
4321 MonoArray *typed_args, *named_args;
4323 CattrNamedArg *arginfo;
4325 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
4327 buffer_add_methodid (buf, domain, attr->ctor);
4331 buffer_add_int (buf, mono_array_length (typed_args));
4332 for (j = 0; j < mono_array_length (typed_args); ++j) {
4333 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
4335 t = mono_method_signature (attr->ctor)->params [j];
4337 buffer_add_cattr_arg (buf, t, domain, val);
4340 buffer_add_int (buf, 0);
4345 buffer_add_int (buf, mono_array_length (named_args));
4347 for (j = 0; j < mono_array_length (named_args); ++j) {
4348 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
4350 if (arginfo [j].prop) {
4351 buffer_add_byte (buf, 0x54);
4352 buffer_add_propertyid (buf, domain, arginfo [j].prop);
4353 } else if (arginfo [j].field) {
4354 buffer_add_byte (buf, 0x53);
4356 g_assert_not_reached ();
4359 buffer_add_cattr_arg (buf, t, domain, val);
4362 buffer_add_int (buf, 0);
4369 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4380 klass = decode_typeid (p, &p, end, &domain, &err);
4385 case CMD_TYPE_GET_INFO: {
4386 buffer_add_string (buf, klass->name_space);
4387 buffer_add_string (buf, klass->name);
4389 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
4390 buffer_add_string (buf, name);
4392 buffer_add_assemblyid (buf, domain, klass->image->assembly);
4393 buffer_add_moduleid (buf, domain, klass->image);
4394 buffer_add_typeid (buf, domain, klass->parent);
4395 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
4396 buffer_add_typeid (buf, domain, klass->element_class);
4398 buffer_add_id (buf, 0);
4399 buffer_add_int (buf, klass->type_token);
4400 buffer_add_byte (buf, klass->rank);
4401 buffer_add_int (buf, klass->flags);
4403 type = &klass->byval_arg;
4404 // FIXME: Can't decide whenever a class represents a byref type
4407 if (type->type == MONO_TYPE_PTR)
4409 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
4411 if (type->type == MONO_TYPE_VALUETYPE)
4413 buffer_add_byte (buf, b);
4416 while ((nested = mono_class_get_nested_types (klass, &iter)))
4418 buffer_add_int (buf, nnested);
4420 while ((nested = mono_class_get_nested_types (klass, &iter)))
4421 buffer_add_typeid (buf, domain, nested);
4424 case CMD_TYPE_GET_METHODS: {
4427 gpointer iter = NULL;
4430 nmethods = mono_class_num_methods (klass);
4432 buffer_add_int (buf, nmethods);
4434 while ((m = mono_class_get_methods (klass, &iter))) {
4435 buffer_add_methodid (buf, domain, m);
4438 g_assert (i == nmethods);
4441 case CMD_TYPE_GET_FIELDS: {
4444 gpointer iter = NULL;
4447 nfields = mono_class_num_fields (klass);
4449 buffer_add_int (buf, nfields);
4451 while ((f = mono_class_get_fields (klass, &iter))) {
4452 buffer_add_fieldid (buf, domain, f);
4453 buffer_add_string (buf, f->name);
4454 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
4455 buffer_add_int (buf, f->type->attrs);
4458 g_assert (i == nfields);
4461 case CMD_TYPE_GET_PROPERTIES: {
4464 gpointer iter = NULL;
4467 nprops = mono_class_num_properties (klass);
4469 buffer_add_int (buf, nprops);
4471 while ((p = mono_class_get_properties (klass, &iter))) {
4472 buffer_add_propertyid (buf, domain, p);
4473 buffer_add_string (buf, p->name);
4474 buffer_add_methodid (buf, domain, p->get);
4475 buffer_add_methodid (buf, domain, p->set);
4476 buffer_add_int (buf, p->attrs);
4479 g_assert (i == nprops);
4482 case CMD_TYPE_GET_CATTRS: {
4483 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
4484 MonoCustomAttrInfo *cinfo;
4486 cinfo = mono_custom_attrs_from_class (klass);
4488 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
4491 case CMD_TYPE_GET_FIELD_CATTRS: {
4492 MonoClass *attr_klass;
4493 MonoCustomAttrInfo *cinfo;
4494 MonoClassField *field;
4496 field = decode_fieldid (p, &p, end, NULL, &err);
4499 attr_klass = decode_typeid (p, &p, end, NULL, &err);
4503 cinfo = mono_custom_attrs_from_field (klass, field);
4505 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
4508 case CMD_TYPE_GET_PROPERTY_CATTRS: {
4509 MonoClass *attr_klass;
4510 MonoCustomAttrInfo *cinfo;
4513 prop = decode_propertyid (p, &p, end, NULL, &err);
4516 attr_klass = decode_typeid (p, &p, end, NULL, &err);
4520 cinfo = mono_custom_attrs_from_property (klass, prop);
4522 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
4525 case CMD_TYPE_GET_VALUES: {
4533 len = decode_int (p, &p, end);
4534 for (i = 0; i < len; ++i) {
4535 f = decode_fieldid (p, &p, end, NULL, &err);
4539 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
4540 return ERR_INVALID_FIELDID;
4541 if (mono_class_field_is_special_static (f))
4542 return ERR_INVALID_FIELDID;
4544 /* Check that the field belongs to the object */
4546 for (k = klass; k; k = k->parent) {
4547 if (k == f->parent) {
4553 return ERR_INVALID_FIELDID;
4555 vtable = mono_class_vtable (domain, f->parent);
4556 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
4557 mono_field_static_get_value (vtable, f, val);
4558 buffer_add_value (buf, f->type, val, domain);
4563 case CMD_TYPE_SET_VALUES: {
4571 len = decode_int (p, &p, end);
4572 for (i = 0; i < len; ++i) {
4573 f = decode_fieldid (p, &p, end, NULL, &err);
4577 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
4578 return ERR_INVALID_FIELDID;
4579 if (mono_class_field_is_special_static (f))
4580 return ERR_INVALID_FIELDID;
4582 /* Check that the field belongs to the object */
4584 for (k = klass; k; k = k->parent) {
4585 if (k == f->parent) {
4591 return ERR_INVALID_FIELDID;
4593 // FIXME: Check for literal/const
4595 vtable = mono_class_vtable (domain, f->parent);
4596 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
4597 err = decode_value (f->type, domain, val, p, &p, end);
4602 mono_field_static_set_value (vtable, f, val);
4607 case CMD_TYPE_GET_OBJECT: {
4608 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
4609 buffer_add_objid (buf, o);
4612 case CMD_TYPE_GET_SOURCE_FILES: {
4613 gpointer iter = NULL;
4615 char *source_file, *base;
4619 files = g_ptr_array_new ();
4621 while ((method = mono_class_get_methods (klass, &iter))) {
4622 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
4625 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
4627 for (i = 0; i < files->len; ++i)
4628 if (!strcmp (g_ptr_array_index (files, i), source_file))
4630 if (i == files->len)
4631 g_ptr_array_add (files, g_strdup (source_file));
4632 g_free (source_file);
4636 buffer_add_int (buf, files->len);
4637 for (i = 0; i < files->len; ++i) {
4638 source_file = g_ptr_array_index (files, i);
4639 base = g_path_get_basename (source_file);
4640 buffer_add_string (buf, base);
4642 g_free (source_file);
4644 g_ptr_array_free (files, TRUE);
4647 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
4648 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
4652 if (mono_class_is_assignable_from (klass, oklass))
4653 buffer_add_byte (buf, 1);
4655 buffer_add_byte (buf, 0);
4659 return ERR_NOT_IMPLEMENTED;
4666 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4671 MonoMethodHeader *header;
4673 method = decode_methodid (p, &p, end, &domain, &err);
4678 case CMD_METHOD_GET_NAME: {
4679 buffer_add_string (buf, method->name);
4682 case CMD_METHOD_GET_DECLARING_TYPE: {
4683 buffer_add_typeid (buf, domain, method->klass);
4686 case CMD_METHOD_GET_DEBUG_INFO: {
4687 MonoDebugMethodInfo *minfo;
4689 int i, n_il_offsets;
4693 header = mono_method_get_header (method);
4695 buffer_add_int (buf, 0);
4696 buffer_add_string (buf, "");
4697 buffer_add_int (buf, 0);
4701 minfo = mono_debug_lookup_method (method);
4703 buffer_add_int (buf, header->code_size);
4704 buffer_add_string (buf, "");
4705 buffer_add_int (buf, 0);
4709 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
4710 buffer_add_int (buf, header->code_size);
4711 buffer_add_string (buf, source_file);
4712 buffer_add_int (buf, n_il_offsets);
4713 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
4714 for (i = 0; i < n_il_offsets; ++i) {
4715 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
4716 buffer_add_int (buf, il_offsets [i]);
4717 buffer_add_int (buf, line_numbers [i]);
4719 g_free (source_file);
4720 g_free (il_offsets);
4721 g_free (line_numbers);
4724 case CMD_METHOD_GET_PARAM_INFO: {
4725 MonoMethodSignature *sig = mono_method_signature (method);
4729 /* FIXME: mono_class_from_mono_type () and byrefs */
4731 /* FIXME: Use a smaller encoding */
4732 buffer_add_int (buf, sig->call_convention);
4733 buffer_add_int (buf, sig->param_count);
4734 buffer_add_int (buf, sig->generic_param_count);
4735 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
4736 for (i = 0; i < sig->param_count; ++i) {
4738 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
4741 /* Emit parameter names */
4742 names = g_new (char *, sig->param_count);
4743 mono_method_get_param_names (method, (const char **) names);
4744 for (i = 0; i < sig->param_count; ++i)
4745 buffer_add_string (buf, names [i]);
4750 case CMD_METHOD_GET_LOCALS_INFO: {
4751 int i, j, num_locals;
4755 header = mono_method_get_header (method);
4758 buffer_add_int (buf, header->num_locals);
4761 for (i = 0; i < header->num_locals; ++i)
4762 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
4765 num_locals = mono_debug_lookup_locals (method, &local_names, &local_indexes);
4766 for (i = 0; i < header->num_locals; ++i) {
4767 for (j = 0; j < num_locals; ++j)
4768 if (local_indexes [j] == i)
4771 buffer_add_string (buf, local_names [j]);
4773 buffer_add_string (buf, "");
4775 g_free (local_names);
4776 g_free (local_indexes);
4779 /* FIXME: This works because we set debug_options.mdb_optimizations */
4780 for (i = 0; i < header->num_locals; ++i) {
4781 buffer_add_int (buf, 0);
4782 buffer_add_int (buf, header->code_size);
4787 case CMD_METHOD_GET_INFO:
4788 buffer_add_int (buf, method->flags);
4789 buffer_add_int (buf, method->iflags);
4790 buffer_add_int (buf, method->token);
4792 case CMD_METHOD_GET_BODY: {
4795 header = mono_method_get_header (method);
4797 buffer_add_int (buf, 0);
4799 buffer_add_int (buf, header->code_size);
4800 for (i = 0; i < header->code_size; ++i)
4801 buffer_add_byte (buf, header->code [i]);
4805 case CMD_METHOD_RESOLVE_TOKEN: {
4806 guint32 token = decode_int (p, &p, end);
4809 switch (mono_metadata_token_code (token)) {
4810 case MONO_TOKEN_STRING: {
4814 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
4817 s2 = mono_string_to_utf8 (s);
4819 buffer_add_byte (buf, TOKEN_TYPE_STRING);
4820 buffer_add_string (buf, s2);
4826 MonoClass *handle_class;
4828 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
4829 val = mono_method_get_wrapper_data (method, token);
4830 handle_class = mono_method_get_wrapper_data (method, token + 1);
4832 if (handle_class == NULL) {
4833 // Can't figure out the token type
4834 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
4838 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
4842 if (handle_class == mono_defaults.typehandle_class) {
4843 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
4844 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
4845 } else if (handle_class == mono_defaults.fieldhandle_class) {
4846 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
4847 buffer_add_fieldid (buf, domain, val);
4848 } else if (handle_class == mono_defaults.methodhandle_class) {
4849 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
4850 buffer_add_methodid (buf, domain, val);
4851 } else if (handle_class == mono_defaults.string_class) {
4854 s = mono_string_to_utf8 (val);
4855 buffer_add_byte (buf, TOKEN_TYPE_STRING);
4856 buffer_add_string (buf, s);
4859 g_assert_not_reached ();
4867 return ERR_NOT_IMPLEMENTED;
4874 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4876 int objid = decode_objid (p, &p, end);
4878 MonoThread *thread_obj;
4879 MonoInternalThread *thread;
4881 err = get_object (objid, (MonoObject**)&thread_obj);
4885 thread = thread_obj->internal_thread;
4888 case CMD_THREAD_GET_NAME: {
4890 gunichar2 *s = mono_thread_get_name (thread, &name_len);
4893 buffer_add_int (buf, 0);
4898 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
4900 buffer_add_int (buf, len);
4901 buffer_add_data (buf, (guint8*)name, len);
4906 case CMD_THREAD_GET_FRAME_INFO: {
4907 DebuggerTlsData *tls;
4908 int i, start_frame, length;
4910 // Wait for suspending if it already started
4912 wait_for_suspend ();
4913 if (!is_suspended ())
4914 return ERR_NOT_SUSPENDED;
4916 start_frame = decode_int (p, &p, end);
4917 length = decode_int (p, &p, end);
4919 if (start_frame != 0 || length != -1)
4920 return ERR_NOT_IMPLEMENTED;
4922 mono_loader_lock ();
4923 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4924 mono_loader_unlock ();
4927 compute_frame_info (thread, tls);
4929 buffer_add_int (buf, tls->frame_count);
4930 for (i = 0; i < tls->frame_count; ++i) {
4931 buffer_add_int (buf, tls->frames [i]->id);
4932 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->method);
4933 buffer_add_int (buf, tls->frames [i]->il_offset);
4935 * Instead of passing the frame type directly to the client, we associate
4936 * it with the previous frame using a set of flags. This avoids lots of
4937 * conditional code in the client, since a frame whose type isn't
4938 * FRAME_TYPE_MANAGED has no method, location, etc.
4940 buffer_add_byte (buf, tls->frames [i]->flags);
4945 case CMD_THREAD_GET_STATE:
4946 buffer_add_int (buf, thread->state);
4948 case CMD_THREAD_GET_INFO:
4949 buffer_add_byte (buf, thread->threadpool_thread);
4952 return ERR_NOT_IMPLEMENTED;
4959 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4963 MonoThread *thread_obj;
4964 MonoInternalThread *thread;
4966 DebuggerTlsData *tls;
4968 MonoDebugMethodJitInfo *jit;
4969 MonoDebugVarInfo *var;
4970 MonoMethodSignature *sig;
4972 MonoMethodHeader *header;
4974 objid = decode_objid (p, &p, end);
4975 err = get_object (objid, (MonoObject**)&thread_obj);
4979 thread = thread_obj->internal_thread;
4981 id = decode_id (p, &p, end);
4983 mono_loader_lock ();
4984 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4985 mono_loader_unlock ();
4988 for (i = 0; i < tls->frame_count; ++i) {
4989 if (tls->frames [i]->id == id)
4992 if (i == tls->frame_count)
4993 return ERR_INVALID_FRAMEID;
4995 frame = tls->frames [i];
4998 frame->jit = mono_debug_find_method (frame->method, frame->domain);
4999 g_assert (frame->jit);
5003 sig = mono_method_signature (frame->method);
5006 case CMD_STACK_FRAME_GET_VALUES: {
5007 len = decode_int (p, &p, end);
5008 header = mono_method_get_header (frame->method);
5010 for (i = 0; i < len; ++i) {
5011 pos = decode_int (p, &p, end);
5016 g_assert (pos >= 0 && pos < jit->num_params);
5018 var = &jit->params [pos];
5020 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain);
5022 g_assert (pos >= 0 && pos < jit->num_locals);
5024 var = &jit->locals [pos];
5026 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain);
5031 case CMD_STACK_FRAME_GET_THIS: {
5032 if (frame->method->klass->valuetype) {
5033 if (!sig->hasthis) {
5034 MonoObject *p = NULL;
5035 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
5037 add_var (buf, &frame->method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain);
5040 if (!sig->hasthis) {
5041 MonoObject *p = NULL;
5042 buffer_add_value (buf, &frame->method->klass->byval_arg, &p, frame->domain);
5044 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain);
5049 case CMD_STACK_FRAME_SET_VALUES: {
5052 MonoDebugVarInfo *var;
5054 len = decode_int (p, &p, end);
5055 header = mono_method_get_header (frame->method);
5057 for (i = 0; i < len; ++i) {
5058 pos = decode_int (p, &p, end);
5063 g_assert (pos >= 0 && pos < jit->num_params);
5065 t = sig->params [pos];
5066 var = &jit->params [pos];
5068 g_assert (pos >= 0 && pos < jit->num_locals);
5070 t = header->locals [pos];
5071 var = &jit->locals [pos];
5074 if (MONO_TYPE_IS_REFERENCE (t))
5075 val_buf = g_alloca (sizeof (MonoObject*));
5077 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
5078 err = decode_value (t, frame->domain, val_buf, p, &p, end);
5082 set_var (t, var, &frame->ctx, frame->domain, val_buf);
5087 return ERR_NOT_IMPLEMENTED;
5094 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5097 int objid, err, index, len, i, esize;
5100 objid = decode_objid (p, &p, end);
5101 err = get_object (objid, (MonoObject**)&arr);
5106 case CMD_ARRAY_REF_GET_LENGTH:
5107 buffer_add_int (buf, arr->obj.vtable->klass->rank);
5109 buffer_add_int (buf, arr->max_length);
5110 buffer_add_int (buf, 0);
5112 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
5113 buffer_add_int (buf, arr->bounds [i].length);
5114 buffer_add_int (buf, arr->bounds [i].lower_bound);
5118 case CMD_ARRAY_REF_GET_VALUES:
5119 index = decode_int (p, &p, end);
5120 len = decode_int (p, &p, end);
5122 g_assert (index >= 0 && len >= 0);
5123 // Reordered to avoid integer overflow
5124 g_assert (!(index > arr->max_length - len));
5126 esize = mono_array_element_size (arr->obj.vtable->klass);
5127 for (i = index; i < index + len; ++i) {
5128 elem = (gpointer*)((char*)arr->vector + (i * esize));
5129 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
5132 case CMD_ARRAY_REF_SET_VALUES:
5133 index = decode_int (p, &p, end);
5134 len = decode_int (p, &p, end);
5136 g_assert (index >= 0 && len >= 0);
5137 // Reordered to avoid integer overflow
5138 g_assert (!(index > arr->max_length - len));
5140 esize = mono_array_element_size (arr->obj.vtable->klass);
5141 for (i = index; i < index + len; ++i) {
5142 elem = (gpointer*)((char*)arr->vector + (i * esize));
5144 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
5148 return ERR_NOT_IMPLEMENTED;
5155 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5161 objid = decode_objid (p, &p, end);
5162 err = get_object (objid, (MonoObject**)&str);
5167 case CMD_STRING_REF_GET_VALUE:
5168 s = mono_string_to_utf8 (str);
5169 buffer_add_string (buf, s);
5173 return ERR_NOT_IMPLEMENTED;
5180 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5189 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
5190 objid = decode_objid (p, &p, end);
5191 err = get_object (objid, &obj);
5193 buffer_add_int (buf, 1);
5195 buffer_add_int (buf, 0);
5199 objid = decode_objid (p, &p, end);
5200 err = get_object (objid, &obj);
5205 case CMD_OBJECT_REF_GET_TYPE:
5206 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
5208 case CMD_OBJECT_REF_GET_VALUES:
5209 len = decode_int (p, &p, end);
5211 for (i = 0; i < len; ++i) {
5212 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
5216 /* Check that the field belongs to the object */
5218 for (k = obj->vtable->klass; k; k = k->parent) {
5219 if (k == f->parent) {
5225 return ERR_INVALID_FIELDID;
5227 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
5231 if (mono_class_field_is_special_static (f))
5232 return ERR_INVALID_FIELDID;
5234 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
5235 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
5236 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5237 mono_field_static_get_value (vtable, f, val);
5238 buffer_add_value (buf, f->type, val, obj->vtable->domain);
5241 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
5245 case CMD_OBJECT_REF_SET_VALUES:
5246 len = decode_int (p, &p, end);
5248 for (i = 0; i < len; ++i) {
5249 f = decode_fieldid (p, &p, end, NULL, &err);
5253 /* Check that the field belongs to the object */
5255 for (k = obj->vtable->klass; k; k = k->parent) {
5256 if (k == f->parent) {
5262 return ERR_INVALID_FIELDID;
5264 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
5268 if (mono_class_field_is_special_static (f))
5269 return ERR_INVALID_FIELDID;
5271 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
5272 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
5274 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5275 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
5280 mono_field_static_set_value (vtable, f, val);
5283 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
5289 case CMD_OBJECT_REF_GET_ADDRESS:
5290 buffer_add_long (buf, (gssize)obj);
5292 case CMD_OBJECT_REF_GET_DOMAIN:
5293 buffer_add_domainid (buf, obj->vtable->domain);
5296 return ERR_NOT_IMPLEMENTED;
5303 command_set_to_string (CommandSet command_set)
5305 switch (command_set) {
5308 case CMD_SET_OBJECT_REF:
5309 return "OBJECT_REF";
5310 case CMD_SET_STRING_REF:
5311 return "STRING_REF";
5312 case CMD_SET_THREAD:
5314 case CMD_SET_ARRAY_REF:
5316 case CMD_SET_EVENT_REQUEST:
5317 return "EVENT_REQUEST";
5318 case CMD_SET_STACK_FRAME:
5319 return "STACK_FRAME";
5320 case CMD_SET_APPDOMAIN:
5322 case CMD_SET_ASSEMBLY:
5324 case CMD_SET_METHOD:
5328 case CMD_SET_MODULE:
5340 * This thread handles communication with the debugger client using a JDWP
5343 static guint32 WINAPI
5344 debugger_thread (void *arg)
5346 int res, len, id, flags, command_set, command;
5347 guint8 header [HEADER_LENGTH];
5348 guint8 *data, *p, *end;
5353 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
5355 debugger_thread_id = GetCurrentThreadId ();
5357 mono_jit_thread_attach (mono_get_root_domain ());
5359 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
5361 mono_set_is_debugger_attached (TRUE);
5364 res = read (conn_fd, header, HEADER_LENGTH);
5366 /* This will break if the socket is closed during shutdown too */
5367 if (res != HEADER_LENGTH)
5371 end = header + HEADER_LENGTH;
5373 len = decode_int (p, &p, end);
5374 id = decode_int (p, &p, end);
5375 flags = decode_byte (p, &p, end);
5376 command_set = decode_byte (p, &p, end);
5377 command = decode_byte (p, &p, end);
5379 g_assert (flags == 0);
5381 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%d), id=%d.\n", command_set_to_string (command_set), command, id));
5383 data = g_malloc (len - HEADER_LENGTH);
5384 res = read (conn_fd, data, len - HEADER_LENGTH);
5385 if (res != len - HEADER_LENGTH)
5389 end = data + (len - HEADER_LENGTH);
5391 buffer_init (&buf, 128);
5396 /* Process the request */
5397 switch (command_set) {
5399 err = vm_commands (command, id, p, end, &buf);
5400 if (!err && command == CMD_VM_INVOKE_METHOD)
5401 /* Sent after the invoke is complete */
5404 case CMD_SET_EVENT_REQUEST:
5405 err = event_commands (command, p, end, &buf);
5407 case CMD_SET_APPDOMAIN:
5408 err = domain_commands (command, p, end, &buf);
5410 case CMD_SET_ASSEMBLY:
5411 err = assembly_commands (command, p, end, &buf);
5413 case CMD_SET_MODULE:
5414 err = module_commands (command, p, end, &buf);
5417 err = type_commands (command, p, end, &buf);
5419 case CMD_SET_METHOD:
5420 err = method_commands (command, p, end, &buf);
5422 case CMD_SET_THREAD:
5423 err = thread_commands (command, p, end, &buf);
5425 case CMD_SET_STACK_FRAME:
5426 err = frame_commands (command, p, end, &buf);
5428 case CMD_SET_ARRAY_REF:
5429 err = array_commands (command, p, end, &buf);
5431 case CMD_SET_STRING_REF:
5432 err = string_commands (command, p, end, &buf);
5434 case CMD_SET_OBJECT_REF:
5435 err = object_commands (command, p, end, &buf);
5438 err = ERR_NOT_IMPLEMENTED;
5442 send_reply_packet (id, err, &buf);
5447 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
5451 mono_set_is_debugger_attached (FALSE);
5453 mono_mutex_lock (&debugger_thread_exited_mutex);
5454 debugger_thread_exited = TRUE;
5455 mono_cond_signal (&debugger_thread_exited_cond);
5456 mono_mutex_unlock (&debugger_thread_exited_mutex);
5458 #ifdef PLATFORM_WIN32
5459 shutdown (conn_fd, SD_BOTH);
5461 shutdown (conn_fd, SHUT_RDWR);
5467 #else /* DISABLE_DEBUGGER_AGENT */
5470 mono_debugger_agent_parse_options (char *options)
5472 g_error ("This runtime is configure with the debugger agent disabled.");
5476 mono_debugger_agent_init (void)
5481 mono_debugger_agent_cleanup (void)
5486 mono_debugger_agent_breakpoint_hit (void *sigctx)
5491 mono_debugger_agent_single_step_event (void *sigctx)
5496 mono_debugger_agent_free_domain_info (MonoDomain *domain)
5500 gboolean mono_debugger_agent_thread_interrupt (MonoJitInfo *ji)
5505 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *ctx)