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 #ifdef HAVE_UCONTEXT_H
43 #ifdef PLATFORM_ANDROID
45 #include <linux/tcp.h>
46 #include <sys/endian.h>
49 #include <mono/metadata/mono-debug.h>
50 #include <mono/metadata/mono-debug-debugger.h>
51 #include <mono/metadata/debug-mono-symfile.h>
52 #include <mono/metadata/gc-internal.h>
53 #include <mono/metadata/threads-types.h>
54 #include <mono/utils/mono-semaphore.h>
55 #include "debugger-agent.h"
58 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
59 #define DISABLE_DEBUGGER_AGENT 1
62 #ifndef DISABLE_DEBUGGER_AGENT
63 #include <mono/io-layer/mono-mutex.h>
86 MonoDebugMethodJitInfo *jit;
95 /* This is the context which needs to be restored after the invoke */
104 gboolean has_context;
105 gpointer resume_event;
106 /* This is computed on demand when it is requested using the wire protocol */
107 /* It is freed up when the thread is resumed */
111 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
114 gboolean frames_up_to_date;
116 * Points to data about a pending invoke which needs to be executed after the thread
121 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
125 /* Used to pass the context to the breakpoint/single step handler */
126 MonoContext handler_ctx;
127 /* Whenever thread_stop () was called for this thread */
130 /* Number of thread interruptions not yet processed */
131 gint32 interrupt_count;
133 /* Whenever to disable breakpoints (used during invokes) */
134 gboolean disable_breakpoints;
138 * Wire Protocol definitions
141 #define HEADER_LENGTH 11
143 #define MAJOR_VERSION 1
144 #define MINOR_VERSION 0
148 CMD_SET_OBJECT_REF = 9,
149 CMD_SET_STRING_REF = 10,
151 CMD_SET_ARRAY_REF = 13,
152 CMD_SET_EVENT_REQUEST = 15,
153 CMD_SET_STACK_FRAME = 16,
154 CMD_SET_APPDOMAIN = 20,
155 CMD_SET_ASSEMBLY = 21,
163 EVENT_KIND_VM_START = 0,
164 EVENT_KIND_VM_DEATH = 1,
165 EVENT_KIND_THREAD_START = 2,
166 EVENT_KIND_THREAD_DEATH = 3,
167 EVENT_KIND_APPDOMAIN_CREATE = 4,
168 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
169 EVENT_KIND_METHOD_ENTRY = 6,
170 EVENT_KIND_METHOD_EXIT = 7,
171 EVENT_KIND_ASSEMBLY_LOAD = 8,
172 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
173 EVENT_KIND_BREAKPOINT = 10,
174 EVENT_KIND_STEP = 11,
175 EVENT_KIND_TYPE_LOAD = 12,
176 EVENT_KIND_EXCEPTION = 13
180 SUSPEND_POLICY_NONE = 0,
181 SUSPEND_POLICY_EVENT_THREAD = 1,
182 SUSPEND_POLICY_ALL = 2
187 ERR_INVALID_OBJECT = 20,
188 ERR_INVALID_FIELDID = 25,
189 ERR_INVALID_FRAMEID = 30,
190 ERR_NOT_IMPLEMENTED = 100,
191 ERR_NOT_SUSPENDED = 101,
192 ERR_INVALID_ARGUMENT = 102,
198 MOD_KIND_THREAD_ONLY = 3,
199 MOD_KIND_LOCATION_ONLY = 7,
200 MOD_KIND_EXCEPTION_ONLY = 8,
202 MOD_KIND_ASSEMBLY_ONLY = 11
217 TOKEN_TYPE_STRING = 0,
219 TOKEN_TYPE_FIELD = 2,
220 TOKEN_TYPE_METHOD = 3,
221 TOKEN_TYPE_UNKNOWN = 4
225 VALUE_TYPE_ID_NULL = 0xf0,
226 VALUE_TYPE_ID_TYPE = 0xf1
230 FRAME_FLAG_DEBUGGER_INVOKE = 1
234 INVOKE_FLAG_DISABLE_BPS = 1
239 CMD_VM_ALL_THREADS = 2,
244 CMD_VM_INVOKE_METHOD = 7
248 CMD_THREAD_GET_FRAME_INFO = 1,
249 CMD_THREAD_GET_NAME = 2,
250 CMD_THREAD_GET_STATE = 3,
251 CMD_THREAD_GET_INFO = 4
255 CMD_EVENT_REQUEST_SET = 1,
256 CMD_EVENT_REQUEST_CLEAR = 2,
257 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
265 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
266 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
267 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
268 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
269 CMD_APPDOMAIN_CREATE_STRING = 5,
270 CMD_APPDOMAIN_GET_CORLIB = 6
274 CMD_ASSEMBLY_GET_LOCATION = 1,
275 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
276 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
277 CMD_ASSEMBLY_GET_OBJECT = 4,
278 CMD_ASSEMBLY_GET_TYPE = 5,
282 CMD_MODULE_GET_INFO = 1,
286 CMD_METHOD_GET_NAME = 1,
287 CMD_METHOD_GET_DECLARING_TYPE = 2,
288 CMD_METHOD_GET_DEBUG_INFO = 3,
289 CMD_METHOD_GET_PARAM_INFO = 4,
290 CMD_METHOD_GET_LOCALS_INFO = 5,
291 CMD_METHOD_GET_INFO = 6,
292 CMD_METHOD_GET_BODY = 7,
293 CMD_METHOD_RESOLVE_TOKEN = 8,
297 CMD_TYPE_GET_INFO = 1,
298 CMD_TYPE_GET_METHODS = 2,
299 CMD_TYPE_GET_FIELDS = 3,
300 CMD_TYPE_GET_VALUES = 4,
301 CMD_TYPE_GET_OBJECT = 5,
302 CMD_TYPE_GET_SOURCE_FILES = 6,
303 CMD_TYPE_SET_VALUES = 7,
304 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
305 CMD_TYPE_GET_PROPERTIES = 9,
306 CMD_TYPE_GET_CATTRS = 10,
307 CMD_TYPE_GET_FIELD_CATTRS = 11,
308 CMD_TYPE_GET_PROPERTY_CATTRS = 12
312 CMD_STACK_FRAME_GET_VALUES = 1,
313 CMD_STACK_FRAME_GET_THIS = 2,
314 CMD_STACK_FRAME_SET_VALUES = 3
318 CMD_ARRAY_REF_GET_LENGTH = 1,
319 CMD_ARRAY_REF_GET_VALUES = 2,
320 CMD_ARRAY_REF_SET_VALUES = 3,
324 CMD_STRING_REF_GET_VALUE = 1,
328 CMD_OBJECT_REF_GET_TYPE = 1,
329 CMD_OBJECT_REF_GET_VALUES = 2,
330 CMD_OBJECT_REF_IS_COLLECTED = 3,
331 CMD_OBJECT_REF_GET_ADDRESS = 4,
332 CMD_OBJECT_REF_GET_DOMAIN = 5,
333 CMD_OBJECT_REF_SET_VALUES = 6
339 int count; /* For kind == MOD_KIND_COUNT */
340 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
341 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
342 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
352 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
356 * Describes a single step request.
360 MonoInternalThread *thread;
365 MonoMethod *last_method;
369 /* Dummy structure used for the profiler callbacks */
374 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
380 static AgentConfig agent_config;
383 * Whenever the agent is fully initialized.
384 * When using the onuncaught or onthrow options, only some parts of the agent are
385 * initialized on startup, and the full initialization which includes connection
386 * establishment and the startup of the agent thread is only done in response to
389 static gint32 inited;
393 static int packet_id = 0;
395 static int objref_id = 0;
397 static int event_request_id = 0;
399 static int frame_id = 0;
401 static GPtrArray *event_requests;
403 static guint32 debugger_tls_id;
405 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
407 /* Maps MonoInternalThread -> DebuggerTlsData */
408 static MonoGHashTable *thread_to_tls;
410 /* Maps tid -> MonoInternalThread */
411 static MonoGHashTable *tid_to_thread;
413 /* Maps tid -> MonoThread (not MonoInternalThread) */
414 static MonoGHashTable *tid_to_thread_obj;
416 static gsize debugger_thread_id;
418 static HANDLE debugger_thread_handle;
420 static int log_level;
422 static FILE *log_file;
424 /* Classes whose class load event has been sent */
425 static GHashTable *loaded_classes;
427 /* Assemblies whose assembly load event has no been sent yet */
428 static GPtrArray *pending_assembly_loads;
430 /* Whenever the debugger thread has exited */
431 static gboolean debugger_thread_exited;
433 /* Cond variable used to wait for debugger_thread_exited becoming true */
434 static mono_cond_t debugger_thread_exited_cond = MONO_COND_INITIALIZER;
436 /* Mutex for the cond var above */
437 static mono_mutex_t debugger_thread_exited_mutex = MONO_MUTEX_INITIALIZER;
439 static DebuggerProfiler debugger_profiler;
441 /* The single step request instance */
442 static MonoSingleStepReq *ss_req = NULL;
444 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
445 /* Number of single stepping operations in progress */
449 static void transport_connect (const char *host, int port);
451 static guint32 WINAPI debugger_thread (void *arg);
453 static void runtime_initialized (MonoProfiler *prof);
455 static void runtime_shutdown (MonoProfiler *prof);
457 static void thread_startup (MonoProfiler *prof, gsize tid);
459 static void thread_end (MonoProfiler *prof, gsize tid);
461 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
463 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
465 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
467 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
469 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
471 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
473 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
475 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
477 static void start_single_stepping (void);
479 static void stop_single_stepping (void);
481 static void suspend_current (void);
483 /* Submodule init/cleanup */
484 static void breakpoints_init (void);
485 static void breakpoints_cleanup (void);
487 static void objrefs_init (void);
488 static void objrefs_cleanup (void);
490 static void ids_init (void);
491 static void ids_cleanup (void);
493 static void suspend_init (void);
495 static ErrorCode ss_start (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
496 static void ss_stop (EventRequest *req);
498 static void start_debugger_thread (void);
500 static void finish_agent_init (gboolean on_startup);
503 parse_address (char *address, char **host, int *port)
505 char *pos = strchr (address, ':');
507 if (pos == NULL || pos == address)
510 *host = g_malloc (pos - address + 1);
511 strncpy (*host, address, pos - address);
512 (*host) [pos - address] = '\0';
514 *port = atoi (pos + 1);
522 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
523 fprintf (stderr, "Available options:\n");
524 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
525 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
526 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
527 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
528 fprintf (stderr, " suspend=y/n\t\t\tWhenever to suspend after startup.\n");
529 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
530 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
534 parse_flag (const char *option, char *flag)
536 if (!strcmp (flag, "y"))
538 else if (!strcmp (flag, "n"))
541 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
548 mono_debugger_agent_parse_options (char *options)
554 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
555 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
559 agent_config.enabled = TRUE;
560 agent_config.suspend = TRUE;
561 agent_config.server = FALSE;
563 args = g_strsplit (options, ",", -1);
564 for (ptr = args; ptr && *ptr; ptr ++) {
567 if (strncmp (arg, "transport=", 10) == 0) {
568 agent_config.transport = g_strdup (arg + 10);
569 } else if (strncmp (arg, "address=", 8) == 0) {
570 agent_config.address = g_strdup (arg + 8);
571 } else if (strncmp (arg, "loglevel=", 9) == 0) {
572 agent_config.log_level = atoi (arg + 9);
573 } else if (strncmp (arg, "logfile=", 8) == 0) {
574 agent_config.log_file = g_strdup (arg + 8);
575 } else if (strncmp (arg, "suspend=", 8) == 0) {
576 agent_config.suspend = parse_flag ("suspend", arg + 8);
577 } else if (strncmp (arg, "server=", 7) == 0) {
578 agent_config.server = parse_flag ("server", arg + 7);
579 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
580 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
581 } else if (strncmp (arg, "onthrow=", 8) == 0) {
582 /* We support multiple onthrow= options */
583 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
584 } else if (strncmp (arg, "help", 4) == 0) {
587 } else if (strncmp (arg, "timeout=", 8) == 0) {
588 agent_config.timeout = atoi (arg + 8);
589 } else if (strncmp (arg, "launch=", 7) == 0) {
590 agent_config.launch = g_strdup (arg + 7);
597 if (agent_config.transport == NULL) {
598 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
601 if (strcmp (agent_config.transport, "dt_socket") != 0) {
602 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
606 if (agent_config.address == NULL && !agent_config.server) {
607 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
611 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
612 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
618 mono_debugger_agent_init (void)
620 if (!agent_config.enabled)
623 /* Need to know whenever a thread has acquired the loader mutex */
624 mono_loader_lock_track_ownership (TRUE);
626 event_requests = g_ptr_array_new ();
628 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
629 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
630 mono_profiler_install_runtime_initialized (runtime_initialized);
631 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_unload, NULL);
632 mono_profiler_install_thread (thread_startup, thread_end);
633 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
634 mono_profiler_install_jit_end (jit_end);
635 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
637 debugger_tls_id = TlsAlloc ();
639 thread_to_tls = mono_g_hash_table_new (NULL, NULL);
640 MONO_GC_REGISTER_ROOT (thread_to_tls);
642 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
643 MONO_GC_REGISTER_ROOT (tid_to_thread);
645 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
646 MONO_GC_REGISTER_ROOT (tid_to_thread_obj);
648 loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
649 pending_assembly_loads = g_ptr_array_new ();
651 log_level = agent_config.log_level;
653 if (agent_config.log_file) {
654 log_file = fopen (agent_config.log_file, "w+");
656 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
668 mini_get_debug_options ()->gen_seq_points = TRUE;
670 * This is needed because currently we don't handle liveness info.
672 mini_get_debug_options ()->mdb_optimizations = TRUE;
674 /* This is needed because we can't set local variables in registers yet */
675 mono_disable_optimizations (MONO_OPT_LINEARS);
677 if (!agent_config.onuncaught && !agent_config.onthrow)
678 finish_agent_init (TRUE);
684 * Finish the initialization of the agent. This involves connecting the transport
685 * and starting the agent thread. This is either done at startup, or
686 * in response to some event like an unhandled exception.
689 finish_agent_init (gboolean on_startup)
695 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
698 if (agent_config.launch) {
701 // FIXME: Generated address
702 // FIXME: Races with transport_connect ()
704 argv [0] = agent_config.launch;
705 argv [1] = agent_config.transport;
706 argv [2] = agent_config.address;
709 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
711 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
716 if (agent_config.address) {
717 res = parse_address (agent_config.address, &host, &port);
724 transport_connect (host, port);
727 /* Do some which is usually done after sending the VMStart () event */
728 vm_start_event_sent = TRUE;
729 start_debugger_thread ();
734 mono_debugger_agent_cleanup (void)
739 /* This will interrupt the agent thread */
740 /* Close the read part only so it can still send back replies */
741 #ifdef PLATFORM_WIN32
742 shutdown (conn_fd, SD_RECEIVE);
744 shutdown (conn_fd, SHUT_RD);
748 * Wait for the thread to exit.
750 * If we continue with the shutdown without waiting for it, then the client might
751 * not receive an answer to its last command like a resume.
752 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
755 //WaitForSingleObject (debugger_thread_handle, INFINITE);
756 if (GetCurrentThreadId () != debugger_thread_id) {
757 mono_mutex_lock (&debugger_thread_exited_mutex);
758 if (!debugger_thread_exited)
759 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
760 mono_mutex_unlock (&debugger_thread_exited_mutex);
763 breakpoints_cleanup ();
771 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
774 transport_connect (const char *host, int port)
776 struct addrinfo hints;
777 struct addrinfo *result, *rp;
779 char port_string [128];
780 char handshake_msg [128];
786 sprintf (port_string, "%d", port);
788 /* Obtain address(es) matching host/port */
790 memset (&hints, 0, sizeof (struct addrinfo));
791 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
792 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
794 hints.ai_protocol = 0; /* Any protocol */
796 s = getaddrinfo (host, port_string, &hints, &result);
798 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d: %s\n", host, port, gai_strerror (s));
803 if (agent_config.server) {
804 /* Wait for a connection */
806 struct sockaddr_in addr;
809 /* No address, generate one */
810 sfd = socket (AF_INET, SOCK_STREAM, 0);
813 /* This will bind the socket to a random port */
814 res = listen (sfd, 16);
816 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
820 addrlen = sizeof (addr);
821 memset (&addr, 0, sizeof (addr));
822 res = getsockname (sfd, &addr, &addrlen);
826 port = ntohs (addr.sin_port);
828 /* Emit the address to stdout */
829 /* FIXME: Should print another interface, not localhost */
830 printf ("%s:%d\n", host, port);
832 /* Listen on the provided address */
833 for (rp = result; rp != NULL; rp = rp->ai_next) {
834 sfd = socket (rp->ai_family, rp->ai_socktype,
839 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
843 res = listen (sfd, 16);
849 freeaddrinfo (result);
852 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
854 if (agent_config.timeout) {
859 tv.tv_usec = agent_config.timeout * 1000;
861 FD_SET (sfd, &readfds);
862 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
864 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
869 conn_fd = accept (sfd, NULL, NULL);
871 fprintf (stderr, "debugger-agent: Unable to listen on %s:%d\n", host, port);
875 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
877 /* Connect to the specified address */
878 /* FIXME: Respect the timeout */
879 for (rp = result; rp != NULL; rp = rp->ai_next) {
880 sfd = socket (rp->ai_family, rp->ai_socktype,
885 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
893 freeaddrinfo (result);
896 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
901 /* Write handshake message */
902 sprintf (handshake_msg, "DWP-Handshake");
903 res = write (conn_fd, handshake_msg, strlen (handshake_msg));
904 g_assert (res != -1);
907 res = read (conn_fd, buf, strlen (handshake_msg));
908 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
909 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
914 * Set TCP_NODELAY on the socket so the client receives events/command
915 * results immediately.
919 int result = setsockopt(conn_fd,
924 g_assert (result >= 0);
929 transport_send (guint8 *data, int len)
933 res = write (conn_fd, data, len);
941 start_debugger_thread (void)
945 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
946 g_assert (debugger_thread_handle);
950 * Functions to decode protocol data
954 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
957 g_assert (*endbuf <= limit);
962 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
965 g_assert (*endbuf <= limit);
967 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
971 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
973 guint32 high = decode_int (buf, &buf, limit);
974 guint32 low = decode_int (buf, &buf, limit);
978 return ((((guint64)high) << 32) | ((guint64)low));
982 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
984 return decode_int (buf, endbuf, limit);
988 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
990 int len = decode_int (buf, &buf, limit);
993 s = g_malloc (len + 1);
996 memcpy (s, buf, len);
1005 * Functions to encode protocol data
1009 guint8 *buf, *p, *end;
1013 buffer_init (Buffer *buf, int size)
1015 buf->buf = g_malloc (size);
1017 buf->end = buf->buf + size;
1021 buffer_make_room (Buffer *buf, int size)
1023 if (buf->end - buf->p < size) {
1024 int new_size = buf->end - buf->buf + size + 32;
1025 guint8 *p = g_realloc (buf->buf, new_size);
1026 size = buf->p - buf->buf;
1029 buf->end = buf->buf + new_size;
1034 buffer_add_byte (Buffer *buf, guint8 val)
1036 buffer_make_room (buf, 1);
1042 buffer_add_int (Buffer *buf, guint32 val)
1044 buffer_make_room (buf, 4);
1045 buf->p [0] = (val >> 24) & 0xff;
1046 buf->p [1] = (val >> 16) & 0xff;
1047 buf->p [2] = (val >> 8) & 0xff;
1048 buf->p [3] = (val >> 0) & 0xff;
1053 buffer_add_long (Buffer *buf, guint64 l)
1055 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1056 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1060 buffer_add_id (Buffer *buf, int id)
1062 buffer_add_int (buf, (guint64)id);
1066 buffer_add_data (Buffer *buf, guint8 *data, int len)
1068 buffer_make_room (buf, len);
1069 memcpy (buf->p, data, len);
1074 buffer_add_string (Buffer *buf, const char *str)
1079 buffer_add_int (buf, 0);
1082 buffer_add_int (buf, len);
1083 buffer_add_data (buf, (guint8*)str, len);
1088 buffer_free (Buffer *buf)
1094 send_packet (int command_set, int command, Buffer *data)
1100 id = InterlockedIncrement (&packet_id);
1102 len = data->p - data->buf + 11;
1103 buffer_init (&buf, len);
1104 buffer_add_int (&buf, len);
1105 buffer_add_int (&buf, id);
1106 buffer_add_byte (&buf, 0); /* flags */
1107 buffer_add_byte (&buf, command_set);
1108 buffer_add_byte (&buf, command);
1109 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1111 res = transport_send (buf.buf, len);
1119 send_reply_packet (int id, int error, Buffer *data)
1125 len = data->p - data->buf + 11;
1126 buffer_init (&buf, len);
1127 buffer_add_int (&buf, len);
1128 buffer_add_int (&buf, id);
1129 buffer_add_byte (&buf, 0x80); /* flags */
1130 buffer_add_byte (&buf, (error >> 8) & 0xff);
1131 buffer_add_byte (&buf, error);
1132 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1134 res = transport_send (buf.buf, len);
1146 * Represents an object accessible by the debugger client.
1149 /* Unique id used in the wire protocol to refer to objects */
1152 * A weakref gc handle pointing to the object. The gc handle is used to
1153 * detect if the object was garbage collected.
1158 /* Maps objid -> ObjRef */
1159 static GHashTable *objrefs;
1162 free_objref (gpointer value)
1166 mono_gchandle_free (o->handle);
1174 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1178 objrefs_cleanup (void)
1180 g_hash_table_destroy (objrefs);
1184 static GHashTable *obj_to_objref;
1187 * Return an ObjRef for OBJ.
1190 get_objref (MonoObject *obj)
1201 /* Use a hash table with masked pointers to internalize object references */
1202 /* FIXME: This can grow indefinitely */
1203 mono_loader_lock ();
1206 obj_to_objref = g_hash_table_new (NULL, NULL);
1208 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1209 /* ref might refer to a different object with the same addr which was GCd */
1210 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1211 mono_loader_unlock ();
1215 ref = g_new0 (ObjRef, 1);
1216 ref->id = InterlockedIncrement (&objref_id);
1217 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1219 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1220 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1222 mono_loader_unlock ();
1228 get_objid (MonoObject *obj)
1230 return get_objref (obj)->id;
1234 * Set OBJ to the object identified by OBJID.
1235 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1239 get_object_allow_null (int objid, MonoObject **obj)
1249 return ERR_INVALID_OBJECT;
1251 mono_loader_lock ();
1253 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1256 *obj = mono_gchandle_get_target (ref->handle);
1257 mono_loader_unlock ();
1259 return ERR_INVALID_OBJECT;
1262 mono_loader_unlock ();
1263 return ERR_INVALID_OBJECT;
1268 get_object (int objid, MonoObject **obj)
1270 int err = get_object_allow_null (objid, obj);
1275 return ERR_INVALID_OBJECT;
1280 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1282 return decode_id (buf, endbuf, limit);
1286 buffer_add_objid (Buffer *buf, MonoObject *o)
1288 buffer_add_id (buf, get_objid (o));
1307 * Represents a runtime structure accessible to the debugger client
1310 /* Unique id used in the wire protocol */
1312 /* Domain of the runtime structure, NULL if the domain was unloaded */
1319 MonoAssembly *assembly;
1320 MonoClassField *field;
1322 MonoProperty *property;
1327 /* Maps runtime structure -> Id */
1328 GHashTable *val_to_id [ID_NUM];
1332 static GPtrArray *ids [ID_NUM];
1339 for (i = 0; i < ID_NUM; ++i)
1340 ids [i] = g_ptr_array_new ();
1348 for (i = 0; i < ID_NUM; ++i) {
1350 for (j = 0; j < ids [i]->len; ++j)
1351 g_free (g_ptr_array_index (ids [i], j));
1352 g_ptr_array_free (ids [i], TRUE);
1359 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1361 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1365 for (i = 0; i < ID_NUM; ++i)
1366 if (info->val_to_id [i])
1367 g_hash_table_destroy (info->val_to_id [i]);
1371 domain_jit_info (domain)->agent_info = NULL;
1373 /* Clear ids referencing structures in the domain */
1374 for (i = 0; i < ID_NUM; ++i) {
1376 for (j = 0; j < ids [i]->len; ++j) {
1377 Id *id = g_ptr_array_index (ids [i], j);
1378 if (id->domain == domain)
1386 get_id (MonoDomain *domain, IdType type, gpointer val)
1389 AgentDomainInfo *info;
1394 mono_loader_lock ();
1396 mono_domain_lock (domain);
1398 if (!domain_jit_info (domain)->agent_info)
1399 domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1400 info = domain_jit_info (domain)->agent_info;
1401 if (info->val_to_id [type] == NULL)
1402 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1404 id = g_hash_table_lookup (info->val_to_id [type], val);
1406 mono_domain_unlock (domain);
1407 mono_loader_unlock ();
1411 id = g_new0 (Id, 1);
1413 id->id = ids [type]->len + 1;
1414 id->domain = domain;
1417 g_hash_table_insert (info->val_to_id [type], val, id);
1419 mono_domain_unlock (domain);
1421 g_ptr_array_add (ids [type], id);
1423 mono_loader_unlock ();
1428 static inline gpointer
1429 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1433 int id = decode_id (buf, endbuf, limit);
1442 // FIXME: error handling
1443 mono_loader_lock ();
1444 g_assert (id > 0 && id <= ids [type]->len);
1446 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1447 mono_loader_unlock ();
1449 if (res->domain == NULL) {
1450 *err = ERR_UNLOADED;
1455 *domain = res->domain;
1457 return res->data.val;
1461 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1463 buffer_add_id (buf, get_id (domain, type, val));
1466 static inline MonoClass*
1467 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1469 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1472 static inline MonoAssembly*
1473 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1475 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1478 static inline MonoImage*
1479 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1481 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1484 static inline MonoMethod*
1485 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1487 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1490 static inline MonoClassField*
1491 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1493 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1496 static inline MonoDomain*
1497 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1499 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1502 static inline MonoProperty*
1503 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1505 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1509 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1511 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1515 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1517 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1521 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1523 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1527 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1529 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1533 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1535 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1539 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1541 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1545 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1547 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1550 static void invoke_method (void);
1557 save_thread_context (MonoContext *ctx)
1559 DebuggerTlsData *tls;
1561 tls = TlsGetValue (debugger_tls_id);
1565 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1567 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1568 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1570 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1574 tls->lmf = mono_get_lmf ();
1575 tls->domain = mono_domain_get ();
1576 tls->has_context = TRUE;
1579 /* The number of times the runtime is suspended */
1580 static gint32 suspend_count;
1582 /* Number of threads suspended */
1584 * If this is equal to the size of thread_to_tls, the runtime is considered
1587 static gint32 threads_suspend_count;
1589 static mono_mutex_t suspend_mutex = MONO_MUTEX_INITIALIZER;
1591 /* Cond variable used to wait for suspend_count becoming 0 */
1592 static mono_cond_t suspend_cond = MONO_COND_INITIALIZER;
1594 /* Semaphore used to wait for a thread becoming suspended */
1595 static MonoSemType suspend_sem;
1600 MONO_SEM_INIT (&suspend_sem, 0);
1604 * mono_debugger_agent_thread_interrupt:
1606 * Called by the abort signal handler.
1609 mono_debugger_agent_thread_interrupt (MonoJitInfo *ji)
1611 DebuggerTlsData *tls;
1616 tls = TlsGetValue (debugger_tls_id);
1621 * We use interrupt_count to determine whenever this interrupt should be processed
1622 * by us or the normal interrupt processing code in the signal handler.
1623 * There is no race here with notify_thread (), since the signal is sent after
1624 * incrementing interrupt_count.
1626 if (tls->interrupt_count == 0)
1629 InterlockedDecrement (&tls->interrupt_count);
1631 // FIXME: Races when the thread leaves managed code before hitting a single step
1635 /* Running managed code, will be suspended by the single step code */
1636 //printf ("S1: %p\n", GetCurrentThreadId ());
1640 * Running native code, will be suspended when it returns to/enters
1641 * managed code. Treat it as already suspended.
1643 //printf ("S2: %p\n", GetCurrentThreadId ());
1644 if (!tls->suspended) {
1645 tls->suspended = TRUE;
1646 MONO_SEM_POST (&suspend_sem);
1655 * Notify a thread that it needs to suspend.
1658 notify_thread (gpointer key, gpointer value, gpointer user_data)
1660 MonoInternalThread *thread = key;
1661 DebuggerTlsData *tls = value;
1662 gsize tid = thread->tid;
1664 if (GetCurrentThreadId () != tid) {
1665 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
1667 * Maybe we could use the normal interrupt infrastructure, but that does a lot
1668 * of things like breaking waits etc. which we don't want.
1670 InterlockedIncrement (&tls->interrupt_count);
1671 #ifdef PLATFORM_WIN32
1672 /*FIXME: Abort thread */
1674 pthread_kill ((pthread_t) tid, mono_thread_get_abort_signal ());
1682 * Increase the suspend count of the VM. While the suspend count is greater
1683 * than 0, runtime threads are suspended at certain points during execution.
1688 mono_loader_lock ();
1690 mono_mutex_lock (&suspend_mutex);
1694 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
1696 if (suspend_count == 1) {
1697 // FIXME: Is it safe to call this inside the lock ?
1698 start_single_stepping ();
1699 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
1702 mono_mutex_unlock (&suspend_mutex);
1704 mono_loader_unlock ();
1710 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
1718 g_assert (debugger_thread_id == GetCurrentThreadId ());
1720 mono_loader_lock ();
1722 mono_mutex_lock (&suspend_mutex);
1724 g_assert (suspend_count > 0);
1727 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
1729 if (suspend_count == 0) {
1730 // FIXME: Is it safe to call this inside the lock ?
1731 stop_single_stepping ();
1732 err = mono_cond_broadcast (&suspend_cond);
1733 g_assert (err == 0);
1736 err = mono_mutex_unlock (&suspend_mutex);
1737 g_assert (err == 0);
1739 mono_loader_unlock ();
1743 invalidate_frames (DebuggerTlsData *tls)
1748 tls = TlsGetValue (debugger_tls_id);
1751 for (i = 0; i < tls->frame_count; ++i) {
1752 if (tls->frames [i]->jit)
1753 mono_debug_free_method_jit_info (tls->frames [i]->jit);
1754 g_free (tls->frames [i]);
1756 g_free (tls->frames);
1757 tls->frame_count = 0;
1764 * Suspend the current thread until the runtime is resumed. If the thread has a
1765 * pending invoke, then the invoke is executed before this function returns.
1768 suspend_current (void)
1771 DebuggerTlsData *tls;
1773 g_assert (debugger_thread_id != GetCurrentThreadId ());
1775 if (mono_loader_lock_is_owned_by_self ()) {
1777 * If we own the loader mutex, can't suspend until we release it, since the
1778 * whole runtime can deadlock otherwise.
1783 tls = TlsGetValue (debugger_tls_id);
1786 mono_mutex_lock (&suspend_mutex);
1788 if (!tls->suspended) {
1789 tls->suspended = TRUE;
1790 MONO_SEM_POST (&suspend_sem);
1793 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
1795 while (suspend_count > 0) {
1796 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
1797 g_assert (err == 0);
1800 tls->suspended = FALSE;
1802 threads_suspend_count --;
1804 mono_mutex_unlock (&suspend_mutex);
1806 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
1809 /* Save the original context */
1810 tls->invoke->has_ctx = TRUE;
1811 memcpy (&tls->invoke->ctx, &tls->ctx, sizeof (MonoContext));
1816 /* The frame info becomes invalid after a resume */
1817 tls->has_context = FALSE;
1818 invalidate_frames (NULL);
1822 count_thread (gpointer key, gpointer value, gpointer user_data)
1824 DebuggerTlsData *tls = value;
1826 if (!tls->suspended && !tls->terminated)
1827 *(int*)user_data = *(int*)user_data + 1;
1831 count_threads_to_wait_for (void)
1835 mono_loader_lock ();
1836 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
1837 mono_loader_unlock ();
1845 * Wait until the runtime is completely suspended.
1848 wait_for_suspend (void)
1850 int nthreads, nwait, err;
1851 gboolean waited = FALSE;
1853 // FIXME: Threads starting/stopping ?
1854 mono_loader_lock ();
1855 nthreads = mono_g_hash_table_size (thread_to_tls);
1856 mono_loader_unlock ();
1859 nwait = count_threads_to_wait_for ();
1861 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
1862 err = MONO_SEM_WAIT (&suspend_sem);
1863 g_assert (err == 0);
1871 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
1877 * Return whenever the runtime is suspended.
1882 return count_threads_to_wait_for () == 0;
1886 * compute_il_offset:
1888 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
1889 * a location of a sequence point.
1890 * We use this function instead of mono_debug_il_offset_from_address () etc,
1891 * which doesn't seem to work in a lot of cases.
1894 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
1896 GPtrArray *seq_points;
1897 int i, last_il_offset, seq_il_offset, seq_native_offset;
1899 mono_domain_lock (domain);
1900 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
1901 mono_domain_unlock (domain);
1902 g_assert (seq_points);
1904 last_il_offset = -1;
1906 /* Find the sequence point */
1907 for (i = 0; i < seq_points->len; i += 2) {
1908 seq_il_offset = GPOINTER_TO_UINT (g_ptr_array_index (seq_points, i));
1909 seq_native_offset = GPOINTER_TO_UINT (g_ptr_array_index (seq_points, i + 1));
1911 if (seq_native_offset > native_offset)
1913 last_il_offset = seq_il_offset;
1916 return last_il_offset;
1920 DebuggerTlsData *tls;
1922 } ComputeFramesUserData;
1925 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
1927 ComputeFramesUserData *ud = user_data;
1931 if (info->type != FRAME_TYPE_MANAGED) {
1932 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
1933 /* Mark the last frame as an invoke frame */
1935 ((StackFrame*)ud->frames->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
1941 method = info->ji->method;
1943 method = info->method;
1945 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
1948 if (info->il_offset == -1) {
1949 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
1950 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
1953 DEBUG (1, fprintf (stderr, "\tFrame: %s %d %d %d\n", mono_method_full_name (method, TRUE), info->native_offset, info->il_offset, info->managed));
1955 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
1957 * mono_arch_find_jit_info () returns the context stored in the LMF for
1958 * native frames, but it should unwind once. This is why we have duplicate
1959 * frames on the stack sometimes.
1960 * !managed also seems to be set for dynamic methods.
1965 frame = g_new0 (StackFrame, 1);
1966 frame->method = method;
1967 frame->il_offset = info->il_offset;
1969 frame->domain = info->domain;
1971 ud->frames = g_slist_append (ud->frames, frame);
1977 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
1979 ComputeFramesUserData user_data;
1981 int i, findex, new_frame_count;
1982 StackFrame **new_frames, *f;
1984 // FIXME: Locking on tls
1985 if (tls->frames && tls->frames_up_to_date)
1988 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
1990 user_data.tls = tls;
1991 user_data.frames = NULL;
1992 if (tls->has_context) {
1993 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
1996 tls->frame_count = 0;
2000 new_frame_count = g_slist_length (user_data.frames);
2001 new_frames = g_new0 (StackFrame*, new_frame_count);
2003 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2007 * Reuse the id for already existing stack frames, so invokes don't invalidate
2008 * the still valid stack frames.
2010 for (i = 0; i < tls->frame_count; ++i) {
2011 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2012 f->id = tls->frames [i]->id;
2017 if (i >= tls->frame_count)
2018 f->id = InterlockedIncrement (&frame_id);
2020 new_frames [findex ++] = f;
2023 g_slist_free (user_data.frames);
2025 invalidate_frames (tls);
2027 tls->frames = new_frames;
2028 tls->frame_count = new_frame_count;
2029 tls->frames_up_to_date = TRUE;
2037 * create_event_list:
2039 * Return a list of event request ids matching EVENT, starting from REQS, which
2040 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2042 * We return request ids, instead of requests, to simplify threading, since
2043 * requests could be deleted anytime when the loader lock is not held.
2044 * LOCKING: Assumes the loader lock is held.
2047 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, MonoException *exc, int *suspend_policy)
2050 GSList *events = NULL;
2052 *suspend_policy = SUSPEND_POLICY_NONE;
2055 reqs = event_requests;
2060 for (i = 0; i < reqs->len; ++i) {
2061 EventRequest *req = g_ptr_array_index (reqs, i);
2062 if (req->event_kind == event) {
2063 gboolean filtered = FALSE;
2066 for (j = 0; j < req->nmodifiers; ++j) {
2067 Modifier *mod = &req->modifiers [j];
2069 if (mod->kind == MOD_KIND_COUNT) {
2071 if (mod->data.count > 0) {
2072 if (mod->data.count > 0) {
2074 if (mod->data.count == 0)
2078 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2079 if (mod->data.thread != mono_thread_internal_current ())
2081 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && exc) {
2082 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, exc->object.vtable->klass))
2084 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2086 gboolean found = FALSE;
2087 MonoAssembly **assemblies = mod->data.assemblies;
2089 for (k = 0; assemblies [k]; ++k)
2090 if (assemblies [k] == ji->method->klass->image->assembly)
2098 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2099 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2104 /* Send a VM START/DEATH event by default */
2105 if (event == EVENT_KIND_VM_START)
2106 events = g_slist_append (events, GINT_TO_POINTER (0));
2107 if (event == EVENT_KIND_VM_DEATH)
2108 events = g_slist_append (events, GINT_TO_POINTER (0));
2113 static G_GNUC_UNUSED const char*
2114 event_to_string (EventKind event)
2117 case EVENT_KIND_VM_START: return "VM_START";
2118 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2119 case EVENT_KIND_THREAD_START: return "THREAD_START";
2120 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2121 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2122 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2123 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2124 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2125 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2126 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2127 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2128 case EVENT_KIND_STEP: return "STEP";
2129 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2130 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2132 g_assert_not_reached ();
2139 * Send an event to the client, suspending the vm if needed.
2140 * LOCKING: Since this can suspend the calling thread, no locks should be held
2142 * The EVENTS list is freed by this function.
2145 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2149 MonoDomain *domain = mono_domain_get ();
2155 if (!vm_start_event_sent && event != EVENT_KIND_VM_START)
2156 // FIXME: We miss those events
2159 if (vm_death_event_sent)
2162 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH)
2171 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
2172 // FIXME: Send these with a NULL thread, don't suspend the current thread
2175 buffer_init (&buf, 128);
2176 buffer_add_byte (&buf, suspend_policy);
2177 buffer_add_int (&buf, g_slist_length (events)); // n of events
2179 for (l = events; l; l = l->next) {
2180 buffer_add_byte (&buf, event); // event kind
2181 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
2183 thread = mono_thread_current ();
2185 if (event == EVENT_KIND_VM_START)
2187 else if (event == EVENT_KIND_THREAD_START)
2188 g_assert (mono_thread_internal_current () == arg);
2190 buffer_add_objid (&buf, (MonoObject*)thread); // thread
2193 case EVENT_KIND_THREAD_START:
2194 case EVENT_KIND_THREAD_DEATH:
2196 case EVENT_KIND_APPDOMAIN_CREATE:
2197 case EVENT_KIND_APPDOMAIN_UNLOAD:
2198 buffer_add_domainid (&buf, arg);
2200 case EVENT_KIND_METHOD_ENTRY:
2201 case EVENT_KIND_METHOD_EXIT:
2202 buffer_add_methodid (&buf, domain, arg);
2204 case EVENT_KIND_ASSEMBLY_LOAD:
2205 case EVENT_KIND_ASSEMBLY_UNLOAD:
2206 buffer_add_assemblyid (&buf, domain, arg);
2208 case EVENT_KIND_TYPE_LOAD:
2209 buffer_add_typeid (&buf, domain, arg);
2211 case EVENT_KIND_BREAKPOINT:
2212 case EVENT_KIND_STEP:
2213 buffer_add_methodid (&buf, domain, arg);
2214 buffer_add_long (&buf, il_offset);
2216 case EVENT_KIND_VM_START:
2217 buffer_add_domainid (&buf, mono_get_root_domain ());
2219 case EVENT_KIND_VM_DEATH:
2221 case EVENT_KIND_EXCEPTION:
2222 buffer_add_objid (&buf, (MonoObject*)arg);
2225 g_assert_not_reached ();
2229 if (event == EVENT_KIND_VM_START) {
2230 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
2231 start_debugger_thread ();
2234 if (event == EVENT_KIND_VM_DEATH) {
2235 vm_death_event_sent = TRUE;
2237 suspend_policy = SUSPEND_POLICY_NONE;
2240 if (mono_runtime_is_shutting_down ())
2241 suspend_policy = SUSPEND_POLICY_NONE;
2243 if (suspend_policy != SUSPEND_POLICY_NONE) {
2245 * Save the thread context and start suspending before sending the packet,
2246 * since we could be receiving the resume request before send_packet ()
2249 save_thread_context (ctx);
2253 send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
2255 g_slist_free (events);
2258 if (event == EVENT_KIND_VM_START)
2259 vm_start_event_sent = TRUE;
2261 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
2265 switch (suspend_policy) {
2266 case SUSPEND_POLICY_NONE:
2268 case SUSPEND_POLICY_ALL:
2271 case SUSPEND_POLICY_EVENT_THREAD:
2275 g_assert_not_reached ();
2280 process_profiler_event (EventKind event, gpointer arg)
2285 mono_loader_lock ();
2286 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
2287 mono_loader_unlock ();
2289 process_event (event, arg, 0, NULL, events, suspend_policy);
2293 runtime_initialized (MonoProfiler *prof)
2295 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
2299 runtime_shutdown (MonoProfiler *prof)
2301 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
2303 mono_debugger_agent_cleanup ();
2307 thread_startup (MonoProfiler *prof, gsize tid)
2309 MonoInternalThread *thread = mono_thread_internal_current ();
2310 MonoInternalThread *old_thread;
2311 DebuggerTlsData *tls;
2313 if (tid == debugger_thread_id)
2316 g_assert (thread->tid == tid);
2318 mono_loader_lock ();
2319 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2320 mono_loader_unlock ();
2322 if (thread == old_thread) {
2324 * For some reason, thread_startup () might be called for the same thread
2325 * multiple times (attach ?).
2327 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
2331 * thread_end () might not be called for some threads, and the tid could
2334 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
2335 mono_loader_lock ();
2336 mono_g_hash_table_remove (thread_to_tls, old_thread);
2337 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
2338 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2339 mono_loader_unlock ();
2343 tls = TlsGetValue (debugger_tls_id);
2345 // FIXME: Free this somewhere
2346 tls = g_new0 (DebuggerTlsData, 1);
2347 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
2348 TlsSetValue (debugger_tls_id, tls);
2350 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2352 mono_loader_lock ();
2353 mono_g_hash_table_insert (thread_to_tls, thread, tls);
2354 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
2355 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
2356 mono_loader_unlock ();
2358 process_profiler_event (EVENT_KIND_THREAD_START, thread);
2361 * suspend_vm () could have missed this thread, so wait for a resume.
2367 thread_end (MonoProfiler *prof, gsize tid)
2369 MonoInternalThread *thread;
2370 DebuggerTlsData *tls = NULL;
2372 mono_loader_lock ();
2373 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2375 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2376 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
2377 tls->terminated = TRUE;
2378 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2379 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
2381 mono_loader_unlock ();
2383 /* We might be called for threads started before we registered the start callback */
2385 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2386 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
2391 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
2393 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
2397 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
2399 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
2403 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
2405 /* Sent later in jit_end () */
2406 mono_loader_lock ();
2407 g_ptr_array_add (pending_assembly_loads, assembly);
2408 mono_loader_unlock ();
2412 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
2414 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
2418 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2423 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2426 #ifdef PLATFORM_WIN32
2427 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
2429 gpointer stackptr = __builtin_frame_address (0);
2432 if (ss_req == NULL || ss_req->start_sp > stackptr || ss_req->thread != mono_thread_internal_current ())
2436 * We need to stop single stepping when exiting a runtime invoke, since if it is
2437 * a step out, it may return to native code, and thus never end.
2439 mono_loader_lock ();
2440 for (i = 0; i < event_requests->len; ++i) {
2441 EventRequest *req = g_ptr_array_index (event_requests, i);
2443 if (req->event_kind == EVENT_KIND_STEP) {
2445 g_ptr_array_remove_index_fast (event_requests, i);
2450 mono_loader_unlock ();
2455 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
2458 * We emit type load events when the first method of the type is JITted,
2459 * since the class load profiler callbacks might be called with the
2460 * loader lock held. They could also occur in the debugger thread.
2461 * Same for assembly load events.
2463 gboolean type_load = FALSE;
2466 MonoAssembly *assembly = NULL;
2468 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
2469 mono_loader_lock ();
2470 if (pending_assembly_loads->len > 0) {
2471 assembly = g_ptr_array_index (pending_assembly_loads, 0);
2472 g_ptr_array_remove_index (pending_assembly_loads, 0);
2474 mono_loader_unlock ();
2477 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
2482 mono_loader_lock ();
2483 if (!g_hash_table_lookup (loaded_classes, method->klass)) {
2485 g_hash_table_insert (loaded_classes, method->klass, method->klass);
2487 mono_loader_unlock ();
2489 process_profiler_event (EVENT_KIND_TYPE_LOAD, method->klass);
2492 add_pending_breakpoints (method, jinfo);
2496 * BREAKPOINTS/SINGLE STEPPING
2500 * Contains information about an inserted breakpoint.
2503 long il_offset, native_offset;
2505 gboolean pending, entry;
2507 } BreakpointInstance;
2510 * Contains generic information about a breakpoint.
2514 * The method where the breakpoint is placed. Can be NULL in which case it
2515 * is inserted into every method. This is used to implement method entry/
2516 * exit events. Can be a generic method definition, in which case the
2517 * breakpoint is inserted into every instance.
2521 gboolean pending, entry;
2524 * A list of BreakpointInstance structures describing where the breakpoint
2525 * was inserted. There could be more than one because of
2526 * generics/appdomains/method entry/exit.
2528 GPtrArray *children;
2531 /* List of breakpoints */
2532 static GPtrArray *breakpoints;
2533 /* Maps breakpoint locations to the number of breakpoints at that location */
2534 static GHashTable *bp_locs;
2537 breakpoints_init (void)
2539 breakpoints = g_ptr_array_new ();
2540 bp_locs = g_hash_table_new (NULL, NULL);
2544 breakpoints_cleanup (void)
2548 mono_loader_lock ();
2550 for (i = 0; i < breakpoints->len; ++i)
2551 g_free (g_ptr_array_index (breakpoints, i));
2553 g_ptr_array_free (breakpoints, TRUE);
2554 g_hash_table_destroy (bp_locs);
2556 mono_loader_unlock ();
2560 * insert_breakpoint:
2562 * Insert the breakpoint described by BP into the method described by
2566 insert_breakpoint (GPtrArray *seq_points, MonoJitInfo *ji, MonoBreakpoint *bp)
2569 gint32 il_offset, native_offset;
2570 BreakpointInstance *inst;
2573 for (i = 0; i < seq_points->len; i += 2) {
2574 il_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i));
2575 native_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i + 1));
2577 if (il_offset == bp->il_offset)
2581 if (i == seq_points->len)
2582 /* Have to handle this somehow */
2585 inst = g_new0 (BreakpointInstance, 1);
2586 inst->native_offset = native_offset;
2587 inst->ip = (guint8*)ji->code_start + native_offset;
2590 mono_loader_lock ();
2592 g_ptr_array_add (bp->children, inst);
2594 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
2595 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
2596 mono_loader_unlock ();
2599 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
2600 mono_arch_set_breakpoint (ji, inst->ip);
2608 remove_breakpoint (BreakpointInstance *inst)
2610 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
2612 MonoJitInfo *ji = inst->ji;
2613 guint8 *ip = inst->ip;
2615 mono_loader_lock ();
2616 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
2617 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
2618 mono_loader_unlock ();
2620 g_assert (count > 0);
2623 mono_arch_clear_breakpoint (ji, ip);
2631 * add_pending_breakpoints:
2633 * Insert pending breakpoints into the newly JITted method METHOD.
2636 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
2639 GPtrArray *seq_points;
2645 domain = mono_domain_get ();
2647 mono_loader_lock ();
2649 for (i = 0; i < breakpoints->len; ++i) {
2650 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
2652 if (bp->pending && (bp->method == method || !bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method))) {
2653 mono_domain_lock (domain);
2654 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
2655 mono_domain_unlock (domain);
2657 /* Could be AOT code */
2659 g_assert (seq_points);
2661 insert_breakpoint (seq_points, ji, bp);
2665 mono_loader_unlock ();
2669 set_bp_in_method (MonoDomain *domain, MonoMethod *method, GPtrArray *seq_points, MonoBreakpoint *bp)
2674 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
2676 /* Might be AOTed code */
2677 code = mono_aot_get_method (domain, method);
2679 ji = mono_jit_info_table_find (domain, code);
2684 insert_breakpoint (seq_points, ji, bp);
2688 set_bp_in_method_cb (gpointer key, gpointer value, gpointer user_data)
2690 MonoMethod *method = key;
2691 GPtrArray *seq_points = value;
2692 MonoBreakpoint *bp = user_data;
2693 MonoDomain *domain = mono_domain_get ();
2696 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method) {
2697 /* Generic instance */
2698 set_bp_in_method (domain, method, seq_points, bp);
2701 /* Method entry/exit */
2702 set_bp_in_method (domain, method, seq_points, bp);
2709 * Set a breakpoint at IL_OFFSET in METHOD.
2710 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
2711 * METHOD can also be a generic method definition, in which case a breakpoint
2712 * is placed in all instances of the method.
2714 static MonoBreakpoint*
2715 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req)
2717 GPtrArray *seq_points;
2722 // - suspend/resume the vm to prevent code patching problems
2724 // - multiple breakpoints on the same location
2725 // - dynamic methods
2728 bp = g_new0 (MonoBreakpoint, 1);
2729 bp->method = method;
2730 bp->il_offset = il_offset;
2732 bp->children = g_ptr_array_new ();
2734 DEBUG(1, fprintf (log_file, "[dbg] Setting breakpoint at %s:0x%x.\n", mono_method_full_name (method, TRUE), (int)il_offset));
2736 domain = mono_domain_get ();
2737 mono_domain_lock (domain);
2739 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2741 set_bp_in_method (domain, method, seq_points, bp);
2743 if (method->is_generic)
2744 /* There might be already JITted instances */
2745 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
2747 /* Not yet JITted */
2751 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
2754 mono_domain_unlock (domain);
2756 mono_loader_lock ();
2757 g_ptr_array_add (breakpoints, bp);
2758 mono_loader_unlock ();
2764 clear_breakpoint (MonoBreakpoint *bp)
2768 // FIXME: locking, races
2769 for (i = 0; i < bp->children->len; ++i) {
2770 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
2772 remove_breakpoint (inst);
2777 mono_loader_lock ();
2778 g_ptr_array_remove (breakpoints, bp);
2779 mono_loader_unlock ();
2781 g_ptr_array_free (bp->children, TRUE);
2786 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
2789 guint8 *orig_ip, *ip;
2790 int i, j, suspend_policy;
2791 guint32 native_offset;
2793 BreakpointInstance *inst;
2795 GSList *events = NULL;
2796 EventKind kind = EVENT_KIND_BREAKPOINT;
2798 // FIXME: Speed this up
2800 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
2801 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
2803 g_assert (ji->method);
2805 /* Compute the native offset of the breakpoint from the ip */
2806 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
2807 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
2808 native_offset = ip - (guint8*)ji->code_start;
2814 * Skip the instruction causing the breakpoint signal.
2816 mono_arch_skip_breakpoint (ctx);
2818 if (ji->method->wrapper_type || tls->disable_breakpoints)
2821 reqs = g_ptr_array_new ();
2823 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
2825 mono_loader_lock ();
2828 for (i = 0; i < breakpoints->len; ++i) {
2829 bp = g_ptr_array_index (breakpoints, i);
2834 for (j = 0; j < bp->children->len; ++j) {
2835 inst = g_ptr_array_index (bp->children, j);
2836 if (inst->ji == ji && inst->native_offset == native_offset)
2837 g_ptr_array_add (reqs, bp->req);
2840 if (reqs->len == 0) {
2841 GPtrArray *seq_points;
2842 int seq_il_offset, seq_native_offset;
2843 MonoDomain *domain = mono_domain_get ();
2845 /* Maybe a method entry/exit event */
2846 mono_domain_lock (domain);
2847 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
2848 mono_domain_unlock (domain);
2850 // FIXME: Generic sharing */
2851 mono_loader_unlock ();
2854 g_assert (seq_points);
2856 for (i = 0; i < seq_points->len; i += 2) {
2857 seq_il_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i));
2858 seq_native_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i + 1));
2860 if (native_offset == seq_native_offset) {
2861 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
2862 kind = EVENT_KIND_METHOD_ENTRY;
2863 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
2864 kind = EVENT_KIND_METHOD_EXIT;
2871 events = create_event_list (EVENT_KIND_BREAKPOINT, reqs, ji, NULL, &suspend_policy);
2872 else if (kind != EVENT_KIND_BREAKPOINT)
2873 events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
2875 g_ptr_array_free (reqs, TRUE);
2877 mono_loader_unlock ();
2880 process_event (kind, ji->method, 0, ctx, events, suspend_policy);
2884 process_breakpoint (void)
2886 DebuggerTlsData *tls;
2888 static void (*restore_context) (void *);
2890 if (!restore_context)
2891 restore_context = mono_get_restore_context ();
2893 tls = TlsGetValue (debugger_tls_id);
2894 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
2896 process_breakpoint_inner (tls, &ctx);
2898 /* This is called when resuming from a signal handler, so it shouldn't return */
2899 restore_context (&ctx);
2900 g_assert_not_reached ();
2904 resume_from_signal_handler (void *sigctx, void *func)
2906 DebuggerTlsData *tls;
2909 /* Save the original context in TLS */
2910 // FIXME: This might not work on an altstack ?
2911 tls = TlsGetValue (debugger_tls_id);
2914 // FIXME: MonoContext usually doesn't include the fp registers, so these are
2915 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
2916 // clob:c could be added to op_seq_point.
2918 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2919 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
2920 MONO_CONTEXT_SET_IP (&ctx, func);
2922 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
2926 mono_debugger_agent_breakpoint_hit (void *sigctx)
2929 * We are called from a signal handler, and running code there causes all kinds of
2930 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
2931 * So set up the signal context to return to the real breakpoint handler function.
2934 resume_from_signal_handler (sigctx, process_breakpoint);
2938 process_single_step_inner (MonoContext *ctx)
2943 int il_offset, suspend_policy;
2944 MonoDomain *domain = mono_domain_get ();
2947 // FIXME: Speed this up
2949 ip = MONO_CONTEXT_GET_IP (ctx);
2951 /* Skip the instruction causing the single step */
2952 mono_arch_skip_single_step (ctx);
2954 if (suspend_count > 0) {
2955 if (debugger_thread_id == GetCurrentThreadId ())
2958 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2960 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
2962 /* See the comment below */
2963 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2966 save_thread_context (ctx);
2972 // FIXME: A suspend race
2975 if (mono_thread_internal_current () != ss_req->thread)
2978 if (log_level > 0) {
2979 const char *depth = NULL;
2981 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
2983 switch (ss_req->depth) {
2984 case STEP_DEPTH_OVER:
2987 case STEP_DEPTH_OUT:
2990 case STEP_DEPTH_INTO:
2994 g_assert_not_reached ();
2997 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));
3001 * We implement step over/out by single stepping until we reach the same
3002 * frame/parent frame.
3005 * - stack growing upward
3009 if (ss_req->depth != STEP_DEPTH_INTO) {
3010 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
3012 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
3015 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
3018 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
3020 g_assert (ji->method);
3022 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
3027 * Stopping in memset makes half-initialized vtypes visible.
3028 * Stopping in memcpy makes half-copied vtypes visible.
3030 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
3034 * The ip points to the instruction causing the single step event, convert it
3035 * to the offset stored in seq_points.
3037 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3038 ip = mono_arch_get_ip_for_single_step (ji, ctx);
3040 g_assert_not_reached ();
3044 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
3045 * example, so do things by hand.
3047 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
3049 if (il_offset == -1)
3052 if (ss_req->size == STEP_SIZE_LINE) {
3053 /* Step until a different source line is reached */
3054 MonoDebugMethodInfo *minfo;
3056 minfo = mono_debug_lookup_method (ji->method);
3059 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
3061 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
3062 mono_debug_free_source_location (loc);
3067 * Step until we reach a location with line number info,
3068 * otherwise the client can't show a location.
3069 * This can happen for example with statics initialized inline
3070 * outside of a cctor.
3075 ss_req->last_method = ji->method;
3076 ss_req->last_line = loc->row;
3077 mono_debug_free_source_location (loc);
3082 // FIXME: Has to lock earlier
3084 reqs = g_ptr_array_new ();
3086 mono_loader_lock ();
3088 g_ptr_array_add (reqs, ss_req->req);
3090 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
3092 g_ptr_array_free (reqs, TRUE);
3094 mono_loader_unlock ();
3096 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
3100 process_single_step (void)
3102 DebuggerTlsData *tls;
3104 static void (*restore_context) (void *);
3106 if (!restore_context)
3107 restore_context = mono_get_restore_context ();
3109 tls = TlsGetValue (debugger_tls_id);
3110 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3112 process_single_step_inner (&ctx);
3114 /* This is called when resuming from a signal handler, so it shouldn't return */
3115 restore_context (&ctx);
3116 g_assert_not_reached ();
3120 * mono_debugger_agent_single_step_event:
3122 * Called from a signal handler to handle a single step event.
3125 mono_debugger_agent_single_step_event (void *sigctx)
3127 /* Resume to process_single_step through the signal context */
3129 // FIXME: Since step out/over is implemented using step in, the step in case should
3130 // be as fast as possible. Move the relevant code from process_single_step_inner ()
3133 if (GetCurrentThreadId () == debugger_thread_id) {
3135 * This could happen despite our best effors when the runtime calls
3136 * assembly/type resolve hooks.
3137 * FIXME: Breakpoints too.
3141 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3142 mono_arch_skip_single_step (&ctx);
3143 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3147 resume_from_signal_handler (sigctx, process_single_step);
3151 * start_single_stepping:
3153 * Turn on single stepping. Can be called multiple times, for example,
3154 * by a single step event request + a suspend.
3157 start_single_stepping (void)
3159 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3160 int val = InterlockedIncrement (&ss_count);
3163 mono_arch_start_single_stepping ();
3165 g_assert_not_reached ();
3170 stop_single_stepping (void)
3172 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3173 int val = InterlockedDecrement (&ss_count);
3176 mono_arch_stop_single_stepping ();
3178 g_assert_not_reached ();
3183 * Start single stepping of thread THREAD
3186 ss_start (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
3188 DebuggerTlsData *tls;
3190 if (suspend_count == 0)
3191 return ERR_NOT_SUSPENDED;
3193 wait_for_suspend ();
3195 // FIXME: Multiple requests
3197 return ERR_NOT_IMPLEMENTED;
3199 ss_req = g_new0 (MonoSingleStepReq, 1);
3201 ss_req->thread = thread;
3202 ss_req->size = size;
3203 ss_req->depth = depth;
3206 mono_loader_lock ();
3207 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3208 mono_loader_unlock ();
3210 g_assert (tls->has_context);
3211 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
3213 if (ss_req->size == STEP_SIZE_LINE) {
3215 MonoDebugMethodInfo *minfo;
3217 /* Compute the initial line info */
3218 compute_frame_info (thread, tls);
3220 g_assert (tls->frame_count);
3221 frame = tls->frames [0];
3223 ss_req->last_method = frame->method;
3224 ss_req->last_line = -1;
3226 minfo = mono_debug_lookup_method (frame->method);
3227 if (minfo && frame->il_offset != -1) {
3228 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
3231 ss_req->last_line = loc->row;
3237 start_single_stepping ();
3243 ss_stop (EventRequest *req)
3247 g_assert (ss_req->req == req);
3252 stop_single_stepping ();
3256 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *ctx)
3261 /* Just-In-Time debugging */
3262 if (agent_config.onthrow && !inited) {
3264 gboolean found = FALSE;
3266 for (l = agent_config.onthrow; l; l = l->next) {
3267 char *ex_type = l->data;
3268 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
3270 if (!strcmp (ex_type, f))
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);
3291 mono_loader_lock ();
3292 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, exc, &suspend_policy);
3293 mono_loader_unlock ();
3295 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, suspend_policy);
3299 mono_debugger_agent_handle_unhandled_exception (MonoException *exc, MonoContext *ctx)
3303 if (!agent_config.onuncaught)
3306 finish_agent_init (FALSE);
3309 * Send an unsolicited EXCEPTION event with a dummy request id.
3311 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3312 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, SUSPEND_POLICY_ALL);
3318 * Add the encoding of the value at ADDR described by T to the buffer.
3321 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
3326 g_assert (*(void**)addr);
3327 addr = *(void**)addr;
3331 case MONO_TYPE_VOID:
3332 buffer_add_byte (buf, t->type);
3334 case MONO_TYPE_BOOLEAN:
3337 buffer_add_byte (buf, t->type);
3338 buffer_add_int (buf, *(gint8*)addr);
3340 case MONO_TYPE_CHAR:
3343 buffer_add_byte (buf, t->type);
3344 buffer_add_int (buf, *(gint16*)addr);
3349 buffer_add_byte (buf, t->type);
3350 buffer_add_int (buf, *(gint32*)addr);
3355 buffer_add_byte (buf, t->type);
3356 buffer_add_long (buf, *(gint64*)addr);
3360 case MONO_TYPE_PTR: {
3361 gssize val = *(gssize*)addr;
3363 buffer_add_byte (buf, t->type);
3364 buffer_add_long (buf, val);
3368 case MONO_TYPE_STRING:
3369 case MONO_TYPE_SZARRAY:
3370 case MONO_TYPE_OBJECT:
3371 case MONO_TYPE_CLASS:
3372 case MONO_TYPE_ARRAY:
3373 obj = *(MonoObject**)addr;
3376 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
3378 if (obj->vtable->klass->valuetype) {
3379 t = &obj->vtable->klass->byval_arg;
3380 addr = mono_object_unbox (obj);
3382 } else if (obj->vtable->klass->rank) {
3383 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
3384 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
3385 buffer_add_byte (buf, MONO_TYPE_CLASS);
3387 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
3389 buffer_add_objid (buf, obj);
3393 case MONO_TYPE_VALUETYPE: {
3397 MonoClass *klass = mono_class_from_mono_type (t);
3399 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
3400 buffer_add_byte (buf, klass->enumtype);
3401 buffer_add_typeid (buf, domain, klass);
3405 while ((f = mono_class_get_fields (klass, &iter))) {
3406 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
3408 if (mono_field_is_deleted (f))
3412 buffer_add_int (buf, nfields);
3415 while ((f = mono_class_get_fields (klass, &iter))) {
3416 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
3418 if (mono_field_is_deleted (f))
3420 buffer_add_value (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain);
3424 case MONO_TYPE_GENERICINST:
3425 if (mono_type_generic_inst_is_valuetype (t)) {
3437 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
3440 int type = decode_byte (buf, &buf, limit);
3442 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t)) {
3443 DEBUG(1, fprintf (log_file, "Expected value of type %d, got %d.\n", t->type, type));
3444 return ERR_INVALID_ARGUMENT;
3448 case MONO_TYPE_BOOLEAN:
3449 *(guint8*)addr = decode_int (buf, &buf, limit);
3451 case MONO_TYPE_CHAR:
3452 *(gunichar2*)addr = decode_int (buf, &buf, limit);
3455 *(gint8*)addr = decode_int (buf, &buf, limit);
3458 *(guint8*)addr = decode_int (buf, &buf, limit);
3461 *(gint16*)addr = decode_int (buf, &buf, limit);
3464 *(guint16*)addr = decode_int (buf, &buf, limit);
3467 *(gint32*)addr = decode_int (buf, &buf, limit);
3470 *(guint32*)addr = decode_int (buf, &buf, limit);
3473 *(gint64*)addr = decode_long (buf, &buf, limit);
3476 *(guint64*)addr = decode_long (buf, &buf, limit);
3479 *(guint32*)addr = decode_int (buf, &buf, limit);
3482 *(guint64*)addr = decode_long (buf, &buf, limit);
3484 case MONO_TYPE_VALUETYPE: {
3485 gboolean is_enum = decode_byte (buf, &buf, limit);
3489 gpointer iter = NULL;
3492 /* Enums are sent as a normal vtype */
3494 return ERR_NOT_IMPLEMENTED;
3495 klass = decode_typeid (buf, &buf, limit, &d, &err);
3499 if (klass != mono_class_from_mono_type (t))
3500 return ERR_INVALID_ARGUMENT;
3502 nfields = decode_int (buf, &buf, limit);
3503 while ((f = mono_class_get_fields (klass, &iter))) {
3504 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
3506 if (mono_field_is_deleted (f))
3508 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
3513 g_assert (nfields == 0);
3517 if (MONO_TYPE_IS_REFERENCE (t)) {
3518 if (type == MONO_TYPE_OBJECT) {
3519 int objid = decode_objid (buf, &buf, limit);
3523 err = get_object (objid, (MonoObject**)&obj);
3527 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
3528 return ERR_INVALID_ARGUMENT;
3529 if (obj && obj->vtable->domain != domain)
3530 return ERR_INVALID_ARGUMENT;
3532 mono_gc_wbarrier_generic_store (addr, obj);
3533 } else if (type == VALUE_TYPE_ID_NULL) {
3534 *(MonoObject**)addr = NULL;
3536 return ERR_INVALID_ARGUMENT;
3550 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain)
3557 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3558 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3561 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
3562 reg_val = mono_arch_context_get_int_reg (ctx, reg);
3564 buffer_add_value (buf, t, ®_val, domain);
3566 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
3567 addr = mono_arch_context_get_int_reg (ctx, reg);
3568 addr += (gint32)var->offset;
3570 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
3572 buffer_add_value (buf, t, addr, domain);
3574 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
3578 g_assert_not_reached ();
3583 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
3589 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3590 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3592 if (MONO_TYPE_IS_REFERENCE (t))
3593 size = sizeof (gpointer);
3595 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
3598 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
3599 // FIXME: Can't set registers, so we disable linears
3602 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
3603 addr = mono_arch_context_get_int_reg (ctx, reg);
3604 addr += (gint32)var->offset;
3606 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
3608 // FIXME: Write barriers
3609 memcpy (addr, val, size);
3611 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
3615 g_assert_not_reached ();
3620 clear_event_request (int req_id, int etype)
3624 mono_loader_lock ();
3625 for (i = 0; i < event_requests->len; ++i) {
3626 EventRequest *req = g_ptr_array_index (event_requests, i);
3628 if (req->id == req_id && req->event_kind == etype) {
3629 if (req->event_kind == EVENT_KIND_BREAKPOINT)
3630 clear_breakpoint (req->info);
3631 if (req->event_kind == EVENT_KIND_STEP)
3633 g_ptr_array_remove_index_fast (event_requests, i);
3638 mono_loader_unlock ();
3642 add_thread (gpointer key, gpointer value, gpointer user_data)
3644 MonoInternalThread *thread = value;
3645 Buffer *buf = user_data;
3647 buffer_add_objid (buf, (MonoObject*)thread);
3651 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
3653 guint8 *p = invoke->p;
3654 guint8 *end = invoke->endp;
3657 MonoMethodSignature *sig;
3660 MonoObject *this, *res, *exc;
3663 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
3668 m = decode_methodid (p, &p, end, &domain, &err);
3671 sig = mono_method_signature (m);
3673 if (m->klass->valuetype)
3674 this_buf = g_alloca (mono_class_instance_size (m->klass));
3676 this_buf = g_alloca (sizeof (MonoObject*));
3677 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
3681 if (!m->klass->valuetype)
3682 this = *(MonoObject**)this_buf;
3686 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>"));
3688 if (this && this->vtable->domain != domain)
3691 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
3692 if (!strcmp (m->name, ".ctor")) {
3693 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
3694 return ERR_INVALID_ARGUMENT;
3696 this = mono_object_new (domain, m->klass);
3698 return ERR_INVALID_ARGUMENT;
3702 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
3703 return ERR_INVALID_ARGUMENT;
3705 nargs = decode_int (p, &p, end);
3706 if (nargs != sig->param_count)
3707 return ERR_INVALID_ARGUMENT;
3708 /* Use alloca to get gc tracking */
3709 arg_buf = g_alloca (nargs * sizeof (gpointer));
3710 memset (arg_buf, 0, nargs * sizeof (gpointer));
3711 args = g_alloca (nargs * sizeof (gpointer));
3712 for (i = 0; i < nargs; ++i) {
3713 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
3714 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
3718 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
3721 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
3722 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
3725 args [i] = arg_buf [i];
3732 flags = decode_int (p, &p, end);
3733 if (flags & INVOKE_FLAG_DISABLE_BPS)
3734 tls->disable_breakpoints = TRUE;
3736 tls->disable_breakpoints = FALSE;
3739 * Add an LMF frame to link the stack frames on the invoke method with our caller.
3741 /* FIXME: Move this to arch specific code */
3742 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
3743 if (invoke->has_ctx) {
3746 lmf_addr = mono_get_lmf_addr ();
3749 memset (&ext, 0, sizeof (ext));
3751 ext.lmf.previous_lmf = *(lmf_addr);
3752 /* Mark that this is a MonoLMFExt */
3753 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
3754 ext.lmf.rsp = (gssize)&ext;
3755 #elif defined(TARGET_X86)
3756 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
3757 /* Mark that this is a MonoLMFExt */
3758 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
3759 ext.lmf.ebp = (gssize)&ext;
3760 #elif defined(TARGET_ARM)
3761 ext.lmf.previous_lmf = *(lmf_addr);
3762 /* Mark that this is a MonoLMFExt */
3763 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
3764 ext.lmf.ebp = (gssize)&ext;
3766 g_assert_not_reached ();
3769 ext.debugger_invoke = TRUE;
3770 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
3772 mono_set_lmf ((MonoLMF*)&ext);
3776 if (m->klass->valuetype)
3777 res = mono_runtime_invoke (m, this_buf, args, &exc);
3779 res = mono_runtime_invoke (m, this, args, &exc);
3781 buffer_add_byte (buf, 0);
3782 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
3784 buffer_add_byte (buf, 1);
3785 if (sig->ret->type == MONO_TYPE_VOID) {
3786 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
3787 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
3790 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
3791 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
3792 buffer_add_value (buf, sig->ret, &res, domain);
3793 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
3795 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
3801 tls->disable_breakpoints = FALSE;
3803 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
3804 if (invoke->has_ctx)
3805 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
3808 // FIXME: byref arguments
3816 * Invoke the method given by tls->invoke in the current thread.
3819 invoke_method (void)
3821 DebuggerTlsData *tls;
3826 static void (*restore_context) (void *);
3827 MonoContext restore_ctx;
3829 if (!restore_context)
3830 restore_context = mono_get_restore_context ();
3832 tls = TlsGetValue (debugger_tls_id);
3835 invoke = tls->invoke;
3839 tls->frames_up_to_date = FALSE;
3843 buffer_init (&buf, 128);
3845 err = do_invoke_method (tls, &buf, invoke);
3847 /* Start suspending before sending the reply */
3850 send_reply_packet (id, err, &buf);
3854 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
3856 if (invoke->has_ctx)
3857 save_thread_context (&restore_ctx);
3866 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
3869 case CMD_VM_VERSION: {
3870 char *build_info, *version;
3872 build_info = mono_get_runtime_build_info ();
3873 version = g_strdup_printf ("mono %s", build_info);
3875 buffer_add_string (buf, version); /* vm version */
3876 buffer_add_int (buf, MAJOR_VERSION);
3877 buffer_add_int (buf, MINOR_VERSION);
3878 g_free (build_info);
3882 case CMD_VM_ALL_THREADS: {
3884 mono_loader_lock ();
3885 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
3886 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
3887 mono_loader_unlock ();
3890 case CMD_VM_SUSPEND:
3892 wait_for_suspend ();
3895 if (suspend_count == 0)
3896 return ERR_NOT_SUSPENDED;
3899 case CMD_VM_DISPOSE:
3900 /* Clear all event requests */
3901 mono_loader_lock ();
3902 while (event_requests->len > 0) {
3903 EventRequest *req = g_ptr_array_index (event_requests, 0);
3905 clear_event_request (req->id, req->event_kind);
3907 mono_loader_unlock ();
3909 // FIXME: Count resumes
3911 disconnected = TRUE;
3914 int exit_code = decode_int (p, &p, end);
3916 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
3918 /* Have to send a reply before exiting */
3919 send_reply_packet (id, 0, buf);
3921 /* Clear all event requests */
3922 mono_loader_lock ();
3923 while (event_requests->len > 0) {
3924 EventRequest *req = g_ptr_array_index (event_requests, 0);
3926 clear_event_request (req->id, req->event_kind);
3928 mono_loader_unlock ();
3930 /* FIXME: Races with normal shutdown */
3931 while (suspend_count > 0)
3935 * The JDWP documentation says that the shutdown is not orderly. It doesn't
3936 * specify whenever a VM_DEATH event is sent. We currently do an orderly
3937 * shutdown similar to Environment.Exit ().
3939 mono_runtime_set_shutting_down ();
3941 mono_threads_set_shutting_down ();
3943 /* Suspend all managed threads since the runtime is going away */
3944 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
3945 mono_thread_suspend_all_other_threads ();
3946 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
3947 mono_runtime_quit ();
3948 #ifdef PLATFORM_WIN32
3949 shutdown (conn_fd, SD_BOTH);
3951 shutdown (conn_fd, SHUT_RDWR);
3953 DEBUG(1, fprintf (log_file, "Exiting...\n"));
3957 case CMD_VM_INVOKE_METHOD: {
3958 int objid = decode_objid (p, &p, end);
3960 DebuggerTlsData *tls;
3963 err = get_object (objid, (MonoObject**)&thread);
3967 // Wait for suspending if it already started
3969 wait_for_suspend ();
3970 if (!is_suspended ())
3971 return ERR_NOT_SUSPENDED;
3973 mono_loader_lock ();
3974 tls = mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
3975 mono_loader_unlock ();
3979 * Store the invoke data into tls, the thread will execute it after it is
3984 tls->invoke = g_new0 (InvokeData, 1);
3985 tls->invoke->id = id;
3986 tls->invoke->p = g_malloc (end - p);
3987 memcpy (tls->invoke->p, p, end - p);
3988 tls->invoke->endp = tls->invoke->p + (end - p);
3994 return ERR_NOT_IMPLEMENTED;
4001 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4006 case CMD_EVENT_REQUEST_SET: {
4008 int i, event_kind, suspend_policy, nmodifiers, mod;
4011 MonoThread *step_thread;
4012 int size, depth, step_thread_id;
4015 event_kind = decode_byte (p, &p, end);
4016 suspend_policy = decode_byte (p, &p, end);
4017 nmodifiers = decode_byte (p, &p, end);
4019 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
4020 req->id = InterlockedIncrement (&event_request_id);
4021 req->event_kind = event_kind;
4022 req->suspend_policy = suspend_policy;
4023 req->nmodifiers = nmodifiers;
4026 for (i = 0; i < nmodifiers; ++i) {
4027 mod = decode_byte (p, &p, end);
4029 req->modifiers [i].kind = mod;
4030 if (mod == MOD_KIND_COUNT) {
4031 req->modifiers [i].data.count = decode_int (p, &p, end);
4032 } else if (mod == MOD_KIND_LOCATION_ONLY) {
4033 method = decode_methodid (p, &p, end, &domain, &err);
4036 location = decode_long (p, &p, end);
4037 } else if (mod == MOD_KIND_STEP) {
4038 step_thread_id = decode_id (p, &p, end);
4039 size = decode_int (p, &p, end);
4040 depth = decode_int (p, &p, end);
4041 } else if (mod == MOD_KIND_THREAD_ONLY) {
4042 int id = decode_id (p, &p, end);
4044 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
4049 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
4050 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
4055 req->modifiers [i].data.exc_class = exc_class;
4057 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
4059 return ERR_INVALID_ARGUMENT;
4062 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
4063 int n = decode_int (p, &p, end);
4066 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
4067 for (j = 0; j < n; ++j) {
4068 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
4070 g_free (req->modifiers [i].data.assemblies);
4076 return ERR_NOT_IMPLEMENTED;
4080 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4083 req->info = set_breakpoint (method, location, req);
4084 } else if (req->event_kind == EVENT_KIND_STEP) {
4085 g_assert (step_thread_id);
4087 err = get_object (step_thread_id, (MonoObject**)&step_thread);
4093 err = ss_start (step_thread->internal_thread, size, depth, req);
4098 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
4099 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req);
4100 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
4101 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req);
4102 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
4104 if (req->nmodifiers) {
4106 return ERR_NOT_IMPLEMENTED;
4110 mono_loader_lock ();
4111 g_ptr_array_add (event_requests, req);
4112 mono_loader_unlock ();
4114 buffer_add_int (buf, req->id);
4117 case CMD_EVENT_REQUEST_CLEAR: {
4118 int etype = decode_byte (p, &p, end);
4119 int req_id = decode_int (p, &p, end);
4121 // FIXME: Make a faster mapping from req_id to request
4122 mono_loader_lock ();
4123 clear_event_request (req_id, etype);
4124 mono_loader_unlock ();
4127 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
4130 mono_loader_lock ();
4132 while (i < event_requests->len) {
4133 EventRequest *req = g_ptr_array_index (event_requests, i);
4135 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4136 clear_breakpoint (req->info);
4138 g_ptr_array_remove_index_fast (event_requests, i);
4144 mono_loader_unlock ();
4148 return ERR_NOT_IMPLEMENTED;
4155 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4161 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
4162 buffer_add_domainid (buf, mono_get_root_domain ());
4165 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
4166 domain = decode_domainid (p, &p, end, NULL, &err);
4169 buffer_add_string (buf, domain->friendly_name);
4172 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
4177 domain = decode_domainid (p, &p, end, NULL, &err);
4180 mono_loader_lock ();
4182 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4185 buffer_add_int (buf, count);
4186 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4188 buffer_add_assemblyid (buf, domain, ass);
4190 mono_loader_unlock ();
4193 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
4194 domain = decode_domainid (p, &p, end, NULL, &err);
4198 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
4201 case CMD_APPDOMAIN_GET_CORLIB: {
4202 domain = decode_domainid (p, &p, end, NULL, &err);
4206 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
4209 case CMD_APPDOMAIN_CREATE_STRING: {
4213 domain = decode_domainid (p, &p, end, NULL, &err);
4216 s = decode_string (p, &p, end);
4218 o = mono_string_new (domain, s);
4219 buffer_add_objid (buf, (MonoObject*)o);
4223 return ERR_NOT_IMPLEMENTED;
4230 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4236 ass = decode_assemblyid (p, &p, end, &domain, &err);
4241 case CMD_ASSEMBLY_GET_LOCATION: {
4242 buffer_add_string (buf, mono_image_get_filename (ass->image));
4245 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
4249 if (ass->image->dynamic) {
4250 buffer_add_id (buf, 0);
4252 token = mono_image_get_entry_point (ass->image);
4254 buffer_add_id (buf, 0);
4256 m = mono_get_method (ass->image, token, NULL);
4257 buffer_add_methodid (buf, domain, m);
4262 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
4263 buffer_add_moduleid (buf, domain, ass->image);
4266 case CMD_ASSEMBLY_GET_OBJECT: {
4267 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
4268 buffer_add_objid (buf, o);
4271 case CMD_ASSEMBLY_GET_TYPE: {
4272 char *s = decode_string (p, &p, end);
4273 gboolean ignorecase = decode_byte (p, &p, end);
4274 MonoTypeNameParse info;
4276 gboolean type_resolve;
4278 if (!mono_reflection_parse_type (s, &info)) {
4281 if (info.assembly.name)
4283 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
4285 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
4286 mono_reflection_free_type_info (&info);
4292 return ERR_NOT_IMPLEMENTED;
4299 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4305 case CMD_MODULE_GET_INFO: {
4306 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
4309 basename = g_path_get_basename (image->name);
4310 buffer_add_string (buf, basename); // name
4311 buffer_add_string (buf, image->module_name); // scopename
4312 buffer_add_string (buf, image->name); // fqname
4313 buffer_add_string (buf, mono_image_get_guid (image)); // guid
4314 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
4319 return ERR_NOT_IMPLEMENTED;
4326 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
4328 if (val && val->vtable->klass == mono_defaults.monotype_class) {
4329 /* Special case these so the client doesn't have to handle Type objects */
4331 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
4332 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
4333 } else if (MONO_TYPE_IS_REFERENCE (t))
4334 buffer_add_value (buf, t, &val, domain);
4336 buffer_add_value (buf, t, mono_object_unbox (val), domain);
4340 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
4346 buffer_add_int (buf, 0);
4350 for (i = 0; i < cinfo->num_attrs; ++i) {
4351 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
4354 buffer_add_int (buf, nattrs);
4356 for (i = 0; i < cinfo->num_attrs; ++i) {
4357 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
4358 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
4359 MonoArray *typed_args, *named_args;
4361 CattrNamedArg *arginfo;
4363 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
4365 buffer_add_methodid (buf, domain, attr->ctor);
4369 buffer_add_int (buf, mono_array_length (typed_args));
4370 for (j = 0; j < mono_array_length (typed_args); ++j) {
4371 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
4373 t = mono_method_signature (attr->ctor)->params [j];
4375 buffer_add_cattr_arg (buf, t, domain, val);
4378 buffer_add_int (buf, 0);
4383 buffer_add_int (buf, mono_array_length (named_args));
4385 for (j = 0; j < mono_array_length (named_args); ++j) {
4386 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
4388 if (arginfo [j].prop) {
4389 buffer_add_byte (buf, 0x54);
4390 buffer_add_propertyid (buf, domain, arginfo [j].prop);
4391 } else if (arginfo [j].field) {
4392 buffer_add_byte (buf, 0x53);
4394 g_assert_not_reached ();
4397 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
4400 buffer_add_int (buf, 0);
4407 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4418 klass = decode_typeid (p, &p, end, &domain, &err);
4423 case CMD_TYPE_GET_INFO: {
4424 buffer_add_string (buf, klass->name_space);
4425 buffer_add_string (buf, klass->name);
4427 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
4428 buffer_add_string (buf, name);
4430 buffer_add_assemblyid (buf, domain, klass->image->assembly);
4431 buffer_add_moduleid (buf, domain, klass->image);
4432 buffer_add_typeid (buf, domain, klass->parent);
4433 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
4434 buffer_add_typeid (buf, domain, klass->element_class);
4436 buffer_add_id (buf, 0);
4437 buffer_add_int (buf, klass->type_token);
4438 buffer_add_byte (buf, klass->rank);
4439 buffer_add_int (buf, klass->flags);
4441 type = &klass->byval_arg;
4442 // FIXME: Can't decide whenever a class represents a byref type
4445 if (type->type == MONO_TYPE_PTR)
4447 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
4449 if (type->type == MONO_TYPE_VALUETYPE)
4451 buffer_add_byte (buf, b);
4454 while ((nested = mono_class_get_nested_types (klass, &iter)))
4456 buffer_add_int (buf, nnested);
4458 while ((nested = mono_class_get_nested_types (klass, &iter)))
4459 buffer_add_typeid (buf, domain, nested);
4462 case CMD_TYPE_GET_METHODS: {
4465 gpointer iter = NULL;
4468 nmethods = mono_class_num_methods (klass);
4470 buffer_add_int (buf, nmethods);
4472 while ((m = mono_class_get_methods (klass, &iter))) {
4473 buffer_add_methodid (buf, domain, m);
4476 g_assert (i == nmethods);
4479 case CMD_TYPE_GET_FIELDS: {
4482 gpointer iter = NULL;
4485 nfields = mono_class_num_fields (klass);
4487 buffer_add_int (buf, nfields);
4489 while ((f = mono_class_get_fields (klass, &iter))) {
4490 buffer_add_fieldid (buf, domain, f);
4491 buffer_add_string (buf, f->name);
4492 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
4493 buffer_add_int (buf, f->type->attrs);
4496 g_assert (i == nfields);
4499 case CMD_TYPE_GET_PROPERTIES: {
4502 gpointer iter = NULL;
4505 nprops = mono_class_num_properties (klass);
4507 buffer_add_int (buf, nprops);
4509 while ((p = mono_class_get_properties (klass, &iter))) {
4510 buffer_add_propertyid (buf, domain, p);
4511 buffer_add_string (buf, p->name);
4512 buffer_add_methodid (buf, domain, p->get);
4513 buffer_add_methodid (buf, domain, p->set);
4514 buffer_add_int (buf, p->attrs);
4517 g_assert (i == nprops);
4520 case CMD_TYPE_GET_CATTRS: {
4521 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
4522 MonoCustomAttrInfo *cinfo;
4524 cinfo = mono_custom_attrs_from_class (klass);
4526 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
4529 case CMD_TYPE_GET_FIELD_CATTRS: {
4530 MonoClass *attr_klass;
4531 MonoCustomAttrInfo *cinfo;
4532 MonoClassField *field;
4534 field = decode_fieldid (p, &p, end, NULL, &err);
4537 attr_klass = decode_typeid (p, &p, end, NULL, &err);
4541 cinfo = mono_custom_attrs_from_field (klass, field);
4543 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
4546 case CMD_TYPE_GET_PROPERTY_CATTRS: {
4547 MonoClass *attr_klass;
4548 MonoCustomAttrInfo *cinfo;
4551 prop = decode_propertyid (p, &p, end, NULL, &err);
4554 attr_klass = decode_typeid (p, &p, end, NULL, &err);
4558 cinfo = mono_custom_attrs_from_property (klass, prop);
4560 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
4563 case CMD_TYPE_GET_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 vtable = mono_class_vtable (domain, f->parent);
4594 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
4595 mono_field_static_get_value (vtable, f, val);
4596 buffer_add_value (buf, f->type, val, domain);
4601 case CMD_TYPE_SET_VALUES: {
4609 len = decode_int (p, &p, end);
4610 for (i = 0; i < len; ++i) {
4611 f = decode_fieldid (p, &p, end, NULL, &err);
4615 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
4616 return ERR_INVALID_FIELDID;
4617 if (mono_class_field_is_special_static (f))
4618 return ERR_INVALID_FIELDID;
4620 /* Check that the field belongs to the object */
4622 for (k = klass; k; k = k->parent) {
4623 if (k == f->parent) {
4629 return ERR_INVALID_FIELDID;
4631 // FIXME: Check for literal/const
4633 vtable = mono_class_vtable (domain, f->parent);
4634 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
4635 err = decode_value (f->type, domain, val, p, &p, end);
4640 mono_field_static_set_value (vtable, f, val);
4645 case CMD_TYPE_GET_OBJECT: {
4646 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
4647 buffer_add_objid (buf, o);
4650 case CMD_TYPE_GET_SOURCE_FILES: {
4651 gpointer iter = NULL;
4653 char *source_file, *base;
4657 files = g_ptr_array_new ();
4659 while ((method = mono_class_get_methods (klass, &iter))) {
4660 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
4663 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
4665 for (i = 0; i < files->len; ++i)
4666 if (!strcmp (g_ptr_array_index (files, i), source_file))
4668 if (i == files->len)
4669 g_ptr_array_add (files, g_strdup (source_file));
4670 g_free (source_file);
4674 buffer_add_int (buf, files->len);
4675 for (i = 0; i < files->len; ++i) {
4676 source_file = g_ptr_array_index (files, i);
4677 base = g_path_get_basename (source_file);
4678 buffer_add_string (buf, base);
4680 g_free (source_file);
4682 g_ptr_array_free (files, TRUE);
4685 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
4686 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
4690 if (mono_class_is_assignable_from (klass, oklass))
4691 buffer_add_byte (buf, 1);
4693 buffer_add_byte (buf, 0);
4697 return ERR_NOT_IMPLEMENTED;
4704 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4709 MonoMethodHeader *header;
4711 method = decode_methodid (p, &p, end, &domain, &err);
4716 case CMD_METHOD_GET_NAME: {
4717 buffer_add_string (buf, method->name);
4720 case CMD_METHOD_GET_DECLARING_TYPE: {
4721 buffer_add_typeid (buf, domain, method->klass);
4724 case CMD_METHOD_GET_DEBUG_INFO: {
4725 MonoDebugMethodInfo *minfo;
4727 int i, n_il_offsets;
4731 header = mono_method_get_header (method);
4733 buffer_add_int (buf, 0);
4734 buffer_add_string (buf, "");
4735 buffer_add_int (buf, 0);
4739 minfo = mono_debug_lookup_method (method);
4741 buffer_add_int (buf, header->code_size);
4742 buffer_add_string (buf, "");
4743 buffer_add_int (buf, 0);
4747 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
4748 buffer_add_int (buf, header->code_size);
4749 buffer_add_string (buf, source_file);
4750 buffer_add_int (buf, n_il_offsets);
4751 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
4752 for (i = 0; i < n_il_offsets; ++i) {
4753 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
4754 buffer_add_int (buf, il_offsets [i]);
4755 buffer_add_int (buf, line_numbers [i]);
4757 g_free (source_file);
4758 g_free (il_offsets);
4759 g_free (line_numbers);
4762 case CMD_METHOD_GET_PARAM_INFO: {
4763 MonoMethodSignature *sig = mono_method_signature (method);
4767 /* FIXME: mono_class_from_mono_type () and byrefs */
4769 /* FIXME: Use a smaller encoding */
4770 buffer_add_int (buf, sig->call_convention);
4771 buffer_add_int (buf, sig->param_count);
4772 buffer_add_int (buf, sig->generic_param_count);
4773 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
4774 for (i = 0; i < sig->param_count; ++i) {
4776 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
4779 /* Emit parameter names */
4780 names = g_new (char *, sig->param_count);
4781 mono_method_get_param_names (method, (const char **) names);
4782 for (i = 0; i < sig->param_count; ++i)
4783 buffer_add_string (buf, names [i]);
4788 case CMD_METHOD_GET_LOCALS_INFO: {
4789 int i, j, num_locals;
4793 header = mono_method_get_header (method);
4796 buffer_add_int (buf, header->num_locals);
4799 for (i = 0; i < header->num_locals; ++i)
4800 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
4803 num_locals = mono_debug_lookup_locals (method, &local_names, &local_indexes);
4804 for (i = 0; i < header->num_locals; ++i) {
4805 for (j = 0; j < num_locals; ++j)
4806 if (local_indexes [j] == i)
4809 buffer_add_string (buf, local_names [j]);
4811 buffer_add_string (buf, "");
4813 g_free (local_names);
4814 g_free (local_indexes);
4817 /* FIXME: This works because we set debug_options.mdb_optimizations */
4818 for (i = 0; i < header->num_locals; ++i) {
4819 buffer_add_int (buf, 0);
4820 buffer_add_int (buf, header->code_size);
4825 case CMD_METHOD_GET_INFO:
4826 buffer_add_int (buf, method->flags);
4827 buffer_add_int (buf, method->iflags);
4828 buffer_add_int (buf, method->token);
4830 case CMD_METHOD_GET_BODY: {
4833 header = mono_method_get_header (method);
4835 buffer_add_int (buf, 0);
4837 buffer_add_int (buf, header->code_size);
4838 for (i = 0; i < header->code_size; ++i)
4839 buffer_add_byte (buf, header->code [i]);
4843 case CMD_METHOD_RESOLVE_TOKEN: {
4844 guint32 token = decode_int (p, &p, end);
4847 switch (mono_metadata_token_code (token)) {
4848 case MONO_TOKEN_STRING: {
4852 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
4855 s2 = mono_string_to_utf8 (s);
4857 buffer_add_byte (buf, TOKEN_TYPE_STRING);
4858 buffer_add_string (buf, s2);
4864 MonoClass *handle_class;
4866 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
4867 val = mono_method_get_wrapper_data (method, token);
4868 handle_class = mono_method_get_wrapper_data (method, token + 1);
4870 if (handle_class == NULL) {
4871 // Can't figure out the token type
4872 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
4876 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
4880 if (handle_class == mono_defaults.typehandle_class) {
4881 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
4882 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
4883 } else if (handle_class == mono_defaults.fieldhandle_class) {
4884 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
4885 buffer_add_fieldid (buf, domain, val);
4886 } else if (handle_class == mono_defaults.methodhandle_class) {
4887 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
4888 buffer_add_methodid (buf, domain, val);
4889 } else if (handle_class == mono_defaults.string_class) {
4892 s = mono_string_to_utf8 (val);
4893 buffer_add_byte (buf, TOKEN_TYPE_STRING);
4894 buffer_add_string (buf, s);
4897 g_assert_not_reached ();
4905 return ERR_NOT_IMPLEMENTED;
4912 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4914 int objid = decode_objid (p, &p, end);
4916 MonoThread *thread_obj;
4917 MonoInternalThread *thread;
4919 err = get_object (objid, (MonoObject**)&thread_obj);
4923 thread = thread_obj->internal_thread;
4926 case CMD_THREAD_GET_NAME: {
4928 gunichar2 *s = mono_thread_get_name (thread, &name_len);
4931 buffer_add_int (buf, 0);
4936 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
4938 buffer_add_int (buf, len);
4939 buffer_add_data (buf, (guint8*)name, len);
4944 case CMD_THREAD_GET_FRAME_INFO: {
4945 DebuggerTlsData *tls;
4946 int i, start_frame, length;
4948 // Wait for suspending if it already started
4950 wait_for_suspend ();
4951 if (!is_suspended ())
4952 return ERR_NOT_SUSPENDED;
4954 start_frame = decode_int (p, &p, end);
4955 length = decode_int (p, &p, end);
4957 if (start_frame != 0 || length != -1)
4958 return ERR_NOT_IMPLEMENTED;
4960 mono_loader_lock ();
4961 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4962 mono_loader_unlock ();
4965 compute_frame_info (thread, tls);
4967 buffer_add_int (buf, tls->frame_count);
4968 for (i = 0; i < tls->frame_count; ++i) {
4969 buffer_add_int (buf, tls->frames [i]->id);
4970 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->method);
4971 buffer_add_int (buf, tls->frames [i]->il_offset);
4973 * Instead of passing the frame type directly to the client, we associate
4974 * it with the previous frame using a set of flags. This avoids lots of
4975 * conditional code in the client, since a frame whose type isn't
4976 * FRAME_TYPE_MANAGED has no method, location, etc.
4978 buffer_add_byte (buf, tls->frames [i]->flags);
4983 case CMD_THREAD_GET_STATE:
4984 buffer_add_int (buf, thread->state);
4986 case CMD_THREAD_GET_INFO:
4987 buffer_add_byte (buf, thread->threadpool_thread);
4990 return ERR_NOT_IMPLEMENTED;
4997 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5001 MonoThread *thread_obj;
5002 MonoInternalThread *thread;
5004 DebuggerTlsData *tls;
5006 MonoDebugMethodJitInfo *jit;
5007 MonoDebugVarInfo *var;
5008 MonoMethodSignature *sig;
5010 MonoMethodHeader *header;
5012 objid = decode_objid (p, &p, end);
5013 err = get_object (objid, (MonoObject**)&thread_obj);
5017 thread = thread_obj->internal_thread;
5019 id = decode_id (p, &p, end);
5021 mono_loader_lock ();
5022 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5023 mono_loader_unlock ();
5026 for (i = 0; i < tls->frame_count; ++i) {
5027 if (tls->frames [i]->id == id)
5030 if (i == tls->frame_count)
5031 return ERR_INVALID_FRAMEID;
5033 frame = tls->frames [i];
5036 frame->jit = mono_debug_find_method (frame->method, frame->domain);
5037 g_assert (frame->jit);
5041 sig = mono_method_signature (frame->method);
5044 case CMD_STACK_FRAME_GET_VALUES: {
5045 len = decode_int (p, &p, end);
5046 header = mono_method_get_header (frame->method);
5048 for (i = 0; i < len; ++i) {
5049 pos = decode_int (p, &p, end);
5054 g_assert (pos >= 0 && pos < jit->num_params);
5056 var = &jit->params [pos];
5058 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain);
5060 g_assert (pos >= 0 && pos < jit->num_locals);
5062 var = &jit->locals [pos];
5064 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain);
5069 case CMD_STACK_FRAME_GET_THIS: {
5070 if (frame->method->klass->valuetype) {
5071 if (!sig->hasthis) {
5072 MonoObject *p = NULL;
5073 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
5075 add_var (buf, &frame->method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain);
5078 if (!sig->hasthis) {
5079 MonoObject *p = NULL;
5080 buffer_add_value (buf, &frame->method->klass->byval_arg, &p, frame->domain);
5082 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain);
5087 case CMD_STACK_FRAME_SET_VALUES: {
5090 MonoDebugVarInfo *var;
5092 len = decode_int (p, &p, end);
5093 header = mono_method_get_header (frame->method);
5095 for (i = 0; i < len; ++i) {
5096 pos = decode_int (p, &p, end);
5101 g_assert (pos >= 0 && pos < jit->num_params);
5103 t = sig->params [pos];
5104 var = &jit->params [pos];
5106 g_assert (pos >= 0 && pos < jit->num_locals);
5108 t = header->locals [pos];
5109 var = &jit->locals [pos];
5112 if (MONO_TYPE_IS_REFERENCE (t))
5113 val_buf = g_alloca (sizeof (MonoObject*));
5115 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
5116 err = decode_value (t, frame->domain, val_buf, p, &p, end);
5120 set_var (t, var, &frame->ctx, frame->domain, val_buf);
5125 return ERR_NOT_IMPLEMENTED;
5132 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5135 int objid, err, index, len, i, esize;
5138 objid = decode_objid (p, &p, end);
5139 err = get_object (objid, (MonoObject**)&arr);
5144 case CMD_ARRAY_REF_GET_LENGTH:
5145 buffer_add_int (buf, arr->obj.vtable->klass->rank);
5147 buffer_add_int (buf, arr->max_length);
5148 buffer_add_int (buf, 0);
5150 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
5151 buffer_add_int (buf, arr->bounds [i].length);
5152 buffer_add_int (buf, arr->bounds [i].lower_bound);
5156 case CMD_ARRAY_REF_GET_VALUES:
5157 index = decode_int (p, &p, end);
5158 len = decode_int (p, &p, end);
5160 g_assert (index >= 0 && len >= 0);
5161 // Reordered to avoid integer overflow
5162 g_assert (!(index > arr->max_length - len));
5164 esize = mono_array_element_size (arr->obj.vtable->klass);
5165 for (i = index; i < index + len; ++i) {
5166 elem = (gpointer*)((char*)arr->vector + (i * esize));
5167 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
5170 case CMD_ARRAY_REF_SET_VALUES:
5171 index = decode_int (p, &p, end);
5172 len = decode_int (p, &p, end);
5174 g_assert (index >= 0 && len >= 0);
5175 // Reordered to avoid integer overflow
5176 g_assert (!(index > arr->max_length - len));
5178 esize = mono_array_element_size (arr->obj.vtable->klass);
5179 for (i = index; i < index + len; ++i) {
5180 elem = (gpointer*)((char*)arr->vector + (i * esize));
5182 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
5186 return ERR_NOT_IMPLEMENTED;
5193 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5199 objid = decode_objid (p, &p, end);
5200 err = get_object (objid, (MonoObject**)&str);
5205 case CMD_STRING_REF_GET_VALUE:
5206 s = mono_string_to_utf8 (str);
5207 buffer_add_string (buf, s);
5211 return ERR_NOT_IMPLEMENTED;
5218 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5227 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
5228 objid = decode_objid (p, &p, end);
5229 err = get_object (objid, &obj);
5231 buffer_add_int (buf, 1);
5233 buffer_add_int (buf, 0);
5237 objid = decode_objid (p, &p, end);
5238 err = get_object (objid, &obj);
5243 case CMD_OBJECT_REF_GET_TYPE:
5244 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
5246 case CMD_OBJECT_REF_GET_VALUES:
5247 len = decode_int (p, &p, end);
5249 for (i = 0; i < len; ++i) {
5250 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
5254 /* Check that the field belongs to the object */
5256 for (k = obj->vtable->klass; k; k = k->parent) {
5257 if (k == f->parent) {
5263 return ERR_INVALID_FIELDID;
5265 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
5269 if (mono_class_field_is_special_static (f))
5270 return ERR_INVALID_FIELDID;
5272 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
5273 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 mono_field_static_get_value (vtable, f, val);
5276 buffer_add_value (buf, f->type, val, obj->vtable->domain);
5279 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
5283 case CMD_OBJECT_REF_SET_VALUES:
5284 len = decode_int (p, &p, end);
5286 for (i = 0; i < len; ++i) {
5287 f = decode_fieldid (p, &p, end, NULL, &err);
5291 /* Check that the field belongs to the object */
5293 for (k = obj->vtable->klass; k; k = k->parent) {
5294 if (k == f->parent) {
5300 return ERR_INVALID_FIELDID;
5302 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
5306 if (mono_class_field_is_special_static (f))
5307 return ERR_INVALID_FIELDID;
5309 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
5310 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
5312 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5313 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
5318 mono_field_static_set_value (vtable, f, val);
5321 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
5327 case CMD_OBJECT_REF_GET_ADDRESS:
5328 buffer_add_long (buf, (gssize)obj);
5330 case CMD_OBJECT_REF_GET_DOMAIN:
5331 buffer_add_domainid (buf, obj->vtable->domain);
5334 return ERR_NOT_IMPLEMENTED;
5341 command_set_to_string (CommandSet command_set)
5343 switch (command_set) {
5346 case CMD_SET_OBJECT_REF:
5347 return "OBJECT_REF";
5348 case CMD_SET_STRING_REF:
5349 return "STRING_REF";
5350 case CMD_SET_THREAD:
5352 case CMD_SET_ARRAY_REF:
5354 case CMD_SET_EVENT_REQUEST:
5355 return "EVENT_REQUEST";
5356 case CMD_SET_STACK_FRAME:
5357 return "STACK_FRAME";
5358 case CMD_SET_APPDOMAIN:
5360 case CMD_SET_ASSEMBLY:
5362 case CMD_SET_METHOD:
5366 case CMD_SET_MODULE:
5378 * This thread handles communication with the debugger client using a JDWP
5381 static guint32 WINAPI
5382 debugger_thread (void *arg)
5384 int res, len, id, flags, command_set, command;
5385 guint8 header [HEADER_LENGTH];
5386 guint8 *data, *p, *end;
5391 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
5393 debugger_thread_id = GetCurrentThreadId ();
5395 mono_jit_thread_attach (mono_get_root_domain ());
5397 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
5399 mono_set_is_debugger_attached (TRUE);
5402 res = read (conn_fd, header, HEADER_LENGTH);
5404 /* This will break if the socket is closed during shutdown too */
5405 if (res != HEADER_LENGTH)
5409 end = header + HEADER_LENGTH;
5411 len = decode_int (p, &p, end);
5412 id = decode_int (p, &p, end);
5413 flags = decode_byte (p, &p, end);
5414 command_set = decode_byte (p, &p, end);
5415 command = decode_byte (p, &p, end);
5417 g_assert (flags == 0);
5419 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%d), id=%d.\n", command_set_to_string (command_set), command, id));
5421 data = g_malloc (len - HEADER_LENGTH);
5422 res = read (conn_fd, data, len - HEADER_LENGTH);
5423 if (res != len - HEADER_LENGTH)
5427 end = data + (len - HEADER_LENGTH);
5429 buffer_init (&buf, 128);
5434 /* Process the request */
5435 switch (command_set) {
5437 err = vm_commands (command, id, p, end, &buf);
5438 if (!err && command == CMD_VM_INVOKE_METHOD)
5439 /* Sent after the invoke is complete */
5442 case CMD_SET_EVENT_REQUEST:
5443 err = event_commands (command, p, end, &buf);
5445 case CMD_SET_APPDOMAIN:
5446 err = domain_commands (command, p, end, &buf);
5448 case CMD_SET_ASSEMBLY:
5449 err = assembly_commands (command, p, end, &buf);
5451 case CMD_SET_MODULE:
5452 err = module_commands (command, p, end, &buf);
5455 err = type_commands (command, p, end, &buf);
5457 case CMD_SET_METHOD:
5458 err = method_commands (command, p, end, &buf);
5460 case CMD_SET_THREAD:
5461 err = thread_commands (command, p, end, &buf);
5463 case CMD_SET_STACK_FRAME:
5464 err = frame_commands (command, p, end, &buf);
5466 case CMD_SET_ARRAY_REF:
5467 err = array_commands (command, p, end, &buf);
5469 case CMD_SET_STRING_REF:
5470 err = string_commands (command, p, end, &buf);
5472 case CMD_SET_OBJECT_REF:
5473 err = object_commands (command, p, end, &buf);
5476 err = ERR_NOT_IMPLEMENTED;
5480 send_reply_packet (id, err, &buf);
5485 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
5489 mono_set_is_debugger_attached (FALSE);
5491 mono_mutex_lock (&debugger_thread_exited_mutex);
5492 debugger_thread_exited = TRUE;
5493 mono_cond_signal (&debugger_thread_exited_cond);
5494 mono_mutex_unlock (&debugger_thread_exited_mutex);
5496 #ifdef PLATFORM_WIN32
5497 shutdown (conn_fd, SD_BOTH);
5499 shutdown (conn_fd, SHUT_RDWR);
5505 #else /* DISABLE_DEBUGGER_AGENT */
5508 mono_debugger_agent_parse_options (char *options)
5510 g_error ("This runtime is configure with the debugger agent disabled.");
5514 mono_debugger_agent_init (void)
5519 mono_debugger_agent_cleanup (void)
5524 mono_debugger_agent_breakpoint_hit (void *sigctx)
5529 mono_debugger_agent_single_step_event (void *sigctx)
5534 mono_debugger_agent_free_domain_info (MonoDomain *domain)
5538 gboolean mono_debugger_agent_thread_interrupt (MonoJitInfo *ji)
5543 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *ctx)
5548 mono_debugger_agent_handle_unhandled_exception (MonoException *exc, MonoContext *ctx)