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
49 /* cygwin's headers do not seem to define these */
50 void WSAAPI freeaddrinfo (struct addrinfo*);
51 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
53 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
58 #ifdef PLATFORM_ANDROID
60 #include <linux/tcp.h>
61 #include <sys/endian.h>
64 #include <mono/metadata/mono-debug.h>
65 #include <mono/metadata/mono-debug-debugger.h>
66 #include <mono/metadata/debug-mono-symfile.h>
67 #include <mono/metadata/gc-internal.h>
68 #include <mono/metadata/threads-types.h>
69 #include <mono/metadata/socket-io.h>
70 #include <mono/utils/mono-semaphore.h>
71 #include "debugger-agent.h"
74 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
75 #define DISABLE_DEBUGGER_AGENT 1
78 #ifdef DISABLE_SOFT_DEBUG
79 #define DISABLE_DEBUGGER_AGENT 1
82 #ifndef DISABLE_DEBUGGER_AGENT
83 #include <mono/io-layer/mono-mutex.h>
85 /* Definitions to make backporting to 2.6 easier */
86 //#define MonoInternalThread MonoThread
87 //#define mono_thread_internal_current mono_thread_current
88 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
111 MonoDebugMethodJitInfo *jit;
114 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
115 * the frame can become invalid.
126 /* This is the context which needs to be restored after the invoke */
130 * If this is set, invoke this method with the arguments given by ARGS.
134 guint32 suspend_count;
141 gboolean has_context;
142 gpointer resume_event;
143 /* This is computed on demand when it is requested using the wire protocol */
144 /* It is freed up when the thread is resumed */
148 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
151 gboolean frames_up_to_date;
153 * Points to data about a pending invoke which needs to be executed after the thread
158 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
163 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
164 * within a finite amount of time.
168 * Set to TRUE if this thread is suspended in suspend_current ().
170 gboolean really_suspended;
171 /* Used to pass the context to the breakpoint/single step handler */
172 MonoContext handler_ctx;
173 /* Whenever thread_stop () was called for this thread */
176 /* Number of thread interruptions not yet processed */
177 gint32 interrupt_count;
179 /* Whenever to disable breakpoints (used during invokes) */
180 gboolean disable_breakpoints;
183 * Number of times this thread has been resumed using resume_thread ().
185 guint32 resume_count;
187 MonoInternalThread *thread;
190 * Information about the frame which transitioned to native code for running
193 StackFrameInfo async_last_frame;
196 * The context where the stack walk can be started for running threads.
198 MonoContext async_ctx;
200 gboolean has_async_ctx;
203 * The lmf where the stack walk can be started for running threads.
208 * The callee address of the last mono_runtime_invoke call
210 gpointer invoke_addr;
214 * Wire Protocol definitions
217 #define HEADER_LENGTH 11
219 #define MAJOR_VERSION 2
220 #define MINOR_VERSION 0
224 CMD_SET_OBJECT_REF = 9,
225 CMD_SET_STRING_REF = 10,
227 CMD_SET_ARRAY_REF = 13,
228 CMD_SET_EVENT_REQUEST = 15,
229 CMD_SET_STACK_FRAME = 16,
230 CMD_SET_APPDOMAIN = 20,
231 CMD_SET_ASSEMBLY = 21,
239 EVENT_KIND_VM_START = 0,
240 EVENT_KIND_VM_DEATH = 1,
241 EVENT_KIND_THREAD_START = 2,
242 EVENT_KIND_THREAD_DEATH = 3,
243 EVENT_KIND_APPDOMAIN_CREATE = 4,
244 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
245 EVENT_KIND_METHOD_ENTRY = 6,
246 EVENT_KIND_METHOD_EXIT = 7,
247 EVENT_KIND_ASSEMBLY_LOAD = 8,
248 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
249 EVENT_KIND_BREAKPOINT = 10,
250 EVENT_KIND_STEP = 11,
251 EVENT_KIND_TYPE_LOAD = 12,
252 EVENT_KIND_EXCEPTION = 13
256 SUSPEND_POLICY_NONE = 0,
257 SUSPEND_POLICY_EVENT_THREAD = 1,
258 SUSPEND_POLICY_ALL = 2
263 ERR_INVALID_OBJECT = 20,
264 ERR_INVALID_FIELDID = 25,
265 ERR_INVALID_FRAMEID = 30,
266 ERR_NOT_IMPLEMENTED = 100,
267 ERR_NOT_SUSPENDED = 101,
268 ERR_INVALID_ARGUMENT = 102,
274 MOD_KIND_THREAD_ONLY = 3,
275 MOD_KIND_LOCATION_ONLY = 7,
276 MOD_KIND_EXCEPTION_ONLY = 8,
278 MOD_KIND_ASSEMBLY_ONLY = 11
293 TOKEN_TYPE_STRING = 0,
295 TOKEN_TYPE_FIELD = 2,
296 TOKEN_TYPE_METHOD = 3,
297 TOKEN_TYPE_UNKNOWN = 4
301 VALUE_TYPE_ID_NULL = 0xf0,
302 VALUE_TYPE_ID_TYPE = 0xf1
306 FRAME_FLAG_DEBUGGER_INVOKE = 1
310 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
311 INVOKE_FLAG_SINGLE_THREADED = 2
316 CMD_VM_ALL_THREADS = 2,
321 CMD_VM_INVOKE_METHOD = 7
325 CMD_THREAD_GET_FRAME_INFO = 1,
326 CMD_THREAD_GET_NAME = 2,
327 CMD_THREAD_GET_STATE = 3,
328 CMD_THREAD_GET_INFO = 4
332 CMD_EVENT_REQUEST_SET = 1,
333 CMD_EVENT_REQUEST_CLEAR = 2,
334 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
342 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
343 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
344 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
345 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
346 CMD_APPDOMAIN_CREATE_STRING = 5,
347 CMD_APPDOMAIN_GET_CORLIB = 6
351 CMD_ASSEMBLY_GET_LOCATION = 1,
352 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
353 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
354 CMD_ASSEMBLY_GET_OBJECT = 4,
355 CMD_ASSEMBLY_GET_TYPE = 5,
356 CMD_ASSEMBLY_GET_NAME = 6
360 CMD_MODULE_GET_INFO = 1,
364 CMD_METHOD_GET_NAME = 1,
365 CMD_METHOD_GET_DECLARING_TYPE = 2,
366 CMD_METHOD_GET_DEBUG_INFO = 3,
367 CMD_METHOD_GET_PARAM_INFO = 4,
368 CMD_METHOD_GET_LOCALS_INFO = 5,
369 CMD_METHOD_GET_INFO = 6,
370 CMD_METHOD_GET_BODY = 7,
371 CMD_METHOD_RESOLVE_TOKEN = 8,
375 CMD_TYPE_GET_INFO = 1,
376 CMD_TYPE_GET_METHODS = 2,
377 CMD_TYPE_GET_FIELDS = 3,
378 CMD_TYPE_GET_VALUES = 4,
379 CMD_TYPE_GET_OBJECT = 5,
380 CMD_TYPE_GET_SOURCE_FILES = 6,
381 CMD_TYPE_SET_VALUES = 7,
382 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
383 CMD_TYPE_GET_PROPERTIES = 9,
384 CMD_TYPE_GET_CATTRS = 10,
385 CMD_TYPE_GET_FIELD_CATTRS = 11,
386 CMD_TYPE_GET_PROPERTY_CATTRS = 12
390 CMD_STACK_FRAME_GET_VALUES = 1,
391 CMD_STACK_FRAME_GET_THIS = 2,
392 CMD_STACK_FRAME_SET_VALUES = 3
396 CMD_ARRAY_REF_GET_LENGTH = 1,
397 CMD_ARRAY_REF_GET_VALUES = 2,
398 CMD_ARRAY_REF_SET_VALUES = 3,
402 CMD_STRING_REF_GET_VALUE = 1,
406 CMD_OBJECT_REF_GET_TYPE = 1,
407 CMD_OBJECT_REF_GET_VALUES = 2,
408 CMD_OBJECT_REF_IS_COLLECTED = 3,
409 CMD_OBJECT_REF_GET_ADDRESS = 4,
410 CMD_OBJECT_REF_GET_DOMAIN = 5,
411 CMD_OBJECT_REF_SET_VALUES = 6
417 int count; /* For kind == MOD_KIND_COUNT */
418 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
419 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
420 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
430 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
434 * Describes a single step request.
438 MonoInternalThread *thread;
443 MonoMethod *last_method;
445 /* Whenever single stepping is performed using start/stop_single_stepping () */
447 /* The list of breakpoints used to implement step-over */
451 /* Dummy structure used for the profiler callbacks */
456 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
462 static AgentConfig agent_config;
465 * Whenever the agent is fully initialized.
466 * When using the onuncaught or onthrow options, only some parts of the agent are
467 * initialized on startup, and the full initialization which includes connection
468 * establishment and the startup of the agent thread is only done in response to
471 static gint32 inited;
475 static int packet_id = 0;
477 static int objref_id = 0;
479 static int event_request_id = 0;
481 static int frame_id = 0;
483 static GPtrArray *event_requests;
485 static guint32 debugger_tls_id;
487 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
489 /* Maps MonoInternalThread -> DebuggerTlsData */
490 static MonoGHashTable *thread_to_tls;
492 /* Maps tid -> MonoInternalThread */
493 static MonoGHashTable *tid_to_thread;
495 /* Maps tid -> MonoThread (not MonoInternalThread) */
496 static MonoGHashTable *tid_to_thread_obj;
498 static gsize debugger_thread_id;
500 static HANDLE debugger_thread_handle;
502 static int log_level;
504 static FILE *log_file;
506 /* Classes whose class load event has been sent */
507 static GHashTable *loaded_classes;
509 /* Assemblies whose assembly load event has no been sent yet */
510 static GPtrArray *pending_assembly_loads;
512 /* Whenever the debugger thread has exited */
513 static gboolean debugger_thread_exited;
515 /* Cond variable used to wait for debugger_thread_exited becoming true */
516 static mono_cond_t debugger_thread_exited_cond;
518 /* Mutex for the cond var above */
519 static mono_mutex_t debugger_thread_exited_mutex;
521 static DebuggerProfiler debugger_profiler;
523 /* The single step request instance */
524 static SingleStepReq *ss_req = NULL;
525 static gpointer ss_invoke_addr = NULL;
527 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
528 /* Number of single stepping operations in progress */
532 static void transport_connect (const char *host, int port);
534 static guint32 WINAPI debugger_thread (void *arg);
536 static void runtime_initialized (MonoProfiler *prof);
538 static void runtime_shutdown (MonoProfiler *prof);
540 static void thread_startup (MonoProfiler *prof, gsize tid);
542 static void thread_end (MonoProfiler *prof, gsize tid);
544 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
546 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
548 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
550 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
552 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
554 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
556 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
558 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
560 static void start_single_stepping (void);
562 static void stop_single_stepping (void);
564 static void suspend_current (void);
566 /* Submodule init/cleanup */
567 static void breakpoints_init (void);
568 static void breakpoints_cleanup (void);
570 static void objrefs_init (void);
571 static void objrefs_cleanup (void);
573 static void ids_init (void);
574 static void ids_cleanup (void);
576 static void suspend_init (void);
578 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls);
579 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
580 static void ss_destroy (SingleStepReq *req);
582 static void start_debugger_thread (void);
584 static void finish_agent_init (gboolean on_startup);
587 parse_address (char *address, char **host, int *port)
589 char *pos = strchr (address, ':');
591 if (pos == NULL || pos == address)
594 *host = g_malloc (pos - address + 1);
595 strncpy (*host, address, pos - address);
596 (*host) [pos - address] = '\0';
598 *port = atoi (pos + 1);
606 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
607 fprintf (stderr, "Available options:\n");
608 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
609 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
610 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
611 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
612 fprintf (stderr, " suspend=y/n\t\t\tWhenever to suspend after startup.\n");
613 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
614 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
618 parse_flag (const char *option, char *flag)
620 if (!strcmp (flag, "y"))
622 else if (!strcmp (flag, "n"))
625 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
632 mono_debugger_agent_parse_options (char *options)
638 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
639 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
643 agent_config.enabled = TRUE;
644 agent_config.suspend = TRUE;
645 agent_config.server = FALSE;
647 args = g_strsplit (options, ",", -1);
648 for (ptr = args; ptr && *ptr; ptr ++) {
651 if (strncmp (arg, "transport=", 10) == 0) {
652 agent_config.transport = g_strdup (arg + 10);
653 } else if (strncmp (arg, "address=", 8) == 0) {
654 agent_config.address = g_strdup (arg + 8);
655 } else if (strncmp (arg, "loglevel=", 9) == 0) {
656 agent_config.log_level = atoi (arg + 9);
657 } else if (strncmp (arg, "logfile=", 8) == 0) {
658 agent_config.log_file = g_strdup (arg + 8);
659 } else if (strncmp (arg, "suspend=", 8) == 0) {
660 agent_config.suspend = parse_flag ("suspend", arg + 8);
661 } else if (strncmp (arg, "server=", 7) == 0) {
662 agent_config.server = parse_flag ("server", arg + 7);
663 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
664 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
665 } else if (strncmp (arg, "onthrow=", 8) == 0) {
666 /* We support multiple onthrow= options */
667 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
668 } else if (strncmp (arg, "onthrow", 7) == 0) {
669 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
670 } else if (strncmp (arg, "help", 4) == 0) {
673 } else if (strncmp (arg, "timeout=", 8) == 0) {
674 agent_config.timeout = atoi (arg + 8);
675 } else if (strncmp (arg, "launch=", 7) == 0) {
676 agent_config.launch = g_strdup (arg + 7);
683 if (agent_config.transport == NULL) {
684 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
687 if (strcmp (agent_config.transport, "dt_socket") != 0) {
688 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
692 if (agent_config.address == NULL && !agent_config.server) {
693 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
697 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
698 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
704 mono_debugger_agent_init (void)
706 if (!agent_config.enabled)
709 /* Need to know whenever a thread has acquired the loader mutex */
710 mono_loader_lock_track_ownership (TRUE);
712 event_requests = g_ptr_array_new ();
714 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
715 mono_cond_init (&debugger_thread_exited_cond, NULL);
717 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
718 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
719 mono_profiler_install_runtime_initialized (runtime_initialized);
720 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_unload, NULL);
721 mono_profiler_install_thread (thread_startup, thread_end);
722 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
723 mono_profiler_install_jit_end (jit_end);
724 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
726 debugger_tls_id = TlsAlloc ();
728 thread_to_tls = mono_g_hash_table_new (NULL, NULL);
729 MONO_GC_REGISTER_ROOT (thread_to_tls);
731 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
732 MONO_GC_REGISTER_ROOT (tid_to_thread);
734 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
735 MONO_GC_REGISTER_ROOT (tid_to_thread_obj);
737 loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
738 pending_assembly_loads = g_ptr_array_new ();
740 log_level = agent_config.log_level;
742 if (agent_config.log_file) {
743 log_file = fopen (agent_config.log_file, "w+");
745 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
757 mini_get_debug_options ()->gen_seq_points = TRUE;
759 * This is needed because currently we don't handle liveness info.
761 mini_get_debug_options ()->mdb_optimizations = TRUE;
763 /* This is needed because we can't set local variables in registers yet */
764 mono_disable_optimizations (MONO_OPT_LINEARS);
766 if (!agent_config.onuncaught && !agent_config.onthrow)
767 finish_agent_init (TRUE);
773 * Finish the initialization of the agent. This involves connecting the transport
774 * and starting the agent thread. This is either done at startup, or
775 * in response to some event like an unhandled exception.
778 finish_agent_init (gboolean on_startup)
784 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
787 if (agent_config.launch) {
790 // FIXME: Generated address
791 // FIXME: Races with transport_connect ()
793 argv [0] = agent_config.launch;
794 argv [1] = agent_config.transport;
795 argv [2] = agent_config.address;
798 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
800 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
805 if (agent_config.address) {
806 res = parse_address (agent_config.address, &host, &port);
813 transport_connect (host, port);
816 /* Do some which is usually done after sending the VMStart () event */
817 vm_start_event_sent = TRUE;
818 start_debugger_thread ();
823 mono_debugger_agent_cleanup (void)
828 /* This will interrupt the agent thread */
829 /* Close the read part only so it can still send back replies */
831 shutdown (conn_fd, SD_RECEIVE);
833 shutdown (conn_fd, SHUT_RD);
837 * Wait for the thread to exit.
839 * If we continue with the shutdown without waiting for it, then the client might
840 * not receive an answer to its last command like a resume.
841 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
844 //WaitForSingleObject (debugger_thread_handle, INFINITE);
845 if (GetCurrentThreadId () != debugger_thread_id) {
846 mono_mutex_lock (&debugger_thread_exited_mutex);
847 if (!debugger_thread_exited) {
849 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
850 mono_mutex_unlock (&debugger_thread_exited_mutex);
852 mono_mutex_lock (&debugger_thread_exited_mutex);
855 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
858 mono_mutex_unlock (&debugger_thread_exited_mutex);
861 breakpoints_cleanup ();
866 shutdown (conn_fd, SD_BOTH);
868 shutdown (conn_fd, SHUT_RDWR);
871 mono_mutex_destroy (&debugger_thread_exited_mutex);
872 mono_cond_destroy (&debugger_thread_exited_cond);
878 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
881 transport_connect (const char *host, int port)
883 struct addrinfo hints;
884 struct addrinfo *result, *rp;
886 char port_string [128];
887 char handshake_msg [128];
893 sprintf (port_string, "%d", port);
895 mono_network_init ();
897 /* Obtain address(es) matching host/port */
899 memset (&hints, 0, sizeof (struct addrinfo));
900 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
901 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
903 hints.ai_protocol = 0; /* Any protocol */
905 s = getaddrinfo (host, port_string, &hints, &result);
907 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d: %s\n", host, port, gai_strerror (s));
912 if (agent_config.server) {
913 /* Wait for a connection */
915 struct sockaddr_in addr;
918 /* No address, generate one */
919 sfd = socket (AF_INET, SOCK_STREAM, 0);
922 /* This will bind the socket to a random port */
923 res = listen (sfd, 16);
925 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
929 addrlen = sizeof (addr);
930 memset (&addr, 0, sizeof (addr));
931 res = getsockname (sfd, &addr, &addrlen);
935 port = ntohs (addr.sin_port);
937 /* Emit the address to stdout */
938 /* FIXME: Should print another interface, not localhost */
939 printf ("%s:%d\n", host, port);
941 /* Listen on the provided address */
942 for (rp = result; rp != NULL; rp = rp->ai_next) {
943 sfd = socket (rp->ai_family, rp->ai_socktype,
948 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
952 res = listen (sfd, 16);
960 * this function is not present on win2000 which we still support, and the
961 * workaround described here:
962 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
963 * only works with MSVC.
965 freeaddrinfo (result);
969 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
971 if (agent_config.timeout) {
976 tv.tv_usec = agent_config.timeout * 1000;
978 FD_SET (sfd, &readfds);
979 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
981 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
986 conn_fd = accept (sfd, NULL, NULL);
988 fprintf (stderr, "debugger-agent: Unable to listen on %s:%d\n", host, port);
992 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
994 /* Connect to the specified address */
995 /* FIXME: Respect the timeout */
996 for (rp = result; rp != NULL; rp = rp->ai_next) {
997 sfd = socket (rp->ai_family, rp->ai_socktype,
1002 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1003 break; /* Success */
1011 /* See the comment above */
1012 freeaddrinfo (result);
1016 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1021 /* Write handshake message */
1022 sprintf (handshake_msg, "DWP-Handshake");
1023 res = send (conn_fd, handshake_msg, strlen (handshake_msg), 0);
1024 g_assert (res != -1);
1027 res = recv (conn_fd, buf, strlen (handshake_msg), 0);
1028 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1029 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1034 * Set TCP_NODELAY on the socket so the client receives events/command
1035 * results immediately.
1039 int result = setsockopt(conn_fd,
1044 g_assert (result >= 0);
1049 transport_send (guint8 *data, int len)
1053 res = send (conn_fd, data, len, 0);
1061 start_debugger_thread (void)
1065 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1066 g_assert (debugger_thread_handle);
1070 * Functions to decode protocol data
1074 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1077 g_assert (*endbuf <= limit);
1082 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1085 g_assert (*endbuf <= limit);
1087 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1090 static inline gint64
1091 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1093 guint32 high = decode_int (buf, &buf, limit);
1094 guint32 low = decode_int (buf, &buf, limit);
1098 return ((((guint64)high) << 32) | ((guint64)low));
1102 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1104 return decode_int (buf, endbuf, limit);
1108 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1110 int len = decode_int (buf, &buf, limit);
1113 s = g_malloc (len + 1);
1116 memcpy (s, buf, len);
1125 * Functions to encode protocol data
1129 guint8 *buf, *p, *end;
1133 buffer_init (Buffer *buf, int size)
1135 buf->buf = g_malloc (size);
1137 buf->end = buf->buf + size;
1141 buffer_make_room (Buffer *buf, int size)
1143 if (buf->end - buf->p < size) {
1144 int new_size = buf->end - buf->buf + size + 32;
1145 guint8 *p = g_realloc (buf->buf, new_size);
1146 size = buf->p - buf->buf;
1149 buf->end = buf->buf + new_size;
1154 buffer_add_byte (Buffer *buf, guint8 val)
1156 buffer_make_room (buf, 1);
1162 buffer_add_int (Buffer *buf, guint32 val)
1164 buffer_make_room (buf, 4);
1165 buf->p [0] = (val >> 24) & 0xff;
1166 buf->p [1] = (val >> 16) & 0xff;
1167 buf->p [2] = (val >> 8) & 0xff;
1168 buf->p [3] = (val >> 0) & 0xff;
1173 buffer_add_long (Buffer *buf, guint64 l)
1175 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1176 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1180 buffer_add_id (Buffer *buf, int id)
1182 buffer_add_int (buf, (guint64)id);
1186 buffer_add_data (Buffer *buf, guint8 *data, int len)
1188 buffer_make_room (buf, len);
1189 memcpy (buf->p, data, len);
1194 buffer_add_string (Buffer *buf, const char *str)
1199 buffer_add_int (buf, 0);
1202 buffer_add_int (buf, len);
1203 buffer_add_data (buf, (guint8*)str, len);
1208 buffer_free (Buffer *buf)
1214 send_packet (int command_set, int command, Buffer *data)
1220 id = InterlockedIncrement (&packet_id);
1222 len = data->p - data->buf + 11;
1223 buffer_init (&buf, len);
1224 buffer_add_int (&buf, len);
1225 buffer_add_int (&buf, id);
1226 buffer_add_byte (&buf, 0); /* flags */
1227 buffer_add_byte (&buf, command_set);
1228 buffer_add_byte (&buf, command);
1229 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1231 res = transport_send (buf.buf, len);
1239 send_reply_packet (int id, int error, Buffer *data)
1245 len = data->p - data->buf + 11;
1246 buffer_init (&buf, len);
1247 buffer_add_int (&buf, len);
1248 buffer_add_int (&buf, id);
1249 buffer_add_byte (&buf, 0x80); /* flags */
1250 buffer_add_byte (&buf, (error >> 8) & 0xff);
1251 buffer_add_byte (&buf, error);
1252 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1254 res = transport_send (buf.buf, len);
1266 * Represents an object accessible by the debugger client.
1269 /* Unique id used in the wire protocol to refer to objects */
1272 * A weakref gc handle pointing to the object. The gc handle is used to
1273 * detect if the object was garbage collected.
1278 /* Maps objid -> ObjRef */
1279 static GHashTable *objrefs;
1282 free_objref (gpointer value)
1286 mono_gchandle_free (o->handle);
1294 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1298 objrefs_cleanup (void)
1300 g_hash_table_destroy (objrefs);
1304 static GHashTable *obj_to_objref;
1307 * Return an ObjRef for OBJ.
1310 get_objref (MonoObject *obj)
1321 /* Use a hash table with masked pointers to internalize object references */
1322 /* FIXME: This can grow indefinitely */
1323 mono_loader_lock ();
1326 obj_to_objref = g_hash_table_new (NULL, NULL);
1328 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1329 /* ref might refer to a different object with the same addr which was GCd */
1330 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1331 mono_loader_unlock ();
1335 ref = g_new0 (ObjRef, 1);
1336 ref->id = InterlockedIncrement (&objref_id);
1337 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1339 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1340 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1342 mono_loader_unlock ();
1348 get_objid (MonoObject *obj)
1350 return get_objref (obj)->id;
1354 * Set OBJ to the object identified by OBJID.
1355 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1359 get_object_allow_null (int objid, MonoObject **obj)
1369 return ERR_INVALID_OBJECT;
1371 mono_loader_lock ();
1373 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1376 *obj = mono_gchandle_get_target (ref->handle);
1377 mono_loader_unlock ();
1379 return ERR_INVALID_OBJECT;
1382 mono_loader_unlock ();
1383 return ERR_INVALID_OBJECT;
1388 get_object (int objid, MonoObject **obj)
1390 int err = get_object_allow_null (objid, obj);
1395 return ERR_INVALID_OBJECT;
1400 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1402 return decode_id (buf, endbuf, limit);
1406 buffer_add_objid (Buffer *buf, MonoObject *o)
1408 buffer_add_id (buf, get_objid (o));
1427 * Represents a runtime structure accessible to the debugger client
1430 /* Unique id used in the wire protocol */
1432 /* Domain of the runtime structure, NULL if the domain was unloaded */
1439 MonoAssembly *assembly;
1440 MonoClassField *field;
1442 MonoProperty *property;
1447 /* Maps runtime structure -> Id */
1448 GHashTable *val_to_id [ID_NUM];
1452 static GPtrArray *ids [ID_NUM];
1459 for (i = 0; i < ID_NUM; ++i)
1460 ids [i] = g_ptr_array_new ();
1468 for (i = 0; i < ID_NUM; ++i) {
1470 for (j = 0; j < ids [i]->len; ++j)
1471 g_free (g_ptr_array_index (ids [i], j));
1472 g_ptr_array_free (ids [i], TRUE);
1479 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1481 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1485 for (i = 0; i < ID_NUM; ++i)
1486 if (info->val_to_id [i])
1487 g_hash_table_destroy (info->val_to_id [i]);
1491 domain_jit_info (domain)->agent_info = NULL;
1493 /* Clear ids referencing structures in the domain */
1494 for (i = 0; i < ID_NUM; ++i) {
1496 for (j = 0; j < ids [i]->len; ++j) {
1497 Id *id = g_ptr_array_index (ids [i], j);
1498 if (id->domain == domain)
1506 get_id (MonoDomain *domain, IdType type, gpointer val)
1509 AgentDomainInfo *info;
1514 mono_loader_lock ();
1516 mono_domain_lock (domain);
1518 if (!domain_jit_info (domain)->agent_info)
1519 domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1520 info = domain_jit_info (domain)->agent_info;
1521 if (info->val_to_id [type] == NULL)
1522 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1524 id = g_hash_table_lookup (info->val_to_id [type], val);
1526 mono_domain_unlock (domain);
1527 mono_loader_unlock ();
1531 id = g_new0 (Id, 1);
1533 id->id = ids [type]->len + 1;
1534 id->domain = domain;
1537 g_hash_table_insert (info->val_to_id [type], val, id);
1539 mono_domain_unlock (domain);
1541 g_ptr_array_add (ids [type], id);
1543 mono_loader_unlock ();
1548 static inline gpointer
1549 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1553 int id = decode_id (buf, endbuf, limit);
1562 // FIXME: error handling
1563 mono_loader_lock ();
1564 g_assert (id > 0 && id <= ids [type]->len);
1566 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1567 mono_loader_unlock ();
1569 if (res->domain == NULL) {
1570 *err = ERR_UNLOADED;
1575 *domain = res->domain;
1577 return res->data.val;
1581 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1583 buffer_add_id (buf, get_id (domain, type, val));
1586 static inline MonoClass*
1587 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1589 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1592 static inline MonoAssembly*
1593 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1595 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1598 static inline MonoImage*
1599 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1601 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1604 static inline MonoMethod*
1605 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1607 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1610 static inline MonoClassField*
1611 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1613 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1616 static inline MonoDomain*
1617 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1619 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1622 static inline MonoProperty*
1623 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1625 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1629 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1631 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1635 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1637 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1641 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1643 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1647 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1649 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1653 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1655 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1659 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1661 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1665 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1667 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1670 static void invoke_method (void);
1677 * save_thread_context:
1679 * Set CTX as the current threads context which is used for computing stack traces.
1680 * This function is signal-safe.
1683 save_thread_context (MonoContext *ctx)
1685 DebuggerTlsData *tls;
1687 tls = TlsGetValue (debugger_tls_id);
1691 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1693 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1694 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1696 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1700 tls->lmf = mono_get_lmf ();
1701 tls->domain = mono_domain_get ();
1702 tls->has_context = TRUE;
1705 /* The number of times the runtime is suspended */
1706 static gint32 suspend_count;
1708 /* Number of threads suspended */
1710 * If this is equal to the size of thread_to_tls, the runtime is considered
1713 static gint32 threads_suspend_count;
1715 static mono_mutex_t suspend_mutex;
1717 /* Cond variable used to wait for suspend_count becoming 0 */
1718 static mono_cond_t suspend_cond;
1720 /* Semaphore used to wait for a thread becoming suspended */
1721 static MonoSemType suspend_sem;
1726 mono_mutex_init (&suspend_mutex, NULL);
1727 mono_cond_init (&suspend_cond, NULL);
1728 MONO_SEM_INIT (&suspend_sem, 0);
1733 StackFrameInfo last_frame;
1734 gboolean last_frame_set;
1737 } GetLastFrameUserData;
1740 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
1742 GetLastFrameUserData *data = user_data;
1744 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
1747 if (!data->last_frame_set) {
1748 /* Store the last frame */
1749 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
1750 data->last_frame_set = TRUE;
1753 /* Store the context/lmf for the frame above the last frame */
1754 memcpy (&data->ctx, ctx, sizeof (MonoContext));
1755 data->lmf = info->lmf;
1762 * mono_debugger_agent_thread_interrupt:
1764 * Called by the abort signal handler.
1765 * Should be signal safe.
1768 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
1770 DebuggerTlsData *tls;
1775 tls = TlsGetValue (debugger_tls_id);
1780 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
1781 * guarantee the signal handler will be called that many times. Instead of tracking
1782 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
1783 * has been requested that hasn't been handled yet, otherwise we can have threads
1784 * refuse to die when VM_EXIT is called
1786 #if defined(__APPLE__)
1787 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
1791 * We use interrupt_count to determine whenever this interrupt should be processed
1792 * by us or the normal interrupt processing code in the signal handler.
1793 * There is no race here with notify_thread (), since the signal is sent after
1794 * incrementing interrupt_count.
1796 if (tls->interrupt_count == 0)
1799 InterlockedDecrement (&tls->interrupt_count);
1802 // FIXME: Races when the thread leaves managed code before hitting a single step
1806 /* Running managed code, will be suspended by the single step code */
1807 DEBUG (1, printf ("[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)GetCurrentThreadId (), ji->method->name, mono_arch_ip_from_context (sigctx)));
1811 * Running native code, will be suspended when it returns to/enters
1812 * managed code. Treat it as already suspended.
1813 * This might interrupt the code in process_single_step_inner (), we use the
1814 * tls->suspending flag to avoid races when that happens.
1816 if (!tls->suspended && !tls->suspending) {
1818 GetLastFrameUserData data;
1820 // FIXME: printf is not signal safe, but this is only used during
1821 // debugger debugging
1822 DEBUG (1, printf ("[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)GetCurrentThreadId (), mono_arch_ip_from_context (sigctx)));
1823 //save_thread_context (&ctx);
1826 /* Already terminated */
1830 * We are in a difficult position: we want to be able to provide stack
1831 * traces for this thread, but we can't use the current ctx+lmf, since
1832 * the thread is still running, so it might return to managed code,
1833 * making these invalid.
1834 * So we start a stack walk and save the first frame, along with the
1835 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
1836 * suspended when it returns to managed code, so the parent's ctx should
1839 data.last_frame_set = FALSE;
1841 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
1842 mono_jit_walk_stack_from_ctx_in_thread (get_last_frame, mono_domain_get (), &ctx, FALSE, tls->thread, mono_get_lmf (), &data);
1844 if (data.last_frame_set) {
1845 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
1846 memcpy (&tls->async_ctx, &data.ctx, sizeof (MonoContext));
1847 tls->async_lmf = data.lmf;
1848 tls->has_async_ctx = TRUE;
1849 tls->domain = mono_domain_get ();
1850 memcpy (&tls->ctx, &ctx, sizeof (MonoContext));
1852 tls->has_async_ctx = FALSE;
1855 tls->suspended = TRUE;
1856 MONO_SEM_POST (&suspend_sem);
1863 static void CALLBACK notify_thread_apc (ULONG_PTR param)
1866 mono_debugger_agent_thread_interrupt (NULL, NULL);
1868 #endif /* HOST_WIN32 */
1871 * reset_native_thread_suspend_state:
1873 * Reset the suspended flag on native threads
1876 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
1878 DebuggerTlsData *tls = value;
1880 if (!tls->really_suspended && tls->suspended)
1881 tls->suspended = FALSE;
1887 * Notify a thread that it needs to suspend.
1890 notify_thread (gpointer key, gpointer value, gpointer user_data)
1892 MonoInternalThread *thread = key;
1893 DebuggerTlsData *tls = value;
1894 gsize tid = thread->tid;
1896 if (GetCurrentThreadId () != tid) {
1897 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
1900 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
1901 * guarantee the signal handler will be called that many times. Instead of tracking
1902 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
1903 * has been requested that hasn't been handled yet, otherwise we can have threads
1904 * refuse to die when VM_EXIT is called
1906 #if defined(__APPLE__)
1907 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
1911 * Maybe we could use the normal interrupt infrastructure, but that does a lot
1912 * of things like breaking waits etc. which we don't want.
1914 InterlockedIncrement (&tls->interrupt_count);
1917 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
1919 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
1921 pthread_kill ((pthread_t) tid, mono_thread_get_abort_signal ());
1927 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
1929 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
1932 if (debugger_thread_id == GetCurrentThreadId ())
1935 /* Prevent races with mono_debugger_agent_thread_interrupt () */
1936 if (suspend_count - tls->resume_count > 0)
1937 tls->suspending = TRUE;
1939 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
1941 if (suspend_count - tls->resume_count == 0) {
1943 * We are executing a single threaded invoke but the single step for
1944 * suspending is still active.
1945 * FIXME: This slows down single threaded invokes.
1947 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
1951 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
1953 /* Can't suspend in these methods */
1954 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
1957 save_thread_context (ctx);
1965 * Increase the suspend count of the VM. While the suspend count is greater
1966 * than 0, runtime threads are suspended at certain points during execution.
1971 mono_loader_lock ();
1973 mono_mutex_lock (&suspend_mutex);
1977 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
1979 if (suspend_count == 1) {
1980 // FIXME: Is it safe to call this inside the lock ?
1981 start_single_stepping ();
1982 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
1985 mono_mutex_unlock (&suspend_mutex);
1987 mono_loader_unlock ();
1993 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2001 g_assert (debugger_thread_id == GetCurrentThreadId ());
2003 mono_loader_lock ();
2005 mono_mutex_lock (&suspend_mutex);
2007 g_assert (suspend_count > 0);
2010 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2012 if (suspend_count == 0) {
2013 // FIXME: Is it safe to call this inside the lock ?
2014 stop_single_stepping ();
2015 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2018 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2019 err = mono_cond_broadcast (&suspend_cond);
2020 g_assert (err == 0);
2022 mono_mutex_unlock (&suspend_mutex);
2023 //g_assert (err == 0);
2025 mono_loader_unlock ();
2031 * Resume just one thread.
2034 resume_thread (MonoInternalThread *thread)
2037 DebuggerTlsData *tls;
2039 g_assert (debugger_thread_id == GetCurrentThreadId ());
2041 mono_loader_lock ();
2043 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2046 mono_mutex_lock (&suspend_mutex);
2048 g_assert (suspend_count > 0);
2050 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2052 tls->resume_count += suspend_count;
2055 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2056 * but only the one whose resume_count field is > 0 will be resumed.
2058 err = mono_cond_broadcast (&suspend_cond);
2059 g_assert (err == 0);
2061 mono_mutex_unlock (&suspend_mutex);
2062 //g_assert (err == 0);
2064 mono_loader_unlock ();
2068 invalidate_frames (DebuggerTlsData *tls)
2073 tls = TlsGetValue (debugger_tls_id);
2076 for (i = 0; i < tls->frame_count; ++i) {
2077 if (tls->frames [i]->jit)
2078 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2079 g_free (tls->frames [i]);
2081 g_free (tls->frames);
2082 tls->frame_count = 0;
2089 * Suspend the current thread until the runtime is resumed. If the thread has a
2090 * pending invoke, then the invoke is executed before this function returns.
2093 suspend_current (void)
2096 DebuggerTlsData *tls;
2098 g_assert (debugger_thread_id != GetCurrentThreadId ());
2100 if (mono_loader_lock_is_owned_by_self ()) {
2102 * If we own the loader mutex, can't suspend until we release it, since the
2103 * whole runtime can deadlock otherwise.
2108 tls = TlsGetValue (debugger_tls_id);
2111 mono_mutex_lock (&suspend_mutex);
2113 tls->suspending = FALSE;
2114 tls->really_suspended = TRUE;
2116 if (!tls->suspended) {
2117 tls->suspended = TRUE;
2118 MONO_SEM_POST (&suspend_sem);
2121 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2123 while (suspend_count - tls->resume_count > 0) {
2125 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2127 mono_mutex_unlock (&suspend_mutex);
2129 mono_mutex_lock (&suspend_mutex);
2135 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2136 g_assert (err == 0);
2140 tls->suspended = FALSE;
2141 tls->really_suspended = FALSE;
2143 threads_suspend_count --;
2145 mono_mutex_unlock (&suspend_mutex);
2147 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2150 /* Save the original context */
2151 tls->invoke->has_ctx = TRUE;
2152 memcpy (&tls->invoke->ctx, &tls->ctx, sizeof (MonoContext));
2157 /* The frame info becomes invalid after a resume */
2158 tls->has_context = FALSE;
2159 tls->has_async_ctx = FALSE;
2160 invalidate_frames (NULL);
2164 count_thread (gpointer key, gpointer value, gpointer user_data)
2166 DebuggerTlsData *tls = value;
2168 if (!tls->suspended && !tls->terminated)
2169 *(int*)user_data = *(int*)user_data + 1;
2173 count_threads_to_wait_for (void)
2177 mono_loader_lock ();
2178 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2179 mono_loader_unlock ();
2187 * Wait until the runtime is completely suspended.
2190 wait_for_suspend (void)
2192 int nthreads, nwait, err;
2193 gboolean waited = FALSE;
2195 // FIXME: Threads starting/stopping ?
2196 mono_loader_lock ();
2197 nthreads = mono_g_hash_table_size (thread_to_tls);
2198 mono_loader_unlock ();
2201 nwait = count_threads_to_wait_for ();
2203 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2204 err = MONO_SEM_WAIT (&suspend_sem);
2205 g_assert (err == 0);
2213 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2219 * Return whenever the runtime is suspended.
2224 return count_threads_to_wait_for () == 0;
2228 * find_seq_point_for_native_offset:
2230 * Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2231 * should be the location of a sequence point.
2234 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2236 MonoSeqPointInfo *seq_points;
2239 mono_domain_lock (domain);
2240 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2241 mono_domain_unlock (domain);
2242 g_assert (seq_points);
2246 for (i = 0; i < seq_points->len; ++i) {
2247 if (seq_points->seq_points [i].native_offset == native_offset)
2248 return &seq_points->seq_points [i];
2257 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2258 * should be the location of a sequence point.
2261 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2263 MonoSeqPointInfo *seq_points;
2266 mono_domain_lock (domain);
2267 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2268 mono_domain_unlock (domain);
2269 g_assert (seq_points);
2273 for (i = 0; i < seq_points->len; ++i) {
2274 if (seq_points->seq_points [i].il_offset == il_offset)
2275 return &seq_points->seq_points [i];
2282 * compute_il_offset:
2284 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2285 * a location of a sequence point.
2286 * We use this function instead of mono_debug_il_offset_from_address () etc,
2287 * which doesn't seem to work in a lot of cases.
2290 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2292 MonoSeqPointInfo *seq_points;
2293 int i, last_il_offset, seq_il_offset, seq_native_offset;
2295 mono_domain_lock (domain);
2296 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2297 mono_domain_unlock (domain);
2298 g_assert (seq_points);
2300 last_il_offset = -1;
2302 /* Find the sequence point */
2303 for (i = 0; i < seq_points->len; ++i) {
2304 seq_il_offset = seq_points->seq_points [i].il_offset;
2305 seq_native_offset = seq_points->seq_points [i].native_offset;
2307 if (seq_native_offset > native_offset)
2309 last_il_offset = seq_il_offset;
2312 return last_il_offset;
2316 DebuggerTlsData *tls;
2318 } ComputeFramesUserData;
2321 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2323 ComputeFramesUserData *ud = user_data;
2327 if (info->type != FRAME_TYPE_MANAGED) {
2328 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2329 /* Mark the last frame as an invoke frame */
2331 ((StackFrame*)ud->frames->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2337 method = info->ji->method;
2339 method = info->method;
2341 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2344 if (info->il_offset == -1) {
2345 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2346 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2349 DEBUG (1, fprintf (stderr, "\tFrame: %s %d %d %d\n", mono_method_full_name (method, TRUE), info->native_offset, info->il_offset, info->managed));
2351 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2353 * mono_arch_find_jit_info () returns the context stored in the LMF for
2354 * native frames, but it should unwind once. This is why we have duplicate
2355 * frames on the stack sometimes.
2356 * !managed also seems to be set for dynamic methods.
2361 frame = g_new0 (StackFrame, 1);
2362 frame->method = method;
2363 frame->il_offset = info->il_offset;
2366 frame->has_ctx = TRUE;
2368 frame->domain = info->domain;
2370 ud->frames = g_slist_append (ud->frames, frame);
2376 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2378 ComputeFramesUserData user_data;
2380 int i, findex, new_frame_count;
2381 StackFrame **new_frames, *f;
2383 // FIXME: Locking on tls
2384 if (tls->frames && tls->frames_up_to_date)
2387 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2389 user_data.tls = tls;
2390 user_data.frames = NULL;
2391 if (tls->terminated) {
2392 tls->frame_count = 0;
2394 } if (!tls->really_suspended && tls->has_async_ctx) {
2395 /* Have to use the state saved by the signal handler */
2396 process_frame (&tls->async_last_frame, NULL, &user_data);
2397 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->async_ctx, FALSE, thread, tls->async_lmf, &user_data);
2398 } else if (tls->has_context) {
2399 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
2402 tls->frame_count = 0;
2406 new_frame_count = g_slist_length (user_data.frames);
2407 new_frames = g_new0 (StackFrame*, new_frame_count);
2409 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2413 * Reuse the id for already existing stack frames, so invokes don't invalidate
2414 * the still valid stack frames.
2416 for (i = 0; i < tls->frame_count; ++i) {
2417 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2418 f->id = tls->frames [i]->id;
2423 if (i >= tls->frame_count)
2424 f->id = InterlockedIncrement (&frame_id);
2426 new_frames [findex ++] = f;
2429 g_slist_free (user_data.frames);
2431 invalidate_frames (tls);
2433 tls->frames = new_frames;
2434 tls->frame_count = new_frame_count;
2435 tls->frames_up_to_date = TRUE;
2443 * create_event_list:
2445 * Return a list of event request ids matching EVENT, starting from REQS, which
2446 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2448 * We return request ids, instead of requests, to simplify threading, since
2449 * requests could be deleted anytime when the loader lock is not held.
2450 * LOCKING: Assumes the loader lock is held.
2453 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, MonoException *exc, int *suspend_policy)
2456 GSList *events = NULL;
2458 *suspend_policy = SUSPEND_POLICY_NONE;
2461 reqs = event_requests;
2466 for (i = 0; i < reqs->len; ++i) {
2467 EventRequest *req = g_ptr_array_index (reqs, i);
2468 if (req->event_kind == event) {
2469 gboolean filtered = FALSE;
2472 for (j = 0; j < req->nmodifiers; ++j) {
2473 Modifier *mod = &req->modifiers [j];
2475 if (mod->kind == MOD_KIND_COUNT) {
2477 if (mod->data.count > 0) {
2478 if (mod->data.count > 0) {
2480 if (mod->data.count == 0)
2484 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2485 if (mod->data.thread != mono_thread_internal_current ())
2487 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && exc) {
2488 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, exc->object.vtable->klass))
2490 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2492 gboolean found = FALSE;
2493 MonoAssembly **assemblies = mod->data.assemblies;
2496 for (k = 0; assemblies [k]; ++k)
2497 if (assemblies [k] == ji->method->klass->image->assembly)
2506 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2507 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2512 /* Send a VM START/DEATH event by default */
2513 if (event == EVENT_KIND_VM_START)
2514 events = g_slist_append (events, GINT_TO_POINTER (0));
2515 if (event == EVENT_KIND_VM_DEATH)
2516 events = g_slist_append (events, GINT_TO_POINTER (0));
2521 static G_GNUC_UNUSED const char*
2522 event_to_string (EventKind event)
2525 case EVENT_KIND_VM_START: return "VM_START";
2526 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2527 case EVENT_KIND_THREAD_START: return "THREAD_START";
2528 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2529 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2530 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2531 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2532 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2533 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2534 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2535 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2536 case EVENT_KIND_STEP: return "STEP";
2537 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2538 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2540 g_assert_not_reached ();
2547 * Send an event to the client, suspending the vm if needed.
2548 * LOCKING: Since this can suspend the calling thread, no locks should be held
2550 * The EVENTS list is freed by this function.
2553 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2557 MonoDomain *domain = mono_domain_get ();
2563 if (!vm_start_event_sent && event != EVENT_KIND_VM_START)
2564 // FIXME: We miss those events
2567 if (vm_death_event_sent)
2570 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH)
2579 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
2580 // FIXME: Send these with a NULL thread, don't suspend the current thread
2583 buffer_init (&buf, 128);
2584 buffer_add_byte (&buf, suspend_policy);
2585 buffer_add_int (&buf, g_slist_length (events)); // n of events
2587 for (l = events; l; l = l->next) {
2588 buffer_add_byte (&buf, event); // event kind
2589 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
2591 thread = mono_thread_current ();
2593 if (event == EVENT_KIND_VM_START)
2595 else if (event == EVENT_KIND_THREAD_START)
2596 g_assert (mono_thread_internal_current () == arg);
2598 buffer_add_objid (&buf, (MonoObject*)thread); // thread
2601 case EVENT_KIND_THREAD_START:
2602 case EVENT_KIND_THREAD_DEATH:
2604 case EVENT_KIND_APPDOMAIN_CREATE:
2605 case EVENT_KIND_APPDOMAIN_UNLOAD:
2606 buffer_add_domainid (&buf, arg);
2608 case EVENT_KIND_METHOD_ENTRY:
2609 case EVENT_KIND_METHOD_EXIT:
2610 buffer_add_methodid (&buf, domain, arg);
2612 case EVENT_KIND_ASSEMBLY_LOAD:
2613 case EVENT_KIND_ASSEMBLY_UNLOAD:
2614 buffer_add_assemblyid (&buf, domain, arg);
2616 case EVENT_KIND_TYPE_LOAD:
2617 buffer_add_typeid (&buf, domain, arg);
2619 case EVENT_KIND_BREAKPOINT:
2620 case EVENT_KIND_STEP:
2621 buffer_add_methodid (&buf, domain, arg);
2622 buffer_add_long (&buf, il_offset);
2624 case EVENT_KIND_VM_START:
2625 buffer_add_domainid (&buf, mono_get_root_domain ());
2627 case EVENT_KIND_VM_DEATH:
2629 case EVENT_KIND_EXCEPTION:
2630 buffer_add_objid (&buf, (MonoObject*)arg);
2633 g_assert_not_reached ();
2637 if (event == EVENT_KIND_VM_START) {
2638 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
2639 start_debugger_thread ();
2642 if (event == EVENT_KIND_VM_DEATH) {
2643 vm_death_event_sent = TRUE;
2645 suspend_policy = SUSPEND_POLICY_NONE;
2648 if (mono_runtime_is_shutting_down ())
2649 suspend_policy = SUSPEND_POLICY_NONE;
2651 if (suspend_policy != SUSPEND_POLICY_NONE) {
2653 * Save the thread context and start suspending before sending the packet,
2654 * since we could be receiving the resume request before send_packet ()
2657 save_thread_context (ctx);
2661 send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
2663 g_slist_free (events);
2666 if (event == EVENT_KIND_VM_START)
2667 vm_start_event_sent = TRUE;
2669 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
2673 switch (suspend_policy) {
2674 case SUSPEND_POLICY_NONE:
2676 case SUSPEND_POLICY_ALL:
2679 case SUSPEND_POLICY_EVENT_THREAD:
2683 g_assert_not_reached ();
2688 process_profiler_event (EventKind event, gpointer arg)
2693 mono_loader_lock ();
2694 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
2695 mono_loader_unlock ();
2697 process_event (event, arg, 0, NULL, events, suspend_policy);
2701 runtime_initialized (MonoProfiler *prof)
2703 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
2707 runtime_shutdown (MonoProfiler *prof)
2709 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
2711 mono_debugger_agent_cleanup ();
2715 thread_startup (MonoProfiler *prof, gsize tid)
2717 MonoInternalThread *thread = mono_thread_internal_current ();
2718 MonoInternalThread *old_thread;
2719 DebuggerTlsData *tls;
2721 if (tid == debugger_thread_id)
2724 g_assert (thread->tid == tid);
2726 mono_loader_lock ();
2727 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2728 mono_loader_unlock ();
2730 if (thread == old_thread) {
2732 * For some reason, thread_startup () might be called for the same thread
2733 * multiple times (attach ?).
2735 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
2739 * thread_end () might not be called for some threads, and the tid could
2742 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
2743 mono_loader_lock ();
2744 mono_g_hash_table_remove (thread_to_tls, old_thread);
2745 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
2746 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2747 mono_loader_unlock ();
2751 tls = TlsGetValue (debugger_tls_id);
2753 // FIXME: Free this somewhere
2754 tls = g_new0 (DebuggerTlsData, 1);
2755 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
2756 MONO_GC_REGISTER_ROOT (tls->thread);
2757 tls->thread = thread;
2758 TlsSetValue (debugger_tls_id, tls);
2760 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2762 mono_loader_lock ();
2763 mono_g_hash_table_insert (thread_to_tls, thread, tls);
2764 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
2765 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
2766 mono_loader_unlock ();
2768 process_profiler_event (EVENT_KIND_THREAD_START, thread);
2771 * suspend_vm () could have missed this thread, so wait for a resume.
2777 thread_end (MonoProfiler *prof, gsize tid)
2779 MonoInternalThread *thread;
2780 DebuggerTlsData *tls = NULL;
2782 mono_loader_lock ();
2783 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2785 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2786 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
2787 tls->terminated = TRUE;
2788 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2789 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
2790 MONO_GC_UNREGISTER_ROOT (tls->thread);
2793 mono_loader_unlock ();
2795 /* We might be called for threads started before we registered the start callback */
2797 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2798 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
2803 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
2805 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
2809 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
2811 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
2815 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
2817 /* Sent later in jit_end () */
2818 mono_loader_lock ();
2819 g_ptr_array_add (pending_assembly_loads, assembly);
2820 mono_loader_unlock ();
2824 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
2826 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
2830 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2832 #if defined(HOST_WIN32) && !defined(__GNUC__)
2833 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
2835 gpointer stackptr = __builtin_frame_address (1);
2837 MonoInternalThread *thread = mono_thread_internal_current ();
2838 DebuggerTlsData *tls;
2840 mono_loader_lock ();
2842 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2843 /* Could be the debugger thread with assembly/type load hooks */
2845 tls->invoke_addr = stackptr;
2847 mono_loader_unlock ();
2851 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2854 #if defined(HOST_WIN32) && !defined(__GNUC__)
2855 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
2857 gpointer stackptr = __builtin_frame_address (1);
2860 if (ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
2864 * We need to stop single stepping when exiting a runtime invoke, since if it is
2865 * a step out, it may return to native code, and thus never end.
2867 mono_loader_lock ();
2868 ss_invoke_addr = NULL;
2870 for (i = 0; i < event_requests->len; ++i) {
2871 EventRequest *req = g_ptr_array_index (event_requests, i);
2873 if (req->event_kind == EVENT_KIND_STEP) {
2874 ss_destroy (req->info);
2875 g_ptr_array_remove_index_fast (event_requests, i);
2880 mono_loader_unlock ();
2884 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
2887 * We emit type load events when the first method of the type is JITted,
2888 * since the class load profiler callbacks might be called with the
2889 * loader lock held. They could also occur in the debugger thread.
2890 * Same for assembly load events.
2892 gboolean type_load = FALSE;
2895 MonoAssembly *assembly = NULL;
2897 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
2898 mono_loader_lock ();
2899 if (pending_assembly_loads->len > 0) {
2900 assembly = g_ptr_array_index (pending_assembly_loads, 0);
2901 g_ptr_array_remove_index (pending_assembly_loads, 0);
2903 mono_loader_unlock ();
2906 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
2911 mono_loader_lock ();
2912 if (!g_hash_table_lookup (loaded_classes, method->klass)) {
2914 g_hash_table_insert (loaded_classes, method->klass, method->klass);
2916 mono_loader_unlock ();
2918 process_profiler_event (EVENT_KIND_TYPE_LOAD, method->klass);
2921 add_pending_breakpoints (method, jinfo);
2925 * BREAKPOINTS/SINGLE STEPPING
2929 * Contains information about an inserted breakpoint.
2932 long il_offset, native_offset;
2934 gboolean pending, entry;
2936 } BreakpointInstance;
2939 * Contains generic information about a breakpoint.
2943 * The method where the breakpoint is placed. Can be NULL in which case it
2944 * is inserted into every method. This is used to implement method entry/
2945 * exit events. Can be a generic method definition, in which case the
2946 * breakpoint is inserted into every instance.
2950 gboolean pending, entry;
2953 * A list of BreakpointInstance structures describing where the breakpoint
2954 * was inserted. There could be more than one because of
2955 * generics/appdomains/method entry/exit.
2957 GPtrArray *children;
2960 /* List of breakpoints */
2961 static GPtrArray *breakpoints;
2962 /* Maps breakpoint locations to the number of breakpoints at that location */
2963 static GHashTable *bp_locs;
2966 breakpoints_init (void)
2968 breakpoints = g_ptr_array_new ();
2969 bp_locs = g_hash_table_new (NULL, NULL);
2973 breakpoints_cleanup (void)
2977 mono_loader_lock ();
2979 for (i = 0; i < breakpoints->len; ++i)
2980 g_free (g_ptr_array_index (breakpoints, i));
2982 g_ptr_array_free (breakpoints, TRUE);
2983 g_hash_table_destroy (bp_locs);
2985 mono_loader_unlock ();
2989 * insert_breakpoint:
2991 * Insert the breakpoint described by BP into the method described by
2995 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoJitInfo *ji, MonoBreakpoint *bp)
2998 gint32 il_offset, native_offset;
2999 BreakpointInstance *inst;
3002 for (i = 0; i < seq_points->len; ++i) {
3003 il_offset = seq_points->seq_points [i].il_offset;
3004 native_offset = seq_points->seq_points [i].native_offset;
3006 if (il_offset == bp->il_offset)
3010 if (i == seq_points->len)
3011 /* Have to handle this somehow */
3014 inst = g_new0 (BreakpointInstance, 1);
3015 inst->native_offset = native_offset;
3016 inst->ip = (guint8*)ji->code_start + native_offset;
3019 mono_loader_lock ();
3021 g_ptr_array_add (bp->children, inst);
3023 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3024 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3025 mono_loader_unlock ();
3028 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3029 mono_arch_set_breakpoint (ji, inst->ip);
3037 remove_breakpoint (BreakpointInstance *inst)
3039 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3041 MonoJitInfo *ji = inst->ji;
3042 guint8 *ip = inst->ip;
3044 mono_loader_lock ();
3045 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3046 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3047 mono_loader_unlock ();
3049 g_assert (count > 0);
3052 mono_arch_clear_breakpoint (ji, ip);
3060 * add_pending_breakpoints:
3062 * Insert pending breakpoints into the newly JITted method METHOD.
3065 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3068 MonoSeqPointInfo *seq_points;
3074 domain = mono_domain_get ();
3076 mono_loader_lock ();
3078 for (i = 0; i < breakpoints->len; ++i) {
3079 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3081 if (bp->pending && (bp->method == method || !bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method))) {
3082 mono_domain_lock (domain);
3083 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3084 mono_domain_unlock (domain);
3086 /* Could be AOT code */
3088 g_assert (seq_points);
3090 insert_breakpoint (seq_points, ji, bp);
3094 mono_loader_unlock ();
3098 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp)
3103 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3105 /* Might be AOTed code */
3106 code = mono_aot_get_method (domain, method);
3108 ji = mono_jit_info_table_find (domain, code);
3113 insert_breakpoint (seq_points, ji, bp);
3117 set_bp_in_method_cb (gpointer key, gpointer value, gpointer user_data)
3119 MonoMethod *method = key;
3120 MonoSeqPointInfo *seq_points = value;
3121 MonoBreakpoint *bp = user_data;
3122 MonoDomain *domain = mono_domain_get ();
3125 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method) {
3126 /* Generic instance */
3127 set_bp_in_method (domain, method, seq_points, bp);
3130 /* Method entry/exit */
3131 set_bp_in_method (domain, method, seq_points, bp);
3138 * Set a breakpoint at IL_OFFSET in METHOD.
3139 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3140 * METHOD can also be a generic method definition, in which case a breakpoint
3141 * is placed in all instances of the method.
3143 static MonoBreakpoint*
3144 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req)
3146 MonoSeqPointInfo *seq_points;
3151 // - suspend/resume the vm to prevent code patching problems
3153 // - multiple breakpoints on the same location
3154 // - dynamic methods
3157 bp = g_new0 (MonoBreakpoint, 1);
3158 bp->method = method;
3159 bp->il_offset = il_offset;
3161 bp->children = g_ptr_array_new ();
3163 DEBUG(1, fprintf (log_file, "[dbg] Setting %sbreakpoint at %s:0x%x.\n", (req->event_kind == EVENT_KIND_STEP) ? "single step " : "", method ? mono_method_full_name (method, TRUE) : "<all>", (int)il_offset));
3165 domain = mono_domain_get ();
3166 mono_domain_lock (domain);
3168 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
3170 set_bp_in_method (domain, method, seq_points, bp);
3172 if (method->is_generic)
3173 /* There might be already JITted instances */
3174 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
3176 /* Not yet JITted */
3180 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
3183 mono_domain_unlock (domain);
3185 mono_loader_lock ();
3186 g_ptr_array_add (breakpoints, bp);
3187 mono_loader_unlock ();
3193 clear_breakpoint (MonoBreakpoint *bp)
3197 // FIXME: locking, races
3198 for (i = 0; i < bp->children->len; ++i) {
3199 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3201 remove_breakpoint (inst);
3206 mono_loader_lock ();
3207 g_ptr_array_remove (breakpoints, bp);
3208 mono_loader_unlock ();
3210 g_ptr_array_free (bp->children, TRUE);
3215 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
3218 guint8 *orig_ip, *ip;
3219 int i, j, suspend_policy;
3220 guint32 native_offset;
3222 BreakpointInstance *inst;
3223 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3224 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3225 EventKind kind = EVENT_KIND_BREAKPOINT;
3227 // FIXME: Speed this up
3229 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3230 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
3232 g_assert (ji->method);
3234 /* Compute the native offset of the breakpoint from the ip */
3235 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3236 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3237 native_offset = ip - (guint8*)ji->code_start;
3243 * Skip the instruction causing the breakpoint signal.
3245 mono_arch_skip_breakpoint (ctx);
3247 if (ji->method->wrapper_type || tls->disable_breakpoints)
3250 bp_reqs = g_ptr_array_new ();
3251 ss_reqs = g_ptr_array_new ();
3252 ss_reqs_orig = g_ptr_array_new ();
3254 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3256 mono_loader_lock ();
3259 for (i = 0; i < breakpoints->len; ++i) {
3260 bp = g_ptr_array_index (breakpoints, i);
3265 for (j = 0; j < bp->children->len; ++j) {
3266 inst = g_ptr_array_index (bp->children, j);
3267 if (inst->ji == ji && inst->native_offset == native_offset) {
3268 if (bp->req->event_kind == EVENT_KIND_STEP) {
3269 g_ptr_array_add (ss_reqs_orig, bp->req);
3271 g_ptr_array_add (bp_reqs, bp->req);
3276 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3277 MonoSeqPointInfo *seq_points;
3278 int seq_il_offset, seq_native_offset;
3279 MonoDomain *domain = mono_domain_get ();
3281 /* Maybe a method entry/exit event */
3282 mono_domain_lock (domain);
3283 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3284 mono_domain_unlock (domain);
3286 // FIXME: Generic sharing */
3287 mono_loader_unlock ();
3290 g_assert (seq_points);
3292 for (i = 0; i < seq_points->len; ++i) {
3293 seq_il_offset = seq_points->seq_points [i].il_offset;
3294 seq_native_offset = seq_points->seq_points [i].native_offset;
3296 if (native_offset == seq_native_offset) {
3297 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3298 kind = EVENT_KIND_METHOD_ENTRY;
3299 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3300 kind = EVENT_KIND_METHOD_EXIT;
3306 /* Process single step requests */
3307 for (i = 0; i < ss_reqs_orig->len; ++i) {
3308 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3309 SingleStepReq *ss_req = bp->req->info;
3310 gboolean hit = TRUE;
3311 MonoSeqPointInfo *info;
3314 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3317 if (ss_req->size == STEP_SIZE_LINE) {
3318 /* Have to check whenever a different source line was reached */
3319 MonoDebugMethodInfo *minfo;
3320 MonoDebugSourceLocation *loc = NULL;
3322 minfo = mono_debug_lookup_method (ji->method);
3325 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3327 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3328 /* Have to continue single stepping */
3332 ss_req->last_method = ji->method;
3333 ss_req->last_line = loc->row;
3334 mono_debug_free_source_location (loc);
3339 g_ptr_array_add (ss_reqs, req);
3341 /* Start single stepping again from the current sequence point */
3342 ss_start (ss_req, ji->method, sp, info, ctx, NULL);
3345 if (ss_reqs->len > 0)
3346 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3347 if (bp_reqs->len > 0)
3348 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3349 if (kind != EVENT_KIND_BREAKPOINT)
3350 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3352 mono_loader_unlock ();
3354 g_ptr_array_free (bp_reqs, TRUE);
3355 g_ptr_array_free (ss_reqs, TRUE);
3358 * FIXME: The first event will suspend, so the second will only be sent after the
3362 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3364 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3365 if (enter_leave_events)
3366 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3370 process_breakpoint (void)
3372 DebuggerTlsData *tls;
3374 static void (*restore_context) (void *);
3376 if (!restore_context)
3377 restore_context = mono_get_restore_context ();
3379 tls = TlsGetValue (debugger_tls_id);
3380 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3382 process_breakpoint_inner (tls, &ctx);
3384 /* This is called when resuming from a signal handler, so it shouldn't return */
3385 restore_context (&ctx);
3386 g_assert_not_reached ();
3390 resume_from_signal_handler (void *sigctx, void *func)
3392 DebuggerTlsData *tls;
3395 /* Save the original context in TLS */
3396 // FIXME: This might not work on an altstack ?
3397 tls = TlsGetValue (debugger_tls_id);
3400 // FIXME: MonoContext usually doesn't include the fp registers, so these are
3401 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3402 // clob:c could be added to op_seq_point.
3404 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3405 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3406 MONO_CONTEXT_SET_IP (&ctx, func);
3407 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3409 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3410 mono_ppc_set_func_into_sigctx (sigctx, func);
3415 mono_debugger_agent_breakpoint_hit (void *sigctx)
3418 * We are called from a signal handler, and running code there causes all kinds of
3419 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
3420 * So set up the signal context to return to the real breakpoint handler function.
3423 resume_from_signal_handler (sigctx, process_breakpoint);
3427 process_single_step_inner (DebuggerTlsData *tls, MonoContext *ctx)
3432 int il_offset, suspend_policy;
3433 MonoDomain *domain = mono_domain_get ();
3436 // FIXME: Speed this up
3438 ip = MONO_CONTEXT_GET_IP (ctx);
3440 /* Skip the instruction causing the single step */
3441 mono_arch_skip_single_step (ctx);
3443 if (suspend_count > 0) {
3444 process_suspend (tls, ctx);
3449 // FIXME: A suspend race
3452 if (mono_thread_internal_current () != ss_req->thread)
3455 if (log_level > 0) {
3456 const char *depth = NULL;
3458 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
3460 switch (ss_req->depth) {
3461 case STEP_DEPTH_OVER:
3464 case STEP_DEPTH_OUT:
3467 case STEP_DEPTH_INTO:
3471 g_assert_not_reached ();
3474 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));
3478 * We implement step over/out by single stepping until we reach the same
3479 * frame/parent frame.
3482 * - stack growing upward
3486 if (ss_req->depth != STEP_DEPTH_INTO) {
3487 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
3489 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
3492 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
3495 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
3497 g_assert (ji->method);
3499 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
3504 * Stopping in memset makes half-initialized vtypes visible.
3505 * Stopping in memcpy makes half-copied vtypes visible.
3507 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
3511 * The ip points to the instruction causing the single step event, convert it
3512 * to the offset stored in seq_points.
3514 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3515 ip = mono_arch_get_ip_for_single_step (ji, ctx);
3517 g_assert_not_reached ();
3521 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
3522 * example, so do things by hand.
3524 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
3526 if (il_offset == -1)
3529 if (ss_req->size == STEP_SIZE_LINE) {
3530 /* Step until a different source line is reached */
3531 MonoDebugMethodInfo *minfo;
3533 minfo = mono_debug_lookup_method (ji->method);
3536 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
3538 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
3539 mono_debug_free_source_location (loc);
3544 * Step until we reach a location with line number info,
3545 * otherwise the client can't show a location.
3546 * This can happen for example with statics initialized inline
3547 * outside of a cctor.
3552 ss_req->last_method = ji->method;
3553 ss_req->last_line = loc->row;
3554 mono_debug_free_source_location (loc);
3559 // FIXME: Has to lock earlier
3561 reqs = g_ptr_array_new ();
3563 mono_loader_lock ();
3565 g_ptr_array_add (reqs, ss_req->req);
3567 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
3569 g_ptr_array_free (reqs, TRUE);
3571 mono_loader_unlock ();
3573 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
3577 process_single_step (void)
3579 DebuggerTlsData *tls;
3581 static void (*restore_context) (void *);
3583 if (!restore_context)
3584 restore_context = mono_get_restore_context ();
3586 tls = TlsGetValue (debugger_tls_id);
3587 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3589 process_single_step_inner (tls, &ctx);
3591 /* This is called when resuming from a signal handler, so it shouldn't return */
3592 restore_context (&ctx);
3593 g_assert_not_reached ();
3597 * mono_debugger_agent_single_step_event:
3599 * Called from a signal handler to handle a single step event.
3602 mono_debugger_agent_single_step_event (void *sigctx)
3604 /* Resume to process_single_step through the signal context */
3606 // FIXME: Since step out/over is implemented using step in, the step in case should
3607 // be as fast as possible. Move the relevant code from process_single_step_inner ()
3610 if (GetCurrentThreadId () == debugger_thread_id) {
3612 * This could happen despite our best effors when the runtime calls
3613 * assembly/type resolve hooks.
3614 * FIXME: Breakpoints too.
3618 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3619 mono_arch_skip_single_step (&ctx);
3620 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3624 resume_from_signal_handler (sigctx, process_single_step);
3628 * start_single_stepping:
3630 * Turn on single stepping. Can be called multiple times, for example,
3631 * by a single step event request + a suspend.
3634 start_single_stepping (void)
3636 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3637 int val = InterlockedIncrement (&ss_count);
3640 mono_arch_start_single_stepping ();
3642 if (ss_req != NULL && ss_invoke_addr == NULL) {
3643 DebuggerTlsData *tls;
3645 mono_loader_lock ();
3647 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
3648 ss_invoke_addr = tls->invoke_addr;
3650 mono_loader_unlock ();
3653 g_assert_not_reached ();
3658 stop_single_stepping (void)
3660 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3661 int val = InterlockedDecrement (&ss_count);
3664 mono_arch_stop_single_stepping ();
3666 g_assert_not_reached ();
3673 * Stop the single stepping operation given by SS_REQ.
3676 ss_stop (SingleStepReq *ss_req)
3678 gboolean use_bps = FALSE;
3685 for (l = ss_req->bps; l; l = l->next) {
3686 clear_breakpoint (l->data);
3688 g_slist_free (ss_req->bps);
3692 if (ss_req->global) {
3693 stop_single_stepping ();
3694 ss_req->global = FALSE;
3701 * Start the single stepping operation given by SS_REQ from the sequence point SP.
3704 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls)
3706 gboolean use_bp = FALSE;
3711 /* Stop the previous operation */
3715 * Implement single stepping using breakpoints if possible.
3717 if (ss_req->depth == STEP_DEPTH_OVER) {
3720 * Find the first sequence point in the current or in a previous frame which
3721 * is not the last in its method.
3723 while (sp && sp->next_len == 0) {
3725 if (tls && frame_index < tls->frame_count) {
3726 StackFrame *frame = tls->frames [frame_index];
3728 method = frame->method;
3729 if (frame->il_offset != -1) {
3730 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
3736 if (sp && sp->next_len > 0) {
3738 for (i = 0; i < sp->next_len; ++i) {
3739 next_sp = &info->seq_points [sp->next [i]];
3741 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req);
3742 ss_req->bps = g_slist_append (ss_req->bps, bp);
3748 ss_req->global = TRUE;
3749 start_single_stepping ();
3751 ss_req->global = FALSE;
3756 * Start single stepping of thread THREAD
3759 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
3761 DebuggerTlsData *tls;
3762 MonoSeqPointInfo *info;
3763 SeqPoint *sp = NULL;
3764 MonoMethod *method = NULL;
3766 if (suspend_count == 0)
3767 return ERR_NOT_SUSPENDED;
3769 wait_for_suspend ();
3771 // FIXME: Multiple requests
3773 DEBUG (0, printf ("Received a single step request while the previous one was still active.\n"));
3774 return ERR_NOT_IMPLEMENTED;
3777 ss_req = g_new0 (SingleStepReq, 1);
3779 ss_req->thread = thread;
3780 ss_req->size = size;
3781 ss_req->depth = depth;
3784 mono_loader_lock ();
3785 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3786 mono_loader_unlock ();
3788 g_assert (tls->has_context);
3789 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
3791 if (ss_req->size == STEP_SIZE_LINE) {
3793 MonoDebugMethodInfo *minfo;
3795 /* Compute the initial line info */
3796 compute_frame_info (thread, tls);
3798 g_assert (tls->frame_count);
3799 frame = tls->frames [0];
3801 ss_req->last_method = frame->method;
3802 ss_req->last_line = -1;
3804 minfo = mono_debug_lookup_method (frame->method);
3805 if (minfo && frame->il_offset != -1) {
3806 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
3809 ss_req->last_line = loc->row;
3815 if (ss_req->depth == STEP_DEPTH_OVER) {
3818 compute_frame_info (thread, tls);
3820 g_assert (tls->frame_count);
3821 frame = tls->frames [0];
3823 if (frame->il_offset != -1) {
3824 /* FIXME: Sort the table and use a binary search */
3825 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
3827 method = frame->method;
3831 ss_start (ss_req, method, sp, info, NULL, tls);
3837 ss_destroy (SingleStepReq *req)
3840 g_assert (ss_req == req);
3849 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *ctx)
3855 /* Just-In-Time debugging */
3856 if (agent_config.onthrow && !inited) {
3858 gboolean found = FALSE;
3860 for (l = agent_config.onthrow; l; l = l->next) {
3861 char *ex_type = l->data;
3862 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
3864 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
3871 finish_agent_init (FALSE);
3874 * Send an unsolicited EXCEPTION event with a dummy request id.
3876 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3877 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, SUSPEND_POLICY_ALL);
3885 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (ctx), NULL);
3887 mono_loader_lock ();
3888 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, exc, &suspend_policy);
3889 mono_loader_unlock ();
3891 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, suspend_policy);
3895 mono_debugger_agent_handle_unhandled_exception (MonoException *exc, MonoContext *ctx)
3899 if (!agent_config.onuncaught)
3902 finish_agent_init (FALSE);
3905 * Send an unsolicited EXCEPTION event with a dummy request id.
3907 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3908 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, SUSPEND_POLICY_ALL);
3912 * buffer_add_value_full:
3914 * Add the encoding of the value at ADDR described by T to the buffer.
3915 * AS_VTYPE determines whenever to treat primitive types as primitive types or
3919 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
3925 g_assert (*(void**)addr);
3926 addr = *(void**)addr;
3931 case MONO_TYPE_BOOLEAN:
3934 case MONO_TYPE_CHAR:
3954 case MONO_TYPE_VOID:
3955 buffer_add_byte (buf, t->type);
3957 case MONO_TYPE_BOOLEAN:
3960 buffer_add_byte (buf, t->type);
3961 buffer_add_int (buf, *(gint8*)addr);
3963 case MONO_TYPE_CHAR:
3966 buffer_add_byte (buf, t->type);
3967 buffer_add_int (buf, *(gint16*)addr);
3972 buffer_add_byte (buf, t->type);
3973 buffer_add_int (buf, *(gint32*)addr);
3978 buffer_add_byte (buf, t->type);
3979 buffer_add_long (buf, *(gint64*)addr);
3983 /* Treat it as a vtype */
3985 case MONO_TYPE_PTR: {
3986 gssize val = *(gssize*)addr;
3988 buffer_add_byte (buf, t->type);
3989 buffer_add_long (buf, val);
3993 case MONO_TYPE_STRING:
3994 case MONO_TYPE_SZARRAY:
3995 case MONO_TYPE_OBJECT:
3996 case MONO_TYPE_CLASS:
3997 case MONO_TYPE_ARRAY:
3998 obj = *(MonoObject**)addr;
4001 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4003 if (obj->vtable->klass->valuetype) {
4004 t = &obj->vtable->klass->byval_arg;
4005 addr = mono_object_unbox (obj);
4007 } else if (obj->vtable->klass->rank) {
4008 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4009 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4010 buffer_add_byte (buf, MONO_TYPE_CLASS);
4012 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4014 buffer_add_objid (buf, obj);
4018 case MONO_TYPE_VALUETYPE: {
4022 MonoClass *klass = mono_class_from_mono_type (t);
4024 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4025 buffer_add_byte (buf, klass->enumtype);
4026 buffer_add_typeid (buf, domain, klass);
4030 while ((f = mono_class_get_fields (klass, &iter))) {
4031 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4033 if (mono_field_is_deleted (f))
4037 buffer_add_int (buf, nfields);
4040 while ((f = mono_class_get_fields (klass, &iter))) {
4041 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4043 if (mono_field_is_deleted (f))
4045 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4049 case MONO_TYPE_GENERICINST:
4050 if (mono_type_generic_inst_is_valuetype (t)) {
4062 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4064 buffer_add_value_full (buf, t, addr, domain, FALSE);
4068 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4071 int type = decode_byte (buf, &buf, limit);
4073 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4074 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4075 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4076 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8)) {
4077 DEBUG(1, fprintf (log_file, "[%p] Expected value of type 0x%0x, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), t->type, type));
4078 return ERR_INVALID_ARGUMENT;
4082 case MONO_TYPE_BOOLEAN:
4083 *(guint8*)addr = decode_int (buf, &buf, limit);
4085 case MONO_TYPE_CHAR:
4086 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4089 *(gint8*)addr = decode_int (buf, &buf, limit);
4092 *(guint8*)addr = decode_int (buf, &buf, limit);
4095 *(gint16*)addr = decode_int (buf, &buf, limit);
4098 *(guint16*)addr = decode_int (buf, &buf, limit);
4101 *(gint32*)addr = decode_int (buf, &buf, limit);
4104 *(guint32*)addr = decode_int (buf, &buf, limit);
4107 *(gint64*)addr = decode_long (buf, &buf, limit);
4110 *(guint64*)addr = decode_long (buf, &buf, limit);
4113 *(guint32*)addr = decode_int (buf, &buf, limit);
4116 *(guint64*)addr = decode_long (buf, &buf, limit);
4119 /* We send these as I8, so we get them back as such */
4120 g_assert (type == MONO_TYPE_I8);
4121 *(gssize*)addr = decode_long (buf, &buf, limit);
4125 /* We send these as vtypes, so we get them back as such */
4126 g_assert (type == MONO_TYPE_VALUETYPE);
4128 case MONO_TYPE_VALUETYPE: {
4129 gboolean is_enum = decode_byte (buf, &buf, limit);
4133 gpointer iter = NULL;
4136 /* Enums are sent as a normal vtype */
4138 return ERR_NOT_IMPLEMENTED;
4139 klass = decode_typeid (buf, &buf, limit, &d, &err);
4143 if (klass != mono_class_from_mono_type (t))
4144 return ERR_INVALID_ARGUMENT;
4146 nfields = decode_int (buf, &buf, limit);
4147 while ((f = mono_class_get_fields (klass, &iter))) {
4148 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4150 if (mono_field_is_deleted (f))
4152 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4157 g_assert (nfields == 0);
4161 if (MONO_TYPE_IS_REFERENCE (t)) {
4162 if (type == MONO_TYPE_OBJECT) {
4163 int objid = decode_objid (buf, &buf, limit);
4167 err = get_object (objid, (MonoObject**)&obj);
4171 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4172 return ERR_INVALID_ARGUMENT;
4173 if (obj && obj->vtable->domain != domain)
4174 return ERR_INVALID_ARGUMENT;
4176 mono_gc_wbarrier_generic_store (addr, obj);
4177 } else if (type == VALUE_TYPE_ID_NULL) {
4178 *(MonoObject**)addr = NULL;
4180 return ERR_INVALID_ARGUMENT;
4194 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4201 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4202 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4205 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4206 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4208 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
4210 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4211 addr = mono_arch_context_get_int_reg (ctx, reg);
4212 addr += (gint32)var->offset;
4214 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4216 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4218 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4222 g_assert_not_reached ();
4227 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
4233 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4234 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4236 if (MONO_TYPE_IS_REFERENCE (t))
4237 size = sizeof (gpointer);
4239 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4242 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4243 // FIXME: Can't set registers, so we disable linears
4246 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4247 addr = mono_arch_context_get_int_reg (ctx, reg);
4248 addr += (gint32)var->offset;
4250 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4252 // FIXME: Write barriers
4253 memcpy (addr, val, size);
4255 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4259 g_assert_not_reached ();
4264 clear_event_request (int req_id, int etype)
4268 mono_loader_lock ();
4269 for (i = 0; i < event_requests->len; ++i) {
4270 EventRequest *req = g_ptr_array_index (event_requests, i);
4272 if (req->id == req_id && req->event_kind == etype) {
4273 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4274 clear_breakpoint (req->info);
4275 if (req->event_kind == EVENT_KIND_STEP)
4276 ss_destroy (req->info);
4277 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
4278 clear_breakpoint (req->info);
4279 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
4280 clear_breakpoint (req->info);
4281 g_ptr_array_remove_index_fast (event_requests, i);
4286 mono_loader_unlock ();
4290 add_thread (gpointer key, gpointer value, gpointer user_data)
4292 MonoInternalThread *thread = value;
4293 Buffer *buf = user_data;
4295 buffer_add_objid (buf, (MonoObject*)thread);
4299 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
4301 guint8 *p = invoke->p;
4302 guint8 *end = invoke->endp;
4305 MonoMethodSignature *sig;
4308 MonoObject *this, *res, *exc;
4311 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4315 if (invoke->method) {
4317 * Invoke this method directly, currently only Environment.Exit () is supported.
4320 DEBUG (1, printf ("[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this ? this->vtable->klass->name : "<null>"));
4321 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
4322 g_assert_not_reached ();
4325 m = decode_methodid (p, &p, end, &domain, &err);
4328 sig = mono_method_signature (m);
4330 if (m->klass->valuetype)
4331 this_buf = g_alloca (mono_class_instance_size (m->klass));
4333 this_buf = g_alloca (sizeof (MonoObject*));
4334 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
4338 if (!m->klass->valuetype)
4339 this = *(MonoObject**)this_buf;
4343 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>"));
4345 if (this && this->vtable->domain != domain)
4348 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
4349 if (!strcmp (m->name, ".ctor")) {
4350 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
4351 return ERR_INVALID_ARGUMENT;
4353 this = mono_object_new (domain, m->klass);
4355 return ERR_INVALID_ARGUMENT;
4359 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
4360 return ERR_INVALID_ARGUMENT;
4362 nargs = decode_int (p, &p, end);
4363 if (nargs != sig->param_count)
4364 return ERR_INVALID_ARGUMENT;
4365 /* Use alloca to get gc tracking */
4366 arg_buf = g_alloca (nargs * sizeof (gpointer));
4367 memset (arg_buf, 0, nargs * sizeof (gpointer));
4368 args = g_alloca (nargs * sizeof (gpointer));
4369 for (i = 0; i < nargs; ++i) {
4370 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
4371 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
4375 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
4378 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
4379 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
4382 args [i] = arg_buf [i];
4389 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
4390 tls->disable_breakpoints = TRUE;
4392 tls->disable_breakpoints = FALSE;
4395 * Add an LMF frame to link the stack frames on the invoke method with our caller.
4397 /* FIXME: Move this to arch specific code */
4398 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4399 if (invoke->has_ctx) {
4402 lmf_addr = mono_get_lmf_addr ();
4405 memset (&ext, 0, sizeof (ext));
4407 ext.lmf.previous_lmf = *(lmf_addr);
4408 /* Mark that this is a MonoLMFExt */
4409 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4410 ext.lmf.rsp = (gssize)&ext;
4411 #elif defined(TARGET_X86)
4412 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
4413 /* Mark that this is a MonoLMFExt */
4414 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4415 ext.lmf.ebp = (gssize)&ext;
4416 #elif defined(TARGET_ARM)
4417 ext.lmf.previous_lmf = *(lmf_addr);
4418 /* Mark that this is a MonoLMFExt */
4419 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4420 ext.lmf.ebp = (gssize)&ext;
4421 #elif defined(TARGET_POWERPC)
4422 ext.lmf.previous_lmf = *(lmf_addr);
4423 /* Mark that this is a MonoLMFExt */
4424 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4425 ext.lmf.ebp = (gssize)&ext;
4427 g_assert_not_reached ();
4430 ext.debugger_invoke = TRUE;
4431 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
4433 mono_set_lmf ((MonoLMF*)&ext);
4437 if (m->klass->valuetype)
4438 res = mono_runtime_invoke (m, this_buf, args, &exc);
4440 res = mono_runtime_invoke (m, this, args, &exc);
4442 buffer_add_byte (buf, 0);
4443 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
4445 buffer_add_byte (buf, 1);
4446 if (sig->ret->type == MONO_TYPE_VOID) {
4447 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
4448 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
4451 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
4452 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
4453 buffer_add_value (buf, sig->ret, &res, domain);
4454 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
4456 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
4462 tls->disable_breakpoints = FALSE;
4464 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4465 if (invoke->has_ctx)
4466 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
4469 // FIXME: byref arguments
4477 * Invoke the method given by tls->invoke in the current thread.
4480 invoke_method (void)
4482 DebuggerTlsData *tls;
4487 static void (*restore_context) (void *);
4488 MonoContext restore_ctx;
4490 if (!restore_context)
4491 restore_context = mono_get_restore_context ();
4493 tls = TlsGetValue (debugger_tls_id);
4496 invoke = tls->invoke;
4500 tls->frames_up_to_date = FALSE;
4504 buffer_init (&buf, 128);
4506 err = do_invoke_method (tls, &buf, invoke);
4508 /* Start suspending before sending the reply */
4509 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
4512 send_reply_packet (id, err, &buf);
4516 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
4518 if (invoke->has_ctx)
4519 save_thread_context (&restore_ctx);
4521 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
4522 g_assert (tls->resume_count);
4523 tls->resume_count -= invoke->suspend_count;
4526 DEBUG (1, printf ("[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
4535 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
4537 MonoThread *thread = value;
4538 DebuggerTlsData *tls;
4541 mono_loader_lock ();
4542 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4544 res = tls->really_suspended;
4545 mono_loader_unlock ();
4551 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
4554 case CMD_VM_VERSION: {
4555 char *build_info, *version;
4557 build_info = mono_get_runtime_build_info ();
4558 version = g_strdup_printf ("mono %s", build_info);
4560 buffer_add_string (buf, version); /* vm version */
4561 buffer_add_int (buf, MAJOR_VERSION);
4562 buffer_add_int (buf, MINOR_VERSION);
4563 g_free (build_info);
4567 case CMD_VM_ALL_THREADS: {
4569 mono_loader_lock ();
4570 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
4571 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
4572 mono_loader_unlock ();
4575 case CMD_VM_SUSPEND:
4577 wait_for_suspend ();
4580 if (suspend_count == 0)
4581 return ERR_NOT_SUSPENDED;
4584 case CMD_VM_DISPOSE:
4585 /* Clear all event requests */
4586 mono_loader_lock ();
4587 while (event_requests->len > 0) {
4588 EventRequest *req = g_ptr_array_index (event_requests, 0);
4590 clear_event_request (req->id, req->event_kind);
4592 mono_loader_unlock ();
4594 // FIXME: Count resumes
4596 disconnected = TRUE;
4599 MonoInternalThread *thread;
4600 DebuggerTlsData *tls;
4601 MonoClass *env_class;
4602 MonoMethod *exit_method;
4606 exit_code = decode_int (p, &p, end);
4608 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
4610 /* Have to send a reply before exiting */
4611 send_reply_packet (id, 0, buf);
4613 /* Clear all event requests */
4614 mono_loader_lock ();
4615 while (event_requests->len > 0) {
4616 EventRequest *req = g_ptr_array_index (event_requests, 0);
4618 clear_event_request (req->id, req->event_kind);
4620 mono_loader_unlock ();
4623 * The JDWP documentation says that the shutdown is not orderly. It doesn't
4624 * specify whenever a VM_DEATH event is sent. We currently do an orderly
4625 * shutdown by hijacking a thread to execute Environment.Exit (). This is
4626 * better than doing the shutdown ourselves, since it avoids various races.
4630 wait_for_suspend ();
4632 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
4633 g_assert (env_class);
4634 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
4635 g_assert (exit_method);
4637 mono_loader_lock ();
4638 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
4639 mono_loader_unlock ();
4642 mono_loader_lock ();
4643 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4644 mono_loader_unlock ();
4646 args = g_new0 (gpointer, 1);
4647 args [0] = g_malloc (sizeof (int));
4648 *(int*)(args [0]) = exit_code;
4650 tls->invoke = g_new0 (InvokeData, 1);
4651 tls->invoke->method = exit_method;
4652 tls->invoke->args = args;
4654 while (suspend_count > 0)
4658 * No thread found, do it ourselves.
4659 * FIXME: This can race with normal shutdown etc.
4661 while (suspend_count > 0)
4664 mono_runtime_set_shutting_down ();
4666 mono_threads_set_shutting_down ();
4668 /* Suspend all managed threads since the runtime is going away */
4669 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
4670 mono_thread_suspend_all_other_threads ();
4671 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
4672 mono_runtime_quit ();
4674 shutdown (conn_fd, SD_BOTH);
4676 shutdown (conn_fd, SHUT_RDWR);
4678 DEBUG(1, fprintf (log_file, "Exiting...\n"));
4684 case CMD_VM_INVOKE_METHOD: {
4685 int objid = decode_objid (p, &p, end);
4687 DebuggerTlsData *tls;
4690 err = get_object (objid, (MonoObject**)&thread);
4694 flags = decode_int (p, &p, end);
4696 // Wait for suspending if it already started
4698 wait_for_suspend ();
4699 if (!is_suspended ())
4700 return ERR_NOT_SUSPENDED;
4702 mono_loader_lock ();
4703 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
4704 mono_loader_unlock ();
4707 if (!tls->really_suspended)
4708 /* The thread is still running native code, can't do invokes */
4709 return ERR_NOT_SUSPENDED;
4712 * Store the invoke data into tls, the thread will execute it after it is
4717 tls->invoke = g_new0 (InvokeData, 1);
4718 tls->invoke->id = id;
4719 tls->invoke->flags = flags;
4720 tls->invoke->p = g_malloc (end - p);
4721 memcpy (tls->invoke->p, p, end - p);
4722 tls->invoke->endp = tls->invoke->p + (end - p);
4723 tls->invoke->suspend_count = suspend_count;
4725 if (flags & INVOKE_FLAG_SINGLE_THREADED)
4726 resume_thread (THREAD_TO_INTERNAL (thread));
4732 return ERR_NOT_IMPLEMENTED;
4739 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4744 case CMD_EVENT_REQUEST_SET: {
4746 int i, event_kind, suspend_policy, nmodifiers, mod;
4749 MonoThread *step_thread;
4750 int size = 0, depth = 0, step_thread_id = 0;
4753 event_kind = decode_byte (p, &p, end);
4754 suspend_policy = decode_byte (p, &p, end);
4755 nmodifiers = decode_byte (p, &p, end);
4757 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
4758 req->id = InterlockedIncrement (&event_request_id);
4759 req->event_kind = event_kind;
4760 req->suspend_policy = suspend_policy;
4761 req->nmodifiers = nmodifiers;
4764 for (i = 0; i < nmodifiers; ++i) {
4765 mod = decode_byte (p, &p, end);
4767 req->modifiers [i].kind = mod;
4768 if (mod == MOD_KIND_COUNT) {
4769 req->modifiers [i].data.count = decode_int (p, &p, end);
4770 } else if (mod == MOD_KIND_LOCATION_ONLY) {
4771 method = decode_methodid (p, &p, end, &domain, &err);
4774 location = decode_long (p, &p, end);
4775 } else if (mod == MOD_KIND_STEP) {
4776 step_thread_id = decode_id (p, &p, end);
4777 size = decode_int (p, &p, end);
4778 depth = decode_int (p, &p, end);
4779 } else if (mod == MOD_KIND_THREAD_ONLY) {
4780 int id = decode_id (p, &p, end);
4782 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
4787 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
4788 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
4793 req->modifiers [i].data.exc_class = exc_class;
4795 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
4797 return ERR_INVALID_ARGUMENT;
4800 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
4801 int n = decode_int (p, &p, end);
4804 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
4805 for (j = 0; j < n; ++j) {
4806 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
4808 g_free (req->modifiers [i].data.assemblies);
4814 return ERR_NOT_IMPLEMENTED;
4818 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4821 req->info = set_breakpoint (method, location, req);
4822 } else if (req->event_kind == EVENT_KIND_STEP) {
4823 g_assert (step_thread_id);
4825 err = get_object (step_thread_id, (MonoObject**)&step_thread);
4831 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
4836 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
4837 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req);
4838 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
4839 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req);
4840 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
4842 if (req->nmodifiers) {
4844 return ERR_NOT_IMPLEMENTED;
4848 mono_loader_lock ();
4849 g_ptr_array_add (event_requests, req);
4850 mono_loader_unlock ();
4852 buffer_add_int (buf, req->id);
4855 case CMD_EVENT_REQUEST_CLEAR: {
4856 int etype = decode_byte (p, &p, end);
4857 int req_id = decode_int (p, &p, end);
4859 // FIXME: Make a faster mapping from req_id to request
4860 mono_loader_lock ();
4861 clear_event_request (req_id, etype);
4862 mono_loader_unlock ();
4865 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
4868 mono_loader_lock ();
4870 while (i < event_requests->len) {
4871 EventRequest *req = g_ptr_array_index (event_requests, i);
4873 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4874 clear_breakpoint (req->info);
4876 g_ptr_array_remove_index_fast (event_requests, i);
4882 mono_loader_unlock ();
4886 return ERR_NOT_IMPLEMENTED;
4893 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4899 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
4900 buffer_add_domainid (buf, mono_get_root_domain ());
4903 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
4904 domain = decode_domainid (p, &p, end, NULL, &err);
4907 buffer_add_string (buf, domain->friendly_name);
4910 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
4915 domain = decode_domainid (p, &p, end, NULL, &err);
4918 mono_loader_lock ();
4920 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4923 buffer_add_int (buf, count);
4924 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4926 buffer_add_assemblyid (buf, domain, ass);
4928 mono_loader_unlock ();
4931 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
4932 domain = decode_domainid (p, &p, end, NULL, &err);
4936 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
4939 case CMD_APPDOMAIN_GET_CORLIB: {
4940 domain = decode_domainid (p, &p, end, NULL, &err);
4944 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
4947 case CMD_APPDOMAIN_CREATE_STRING: {
4951 domain = decode_domainid (p, &p, end, NULL, &err);
4954 s = decode_string (p, &p, end);
4956 o = mono_string_new (domain, s);
4957 buffer_add_objid (buf, (MonoObject*)o);
4961 return ERR_NOT_IMPLEMENTED;
4968 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4974 ass = decode_assemblyid (p, &p, end, &domain, &err);
4979 case CMD_ASSEMBLY_GET_LOCATION: {
4980 buffer_add_string (buf, mono_image_get_filename (ass->image));
4983 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
4987 if (ass->image->dynamic) {
4988 buffer_add_id (buf, 0);
4990 token = mono_image_get_entry_point (ass->image);
4992 buffer_add_id (buf, 0);
4994 m = mono_get_method (ass->image, token, NULL);
4995 buffer_add_methodid (buf, domain, m);
5000 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5001 buffer_add_moduleid (buf, domain, ass->image);
5004 case CMD_ASSEMBLY_GET_OBJECT: {
5005 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5006 buffer_add_objid (buf, o);
5009 case CMD_ASSEMBLY_GET_TYPE: {
5010 char *s = decode_string (p, &p, end);
5011 gboolean ignorecase = decode_byte (p, &p, end);
5012 MonoTypeNameParse info;
5014 gboolean type_resolve;
5016 if (!mono_reflection_parse_type (s, &info)) {
5019 if (info.assembly.name)
5021 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5023 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5024 mono_reflection_free_type_info (&info);
5029 case CMD_ASSEMBLY_GET_NAME: {
5031 MonoAssembly *mass = ass;
5033 name = g_strdup_printf (
5034 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5036 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5037 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5038 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5039 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5041 buffer_add_string (buf, name);
5046 return ERR_NOT_IMPLEMENTED;
5053 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5059 case CMD_MODULE_GET_INFO: {
5060 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
5063 basename = g_path_get_basename (image->name);
5064 buffer_add_string (buf, basename); // name
5065 buffer_add_string (buf, image->module_name); // scopename
5066 buffer_add_string (buf, image->name); // fqname
5067 buffer_add_string (buf, mono_image_get_guid (image)); // guid
5068 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
5073 return ERR_NOT_IMPLEMENTED;
5080 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
5082 if (val && val->vtable->klass == mono_defaults.monotype_class) {
5083 /* Special case these so the client doesn't have to handle Type objects */
5085 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
5086 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
5087 } else if (MONO_TYPE_IS_REFERENCE (t))
5088 buffer_add_value (buf, t, &val, domain);
5090 buffer_add_value (buf, t, mono_object_unbox (val), domain);
5094 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
5100 buffer_add_int (buf, 0);
5104 for (i = 0; i < cinfo->num_attrs; ++i) {
5105 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
5108 buffer_add_int (buf, nattrs);
5110 for (i = 0; i < cinfo->num_attrs; ++i) {
5111 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
5112 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
5113 MonoArray *typed_args, *named_args;
5115 CattrNamedArg *arginfo;
5117 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
5119 buffer_add_methodid (buf, domain, attr->ctor);
5123 buffer_add_int (buf, mono_array_length (typed_args));
5124 for (j = 0; j < mono_array_length (typed_args); ++j) {
5125 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
5127 t = mono_method_signature (attr->ctor)->params [j];
5129 buffer_add_cattr_arg (buf, t, domain, val);
5132 buffer_add_int (buf, 0);
5137 buffer_add_int (buf, mono_array_length (named_args));
5139 for (j = 0; j < mono_array_length (named_args); ++j) {
5140 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
5142 if (arginfo [j].prop) {
5143 buffer_add_byte (buf, 0x54);
5144 buffer_add_propertyid (buf, domain, arginfo [j].prop);
5145 } else if (arginfo [j].field) {
5146 buffer_add_byte (buf, 0x53);
5148 g_assert_not_reached ();
5151 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
5154 buffer_add_int (buf, 0);
5161 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5172 klass = decode_typeid (p, &p, end, &domain, &err);
5177 case CMD_TYPE_GET_INFO: {
5178 buffer_add_string (buf, klass->name_space);
5179 buffer_add_string (buf, klass->name);
5181 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
5182 buffer_add_string (buf, name);
5184 buffer_add_assemblyid (buf, domain, klass->image->assembly);
5185 buffer_add_moduleid (buf, domain, klass->image);
5186 buffer_add_typeid (buf, domain, klass->parent);
5187 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
5188 buffer_add_typeid (buf, domain, klass->element_class);
5190 buffer_add_id (buf, 0);
5191 buffer_add_int (buf, klass->type_token);
5192 buffer_add_byte (buf, klass->rank);
5193 buffer_add_int (buf, klass->flags);
5195 type = &klass->byval_arg;
5196 // FIXME: Can't decide whenever a class represents a byref type
5199 if (type->type == MONO_TYPE_PTR)
5201 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
5203 if (type->type == MONO_TYPE_VALUETYPE)
5205 buffer_add_byte (buf, b);
5208 while ((nested = mono_class_get_nested_types (klass, &iter)))
5210 buffer_add_int (buf, nnested);
5212 while ((nested = mono_class_get_nested_types (klass, &iter)))
5213 buffer_add_typeid (buf, domain, nested);
5216 case CMD_TYPE_GET_METHODS: {
5219 gpointer iter = NULL;
5222 nmethods = mono_class_num_methods (klass);
5224 buffer_add_int (buf, nmethods);
5226 while ((m = mono_class_get_methods (klass, &iter))) {
5227 buffer_add_methodid (buf, domain, m);
5230 g_assert (i == nmethods);
5233 case CMD_TYPE_GET_FIELDS: {
5236 gpointer iter = NULL;
5239 nfields = mono_class_num_fields (klass);
5241 buffer_add_int (buf, nfields);
5243 while ((f = mono_class_get_fields (klass, &iter))) {
5244 buffer_add_fieldid (buf, domain, f);
5245 buffer_add_string (buf, f->name);
5246 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
5247 buffer_add_int (buf, f->type->attrs);
5250 g_assert (i == nfields);
5253 case CMD_TYPE_GET_PROPERTIES: {
5256 gpointer iter = NULL;
5259 nprops = mono_class_num_properties (klass);
5261 buffer_add_int (buf, nprops);
5263 while ((p = mono_class_get_properties (klass, &iter))) {
5264 buffer_add_propertyid (buf, domain, p);
5265 buffer_add_string (buf, p->name);
5266 buffer_add_methodid (buf, domain, p->get);
5267 buffer_add_methodid (buf, domain, p->set);
5268 buffer_add_int (buf, p->attrs);
5271 g_assert (i == nprops);
5274 case CMD_TYPE_GET_CATTRS: {
5275 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
5276 MonoCustomAttrInfo *cinfo;
5278 cinfo = mono_custom_attrs_from_class (klass);
5280 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5283 case CMD_TYPE_GET_FIELD_CATTRS: {
5284 MonoClass *attr_klass;
5285 MonoCustomAttrInfo *cinfo;
5286 MonoClassField *field;
5288 field = decode_fieldid (p, &p, end, NULL, &err);
5291 attr_klass = decode_typeid (p, &p, end, NULL, &err);
5295 cinfo = mono_custom_attrs_from_field (klass, field);
5297 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5300 case CMD_TYPE_GET_PROPERTY_CATTRS: {
5301 MonoClass *attr_klass;
5302 MonoCustomAttrInfo *cinfo;
5305 prop = decode_propertyid (p, &p, end, NULL, &err);
5308 attr_klass = decode_typeid (p, &p, end, NULL, &err);
5312 cinfo = mono_custom_attrs_from_property (klass, prop);
5314 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5317 case CMD_TYPE_GET_VALUES: {
5325 len = decode_int (p, &p, end);
5326 for (i = 0; i < len; ++i) {
5327 f = decode_fieldid (p, &p, end, NULL, &err);
5331 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
5332 return ERR_INVALID_FIELDID;
5333 if (mono_class_field_is_special_static (f))
5334 return ERR_INVALID_FIELDID;
5336 /* Check that the field belongs to the object */
5338 for (k = klass; k; k = k->parent) {
5339 if (k == f->parent) {
5345 return ERR_INVALID_FIELDID;
5347 vtable = mono_class_vtable (domain, f->parent);
5348 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5349 mono_field_static_get_value (vtable, f, val);
5350 buffer_add_value (buf, f->type, val, domain);
5355 case CMD_TYPE_SET_VALUES: {
5363 len = decode_int (p, &p, end);
5364 for (i = 0; i < len; ++i) {
5365 f = decode_fieldid (p, &p, end, NULL, &err);
5369 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
5370 return ERR_INVALID_FIELDID;
5371 if (mono_class_field_is_special_static (f))
5372 return ERR_INVALID_FIELDID;
5374 /* Check that the field belongs to the object */
5376 for (k = klass; k; k = k->parent) {
5377 if (k == f->parent) {
5383 return ERR_INVALID_FIELDID;
5385 // FIXME: Check for literal/const
5387 vtable = mono_class_vtable (domain, f->parent);
5388 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5389 err = decode_value (f->type, domain, val, p, &p, end);
5394 mono_field_static_set_value (vtable, f, val);
5399 case CMD_TYPE_GET_OBJECT: {
5400 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
5401 buffer_add_objid (buf, o);
5404 case CMD_TYPE_GET_SOURCE_FILES: {
5405 gpointer iter = NULL;
5407 char *source_file, *base;
5411 files = g_ptr_array_new ();
5413 while ((method = mono_class_get_methods (klass, &iter))) {
5414 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
5417 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
5419 for (i = 0; i < files->len; ++i)
5420 if (!strcmp (g_ptr_array_index (files, i), source_file))
5422 if (i == files->len)
5423 g_ptr_array_add (files, g_strdup (source_file));
5424 g_free (source_file);
5428 buffer_add_int (buf, files->len);
5429 for (i = 0; i < files->len; ++i) {
5430 source_file = g_ptr_array_index (files, i);
5431 base = g_path_get_basename (source_file);
5432 buffer_add_string (buf, base);
5434 g_free (source_file);
5436 g_ptr_array_free (files, TRUE);
5439 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
5440 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
5444 if (mono_class_is_assignable_from (klass, oklass))
5445 buffer_add_byte (buf, 1);
5447 buffer_add_byte (buf, 0);
5451 return ERR_NOT_IMPLEMENTED;
5458 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5463 MonoMethodHeader *header;
5465 method = decode_methodid (p, &p, end, &domain, &err);
5470 case CMD_METHOD_GET_NAME: {
5471 buffer_add_string (buf, method->name);
5474 case CMD_METHOD_GET_DECLARING_TYPE: {
5475 buffer_add_typeid (buf, domain, method->klass);
5478 case CMD_METHOD_GET_DEBUG_INFO: {
5479 MonoDebugMethodInfo *minfo;
5481 int i, n_il_offsets;
5485 header = mono_method_get_header (method);
5487 buffer_add_int (buf, 0);
5488 buffer_add_string (buf, "");
5489 buffer_add_int (buf, 0);
5493 minfo = mono_debug_lookup_method (method);
5495 buffer_add_int (buf, header->code_size);
5496 buffer_add_string (buf, "");
5497 buffer_add_int (buf, 0);
5501 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
5502 buffer_add_int (buf, header->code_size);
5503 buffer_add_string (buf, source_file);
5504 buffer_add_int (buf, n_il_offsets);
5505 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
5506 for (i = 0; i < n_il_offsets; ++i) {
5507 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
5508 buffer_add_int (buf, il_offsets [i]);
5509 buffer_add_int (buf, line_numbers [i]);
5511 g_free (source_file);
5512 g_free (il_offsets);
5513 g_free (line_numbers);
5516 case CMD_METHOD_GET_PARAM_INFO: {
5517 MonoMethodSignature *sig = mono_method_signature (method);
5521 /* FIXME: mono_class_from_mono_type () and byrefs */
5523 /* FIXME: Use a smaller encoding */
5524 buffer_add_int (buf, sig->call_convention);
5525 buffer_add_int (buf, sig->param_count);
5526 buffer_add_int (buf, sig->generic_param_count);
5527 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
5528 for (i = 0; i < sig->param_count; ++i) {
5530 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
5533 /* Emit parameter names */
5534 names = g_new (char *, sig->param_count);
5535 mono_method_get_param_names (method, (const char **) names);
5536 for (i = 0; i < sig->param_count; ++i)
5537 buffer_add_string (buf, names [i]);
5542 case CMD_METHOD_GET_LOCALS_INFO: {
5543 int i, j, num_locals;
5547 header = mono_method_get_header (method);
5550 buffer_add_int (buf, header->num_locals);
5553 for (i = 0; i < header->num_locals; ++i)
5554 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
5557 num_locals = mono_debug_lookup_locals (method, &local_names, &local_indexes);
5558 for (i = 0; i < header->num_locals; ++i) {
5559 for (j = 0; j < num_locals; ++j)
5560 if (local_indexes [j] == i)
5563 buffer_add_string (buf, local_names [j]);
5565 buffer_add_string (buf, "");
5567 g_free (local_names);
5568 g_free (local_indexes);
5571 /* FIXME: This works because we set debug_options.mdb_optimizations */
5572 for (i = 0; i < header->num_locals; ++i) {
5573 buffer_add_int (buf, 0);
5574 buffer_add_int (buf, header->code_size);
5579 case CMD_METHOD_GET_INFO:
5580 buffer_add_int (buf, method->flags);
5581 buffer_add_int (buf, method->iflags);
5582 buffer_add_int (buf, method->token);
5584 case CMD_METHOD_GET_BODY: {
5587 header = mono_method_get_header (method);
5589 buffer_add_int (buf, 0);
5591 buffer_add_int (buf, header->code_size);
5592 for (i = 0; i < header->code_size; ++i)
5593 buffer_add_byte (buf, header->code [i]);
5597 case CMD_METHOD_RESOLVE_TOKEN: {
5598 guint32 token = decode_int (p, &p, end);
5601 switch (mono_metadata_token_code (token)) {
5602 case MONO_TOKEN_STRING: {
5606 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
5609 s2 = mono_string_to_utf8 (s);
5611 buffer_add_byte (buf, TOKEN_TYPE_STRING);
5612 buffer_add_string (buf, s2);
5618 MonoClass *handle_class;
5620 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
5621 val = mono_method_get_wrapper_data (method, token);
5622 handle_class = mono_method_get_wrapper_data (method, token + 1);
5624 if (handle_class == NULL) {
5625 // Can't figure out the token type
5626 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
5630 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
5634 if (handle_class == mono_defaults.typehandle_class) {
5635 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
5636 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
5637 } else if (handle_class == mono_defaults.fieldhandle_class) {
5638 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
5639 buffer_add_fieldid (buf, domain, val);
5640 } else if (handle_class == mono_defaults.methodhandle_class) {
5641 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
5642 buffer_add_methodid (buf, domain, val);
5643 } else if (handle_class == mono_defaults.string_class) {
5646 s = mono_string_to_utf8 (val);
5647 buffer_add_byte (buf, TOKEN_TYPE_STRING);
5648 buffer_add_string (buf, s);
5651 g_assert_not_reached ();
5659 return ERR_NOT_IMPLEMENTED;
5666 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5668 int objid = decode_objid (p, &p, end);
5670 MonoThread *thread_obj;
5671 MonoInternalThread *thread;
5673 err = get_object (objid, (MonoObject**)&thread_obj);
5677 thread = THREAD_TO_INTERNAL (thread_obj);
5680 case CMD_THREAD_GET_NAME: {
5682 gunichar2 *s = mono_thread_get_name (thread, &name_len);
5685 buffer_add_int (buf, 0);
5690 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
5692 buffer_add_int (buf, len);
5693 buffer_add_data (buf, (guint8*)name, len);
5698 case CMD_THREAD_GET_FRAME_INFO: {
5699 DebuggerTlsData *tls;
5700 int i, start_frame, length;
5702 // Wait for suspending if it already started
5704 wait_for_suspend ();
5705 if (!is_suspended ())
5706 return ERR_NOT_SUSPENDED;
5708 start_frame = decode_int (p, &p, end);
5709 length = decode_int (p, &p, end);
5711 if (start_frame != 0 || length != -1)
5712 return ERR_NOT_IMPLEMENTED;
5714 mono_loader_lock ();
5715 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5716 mono_loader_unlock ();
5719 compute_frame_info (thread, tls);
5721 buffer_add_int (buf, tls->frame_count);
5722 for (i = 0; i < tls->frame_count; ++i) {
5723 buffer_add_int (buf, tls->frames [i]->id);
5724 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->method);
5725 buffer_add_int (buf, tls->frames [i]->il_offset);
5727 * Instead of passing the frame type directly to the client, we associate
5728 * it with the previous frame using a set of flags. This avoids lots of
5729 * conditional code in the client, since a frame whose type isn't
5730 * FRAME_TYPE_MANAGED has no method, location, etc.
5732 buffer_add_byte (buf, tls->frames [i]->flags);
5737 case CMD_THREAD_GET_STATE:
5738 buffer_add_int (buf, thread->state);
5740 case CMD_THREAD_GET_INFO:
5741 buffer_add_byte (buf, thread->threadpool_thread);
5744 return ERR_NOT_IMPLEMENTED;
5751 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5755 MonoThread *thread_obj;
5756 MonoInternalThread *thread;
5758 DebuggerTlsData *tls;
5760 MonoDebugMethodJitInfo *jit;
5761 MonoDebugVarInfo *var;
5762 MonoMethodSignature *sig;
5764 MonoMethodHeader *header;
5766 objid = decode_objid (p, &p, end);
5767 err = get_object (objid, (MonoObject**)&thread_obj);
5771 thread = THREAD_TO_INTERNAL (thread_obj);
5773 id = decode_id (p, &p, end);
5775 mono_loader_lock ();
5776 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5777 mono_loader_unlock ();
5780 for (i = 0; i < tls->frame_count; ++i) {
5781 if (tls->frames [i]->id == id)
5784 if (i == tls->frame_count)
5785 return ERR_INVALID_FRAMEID;
5787 frame = tls->frames [i];
5789 if (!frame->has_ctx)
5791 return ERR_INVALID_FRAMEID;
5794 frame->jit = mono_debug_find_method (frame->method, frame->domain);
5795 g_assert (frame->jit);
5799 sig = mono_method_signature (frame->method);
5802 case CMD_STACK_FRAME_GET_VALUES: {
5803 len = decode_int (p, &p, end);
5804 header = mono_method_get_header (frame->method);
5806 for (i = 0; i < len; ++i) {
5807 pos = decode_int (p, &p, end);
5812 g_assert (pos >= 0 && pos < jit->num_params);
5814 var = &jit->params [pos];
5816 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
5818 g_assert (pos >= 0 && pos < jit->num_locals);
5820 var = &jit->locals [pos];
5822 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
5827 case CMD_STACK_FRAME_GET_THIS: {
5828 if (frame->method->klass->valuetype) {
5829 if (!sig->hasthis) {
5830 MonoObject *p = NULL;
5831 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
5833 add_var (buf, &frame->method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
5836 if (!sig->hasthis) {
5837 MonoObject *p = NULL;
5838 buffer_add_value (buf, &frame->method->klass->byval_arg, &p, frame->domain);
5840 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
5845 case CMD_STACK_FRAME_SET_VALUES: {
5848 MonoDebugVarInfo *var;
5850 len = decode_int (p, &p, end);
5851 header = mono_method_get_header (frame->method);
5853 for (i = 0; i < len; ++i) {
5854 pos = decode_int (p, &p, end);
5859 g_assert (pos >= 0 && pos < jit->num_params);
5861 t = sig->params [pos];
5862 var = &jit->params [pos];
5864 g_assert (pos >= 0 && pos < jit->num_locals);
5866 t = header->locals [pos];
5867 var = &jit->locals [pos];
5870 if (MONO_TYPE_IS_REFERENCE (t))
5871 val_buf = g_alloca (sizeof (MonoObject*));
5873 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
5874 err = decode_value (t, frame->domain, val_buf, p, &p, end);
5878 set_var (t, var, &frame->ctx, frame->domain, val_buf);
5883 return ERR_NOT_IMPLEMENTED;
5890 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5893 int objid, err, index, len, i, esize;
5896 objid = decode_objid (p, &p, end);
5897 err = get_object (objid, (MonoObject**)&arr);
5902 case CMD_ARRAY_REF_GET_LENGTH:
5903 buffer_add_int (buf, arr->obj.vtable->klass->rank);
5905 buffer_add_int (buf, arr->max_length);
5906 buffer_add_int (buf, 0);
5908 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
5909 buffer_add_int (buf, arr->bounds [i].length);
5910 buffer_add_int (buf, arr->bounds [i].lower_bound);
5914 case CMD_ARRAY_REF_GET_VALUES:
5915 index = decode_int (p, &p, end);
5916 len = decode_int (p, &p, end);
5918 g_assert (index >= 0 && len >= 0);
5919 // Reordered to avoid integer overflow
5920 g_assert (!(index > arr->max_length - len));
5922 esize = mono_array_element_size (arr->obj.vtable->klass);
5923 for (i = index; i < index + len; ++i) {
5924 elem = (gpointer*)((char*)arr->vector + (i * esize));
5925 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
5928 case CMD_ARRAY_REF_SET_VALUES:
5929 index = decode_int (p, &p, end);
5930 len = decode_int (p, &p, end);
5932 g_assert (index >= 0 && len >= 0);
5933 // Reordered to avoid integer overflow
5934 g_assert (!(index > arr->max_length - len));
5936 esize = mono_array_element_size (arr->obj.vtable->klass);
5937 for (i = index; i < index + len; ++i) {
5938 elem = (gpointer*)((char*)arr->vector + (i * esize));
5940 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
5944 return ERR_NOT_IMPLEMENTED;
5951 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5957 objid = decode_objid (p, &p, end);
5958 err = get_object (objid, (MonoObject**)&str);
5963 case CMD_STRING_REF_GET_VALUE:
5964 s = mono_string_to_utf8 (str);
5965 buffer_add_string (buf, s);
5969 return ERR_NOT_IMPLEMENTED;
5976 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5985 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
5986 objid = decode_objid (p, &p, end);
5987 err = get_object (objid, &obj);
5989 buffer_add_int (buf, 1);
5991 buffer_add_int (buf, 0);
5995 objid = decode_objid (p, &p, end);
5996 err = get_object (objid, &obj);
6001 case CMD_OBJECT_REF_GET_TYPE:
6002 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
6004 case CMD_OBJECT_REF_GET_VALUES:
6005 len = decode_int (p, &p, end);
6007 for (i = 0; i < len; ++i) {
6008 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
6012 /* Check that the field belongs to the object */
6014 for (k = obj->vtable->klass; k; k = k->parent) {
6015 if (k == f->parent) {
6021 return ERR_INVALID_FIELDID;
6023 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6027 if (mono_class_field_is_special_static (f))
6028 return ERR_INVALID_FIELDID;
6030 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6031 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6032 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6033 mono_field_static_get_value (vtable, f, val);
6034 buffer_add_value (buf, f->type, val, obj->vtable->domain);
6037 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
6041 case CMD_OBJECT_REF_SET_VALUES:
6042 len = decode_int (p, &p, end);
6044 for (i = 0; i < len; ++i) {
6045 f = decode_fieldid (p, &p, end, NULL, &err);
6049 /* Check that the field belongs to the object */
6051 for (k = obj->vtable->klass; k; k = k->parent) {
6052 if (k == f->parent) {
6058 return ERR_INVALID_FIELDID;
6060 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6064 if (mono_class_field_is_special_static (f))
6065 return ERR_INVALID_FIELDID;
6067 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6068 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6070 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6071 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
6076 mono_field_static_set_value (vtable, f, val);
6079 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
6085 case CMD_OBJECT_REF_GET_ADDRESS:
6086 buffer_add_long (buf, (gssize)obj);
6088 case CMD_OBJECT_REF_GET_DOMAIN:
6089 buffer_add_domainid (buf, obj->vtable->domain);
6092 return ERR_NOT_IMPLEMENTED;
6099 command_set_to_string (CommandSet command_set)
6101 switch (command_set) {
6104 case CMD_SET_OBJECT_REF:
6105 return "OBJECT_REF";
6106 case CMD_SET_STRING_REF:
6107 return "STRING_REF";
6108 case CMD_SET_THREAD:
6110 case CMD_SET_ARRAY_REF:
6112 case CMD_SET_EVENT_REQUEST:
6113 return "EVENT_REQUEST";
6114 case CMD_SET_STACK_FRAME:
6115 return "STACK_FRAME";
6116 case CMD_SET_APPDOMAIN:
6118 case CMD_SET_ASSEMBLY:
6120 case CMD_SET_METHOD:
6124 case CMD_SET_MODULE:
6136 * This thread handles communication with the debugger client using a JDWP
6139 static guint32 WINAPI
6140 debugger_thread (void *arg)
6142 int res, len, id, flags, command_set, command;
6143 guint8 header [HEADER_LENGTH];
6144 guint8 *data, *p, *end;
6149 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
6151 debugger_thread_id = GetCurrentThreadId ();
6153 mono_jit_thread_attach (mono_get_root_domain ());
6155 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
6157 mono_set_is_debugger_attached (TRUE);
6160 res = recv (conn_fd, header, HEADER_LENGTH, 0);
6162 /* This will break if the socket is closed during shutdown too */
6163 if (res != HEADER_LENGTH)
6167 end = header + HEADER_LENGTH;
6169 len = decode_int (p, &p, end);
6170 id = decode_int (p, &p, end);
6171 flags = decode_byte (p, &p, end);
6172 command_set = decode_byte (p, &p, end);
6173 command = decode_byte (p, &p, end);
6175 g_assert (flags == 0);
6177 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%d), id=%d.\n", command_set_to_string (command_set), command, id));
6179 data = g_malloc (len - HEADER_LENGTH);
6180 if (len - HEADER_LENGTH > 0)
6182 res = recv (conn_fd, data, len - HEADER_LENGTH, 0);
6183 if (res != len - HEADER_LENGTH)
6188 end = data + (len - HEADER_LENGTH);
6190 buffer_init (&buf, 128);
6195 /* Process the request */
6196 switch (command_set) {
6198 err = vm_commands (command, id, p, end, &buf);
6199 if (!err && command == CMD_VM_INVOKE_METHOD)
6200 /* Sent after the invoke is complete */
6203 case CMD_SET_EVENT_REQUEST:
6204 err = event_commands (command, p, end, &buf);
6206 case CMD_SET_APPDOMAIN:
6207 err = domain_commands (command, p, end, &buf);
6209 case CMD_SET_ASSEMBLY:
6210 err = assembly_commands (command, p, end, &buf);
6212 case CMD_SET_MODULE:
6213 err = module_commands (command, p, end, &buf);
6216 err = type_commands (command, p, end, &buf);
6218 case CMD_SET_METHOD:
6219 err = method_commands (command, p, end, &buf);
6221 case CMD_SET_THREAD:
6222 err = thread_commands (command, p, end, &buf);
6224 case CMD_SET_STACK_FRAME:
6225 err = frame_commands (command, p, end, &buf);
6227 case CMD_SET_ARRAY_REF:
6228 err = array_commands (command, p, end, &buf);
6230 case CMD_SET_STRING_REF:
6231 err = string_commands (command, p, end, &buf);
6233 case CMD_SET_OBJECT_REF:
6234 err = object_commands (command, p, end, &buf);
6237 err = ERR_NOT_IMPLEMENTED;
6241 send_reply_packet (id, err, &buf);
6246 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
6250 mono_set_is_debugger_attached (FALSE);
6252 mono_mutex_lock (&debugger_thread_exited_mutex);
6253 debugger_thread_exited = TRUE;
6254 mono_cond_signal (&debugger_thread_exited_cond);
6255 mono_mutex_unlock (&debugger_thread_exited_mutex);
6257 DEBUG (1, printf ("[dbg] Debugger thread exited.\n"));
6262 #else /* DISABLE_DEBUGGER_AGENT */
6265 mono_debugger_agent_parse_options (char *options)
6267 g_error ("This runtime is configure with the debugger agent disabled.");
6271 mono_debugger_agent_init (void)
6276 mono_debugger_agent_breakpoint_hit (void *sigctx)
6281 mono_debugger_agent_single_step_event (void *sigctx)
6286 mono_debugger_agent_free_domain_info (MonoDomain *domain)
6291 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
6297 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *ctx)
6302 mono_debugger_agent_handle_unhandled_exception (MonoException *exc, MonoContext *ctx)