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.
120 typedef struct _InvokeData InvokeData;
128 /* This is the context which needs to be restored after the invoke */
132 * If this is set, invoke this method with the arguments given by ARGS.
136 guint32 suspend_count;
138 InvokeData *last_invoke;
145 gboolean has_context;
146 gpointer resume_event;
147 /* This is computed on demand when it is requested using the wire protocol */
148 /* It is freed up when the thread is resumed */
152 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
155 gboolean frames_up_to_date;
157 * Points to data about a pending invoke which needs to be executed after the thread
160 InvokeData *pending_invoke;
162 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
167 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
168 * within a finite amount of time.
172 * Set to TRUE if this thread is suspended in suspend_current ().
174 gboolean really_suspended;
175 /* Used to pass the context to the breakpoint/single step handler */
176 MonoContext handler_ctx;
177 /* Whenever thread_stop () was called for this thread */
180 /* Number of thread interruptions not yet processed */
181 gint32 interrupt_count;
183 /* Whenever to disable breakpoints (used during invokes) */
184 gboolean disable_breakpoints;
187 * Number of times this thread has been resumed using resume_thread ().
189 guint32 resume_count;
191 MonoInternalThread *thread;
194 * Information about the frame which transitioned to native code for running
197 StackFrameInfo async_last_frame;
200 * The context where the stack walk can be started for running threads.
202 MonoContext async_ctx;
204 gboolean has_async_ctx;
207 * The lmf where the stack walk can be started for running threads.
212 * The callee address of the last mono_runtime_invoke call
214 gpointer invoke_addr;
216 gboolean abort_requested;
219 * The current mono_runtime_invoke invocation.
225 * Wire Protocol definitions
228 #define HEADER_LENGTH 11
230 #define MAJOR_VERSION 2
231 #define MINOR_VERSION 1
235 CMD_SET_OBJECT_REF = 9,
236 CMD_SET_STRING_REF = 10,
238 CMD_SET_ARRAY_REF = 13,
239 CMD_SET_EVENT_REQUEST = 15,
240 CMD_SET_STACK_FRAME = 16,
241 CMD_SET_APPDOMAIN = 20,
242 CMD_SET_ASSEMBLY = 21,
250 EVENT_KIND_VM_START = 0,
251 EVENT_KIND_VM_DEATH = 1,
252 EVENT_KIND_THREAD_START = 2,
253 EVENT_KIND_THREAD_DEATH = 3,
254 EVENT_KIND_APPDOMAIN_CREATE = 4,
255 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
256 EVENT_KIND_METHOD_ENTRY = 6,
257 EVENT_KIND_METHOD_EXIT = 7,
258 EVENT_KIND_ASSEMBLY_LOAD = 8,
259 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
260 EVENT_KIND_BREAKPOINT = 10,
261 EVENT_KIND_STEP = 11,
262 EVENT_KIND_TYPE_LOAD = 12,
263 EVENT_KIND_EXCEPTION = 13
267 SUSPEND_POLICY_NONE = 0,
268 SUSPEND_POLICY_EVENT_THREAD = 1,
269 SUSPEND_POLICY_ALL = 2
274 ERR_INVALID_OBJECT = 20,
275 ERR_INVALID_FIELDID = 25,
276 ERR_INVALID_FRAMEID = 30,
277 ERR_NOT_IMPLEMENTED = 100,
278 ERR_NOT_SUSPENDED = 101,
279 ERR_INVALID_ARGUMENT = 102,
281 ERR_NO_INVOCATION = 104
286 MOD_KIND_THREAD_ONLY = 3,
287 MOD_KIND_LOCATION_ONLY = 7,
288 MOD_KIND_EXCEPTION_ONLY = 8,
290 MOD_KIND_ASSEMBLY_ONLY = 11
305 TOKEN_TYPE_STRING = 0,
307 TOKEN_TYPE_FIELD = 2,
308 TOKEN_TYPE_METHOD = 3,
309 TOKEN_TYPE_UNKNOWN = 4
313 VALUE_TYPE_ID_NULL = 0xf0,
314 VALUE_TYPE_ID_TYPE = 0xf1
318 FRAME_FLAG_DEBUGGER_INVOKE = 1
322 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
323 INVOKE_FLAG_SINGLE_THREADED = 2
328 CMD_VM_ALL_THREADS = 2,
333 CMD_VM_INVOKE_METHOD = 7,
334 CMD_VM_SET_PROTOCOL_VERSION = 8,
335 CMD_VM_ABORT_INVOKE = 9
339 CMD_THREAD_GET_FRAME_INFO = 1,
340 CMD_THREAD_GET_NAME = 2,
341 CMD_THREAD_GET_STATE = 3,
342 CMD_THREAD_GET_INFO = 4
346 CMD_EVENT_REQUEST_SET = 1,
347 CMD_EVENT_REQUEST_CLEAR = 2,
348 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
356 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
357 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
358 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
359 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
360 CMD_APPDOMAIN_CREATE_STRING = 5,
361 CMD_APPDOMAIN_GET_CORLIB = 6,
362 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
366 CMD_ASSEMBLY_GET_LOCATION = 1,
367 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
368 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
369 CMD_ASSEMBLY_GET_OBJECT = 4,
370 CMD_ASSEMBLY_GET_TYPE = 5,
371 CMD_ASSEMBLY_GET_NAME = 6
375 CMD_MODULE_GET_INFO = 1,
379 CMD_METHOD_GET_NAME = 1,
380 CMD_METHOD_GET_DECLARING_TYPE = 2,
381 CMD_METHOD_GET_DEBUG_INFO = 3,
382 CMD_METHOD_GET_PARAM_INFO = 4,
383 CMD_METHOD_GET_LOCALS_INFO = 5,
384 CMD_METHOD_GET_INFO = 6,
385 CMD_METHOD_GET_BODY = 7,
386 CMD_METHOD_RESOLVE_TOKEN = 8,
390 CMD_TYPE_GET_INFO = 1,
391 CMD_TYPE_GET_METHODS = 2,
392 CMD_TYPE_GET_FIELDS = 3,
393 CMD_TYPE_GET_VALUES = 4,
394 CMD_TYPE_GET_OBJECT = 5,
395 CMD_TYPE_GET_SOURCE_FILES = 6,
396 CMD_TYPE_SET_VALUES = 7,
397 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
398 CMD_TYPE_GET_PROPERTIES = 9,
399 CMD_TYPE_GET_CATTRS = 10,
400 CMD_TYPE_GET_FIELD_CATTRS = 11,
401 CMD_TYPE_GET_PROPERTY_CATTRS = 12
405 CMD_STACK_FRAME_GET_VALUES = 1,
406 CMD_STACK_FRAME_GET_THIS = 2,
407 CMD_STACK_FRAME_SET_VALUES = 3
411 CMD_ARRAY_REF_GET_LENGTH = 1,
412 CMD_ARRAY_REF_GET_VALUES = 2,
413 CMD_ARRAY_REF_SET_VALUES = 3,
417 CMD_STRING_REF_GET_VALUE = 1,
421 CMD_OBJECT_REF_GET_TYPE = 1,
422 CMD_OBJECT_REF_GET_VALUES = 2,
423 CMD_OBJECT_REF_IS_COLLECTED = 3,
424 CMD_OBJECT_REF_GET_ADDRESS = 4,
425 CMD_OBJECT_REF_GET_DOMAIN = 5,
426 CMD_OBJECT_REF_SET_VALUES = 6
432 int count; /* For kind == MOD_KIND_COUNT */
433 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
434 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
435 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
437 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
446 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
450 * Describes a single step request.
454 MonoInternalThread *thread;
459 MonoMethod *last_method;
461 /* Whenever single stepping is performed using start/stop_single_stepping () */
463 /* The list of breakpoints used to implement step-over */
468 * Contains additional information for an event
471 /* For EVENT_KIND_EXCEPTION */
473 MonoContext catch_ctx;
477 /* Dummy structure used for the profiler callbacks */
482 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
488 static AgentConfig agent_config;
491 * Whenever the agent is fully initialized.
492 * When using the onuncaught or onthrow options, only some parts of the agent are
493 * initialized on startup, and the full initialization which includes connection
494 * establishment and the startup of the agent thread is only done in response to
497 static gint32 inited;
501 static int packet_id = 0;
503 static int objref_id = 0;
505 static int event_request_id = 0;
507 static int frame_id = 0;
509 static GPtrArray *event_requests;
511 static guint32 debugger_tls_id;
513 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
515 /* Maps MonoInternalThread -> DebuggerTlsData */
516 static MonoGHashTable *thread_to_tls;
518 /* Maps tid -> MonoInternalThread */
519 static MonoGHashTable *tid_to_thread;
521 /* Maps tid -> MonoThread (not MonoInternalThread) */
522 static MonoGHashTable *tid_to_thread_obj;
524 static gsize debugger_thread_id;
526 static HANDLE debugger_thread_handle;
528 static int log_level;
530 static FILE *log_file;
532 /* Classes whose class load event has been sent */
533 static GHashTable *loaded_classes;
535 /* Assemblies whose assembly load event has no been sent yet */
536 static GPtrArray *pending_assembly_loads;
538 /* Whenever the debugger thread has exited */
539 static gboolean debugger_thread_exited;
541 /* Cond variable used to wait for debugger_thread_exited becoming true */
542 static mono_cond_t debugger_thread_exited_cond;
544 /* Mutex for the cond var above */
545 static mono_mutex_t debugger_thread_exited_mutex;
547 static DebuggerProfiler debugger_profiler;
549 /* The single step request instance */
550 static SingleStepReq *ss_req = NULL;
551 static gpointer ss_invoke_addr = NULL;
553 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
554 /* Number of single stepping operations in progress */
558 /* The protocol version of the client */
559 static int major_version, minor_version;
561 /* Whenever the variables above are set by the client */
562 static gboolean protocol_version_set;
564 static void transport_connect (const char *host, int port);
566 static guint32 WINAPI debugger_thread (void *arg);
568 static void runtime_initialized (MonoProfiler *prof);
570 static void runtime_shutdown (MonoProfiler *prof);
572 static void thread_startup (MonoProfiler *prof, intptr_t tid);
574 static void thread_end (MonoProfiler *prof, intptr_t tid);
576 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
578 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
580 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
582 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
584 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
586 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
588 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
590 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
592 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
594 static void start_single_stepping (void);
596 static void stop_single_stepping (void);
598 static void suspend_current (void);
600 /* Submodule init/cleanup */
601 static void breakpoints_init (void);
602 static void breakpoints_cleanup (void);
604 static void objrefs_init (void);
605 static void objrefs_cleanup (void);
607 static void ids_init (void);
608 static void ids_cleanup (void);
610 static void suspend_init (void);
612 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls);
613 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
614 static void ss_destroy (SingleStepReq *req);
616 static void start_debugger_thread (void);
618 static void finish_agent_init (gboolean on_startup);
621 parse_address (char *address, char **host, int *port)
623 char *pos = strchr (address, ':');
625 if (pos == NULL || pos == address)
628 *host = g_malloc (pos - address + 1);
629 strncpy (*host, address, pos - address);
630 (*host) [pos - address] = '\0';
632 *port = atoi (pos + 1);
640 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
641 fprintf (stderr, "Available options:\n");
642 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
643 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
644 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
645 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
646 fprintf (stderr, " suspend=y/n\t\t\tWhenever to suspend after startup.\n");
647 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
648 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
652 parse_flag (const char *option, char *flag)
654 if (!strcmp (flag, "y"))
656 else if (!strcmp (flag, "n"))
659 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
666 mono_debugger_agent_parse_options (char *options)
672 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
673 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
677 agent_config.enabled = TRUE;
678 agent_config.suspend = TRUE;
679 agent_config.server = FALSE;
681 args = g_strsplit (options, ",", -1);
682 for (ptr = args; ptr && *ptr; ptr ++) {
685 if (strncmp (arg, "transport=", 10) == 0) {
686 agent_config.transport = g_strdup (arg + 10);
687 } else if (strncmp (arg, "address=", 8) == 0) {
688 agent_config.address = g_strdup (arg + 8);
689 } else if (strncmp (arg, "loglevel=", 9) == 0) {
690 agent_config.log_level = atoi (arg + 9);
691 } else if (strncmp (arg, "logfile=", 8) == 0) {
692 agent_config.log_file = g_strdup (arg + 8);
693 } else if (strncmp (arg, "suspend=", 8) == 0) {
694 agent_config.suspend = parse_flag ("suspend", arg + 8);
695 } else if (strncmp (arg, "server=", 7) == 0) {
696 agent_config.server = parse_flag ("server", arg + 7);
697 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
698 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
699 } else if (strncmp (arg, "onthrow=", 8) == 0) {
700 /* We support multiple onthrow= options */
701 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
702 } else if (strncmp (arg, "onthrow", 7) == 0) {
703 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
704 } else if (strncmp (arg, "help", 4) == 0) {
707 } else if (strncmp (arg, "timeout=", 8) == 0) {
708 agent_config.timeout = atoi (arg + 8);
709 } else if (strncmp (arg, "launch=", 7) == 0) {
710 agent_config.launch = g_strdup (arg + 7);
717 if (agent_config.transport == NULL) {
718 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
721 if (strcmp (agent_config.transport, "dt_socket") != 0) {
722 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
726 if (agent_config.address == NULL && !agent_config.server) {
727 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
731 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
732 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
738 mono_debugger_agent_init (void)
740 if (!agent_config.enabled)
743 /* Need to know whenever a thread has acquired the loader mutex */
744 mono_loader_lock_track_ownership (TRUE);
746 event_requests = g_ptr_array_new ();
748 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
749 mono_cond_init (&debugger_thread_exited_cond, NULL);
751 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
752 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
753 mono_profiler_install_runtime_initialized (runtime_initialized);
754 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
755 mono_profiler_install_thread (thread_startup, thread_end);
756 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
757 mono_profiler_install_jit_end (jit_end);
758 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
760 debugger_tls_id = TlsAlloc ();
762 thread_to_tls = mono_g_hash_table_new (NULL, NULL);
763 MONO_GC_REGISTER_ROOT (thread_to_tls);
765 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
766 MONO_GC_REGISTER_ROOT (tid_to_thread);
768 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
769 MONO_GC_REGISTER_ROOT (tid_to_thread_obj);
771 loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
772 pending_assembly_loads = g_ptr_array_new ();
774 log_level = agent_config.log_level;
776 if (agent_config.log_file) {
777 log_file = fopen (agent_config.log_file, "w+");
779 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
791 mini_get_debug_options ()->gen_seq_points = TRUE;
793 * This is needed because currently we don't handle liveness info.
795 mini_get_debug_options ()->mdb_optimizations = TRUE;
797 /* This is needed because we can't set local variables in registers yet */
798 mono_disable_optimizations (MONO_OPT_LINEARS);
800 if (!agent_config.onuncaught && !agent_config.onthrow)
801 finish_agent_init (TRUE);
807 * Finish the initialization of the agent. This involves connecting the transport
808 * and starting the agent thread. This is either done at startup, or
809 * in response to some event like an unhandled exception.
812 finish_agent_init (gboolean on_startup)
818 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
821 if (agent_config.launch) {
824 // FIXME: Generated address
825 // FIXME: Races with transport_connect ()
827 argv [0] = agent_config.launch;
828 argv [1] = agent_config.transport;
829 argv [2] = agent_config.address;
832 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
834 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
839 if (agent_config.address) {
840 res = parse_address (agent_config.address, &host, &port);
847 transport_connect (host, port);
850 /* Do some which is usually done after sending the VMStart () event */
851 vm_start_event_sent = TRUE;
852 start_debugger_thread ();
857 mono_debugger_agent_cleanup (void)
862 /* This will interrupt the agent thread */
863 /* Close the read part only so it can still send back replies */
865 shutdown (conn_fd, SD_RECEIVE);
867 shutdown (conn_fd, SHUT_RD);
871 * Wait for the thread to exit.
873 * If we continue with the shutdown without waiting for it, then the client might
874 * not receive an answer to its last command like a resume.
875 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
878 //WaitForSingleObject (debugger_thread_handle, INFINITE);
879 if (GetCurrentThreadId () != debugger_thread_id) {
880 mono_mutex_lock (&debugger_thread_exited_mutex);
881 if (!debugger_thread_exited) {
883 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
884 mono_mutex_unlock (&debugger_thread_exited_mutex);
886 mono_mutex_lock (&debugger_thread_exited_mutex);
889 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
892 mono_mutex_unlock (&debugger_thread_exited_mutex);
895 breakpoints_cleanup ();
900 shutdown (conn_fd, SD_BOTH);
902 shutdown (conn_fd, SHUT_RDWR);
905 mono_mutex_destroy (&debugger_thread_exited_mutex);
906 mono_cond_destroy (&debugger_thread_exited_cond);
912 * recv() + handle incomplete reads and EINTR
915 recv_length (int fd, void *buf, int len, int flags)
921 res = recv (fd, (char *) buf + total, len - total, flags);
924 } while ((res > 0 && total < len) || (res == -1 && errno == EINTR));
930 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
933 transport_connect (const char *host, int port)
935 struct addrinfo hints;
936 struct addrinfo *result, *rp;
938 char port_string [128];
939 char handshake_msg [128];
945 sprintf (port_string, "%d", port);
947 mono_network_init ();
949 /* Obtain address(es) matching host/port */
951 memset (&hints, 0, sizeof (struct addrinfo));
952 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
953 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
955 hints.ai_protocol = 0; /* Any protocol */
957 s = getaddrinfo (host, port_string, &hints, &result);
959 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d: %s\n", host, port, gai_strerror (s));
964 if (agent_config.server) {
965 /* Wait for a connection */
967 struct sockaddr_in addr;
970 /* No address, generate one */
971 sfd = socket (AF_INET, SOCK_STREAM, 0);
974 /* This will bind the socket to a random port */
975 res = listen (sfd, 16);
977 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
981 addrlen = sizeof (addr);
982 memset (&addr, 0, sizeof (addr));
983 res = getsockname (sfd, &addr, &addrlen);
987 port = ntohs (addr.sin_port);
989 /* Emit the address to stdout */
990 /* FIXME: Should print another interface, not localhost */
991 printf ("%s:%d\n", host, port);
993 /* Listen on the provided address */
994 for (rp = result; rp != NULL; rp = rp->ai_next) {
995 sfd = socket (rp->ai_family, rp->ai_socktype,
1000 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1004 res = listen (sfd, 16);
1012 * this function is not present on win2000 which we still support, and the
1013 * workaround described here:
1014 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1015 * only works with MSVC.
1017 freeaddrinfo (result);
1021 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1023 if (agent_config.timeout) {
1028 tv.tv_usec = agent_config.timeout * 1000;
1030 FD_SET (sfd, &readfds);
1031 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1033 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1038 conn_fd = accept (sfd, NULL, NULL);
1039 if (conn_fd == -1) {
1040 fprintf (stderr, "debugger-agent: Unable to listen on %s:%d\n", host, port);
1044 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1046 /* Connect to the specified address */
1047 /* FIXME: Respect the timeout */
1048 for (rp = result; rp != NULL; rp = rp->ai_next) {
1049 sfd = socket (rp->ai_family, rp->ai_socktype,
1054 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1055 break; /* Success */
1063 /* See the comment above */
1064 freeaddrinfo (result);
1068 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1073 /* Write handshake message */
1074 sprintf (handshake_msg, "DWP-Handshake");
1076 res = send (conn_fd, handshake_msg, strlen (handshake_msg), 0);
1077 } while (res == -1 && errno == EINTR);
1078 g_assert (res != -1);
1081 res = recv_length (conn_fd, buf, strlen (handshake_msg), 0);
1082 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1083 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1088 * To support older clients, the client sends its protocol version after connecting
1089 * using a command. Until that is received, default to our protocol version.
1091 major_version = MAJOR_VERSION;
1092 minor_version = MINOR_VERSION;
1093 protocol_version_set = FALSE;
1096 * Set TCP_NODELAY on the socket so the client receives events/command
1097 * results immediately.
1101 int result = setsockopt(conn_fd,
1106 g_assert (result >= 0);
1111 transport_send (guint8 *data, int len)
1116 res = send (conn_fd, data, len, 0);
1117 } while (res == -1 && errno == EINTR);
1125 start_debugger_thread (void)
1129 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1130 g_assert (debugger_thread_handle);
1134 * Functions to decode protocol data
1138 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1141 g_assert (*endbuf <= limit);
1146 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1149 g_assert (*endbuf <= limit);
1151 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1154 static inline gint64
1155 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1157 guint32 high = decode_int (buf, &buf, limit);
1158 guint32 low = decode_int (buf, &buf, limit);
1162 return ((((guint64)high) << 32) | ((guint64)low));
1166 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1168 return decode_int (buf, endbuf, limit);
1172 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1174 int len = decode_int (buf, &buf, limit);
1177 s = g_malloc (len + 1);
1180 memcpy (s, buf, len);
1189 * Functions to encode protocol data
1193 guint8 *buf, *p, *end;
1197 buffer_init (Buffer *buf, int size)
1199 buf->buf = g_malloc (size);
1201 buf->end = buf->buf + size;
1205 buffer_make_room (Buffer *buf, int size)
1207 if (buf->end - buf->p < size) {
1208 int new_size = buf->end - buf->buf + size + 32;
1209 guint8 *p = g_realloc (buf->buf, new_size);
1210 size = buf->p - buf->buf;
1213 buf->end = buf->buf + new_size;
1218 buffer_add_byte (Buffer *buf, guint8 val)
1220 buffer_make_room (buf, 1);
1226 buffer_add_int (Buffer *buf, guint32 val)
1228 buffer_make_room (buf, 4);
1229 buf->p [0] = (val >> 24) & 0xff;
1230 buf->p [1] = (val >> 16) & 0xff;
1231 buf->p [2] = (val >> 8) & 0xff;
1232 buf->p [3] = (val >> 0) & 0xff;
1237 buffer_add_long (Buffer *buf, guint64 l)
1239 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1240 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1244 buffer_add_id (Buffer *buf, int id)
1246 buffer_add_int (buf, (guint64)id);
1250 buffer_add_data (Buffer *buf, guint8 *data, int len)
1252 buffer_make_room (buf, len);
1253 memcpy (buf->p, data, len);
1258 buffer_add_string (Buffer *buf, const char *str)
1263 buffer_add_int (buf, 0);
1266 buffer_add_int (buf, len);
1267 buffer_add_data (buf, (guint8*)str, len);
1272 buffer_free (Buffer *buf)
1278 send_packet (int command_set, int command, Buffer *data)
1284 id = InterlockedIncrement (&packet_id);
1286 len = data->p - data->buf + 11;
1287 buffer_init (&buf, len);
1288 buffer_add_int (&buf, len);
1289 buffer_add_int (&buf, id);
1290 buffer_add_byte (&buf, 0); /* flags */
1291 buffer_add_byte (&buf, command_set);
1292 buffer_add_byte (&buf, command);
1293 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1295 res = transport_send (buf.buf, len);
1303 send_reply_packet (int id, int error, Buffer *data)
1309 len = data->p - data->buf + 11;
1310 buffer_init (&buf, len);
1311 buffer_add_int (&buf, len);
1312 buffer_add_int (&buf, id);
1313 buffer_add_byte (&buf, 0x80); /* flags */
1314 buffer_add_byte (&buf, (error >> 8) & 0xff);
1315 buffer_add_byte (&buf, error);
1316 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1318 res = transport_send (buf.buf, len);
1330 * Represents an object accessible by the debugger client.
1333 /* Unique id used in the wire protocol to refer to objects */
1336 * A weakref gc handle pointing to the object. The gc handle is used to
1337 * detect if the object was garbage collected.
1342 /* Maps objid -> ObjRef */
1343 static GHashTable *objrefs;
1346 free_objref (gpointer value)
1350 mono_gchandle_free (o->handle);
1358 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1362 objrefs_cleanup (void)
1364 g_hash_table_destroy (objrefs);
1368 static GHashTable *obj_to_objref;
1371 * Return an ObjRef for OBJ.
1374 get_objref (MonoObject *obj)
1385 /* Use a hash table with masked pointers to internalize object references */
1386 /* FIXME: This can grow indefinitely */
1387 mono_loader_lock ();
1390 obj_to_objref = g_hash_table_new (NULL, NULL);
1392 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1393 /* ref might refer to a different object with the same addr which was GCd */
1394 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1395 mono_loader_unlock ();
1399 ref = g_new0 (ObjRef, 1);
1400 ref->id = InterlockedIncrement (&objref_id);
1401 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1403 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1404 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1406 mono_loader_unlock ();
1412 get_objid (MonoObject *obj)
1414 return get_objref (obj)->id;
1418 * Set OBJ to the object identified by OBJID.
1419 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1423 get_object_allow_null (int objid, MonoObject **obj)
1433 return ERR_INVALID_OBJECT;
1435 mono_loader_lock ();
1437 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1440 *obj = mono_gchandle_get_target (ref->handle);
1441 mono_loader_unlock ();
1443 return ERR_INVALID_OBJECT;
1446 mono_loader_unlock ();
1447 return ERR_INVALID_OBJECT;
1452 get_object (int objid, MonoObject **obj)
1454 int err = get_object_allow_null (objid, obj);
1459 return ERR_INVALID_OBJECT;
1464 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1466 return decode_id (buf, endbuf, limit);
1470 buffer_add_objid (Buffer *buf, MonoObject *o)
1472 buffer_add_id (buf, get_objid (o));
1491 * Represents a runtime structure accessible to the debugger client
1494 /* Unique id used in the wire protocol */
1496 /* Domain of the runtime structure, NULL if the domain was unloaded */
1503 MonoAssembly *assembly;
1504 MonoClassField *field;
1506 MonoProperty *property;
1511 /* Maps runtime structure -> Id */
1512 GHashTable *val_to_id [ID_NUM];
1516 static GPtrArray *ids [ID_NUM];
1523 for (i = 0; i < ID_NUM; ++i)
1524 ids [i] = g_ptr_array_new ();
1532 for (i = 0; i < ID_NUM; ++i) {
1534 for (j = 0; j < ids [i]->len; ++j)
1535 g_free (g_ptr_array_index (ids [i], j));
1536 g_ptr_array_free (ids [i], TRUE);
1543 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1545 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1549 for (i = 0; i < ID_NUM; ++i)
1550 if (info->val_to_id [i])
1551 g_hash_table_destroy (info->val_to_id [i]);
1555 domain_jit_info (domain)->agent_info = NULL;
1557 /* Clear ids referencing structures in the domain */
1558 for (i = 0; i < ID_NUM; ++i) {
1560 for (j = 0; j < ids [i]->len; ++j) {
1561 Id *id = g_ptr_array_index (ids [i], j);
1562 if (id->domain == domain)
1570 get_id (MonoDomain *domain, IdType type, gpointer val)
1573 AgentDomainInfo *info;
1578 mono_loader_lock ();
1580 mono_domain_lock (domain);
1582 if (!domain_jit_info (domain)->agent_info)
1583 domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1584 info = domain_jit_info (domain)->agent_info;
1585 if (info->val_to_id [type] == NULL)
1586 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1588 id = g_hash_table_lookup (info->val_to_id [type], val);
1590 mono_domain_unlock (domain);
1591 mono_loader_unlock ();
1595 id = g_new0 (Id, 1);
1597 id->id = ids [type]->len + 1;
1598 id->domain = domain;
1601 g_hash_table_insert (info->val_to_id [type], val, id);
1603 mono_domain_unlock (domain);
1605 g_ptr_array_add (ids [type], id);
1607 mono_loader_unlock ();
1612 static inline gpointer
1613 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1617 int id = decode_id (buf, endbuf, limit);
1626 // FIXME: error handling
1627 mono_loader_lock ();
1628 g_assert (id > 0 && id <= ids [type]->len);
1630 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1631 mono_loader_unlock ();
1633 if (res->domain == NULL) {
1634 *err = ERR_UNLOADED;
1639 *domain = res->domain;
1641 return res->data.val;
1645 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1647 buffer_add_id (buf, get_id (domain, type, val));
1650 static inline MonoClass*
1651 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1653 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1656 static inline MonoAssembly*
1657 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1659 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1662 static inline MonoImage*
1663 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1665 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1668 static inline MonoMethod*
1669 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1671 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1674 static inline MonoClassField*
1675 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1677 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1680 static inline MonoDomain*
1681 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1683 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1686 static inline MonoProperty*
1687 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1689 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1693 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1695 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1699 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1701 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1705 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1707 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1711 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1713 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1717 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1719 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1723 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1725 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1729 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1731 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1734 static void invoke_method (void);
1741 * save_thread_context:
1743 * Set CTX as the current threads context which is used for computing stack traces.
1744 * This function is signal-safe.
1747 save_thread_context (MonoContext *ctx)
1749 DebuggerTlsData *tls;
1751 tls = TlsGetValue (debugger_tls_id);
1755 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1757 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1758 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1760 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1764 tls->lmf = mono_get_lmf ();
1765 tls->domain = mono_domain_get ();
1766 tls->has_context = TRUE;
1769 /* The number of times the runtime is suspended */
1770 static gint32 suspend_count;
1772 /* Number of threads suspended */
1774 * If this is equal to the size of thread_to_tls, the runtime is considered
1777 static gint32 threads_suspend_count;
1779 static mono_mutex_t suspend_mutex;
1781 /* Cond variable used to wait for suspend_count becoming 0 */
1782 static mono_cond_t suspend_cond;
1784 /* Semaphore used to wait for a thread becoming suspended */
1785 static MonoSemType suspend_sem;
1790 mono_mutex_init (&suspend_mutex, NULL);
1791 mono_cond_init (&suspend_cond, NULL);
1792 MONO_SEM_INIT (&suspend_sem, 0);
1797 StackFrameInfo last_frame;
1798 gboolean last_frame_set;
1801 } GetLastFrameUserData;
1804 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
1806 GetLastFrameUserData *data = user_data;
1808 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
1811 if (!data->last_frame_set) {
1812 /* Store the last frame */
1813 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
1814 data->last_frame_set = TRUE;
1817 /* Store the context/lmf for the frame above the last frame */
1818 memcpy (&data->ctx, ctx, sizeof (MonoContext));
1819 data->lmf = info->lmf;
1826 * mono_debugger_agent_thread_interrupt:
1828 * Called by the abort signal handler.
1829 * Should be signal safe.
1832 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
1834 DebuggerTlsData *tls;
1839 tls = TlsGetValue (debugger_tls_id);
1844 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
1845 * guarantee the signal handler will be called that many times. Instead of tracking
1846 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
1847 * has been requested that hasn't been handled yet, otherwise we can have threads
1848 * refuse to die when VM_EXIT is called
1850 #if defined(__APPLE__)
1851 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
1855 * We use interrupt_count to determine whenever this interrupt should be processed
1856 * by us or the normal interrupt processing code in the signal handler.
1857 * There is no race here with notify_thread (), since the signal is sent after
1858 * incrementing interrupt_count.
1860 if (tls->interrupt_count == 0)
1863 InterlockedDecrement (&tls->interrupt_count);
1866 // FIXME: Races when the thread leaves managed code before hitting a single step
1870 /* Running managed code, will be suspended by the single step code */
1871 DEBUG (1, printf ("[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)GetCurrentThreadId (), ji->method->name, mono_arch_ip_from_context (sigctx)));
1875 * Running native code, will be suspended when it returns to/enters
1876 * managed code. Treat it as already suspended.
1877 * This might interrupt the code in process_single_step_inner (), we use the
1878 * tls->suspending flag to avoid races when that happens.
1880 if (!tls->suspended && !tls->suspending) {
1882 GetLastFrameUserData data;
1884 // FIXME: printf is not signal safe, but this is only used during
1885 // debugger debugging
1886 DEBUG (1, printf ("[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)GetCurrentThreadId (), mono_arch_ip_from_context (sigctx)));
1887 //save_thread_context (&ctx);
1890 /* Already terminated */
1894 * We are in a difficult position: we want to be able to provide stack
1895 * traces for this thread, but we can't use the current ctx+lmf, since
1896 * the thread is still running, so it might return to managed code,
1897 * making these invalid.
1898 * So we start a stack walk and save the first frame, along with the
1899 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
1900 * suspended when it returns to managed code, so the parent's ctx should
1903 data.last_frame_set = FALSE;
1905 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
1906 mono_jit_walk_stack_from_ctx_in_thread (get_last_frame, mono_domain_get (), &ctx, FALSE, tls->thread, mono_get_lmf (), &data);
1908 if (data.last_frame_set) {
1909 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
1910 memcpy (&tls->async_ctx, &data.ctx, sizeof (MonoContext));
1911 tls->async_lmf = data.lmf;
1912 tls->has_async_ctx = TRUE;
1913 tls->domain = mono_domain_get ();
1914 memcpy (&tls->ctx, &ctx, sizeof (MonoContext));
1916 tls->has_async_ctx = FALSE;
1919 mono_memory_barrier ();
1921 tls->suspended = TRUE;
1922 MONO_SEM_POST (&suspend_sem);
1929 static void CALLBACK notify_thread_apc (ULONG_PTR param)
1932 mono_debugger_agent_thread_interrupt (NULL, NULL);
1934 #endif /* HOST_WIN32 */
1937 * reset_native_thread_suspend_state:
1939 * Reset the suspended flag on native threads
1942 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
1944 DebuggerTlsData *tls = value;
1946 if (!tls->really_suspended && tls->suspended)
1947 tls->suspended = FALSE;
1953 * Notify a thread that it needs to suspend.
1956 notify_thread (gpointer key, gpointer value, gpointer user_data)
1958 MonoInternalThread *thread = key;
1959 DebuggerTlsData *tls = value;
1960 gsize tid = thread->tid;
1962 if (GetCurrentThreadId () == tid || tls->terminated)
1965 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
1968 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
1969 * guarantee the signal handler will be called that many times. Instead of tracking
1970 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
1971 * has been requested that hasn't been handled yet, otherwise we can have threads
1972 * refuse to die when VM_EXIT is called
1974 #if defined(__APPLE__)
1975 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
1979 * Maybe we could use the normal interrupt infrastructure, but that does a lot
1980 * of things like breaking waits etc. which we don't want.
1982 InterlockedIncrement (&tls->interrupt_count);
1985 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
1987 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
1989 pthread_kill ((pthread_t) tid, mono_thread_get_abort_signal ());
1994 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
1996 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
1999 if (debugger_thread_id == GetCurrentThreadId ())
2002 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2003 if (suspend_count - tls->resume_count > 0)
2004 tls->suspending = TRUE;
2006 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2008 if (suspend_count - tls->resume_count == 0) {
2010 * We are executing a single threaded invoke but the single step for
2011 * suspending is still active.
2012 * FIXME: This slows down single threaded invokes.
2014 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2018 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2020 /* Can't suspend in these methods */
2021 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2024 save_thread_context (ctx);
2032 * Increase the suspend count of the VM. While the suspend count is greater
2033 * than 0, runtime threads are suspended at certain points during execution.
2038 mono_loader_lock ();
2040 mono_mutex_lock (&suspend_mutex);
2044 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2046 if (suspend_count == 1) {
2047 // FIXME: Is it safe to call this inside the lock ?
2048 start_single_stepping ();
2049 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2052 mono_mutex_unlock (&suspend_mutex);
2054 mono_loader_unlock ();
2060 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2068 g_assert (debugger_thread_id == GetCurrentThreadId ());
2070 mono_loader_lock ();
2072 mono_mutex_lock (&suspend_mutex);
2074 g_assert (suspend_count > 0);
2077 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2079 if (suspend_count == 0) {
2080 // FIXME: Is it safe to call this inside the lock ?
2081 stop_single_stepping ();
2082 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2085 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2086 err = mono_cond_broadcast (&suspend_cond);
2087 g_assert (err == 0);
2089 mono_mutex_unlock (&suspend_mutex);
2090 //g_assert (err == 0);
2092 mono_loader_unlock ();
2098 * Resume just one thread.
2101 resume_thread (MonoInternalThread *thread)
2104 DebuggerTlsData *tls;
2106 g_assert (debugger_thread_id == GetCurrentThreadId ());
2108 mono_loader_lock ();
2110 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2113 mono_mutex_lock (&suspend_mutex);
2115 g_assert (suspend_count > 0);
2117 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2119 tls->resume_count += suspend_count;
2122 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2123 * but only the one whose resume_count field is > 0 will be resumed.
2125 err = mono_cond_broadcast (&suspend_cond);
2126 g_assert (err == 0);
2128 mono_mutex_unlock (&suspend_mutex);
2129 //g_assert (err == 0);
2131 mono_loader_unlock ();
2135 invalidate_frames (DebuggerTlsData *tls)
2140 tls = TlsGetValue (debugger_tls_id);
2143 for (i = 0; i < tls->frame_count; ++i) {
2144 if (tls->frames [i]->jit)
2145 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2146 g_free (tls->frames [i]);
2148 g_free (tls->frames);
2149 tls->frame_count = 0;
2156 * Suspend the current thread until the runtime is resumed. If the thread has a
2157 * pending invoke, then the invoke is executed before this function returns.
2160 suspend_current (void)
2163 DebuggerTlsData *tls;
2165 g_assert (debugger_thread_id != GetCurrentThreadId ());
2167 if (mono_loader_lock_is_owned_by_self ()) {
2169 * If we own the loader mutex, can't suspend until we release it, since the
2170 * whole runtime can deadlock otherwise.
2175 tls = TlsGetValue (debugger_tls_id);
2178 mono_mutex_lock (&suspend_mutex);
2180 tls->suspending = FALSE;
2181 tls->really_suspended = TRUE;
2183 if (!tls->suspended) {
2184 tls->suspended = TRUE;
2185 MONO_SEM_POST (&suspend_sem);
2188 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2190 while (suspend_count - tls->resume_count > 0) {
2192 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2194 mono_mutex_unlock (&suspend_mutex);
2196 mono_mutex_lock (&suspend_mutex);
2202 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2203 g_assert (err == 0);
2207 tls->suspended = FALSE;
2208 tls->really_suspended = FALSE;
2210 threads_suspend_count --;
2212 mono_mutex_unlock (&suspend_mutex);
2214 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2216 if (tls->pending_invoke) {
2217 /* Save the original context */
2218 tls->pending_invoke->has_ctx = TRUE;
2219 memcpy (&tls->pending_invoke->ctx, &tls->ctx, sizeof (MonoContext));
2224 /* The frame info becomes invalid after a resume */
2225 tls->has_context = FALSE;
2226 tls->has_async_ctx = FALSE;
2227 invalidate_frames (NULL);
2231 count_thread (gpointer key, gpointer value, gpointer user_data)
2233 DebuggerTlsData *tls = value;
2235 if (!tls->suspended && !tls->terminated)
2236 *(int*)user_data = *(int*)user_data + 1;
2240 count_threads_to_wait_for (void)
2244 mono_loader_lock ();
2245 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2246 mono_loader_unlock ();
2254 * Wait until the runtime is completely suspended.
2257 wait_for_suspend (void)
2259 int nthreads, nwait, err;
2260 gboolean waited = FALSE;
2262 // FIXME: Threads starting/stopping ?
2263 mono_loader_lock ();
2264 nthreads = mono_g_hash_table_size (thread_to_tls);
2265 mono_loader_unlock ();
2268 nwait = count_threads_to_wait_for ();
2270 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2271 err = MONO_SEM_WAIT (&suspend_sem);
2272 g_assert (err == 0);
2280 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2286 * Return whenever the runtime is suspended.
2291 return count_threads_to_wait_for () == 0;
2295 * find_seq_point_for_native_offset:
2297 * Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2298 * should be the location of a sequence point.
2301 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2303 MonoSeqPointInfo *seq_points;
2306 mono_domain_lock (domain);
2307 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2308 mono_domain_unlock (domain);
2309 g_assert (seq_points);
2313 for (i = 0; i < seq_points->len; ++i) {
2314 if (seq_points->seq_points [i].native_offset == native_offset)
2315 return &seq_points->seq_points [i];
2324 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2325 * should be the location of a sequence point.
2328 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2330 MonoSeqPointInfo *seq_points;
2333 mono_domain_lock (domain);
2334 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2335 mono_domain_unlock (domain);
2336 g_assert (seq_points);
2340 for (i = 0; i < seq_points->len; ++i) {
2341 if (seq_points->seq_points [i].il_offset == il_offset)
2342 return &seq_points->seq_points [i];
2349 * compute_il_offset:
2351 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2352 * a location of a sequence point.
2353 * We use this function instead of mono_debug_il_offset_from_address () etc,
2354 * which doesn't seem to work in a lot of cases.
2357 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2359 MonoSeqPointInfo *seq_points;
2360 int i, last_il_offset, seq_il_offset, seq_native_offset;
2362 mono_domain_lock (domain);
2363 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2364 mono_domain_unlock (domain);
2365 g_assert (seq_points);
2367 last_il_offset = -1;
2369 /* Find the sequence point */
2370 for (i = 0; i < seq_points->len; ++i) {
2371 seq_il_offset = seq_points->seq_points [i].il_offset;
2372 seq_native_offset = seq_points->seq_points [i].native_offset;
2374 if (seq_native_offset > native_offset)
2376 last_il_offset = seq_il_offset;
2379 return last_il_offset;
2383 DebuggerTlsData *tls;
2385 } ComputeFramesUserData;
2388 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2390 ComputeFramesUserData *ud = user_data;
2394 if (info->type != FRAME_TYPE_MANAGED) {
2395 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2396 /* Mark the last frame as an invoke frame */
2398 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2404 method = info->ji->method;
2406 method = info->method;
2408 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2411 if (info->il_offset == -1) {
2412 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2413 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2416 DEBUG (1, fprintf (stderr, "\tFrame: %s %d %d %d\n", mono_method_full_name (method, TRUE), info->native_offset, info->il_offset, info->managed));
2418 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2420 * mono_arch_find_jit_info () returns the context stored in the LMF for
2421 * native frames, but it should unwind once. This is why we have duplicate
2422 * frames on the stack sometimes.
2423 * !managed also seems to be set for dynamic methods.
2428 frame = g_new0 (StackFrame, 1);
2429 frame->method = method;
2430 frame->il_offset = info->il_offset;
2433 frame->has_ctx = TRUE;
2435 frame->domain = info->domain;
2437 ud->frames = g_slist_append (ud->frames, frame);
2443 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2445 ComputeFramesUserData user_data;
2447 int i, findex, new_frame_count;
2448 StackFrame **new_frames, *f;
2450 // FIXME: Locking on tls
2451 if (tls->frames && tls->frames_up_to_date)
2454 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2456 user_data.tls = tls;
2457 user_data.frames = NULL;
2458 if (tls->terminated) {
2459 tls->frame_count = 0;
2461 } if (!tls->really_suspended && tls->has_async_ctx) {
2462 /* Have to use the state saved by the signal handler */
2463 process_frame (&tls->async_last_frame, NULL, &user_data);
2464 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->async_ctx, FALSE, thread, tls->async_lmf, &user_data);
2465 } else if (tls->has_context) {
2466 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
2469 tls->frame_count = 0;
2473 new_frame_count = g_slist_length (user_data.frames);
2474 new_frames = g_new0 (StackFrame*, new_frame_count);
2476 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2480 * Reuse the id for already existing stack frames, so invokes don't invalidate
2481 * the still valid stack frames.
2483 for (i = 0; i < tls->frame_count; ++i) {
2484 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2485 f->id = tls->frames [i]->id;
2490 if (i >= tls->frame_count)
2491 f->id = InterlockedIncrement (&frame_id);
2493 new_frames [findex ++] = f;
2496 g_slist_free (user_data.frames);
2498 invalidate_frames (tls);
2500 tls->frames = new_frames;
2501 tls->frame_count = new_frame_count;
2502 tls->frames_up_to_date = TRUE;
2510 * create_event_list:
2512 * Return a list of event request ids matching EVENT, starting from REQS, which
2513 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2515 * We return request ids, instead of requests, to simplify threading, since
2516 * requests could be deleted anytime when the loader lock is not held.
2517 * LOCKING: Assumes the loader lock is held.
2520 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
2523 GSList *events = NULL;
2525 *suspend_policy = SUSPEND_POLICY_NONE;
2528 reqs = event_requests;
2533 for (i = 0; i < reqs->len; ++i) {
2534 EventRequest *req = g_ptr_array_index (reqs, i);
2535 if (req->event_kind == event) {
2536 gboolean filtered = FALSE;
2539 for (j = 0; j < req->nmodifiers; ++j) {
2540 Modifier *mod = &req->modifiers [j];
2542 if (mod->kind == MOD_KIND_COUNT) {
2544 if (mod->data.count > 0) {
2545 if (mod->data.count > 0) {
2547 if (mod->data.count == 0)
2551 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2552 if (mod->data.thread != mono_thread_internal_current ())
2554 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
2555 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
2557 if (ei->caught && !mod->caught)
2559 if (!ei->caught && !mod->uncaught)
2561 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2563 gboolean found = FALSE;
2564 MonoAssembly **assemblies = mod->data.assemblies;
2567 for (k = 0; assemblies [k]; ++k)
2568 if (assemblies [k] == ji->method->klass->image->assembly)
2577 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2578 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2583 /* Send a VM START/DEATH event by default */
2584 if (event == EVENT_KIND_VM_START)
2585 events = g_slist_append (events, GINT_TO_POINTER (0));
2586 if (event == EVENT_KIND_VM_DEATH)
2587 events = g_slist_append (events, GINT_TO_POINTER (0));
2592 static G_GNUC_UNUSED const char*
2593 event_to_string (EventKind event)
2596 case EVENT_KIND_VM_START: return "VM_START";
2597 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2598 case EVENT_KIND_THREAD_START: return "THREAD_START";
2599 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2600 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2601 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2602 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2603 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2604 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2605 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2606 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2607 case EVENT_KIND_STEP: return "STEP";
2608 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2609 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2611 g_assert_not_reached ();
2618 * Send an event to the client, suspending the vm if needed.
2619 * LOCKING: Since this can suspend the calling thread, no locks should be held
2621 * The EVENTS list is freed by this function.
2624 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2628 MonoDomain *domain = mono_domain_get ();
2634 if (!vm_start_event_sent && event != EVENT_KIND_VM_START)
2635 // FIXME: We miss those events
2638 if (vm_death_event_sent)
2641 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH)
2650 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
2651 // FIXME: Send these with a NULL thread, don't suspend the current thread
2654 buffer_init (&buf, 128);
2655 buffer_add_byte (&buf, suspend_policy);
2656 buffer_add_int (&buf, g_slist_length (events)); // n of events
2658 for (l = events; l; l = l->next) {
2659 buffer_add_byte (&buf, event); // event kind
2660 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
2662 thread = mono_thread_current ();
2664 if (event == EVENT_KIND_VM_START)
2666 else if (event == EVENT_KIND_THREAD_START)
2667 g_assert (mono_thread_internal_current () == arg);
2669 buffer_add_objid (&buf, (MonoObject*)thread); // thread
2672 case EVENT_KIND_THREAD_START:
2673 case EVENT_KIND_THREAD_DEATH:
2675 case EVENT_KIND_APPDOMAIN_CREATE:
2676 case EVENT_KIND_APPDOMAIN_UNLOAD:
2677 buffer_add_domainid (&buf, arg);
2679 case EVENT_KIND_METHOD_ENTRY:
2680 case EVENT_KIND_METHOD_EXIT:
2681 buffer_add_methodid (&buf, domain, arg);
2683 case EVENT_KIND_ASSEMBLY_LOAD:
2684 case EVENT_KIND_ASSEMBLY_UNLOAD:
2685 buffer_add_assemblyid (&buf, domain, arg);
2687 case EVENT_KIND_TYPE_LOAD:
2688 buffer_add_typeid (&buf, domain, arg);
2690 case EVENT_KIND_BREAKPOINT:
2691 case EVENT_KIND_STEP:
2692 buffer_add_methodid (&buf, domain, arg);
2693 buffer_add_long (&buf, il_offset);
2695 case EVENT_KIND_VM_START:
2696 buffer_add_domainid (&buf, mono_get_root_domain ());
2698 case EVENT_KIND_VM_DEATH:
2700 case EVENT_KIND_EXCEPTION: {
2701 EventInfo *ei = arg;
2702 buffer_add_objid (&buf, ei->exc);
2706 g_assert_not_reached ();
2710 if (event == EVENT_KIND_VM_START) {
2711 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
2712 start_debugger_thread ();
2715 if (event == EVENT_KIND_VM_DEATH) {
2716 vm_death_event_sent = TRUE;
2718 suspend_policy = SUSPEND_POLICY_NONE;
2721 if (mono_runtime_is_shutting_down ())
2722 suspend_policy = SUSPEND_POLICY_NONE;
2724 if (suspend_policy != SUSPEND_POLICY_NONE) {
2726 * Save the thread context and start suspending before sending the packet,
2727 * since we could be receiving the resume request before send_packet ()
2730 save_thread_context (ctx);
2734 send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
2736 g_slist_free (events);
2739 if (event == EVENT_KIND_VM_START)
2740 vm_start_event_sent = TRUE;
2742 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
2746 switch (suspend_policy) {
2747 case SUSPEND_POLICY_NONE:
2749 case SUSPEND_POLICY_ALL:
2752 case SUSPEND_POLICY_EVENT_THREAD:
2756 g_assert_not_reached ();
2761 process_profiler_event (EventKind event, gpointer arg)
2766 mono_loader_lock ();
2767 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
2768 mono_loader_unlock ();
2770 process_event (event, arg, 0, NULL, events, suspend_policy);
2774 runtime_initialized (MonoProfiler *prof)
2776 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
2780 runtime_shutdown (MonoProfiler *prof)
2782 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
2784 mono_debugger_agent_cleanup ();
2788 thread_startup (MonoProfiler *prof, intptr_t tid)
2790 MonoInternalThread *thread = mono_thread_internal_current ();
2791 MonoInternalThread *old_thread;
2792 DebuggerTlsData *tls;
2794 if (tid == debugger_thread_id)
2797 g_assert (thread->tid == tid);
2799 mono_loader_lock ();
2800 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2801 mono_loader_unlock ();
2803 if (thread == old_thread) {
2805 * For some reason, thread_startup () might be called for the same thread
2806 * multiple times (attach ?).
2808 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
2812 * thread_end () might not be called for some threads, and the tid could
2815 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
2816 mono_loader_lock ();
2817 mono_g_hash_table_remove (thread_to_tls, old_thread);
2818 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
2819 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2820 mono_loader_unlock ();
2824 tls = TlsGetValue (debugger_tls_id);
2826 // FIXME: Free this somewhere
2827 tls = g_new0 (DebuggerTlsData, 1);
2828 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
2829 MONO_GC_REGISTER_ROOT (tls->thread);
2830 tls->thread = thread;
2831 TlsSetValue (debugger_tls_id, tls);
2833 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2835 mono_loader_lock ();
2836 mono_g_hash_table_insert (thread_to_tls, thread, tls);
2837 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
2838 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
2839 mono_loader_unlock ();
2841 process_profiler_event (EVENT_KIND_THREAD_START, thread);
2844 * suspend_vm () could have missed this thread, so wait for a resume.
2850 thread_end (MonoProfiler *prof, intptr_t tid)
2852 MonoInternalThread *thread;
2853 DebuggerTlsData *tls = NULL;
2855 mono_loader_lock ();
2856 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2858 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2859 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
2860 tls->terminated = TRUE;
2861 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2862 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
2863 MONO_GC_UNREGISTER_ROOT (tls->thread);
2866 mono_loader_unlock ();
2868 /* We might be called for threads started before we registered the start callback */
2870 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2871 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
2876 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
2878 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
2882 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
2884 /* Invalidate each thread's frame stack */
2885 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
2886 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
2890 * invalidate_each_thread:
2892 * A GHFunc to invalidate frames.
2893 * value must be a DebuggerTlsData*
2896 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
2898 invalidate_frames (value);
2902 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
2904 /* Sent later in jit_end () */
2905 mono_loader_lock ();
2906 g_ptr_array_add (pending_assembly_loads, assembly);
2907 mono_loader_unlock ();
2911 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
2913 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
2917 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2919 #if defined(HOST_WIN32) && !defined(__GNUC__)
2920 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
2922 gpointer stackptr = __builtin_frame_address (1);
2924 MonoInternalThread *thread = mono_thread_internal_current ();
2925 DebuggerTlsData *tls;
2927 mono_loader_lock ();
2929 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2930 /* Could be the debugger thread with assembly/type load hooks */
2932 tls->invoke_addr = stackptr;
2934 mono_loader_unlock ();
2938 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2941 #if defined(HOST_WIN32) && !defined(__GNUC__)
2942 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
2944 gpointer stackptr = __builtin_frame_address (1);
2947 if (ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
2951 * We need to stop single stepping when exiting a runtime invoke, since if it is
2952 * a step out, it may return to native code, and thus never end.
2954 mono_loader_lock ();
2955 ss_invoke_addr = NULL;
2957 for (i = 0; i < event_requests->len; ++i) {
2958 EventRequest *req = g_ptr_array_index (event_requests, i);
2960 if (req->event_kind == EVENT_KIND_STEP) {
2961 ss_destroy (req->info);
2962 g_ptr_array_remove_index_fast (event_requests, i);
2967 mono_loader_unlock ();
2971 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
2974 * We emit type load events when the first method of the type is JITted,
2975 * since the class load profiler callbacks might be called with the
2976 * loader lock held. They could also occur in the debugger thread.
2977 * Same for assembly load events.
2979 gboolean type_load = FALSE;
2982 MonoAssembly *assembly = NULL;
2984 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
2985 mono_loader_lock ();
2986 if (pending_assembly_loads->len > 0) {
2987 assembly = g_ptr_array_index (pending_assembly_loads, 0);
2988 g_ptr_array_remove_index (pending_assembly_loads, 0);
2990 mono_loader_unlock ();
2993 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
2998 mono_loader_lock ();
2999 if (!g_hash_table_lookup (loaded_classes, method->klass)) {
3001 g_hash_table_insert (loaded_classes, method->klass, method->klass);
3003 mono_loader_unlock ();
3005 process_profiler_event (EVENT_KIND_TYPE_LOAD, method->klass);
3008 add_pending_breakpoints (method, jinfo);
3012 * BREAKPOINTS/SINGLE STEPPING
3016 * Contains information about an inserted breakpoint.
3019 long il_offset, native_offset;
3021 gboolean pending, entry;
3023 } BreakpointInstance;
3026 * Contains generic information about a breakpoint.
3030 * The method where the breakpoint is placed. Can be NULL in which case it
3031 * is inserted into every method. This is used to implement method entry/
3032 * exit events. Can be a generic method definition, in which case the
3033 * breakpoint is inserted into every instance.
3037 gboolean pending, entry;
3040 * A list of BreakpointInstance structures describing where the breakpoint
3041 * was inserted. There could be more than one because of
3042 * generics/appdomains/method entry/exit.
3044 GPtrArray *children;
3047 /* List of breakpoints */
3048 static GPtrArray *breakpoints;
3049 /* Maps breakpoint locations to the number of breakpoints at that location */
3050 static GHashTable *bp_locs;
3053 breakpoints_init (void)
3055 breakpoints = g_ptr_array_new ();
3056 bp_locs = g_hash_table_new (NULL, NULL);
3060 breakpoints_cleanup (void)
3064 mono_loader_lock ();
3066 for (i = 0; i < breakpoints->len; ++i)
3067 g_free (g_ptr_array_index (breakpoints, i));
3069 g_ptr_array_free (breakpoints, TRUE);
3070 g_hash_table_destroy (bp_locs);
3072 mono_loader_unlock ();
3076 * insert_breakpoint:
3078 * Insert the breakpoint described by BP into the method described by
3082 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoJitInfo *ji, MonoBreakpoint *bp)
3085 gint32 il_offset, native_offset;
3086 BreakpointInstance *inst;
3089 for (i = 0; i < seq_points->len; ++i) {
3090 il_offset = seq_points->seq_points [i].il_offset;
3091 native_offset = seq_points->seq_points [i].native_offset;
3093 if (il_offset == bp->il_offset)
3097 if (i == seq_points->len)
3098 /* Have to handle this somehow */
3101 inst = g_new0 (BreakpointInstance, 1);
3102 inst->native_offset = native_offset;
3103 inst->ip = (guint8*)ji->code_start + native_offset;
3106 mono_loader_lock ();
3108 g_ptr_array_add (bp->children, inst);
3110 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3111 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3112 mono_loader_unlock ();
3115 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3116 mono_arch_set_breakpoint (ji, inst->ip);
3124 remove_breakpoint (BreakpointInstance *inst)
3126 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3128 MonoJitInfo *ji = inst->ji;
3129 guint8 *ip = inst->ip;
3131 mono_loader_lock ();
3132 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3133 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3134 mono_loader_unlock ();
3136 g_assert (count > 0);
3139 mono_arch_clear_breakpoint (ji, ip);
3147 * add_pending_breakpoints:
3149 * Insert pending breakpoints into the newly JITted method METHOD.
3152 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3155 MonoSeqPointInfo *seq_points;
3161 domain = mono_domain_get ();
3163 mono_loader_lock ();
3165 for (i = 0; i < breakpoints->len; ++i) {
3166 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3168 if (bp->pending && (bp->method == method || !bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method))) {
3169 mono_domain_lock (domain);
3170 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3171 mono_domain_unlock (domain);
3173 /* Could be AOT code */
3175 g_assert (seq_points);
3177 insert_breakpoint (seq_points, ji, bp);
3181 mono_loader_unlock ();
3185 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp)
3190 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3192 /* Might be AOTed code */
3193 code = mono_aot_get_method (domain, method);
3195 ji = mono_jit_info_table_find (domain, code);
3200 insert_breakpoint (seq_points, ji, bp);
3204 set_bp_in_method_cb (gpointer key, gpointer value, gpointer user_data)
3206 MonoMethod *method = key;
3207 MonoSeqPointInfo *seq_points = value;
3208 MonoBreakpoint *bp = user_data;
3209 MonoDomain *domain = mono_domain_get ();
3212 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method) {
3213 /* Generic instance */
3214 set_bp_in_method (domain, method, seq_points, bp);
3217 /* Method entry/exit */
3218 set_bp_in_method (domain, method, seq_points, bp);
3225 * Set a breakpoint at IL_OFFSET in METHOD.
3226 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3227 * METHOD can also be a generic method definition, in which case a breakpoint
3228 * is placed in all instances of the method.
3230 static MonoBreakpoint*
3231 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req)
3233 MonoSeqPointInfo *seq_points;
3238 // - suspend/resume the vm to prevent code patching problems
3240 // - multiple breakpoints on the same location
3241 // - dynamic methods
3244 bp = g_new0 (MonoBreakpoint, 1);
3245 bp->method = method;
3246 bp->il_offset = il_offset;
3248 bp->children = g_ptr_array_new ();
3250 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));
3252 domain = mono_domain_get ();
3253 mono_domain_lock (domain);
3255 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
3257 set_bp_in_method (domain, method, seq_points, bp);
3259 if (method->is_generic)
3260 /* There might be already JITted instances */
3261 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
3263 /* Not yet JITted */
3267 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
3270 mono_domain_unlock (domain);
3272 mono_loader_lock ();
3273 g_ptr_array_add (breakpoints, bp);
3274 mono_loader_unlock ();
3280 clear_breakpoint (MonoBreakpoint *bp)
3284 // FIXME: locking, races
3285 for (i = 0; i < bp->children->len; ++i) {
3286 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3288 remove_breakpoint (inst);
3293 mono_loader_lock ();
3294 g_ptr_array_remove (breakpoints, bp);
3295 mono_loader_unlock ();
3297 g_ptr_array_free (bp->children, TRUE);
3302 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
3305 guint8 *orig_ip, *ip;
3306 int i, j, suspend_policy;
3307 guint32 native_offset;
3309 BreakpointInstance *inst;
3310 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3311 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3312 EventKind kind = EVENT_KIND_BREAKPOINT;
3314 // FIXME: Speed this up
3316 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3317 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
3319 g_assert (ji->method);
3321 /* Compute the native offset of the breakpoint from the ip */
3322 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3323 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3324 native_offset = ip - (guint8*)ji->code_start;
3330 * Skip the instruction causing the breakpoint signal.
3332 mono_arch_skip_breakpoint (ctx);
3334 if (ji->method->wrapper_type || tls->disable_breakpoints)
3337 bp_reqs = g_ptr_array_new ();
3338 ss_reqs = g_ptr_array_new ();
3339 ss_reqs_orig = g_ptr_array_new ();
3341 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3343 mono_loader_lock ();
3346 for (i = 0; i < breakpoints->len; ++i) {
3347 bp = g_ptr_array_index (breakpoints, i);
3352 for (j = 0; j < bp->children->len; ++j) {
3353 inst = g_ptr_array_index (bp->children, j);
3354 if (inst->ji == ji && inst->native_offset == native_offset) {
3355 if (bp->req->event_kind == EVENT_KIND_STEP) {
3356 g_ptr_array_add (ss_reqs_orig, bp->req);
3358 g_ptr_array_add (bp_reqs, bp->req);
3363 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3364 MonoSeqPointInfo *seq_points;
3365 int seq_il_offset, seq_native_offset;
3366 MonoDomain *domain = mono_domain_get ();
3368 /* Maybe a method entry/exit event */
3369 mono_domain_lock (domain);
3370 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3371 mono_domain_unlock (domain);
3373 // FIXME: Generic sharing */
3374 mono_loader_unlock ();
3377 g_assert (seq_points);
3379 for (i = 0; i < seq_points->len; ++i) {
3380 seq_il_offset = seq_points->seq_points [i].il_offset;
3381 seq_native_offset = seq_points->seq_points [i].native_offset;
3383 if (native_offset == seq_native_offset) {
3384 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3385 kind = EVENT_KIND_METHOD_ENTRY;
3386 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3387 kind = EVENT_KIND_METHOD_EXIT;
3393 /* Process single step requests */
3394 for (i = 0; i < ss_reqs_orig->len; ++i) {
3395 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3396 SingleStepReq *ss_req = bp->req->info;
3397 gboolean hit = TRUE;
3398 MonoSeqPointInfo *info;
3401 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3404 if (ss_req->size == STEP_SIZE_LINE) {
3405 /* Have to check whenever a different source line was reached */
3406 MonoDebugMethodInfo *minfo;
3407 MonoDebugSourceLocation *loc = NULL;
3409 minfo = mono_debug_lookup_method (ji->method);
3412 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3414 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3415 /* Have to continue single stepping */
3419 ss_req->last_method = ji->method;
3420 ss_req->last_line = loc->row;
3421 mono_debug_free_source_location (loc);
3426 g_ptr_array_add (ss_reqs, req);
3428 /* Start single stepping again from the current sequence point */
3429 ss_start (ss_req, ji->method, sp, info, ctx, NULL);
3432 if (ss_reqs->len > 0)
3433 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3434 if (bp_reqs->len > 0)
3435 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3436 if (kind != EVENT_KIND_BREAKPOINT)
3437 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3439 mono_loader_unlock ();
3441 g_ptr_array_free (bp_reqs, TRUE);
3442 g_ptr_array_free (ss_reqs, TRUE);
3445 * FIXME: The first event will suspend, so the second will only be sent after the
3449 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3451 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3452 if (enter_leave_events)
3453 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3457 process_breakpoint (void)
3459 DebuggerTlsData *tls;
3461 static void (*restore_context) (void *);
3463 if (!restore_context)
3464 restore_context = mono_get_restore_context ();
3466 tls = TlsGetValue (debugger_tls_id);
3467 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3469 process_breakpoint_inner (tls, &ctx);
3471 /* This is called when resuming from a signal handler, so it shouldn't return */
3472 restore_context (&ctx);
3473 g_assert_not_reached ();
3477 resume_from_signal_handler (void *sigctx, void *func)
3479 DebuggerTlsData *tls;
3482 /* Save the original context in TLS */
3483 // FIXME: This might not work on an altstack ?
3484 tls = TlsGetValue (debugger_tls_id);
3487 // FIXME: MonoContext usually doesn't include the fp registers, so these are
3488 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3489 // clob:c could be added to op_seq_point.
3491 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3492 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3493 MONO_CONTEXT_SET_IP (&ctx, func);
3494 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3496 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3497 mono_ppc_set_func_into_sigctx (sigctx, func);
3502 mono_debugger_agent_breakpoint_hit (void *sigctx)
3505 * We are called from a signal handler, and running code there causes all kinds of
3506 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
3507 * So set up the signal context to return to the real breakpoint handler function.
3510 resume_from_signal_handler (sigctx, process_breakpoint);
3514 process_single_step_inner (DebuggerTlsData *tls, MonoContext *ctx)
3519 int il_offset, suspend_policy;
3523 // FIXME: Speed this up
3525 ip = MONO_CONTEXT_GET_IP (ctx);
3527 /* Skip the instruction causing the single step */
3528 mono_arch_skip_single_step (ctx);
3530 if (suspend_count > 0) {
3531 process_suspend (tls, ctx);
3536 // FIXME: A suspend race
3539 if (mono_thread_internal_current () != ss_req->thread)
3542 if (log_level > 0) {
3543 const char *depth = NULL;
3545 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
3547 switch (ss_req->depth) {
3548 case STEP_DEPTH_OVER:
3551 case STEP_DEPTH_OUT:
3554 case STEP_DEPTH_INTO:
3558 g_assert_not_reached ();
3561 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));
3565 * We implement step over/out by single stepping until we reach the same
3566 * frame/parent frame.
3569 * - stack growing upward
3573 if (ss_req->depth != STEP_DEPTH_INTO) {
3574 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
3576 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
3579 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
3582 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
3584 g_assert (ji->method);
3586 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
3591 * Stopping in memset makes half-initialized vtypes visible.
3592 * Stopping in memcpy makes half-copied vtypes visible.
3594 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
3598 * The ip points to the instruction causing the single step event, convert it
3599 * to the offset stored in seq_points.
3601 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3602 ip = mono_arch_get_ip_for_single_step (ji, ctx);
3604 g_assert_not_reached ();
3608 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
3609 * example, so do things by hand.
3611 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
3613 if (il_offset == -1)
3616 if (ss_req->size == STEP_SIZE_LINE) {
3617 /* Step until a different source line is reached */
3618 MonoDebugMethodInfo *minfo;
3620 minfo = mono_debug_lookup_method (ji->method);
3623 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
3625 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
3626 mono_debug_free_source_location (loc);
3631 * Step until we reach a location with line number info,
3632 * otherwise the client can't show a location.
3633 * This can happen for example with statics initialized inline
3634 * outside of a cctor.
3639 ss_req->last_method = ji->method;
3640 ss_req->last_line = loc->row;
3641 mono_debug_free_source_location (loc);
3646 // FIXME: Has to lock earlier
3648 reqs = g_ptr_array_new ();
3650 mono_loader_lock ();
3652 g_ptr_array_add (reqs, ss_req->req);
3654 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
3656 g_ptr_array_free (reqs, TRUE);
3658 mono_loader_unlock ();
3660 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
3664 process_single_step (void)
3666 DebuggerTlsData *tls;
3668 static void (*restore_context) (void *);
3670 if (!restore_context)
3671 restore_context = mono_get_restore_context ();
3673 tls = TlsGetValue (debugger_tls_id);
3674 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3676 process_single_step_inner (tls, &ctx);
3678 /* This is called when resuming from a signal handler, so it shouldn't return */
3679 restore_context (&ctx);
3680 g_assert_not_reached ();
3684 * mono_debugger_agent_single_step_event:
3686 * Called from a signal handler to handle a single step event.
3689 mono_debugger_agent_single_step_event (void *sigctx)
3691 /* Resume to process_single_step through the signal context */
3693 // FIXME: Since step out/over is implemented using step in, the step in case should
3694 // be as fast as possible. Move the relevant code from process_single_step_inner ()
3697 if (GetCurrentThreadId () == debugger_thread_id) {
3699 * This could happen despite our best effors when the runtime calls
3700 * assembly/type resolve hooks.
3701 * FIXME: Breakpoints too.
3705 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3706 mono_arch_skip_single_step (&ctx);
3707 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3711 resume_from_signal_handler (sigctx, process_single_step);
3715 * start_single_stepping:
3717 * Turn on single stepping. Can be called multiple times, for example,
3718 * by a single step event request + a suspend.
3721 start_single_stepping (void)
3723 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3724 int val = InterlockedIncrement (&ss_count);
3727 mono_arch_start_single_stepping ();
3729 if (ss_req != NULL && ss_invoke_addr == NULL) {
3730 DebuggerTlsData *tls;
3732 mono_loader_lock ();
3734 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
3735 ss_invoke_addr = tls->invoke_addr;
3737 mono_loader_unlock ();
3740 g_assert_not_reached ();
3745 stop_single_stepping (void)
3747 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3748 int val = InterlockedDecrement (&ss_count);
3751 mono_arch_stop_single_stepping ();
3753 g_assert_not_reached ();
3760 * Stop the single stepping operation given by SS_REQ.
3763 ss_stop (SingleStepReq *ss_req)
3765 gboolean use_bps = FALSE;
3772 for (l = ss_req->bps; l; l = l->next) {
3773 clear_breakpoint (l->data);
3775 g_slist_free (ss_req->bps);
3779 if (ss_req->global) {
3780 stop_single_stepping ();
3781 ss_req->global = FALSE;
3788 * Start the single stepping operation given by SS_REQ from the sequence point SP.
3791 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls)
3793 gboolean use_bp = FALSE;
3798 /* Stop the previous operation */
3802 * Implement single stepping using breakpoints if possible.
3804 if (ss_req->depth == STEP_DEPTH_OVER) {
3807 * Find the first sequence point in the current or in a previous frame which
3808 * is not the last in its method.
3810 while (sp && sp->next_len == 0) {
3812 if (tls && frame_index < tls->frame_count) {
3813 StackFrame *frame = tls->frames [frame_index];
3815 method = frame->method;
3816 if (frame->il_offset != -1) {
3817 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
3823 if (sp && sp->next_len > 0) {
3825 for (i = 0; i < sp->next_len; ++i) {
3826 next_sp = &info->seq_points [sp->next [i]];
3828 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req);
3829 ss_req->bps = g_slist_append (ss_req->bps, bp);
3835 ss_req->global = TRUE;
3836 start_single_stepping ();
3838 ss_req->global = FALSE;
3843 * Start single stepping of thread THREAD
3846 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
3848 DebuggerTlsData *tls;
3849 MonoSeqPointInfo *info;
3850 SeqPoint *sp = NULL;
3851 MonoMethod *method = NULL;
3853 if (suspend_count == 0)
3854 return ERR_NOT_SUSPENDED;
3856 wait_for_suspend ();
3858 // FIXME: Multiple requests
3860 DEBUG (0, printf ("Received a single step request while the previous one was still active.\n"));
3861 return ERR_NOT_IMPLEMENTED;
3864 ss_req = g_new0 (SingleStepReq, 1);
3866 ss_req->thread = thread;
3867 ss_req->size = size;
3868 ss_req->depth = depth;
3871 mono_loader_lock ();
3872 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3873 mono_loader_unlock ();
3875 g_assert (tls->has_context);
3876 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
3878 if (ss_req->size == STEP_SIZE_LINE) {
3880 MonoDebugMethodInfo *minfo;
3882 /* Compute the initial line info */
3883 compute_frame_info (thread, tls);
3885 g_assert (tls->frame_count);
3886 frame = tls->frames [0];
3888 ss_req->last_method = frame->method;
3889 ss_req->last_line = -1;
3891 minfo = mono_debug_lookup_method (frame->method);
3892 if (minfo && frame->il_offset != -1) {
3893 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
3896 ss_req->last_line = loc->row;
3902 if (ss_req->depth == STEP_DEPTH_OVER) {
3905 compute_frame_info (thread, tls);
3907 g_assert (tls->frame_count);
3908 frame = tls->frames [0];
3910 if (frame->il_offset != -1) {
3911 /* FIXME: Sort the table and use a binary search */
3912 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
3914 method = frame->method;
3918 ss_start (ss_req, method, sp, info, NULL, tls);
3924 ss_destroy (SingleStepReq *req)
3927 g_assert (ss_req == req);
3936 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
3937 MonoContext *catch_ctx)
3944 if (thread_to_tls != NULL) {
3945 MonoInternalThread *thread = mono_thread_internal_current ();
3946 DebuggerTlsData *tls;
3948 mono_loader_lock ();
3949 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3950 mono_loader_unlock ();
3952 if (tls && tls->abort_requested)
3956 memset (&ei, 0, sizeof (EventInfo));
3958 /* Just-In-Time debugging */
3960 if (agent_config.onuncaught && !inited) {
3961 finish_agent_init (FALSE);
3964 * Send an unsolicited EXCEPTION event with a dummy request id.
3966 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3967 ei.exc = (MonoObject*)exc;
3968 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
3971 } else if (agent_config.onthrow && !inited) {
3973 gboolean found = FALSE;
3975 for (l = agent_config.onthrow; l; l = l->next) {
3976 char *ex_type = l->data;
3977 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
3979 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
3986 finish_agent_init (FALSE);
3989 * Send an unsolicited EXCEPTION event with a dummy request id.
3991 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3992 ei.exc = (MonoObject*)exc;
3993 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4001 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
4003 ei.exc = (MonoObject*)exc;
4004 ei.caught = catch_ctx != NULL;
4006 mono_loader_lock ();
4007 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
4008 mono_loader_unlock ();
4010 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
4014 * buffer_add_value_full:
4016 * Add the encoding of the value at ADDR described by T to the buffer.
4017 * AS_VTYPE determines whenever to treat primitive types as primitive types or
4021 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
4027 g_assert (*(void**)addr);
4028 addr = *(void**)addr;
4033 case MONO_TYPE_BOOLEAN:
4036 case MONO_TYPE_CHAR:
4056 case MONO_TYPE_VOID:
4057 buffer_add_byte (buf, t->type);
4059 case MONO_TYPE_BOOLEAN:
4062 buffer_add_byte (buf, t->type);
4063 buffer_add_int (buf, *(gint8*)addr);
4065 case MONO_TYPE_CHAR:
4068 buffer_add_byte (buf, t->type);
4069 buffer_add_int (buf, *(gint16*)addr);
4074 buffer_add_byte (buf, t->type);
4075 buffer_add_int (buf, *(gint32*)addr);
4080 buffer_add_byte (buf, t->type);
4081 buffer_add_long (buf, *(gint64*)addr);
4085 /* Treat it as a vtype */
4087 case MONO_TYPE_PTR: {
4088 gssize val = *(gssize*)addr;
4090 buffer_add_byte (buf, t->type);
4091 buffer_add_long (buf, val);
4095 case MONO_TYPE_STRING:
4096 case MONO_TYPE_SZARRAY:
4097 case MONO_TYPE_OBJECT:
4098 case MONO_TYPE_CLASS:
4099 case MONO_TYPE_ARRAY:
4100 obj = *(MonoObject**)addr;
4103 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4105 if (obj->vtable->klass->valuetype) {
4106 t = &obj->vtable->klass->byval_arg;
4107 addr = mono_object_unbox (obj);
4109 } else if (obj->vtable->klass->rank) {
4110 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4111 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4112 buffer_add_byte (buf, MONO_TYPE_CLASS);
4114 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4116 buffer_add_objid (buf, obj);
4120 case MONO_TYPE_VALUETYPE: {
4124 MonoClass *klass = mono_class_from_mono_type (t);
4126 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4127 buffer_add_byte (buf, klass->enumtype);
4128 buffer_add_typeid (buf, domain, klass);
4132 while ((f = mono_class_get_fields (klass, &iter))) {
4133 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4135 if (mono_field_is_deleted (f))
4139 buffer_add_int (buf, nfields);
4142 while ((f = mono_class_get_fields (klass, &iter))) {
4143 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4145 if (mono_field_is_deleted (f))
4147 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4151 case MONO_TYPE_GENERICINST:
4152 if (mono_type_generic_inst_is_valuetype (t)) {
4164 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4166 buffer_add_value_full (buf, t, addr, domain, FALSE);
4170 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4173 int type = decode_byte (buf, &buf, limit);
4175 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4176 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4177 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4178 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
4179 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
4180 char *name = mono_type_full_name (t);
4181 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
4183 return ERR_INVALID_ARGUMENT;
4187 case MONO_TYPE_BOOLEAN:
4188 *(guint8*)addr = decode_int (buf, &buf, limit);
4190 case MONO_TYPE_CHAR:
4191 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4194 *(gint8*)addr = decode_int (buf, &buf, limit);
4197 *(guint8*)addr = decode_int (buf, &buf, limit);
4200 *(gint16*)addr = decode_int (buf, &buf, limit);
4203 *(guint16*)addr = decode_int (buf, &buf, limit);
4206 *(gint32*)addr = decode_int (buf, &buf, limit);
4209 *(guint32*)addr = decode_int (buf, &buf, limit);
4212 *(gint64*)addr = decode_long (buf, &buf, limit);
4215 *(guint64*)addr = decode_long (buf, &buf, limit);
4218 *(guint32*)addr = decode_int (buf, &buf, limit);
4221 *(guint64*)addr = decode_long (buf, &buf, limit);
4224 /* We send these as I8, so we get them back as such */
4225 g_assert (type == MONO_TYPE_I8);
4226 *(gssize*)addr = decode_long (buf, &buf, limit);
4228 case MONO_TYPE_GENERICINST:
4229 if (MONO_TYPE_ISSTRUCT (t)) {
4230 /* The client sends these as a valuetype */
4238 /* We send these as vtypes, so we get them back as such */
4239 g_assert (type == MONO_TYPE_VALUETYPE);
4242 case MONO_TYPE_VALUETYPE: {
4243 gboolean is_enum = decode_byte (buf, &buf, limit);
4247 gpointer iter = NULL;
4250 /* Enums are sent as a normal vtype */
4252 return ERR_NOT_IMPLEMENTED;
4253 klass = decode_typeid (buf, &buf, limit, &d, &err);
4257 if (klass != mono_class_from_mono_type (t))
4258 return ERR_INVALID_ARGUMENT;
4260 nfields = decode_int (buf, &buf, limit);
4261 while ((f = mono_class_get_fields (klass, &iter))) {
4262 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4264 if (mono_field_is_deleted (f))
4266 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4271 g_assert (nfields == 0);
4276 if (MONO_TYPE_IS_REFERENCE (t)) {
4277 if (type == MONO_TYPE_OBJECT) {
4278 int objid = decode_objid (buf, &buf, limit);
4282 err = get_object (objid, (MonoObject**)&obj);
4286 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4287 return ERR_INVALID_ARGUMENT;
4288 if (obj && obj->vtable->domain != domain)
4289 return ERR_INVALID_ARGUMENT;
4291 mono_gc_wbarrier_generic_store (addr, obj);
4292 } else if (type == VALUE_TYPE_ID_NULL) {
4293 *(MonoObject**)addr = NULL;
4295 return ERR_INVALID_ARGUMENT;
4309 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4316 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4317 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4320 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4321 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4323 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
4325 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4326 addr = mono_arch_context_get_int_reg (ctx, reg);
4327 addr += (gint32)var->offset;
4329 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4331 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4333 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4337 g_assert_not_reached ();
4342 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
4348 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4349 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4351 if (MONO_TYPE_IS_REFERENCE (t))
4352 size = sizeof (gpointer);
4354 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4357 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4358 // FIXME: Can't set registers, so we disable linears
4361 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4362 addr = mono_arch_context_get_int_reg (ctx, reg);
4363 addr += (gint32)var->offset;
4365 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4367 // FIXME: Write barriers
4368 memcpy (addr, val, size);
4370 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4374 g_assert_not_reached ();
4379 clear_event_request (int req_id, int etype)
4383 mono_loader_lock ();
4384 for (i = 0; i < event_requests->len; ++i) {
4385 EventRequest *req = g_ptr_array_index (event_requests, i);
4387 if (req->id == req_id && req->event_kind == etype) {
4388 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4389 clear_breakpoint (req->info);
4390 if (req->event_kind == EVENT_KIND_STEP)
4391 ss_destroy (req->info);
4392 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
4393 clear_breakpoint (req->info);
4394 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
4395 clear_breakpoint (req->info);
4396 g_ptr_array_remove_index_fast (event_requests, i);
4401 mono_loader_unlock ();
4405 add_thread (gpointer key, gpointer value, gpointer user_data)
4407 MonoInternalThread *thread = value;
4408 Buffer *buf = user_data;
4410 buffer_add_objid (buf, (MonoObject*)thread);
4414 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
4416 guint8 *p = invoke->p;
4417 guint8 *end = invoke->endp;
4420 MonoMethodSignature *sig;
4423 MonoObject *this, *res, *exc;
4426 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4430 if (invoke->method) {
4432 * Invoke this method directly, currently only Environment.Exit () is supported.
4435 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>"));
4436 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
4437 g_assert_not_reached ();
4440 m = decode_methodid (p, &p, end, &domain, &err);
4443 sig = mono_method_signature (m);
4445 if (m->klass->valuetype)
4446 this_buf = g_alloca (mono_class_instance_size (m->klass));
4448 this_buf = g_alloca (sizeof (MonoObject*));
4449 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
4450 /* Should be null */
4451 int type = decode_byte (p, &p, end);
4452 if (type != VALUE_TYPE_ID_NULL)
4453 return ERR_INVALID_ARGUMENT;
4454 memset (this_buf, 0, mono_class_instance_size (m->klass));
4456 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
4461 if (!m->klass->valuetype)
4462 this = *(MonoObject**)this_buf;
4466 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>"));
4468 if (this && this->vtable->domain != domain)
4471 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
4472 if (!strcmp (m->name, ".ctor")) {
4473 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
4474 return ERR_INVALID_ARGUMENT;
4476 this = mono_object_new (domain, m->klass);
4478 return ERR_INVALID_ARGUMENT;
4482 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
4483 return ERR_INVALID_ARGUMENT;
4485 nargs = decode_int (p, &p, end);
4486 if (nargs != sig->param_count)
4487 return ERR_INVALID_ARGUMENT;
4488 /* Use alloca to get gc tracking */
4489 arg_buf = g_alloca (nargs * sizeof (gpointer));
4490 memset (arg_buf, 0, nargs * sizeof (gpointer));
4491 args = g_alloca (nargs * sizeof (gpointer));
4492 for (i = 0; i < nargs; ++i) {
4493 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
4494 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
4498 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
4501 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
4502 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
4505 args [i] = arg_buf [i];
4512 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
4513 tls->disable_breakpoints = TRUE;
4515 tls->disable_breakpoints = FALSE;
4518 * Add an LMF frame to link the stack frames on the invoke method with our caller.
4520 /* FIXME: Move this to arch specific code */
4521 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4522 if (invoke->has_ctx) {
4525 lmf_addr = mono_get_lmf_addr ();
4528 memset (&ext, 0, sizeof (ext));
4530 ext.lmf.previous_lmf = *(lmf_addr);
4531 /* Mark that this is a MonoLMFExt */
4532 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4533 ext.lmf.rsp = (gssize)&ext;
4534 #elif defined(TARGET_X86)
4535 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
4536 /* Mark that this is a MonoLMFExt */
4537 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4538 ext.lmf.ebp = (gssize)&ext;
4539 #elif defined(TARGET_ARM)
4540 ext.lmf.previous_lmf = *(lmf_addr);
4541 /* Mark that this is a MonoLMFExt */
4542 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4543 ext.lmf.ebp = (gssize)&ext;
4544 #elif defined(TARGET_POWERPC)
4545 ext.lmf.previous_lmf = *(lmf_addr);
4546 /* Mark that this is a MonoLMFExt */
4547 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
4548 ext.lmf.ebp = (gssize)&ext;
4550 g_assert_not_reached ();
4553 ext.debugger_invoke = TRUE;
4554 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
4556 mono_set_lmf ((MonoLMF*)&ext);
4560 if (m->klass->valuetype)
4561 res = mono_runtime_invoke (m, this_buf, args, &exc);
4563 res = mono_runtime_invoke (m, this, args, &exc);
4565 buffer_add_byte (buf, 0);
4566 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
4568 buffer_add_byte (buf, 1);
4569 if (sig->ret->type == MONO_TYPE_VOID) {
4570 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
4571 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
4574 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
4575 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
4576 buffer_add_value (buf, sig->ret, &res, domain);
4577 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
4579 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
4585 tls->disable_breakpoints = FALSE;
4587 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
4588 if (invoke->has_ctx)
4589 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
4592 // FIXME: byref arguments
4600 * Invoke the method given by tls->pending_invoke in the current thread.
4603 invoke_method (void)
4605 DebuggerTlsData *tls;
4610 static void (*restore_context) (void *);
4611 MonoContext restore_ctx;
4613 if (!restore_context)
4614 restore_context = mono_get_restore_context ();
4616 tls = TlsGetValue (debugger_tls_id);
4620 * Store the `InvokeData *' in `tls->invoke' until we're done with
4621 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
4624 mono_loader_lock ();
4626 invoke = tls->pending_invoke;
4628 tls->pending_invoke = NULL;
4630 invoke->last_invoke = tls->invoke;
4631 tls->invoke = invoke;
4633 mono_loader_unlock ();
4635 tls->frames_up_to_date = FALSE;
4639 buffer_init (&buf, 128);
4641 err = do_invoke_method (tls, &buf, invoke);
4643 /* Start suspending before sending the reply */
4644 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
4647 send_reply_packet (id, err, &buf);
4651 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
4653 if (invoke->has_ctx)
4654 save_thread_context (&restore_ctx);
4656 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
4657 g_assert (tls->resume_count);
4658 tls->resume_count -= invoke->suspend_count;
4661 DEBUG (1, printf ("[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
4664 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
4666 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
4667 * after the mono_runtime_invoke() already returned, but it doesn't matter
4668 * because we reset the abort here.
4671 mono_loader_lock ();
4673 if (tls->abort_requested)
4674 mono_thread_internal_reset_abort (tls->thread);
4676 tls->invoke = tls->invoke->last_invoke;
4677 tls->abort_requested = FALSE;
4679 mono_loader_unlock ();
4688 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
4690 MonoThread *thread = value;
4691 DebuggerTlsData *tls;
4694 mono_loader_lock ();
4695 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4697 res = tls->really_suspended;
4698 mono_loader_unlock ();
4704 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
4707 case CMD_VM_VERSION: {
4708 char *build_info, *version;
4710 build_info = mono_get_runtime_build_info ();
4711 version = g_strdup_printf ("mono %s", build_info);
4713 buffer_add_string (buf, version); /* vm version */
4714 buffer_add_int (buf, MAJOR_VERSION);
4715 buffer_add_int (buf, MINOR_VERSION);
4716 g_free (build_info);
4720 case CMD_VM_SET_PROTOCOL_VERSION: {
4721 major_version = decode_int (p, &p, end);
4722 minor_version = decode_int (p, &p, end);
4723 protocol_version_set = TRUE;
4724 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
4727 case CMD_VM_ALL_THREADS: {
4729 mono_loader_lock ();
4730 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
4731 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
4732 mono_loader_unlock ();
4735 case CMD_VM_SUSPEND:
4737 wait_for_suspend ();
4740 if (suspend_count == 0)
4741 return ERR_NOT_SUSPENDED;
4744 case CMD_VM_DISPOSE:
4745 /* Clear all event requests */
4746 mono_loader_lock ();
4747 while (event_requests->len > 0) {
4748 EventRequest *req = g_ptr_array_index (event_requests, 0);
4750 clear_event_request (req->id, req->event_kind);
4752 mono_loader_unlock ();
4754 // FIXME: Count resumes
4756 disconnected = TRUE;
4759 MonoInternalThread *thread;
4760 DebuggerTlsData *tls;
4761 MonoClass *env_class;
4762 MonoMethod *exit_method;
4766 exit_code = decode_int (p, &p, end);
4768 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
4770 /* Have to send a reply before exiting */
4771 send_reply_packet (id, 0, buf);
4773 /* Clear all event requests */
4774 mono_loader_lock ();
4775 while (event_requests->len > 0) {
4776 EventRequest *req = g_ptr_array_index (event_requests, 0);
4778 clear_event_request (req->id, req->event_kind);
4780 mono_loader_unlock ();
4783 * The JDWP documentation says that the shutdown is not orderly. It doesn't
4784 * specify whenever a VM_DEATH event is sent. We currently do an orderly
4785 * shutdown by hijacking a thread to execute Environment.Exit (). This is
4786 * better than doing the shutdown ourselves, since it avoids various races.
4790 wait_for_suspend ();
4792 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
4793 g_assert (env_class);
4794 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
4795 g_assert (exit_method);
4797 mono_loader_lock ();
4798 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
4799 mono_loader_unlock ();
4802 mono_loader_lock ();
4803 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4804 mono_loader_unlock ();
4806 args = g_new0 (gpointer, 1);
4807 args [0] = g_malloc (sizeof (int));
4808 *(int*)(args [0]) = exit_code;
4810 tls->pending_invoke = g_new0 (InvokeData, 1);
4811 tls->pending_invoke->method = exit_method;
4812 tls->pending_invoke->args = args;
4814 while (suspend_count > 0)
4818 * No thread found, do it ourselves.
4819 * FIXME: This can race with normal shutdown etc.
4821 while (suspend_count > 0)
4824 mono_runtime_set_shutting_down ();
4826 mono_threads_set_shutting_down ();
4828 /* Suspend all managed threads since the runtime is going away */
4829 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
4830 mono_thread_suspend_all_other_threads ();
4831 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
4832 mono_runtime_quit ();
4834 shutdown (conn_fd, SD_BOTH);
4836 shutdown (conn_fd, SHUT_RDWR);
4838 DEBUG(1, fprintf (log_file, "Exiting...\n"));
4844 case CMD_VM_INVOKE_METHOD: {
4845 int objid = decode_objid (p, &p, end);
4847 DebuggerTlsData *tls;
4850 err = get_object (objid, (MonoObject**)&thread);
4854 flags = decode_int (p, &p, end);
4856 // Wait for suspending if it already started
4858 wait_for_suspend ();
4859 if (!is_suspended ())
4860 return ERR_NOT_SUSPENDED;
4862 mono_loader_lock ();
4863 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
4864 mono_loader_unlock ();
4867 if (!tls->really_suspended)
4868 /* The thread is still running native code, can't do invokes */
4869 return ERR_NOT_SUSPENDED;
4872 * Store the invoke data into tls, the thread will execute it after it is
4875 if (tls->pending_invoke)
4877 tls->pending_invoke = g_new0 (InvokeData, 1);
4878 tls->pending_invoke->id = id;
4879 tls->pending_invoke->flags = flags;
4880 tls->pending_invoke->p = g_malloc (end - p);
4881 memcpy (tls->pending_invoke->p, p, end - p);
4882 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
4883 tls->pending_invoke->suspend_count = suspend_count;
4885 if (flags & INVOKE_FLAG_SINGLE_THREADED)
4886 resume_thread (THREAD_TO_INTERNAL (thread));
4891 case CMD_VM_ABORT_INVOKE: {
4892 int objid = decode_objid (p, &p, end);
4894 DebuggerTlsData *tls;
4897 err = get_object (objid, (MonoObject**)&thread);
4901 invoke_id = decode_int (p, &p, end);
4903 mono_loader_lock ();
4904 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
4907 if (tls->abort_requested) {
4908 mono_loader_unlock ();
4913 * Check whether we're still inside the mono_runtime_invoke() and that it's
4914 * actually the correct invocation.
4916 * Careful, we do not stop the thread that's doing the invocation, so we can't
4917 * inspect its stack. However, invoke_method() also acquires the loader lock
4918 * when it's done, so we're safe here.
4922 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
4923 mono_loader_unlock ();
4924 return ERR_NO_INVOCATION;
4927 tls->abort_requested = TRUE;
4929 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
4930 mono_loader_unlock ();
4935 return ERR_NOT_IMPLEMENTED;
4942 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4947 case CMD_EVENT_REQUEST_SET: {
4949 int i, event_kind, suspend_policy, nmodifiers, mod;
4952 MonoThread *step_thread;
4953 int size = 0, depth = 0, step_thread_id = 0;
4956 event_kind = decode_byte (p, &p, end);
4957 suspend_policy = decode_byte (p, &p, end);
4958 nmodifiers = decode_byte (p, &p, end);
4960 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
4961 req->id = InterlockedIncrement (&event_request_id);
4962 req->event_kind = event_kind;
4963 req->suspend_policy = suspend_policy;
4964 req->nmodifiers = nmodifiers;
4967 for (i = 0; i < nmodifiers; ++i) {
4968 mod = decode_byte (p, &p, end);
4970 req->modifiers [i].kind = mod;
4971 if (mod == MOD_KIND_COUNT) {
4972 req->modifiers [i].data.count = decode_int (p, &p, end);
4973 } else if (mod == MOD_KIND_LOCATION_ONLY) {
4974 method = decode_methodid (p, &p, end, &domain, &err);
4977 location = decode_long (p, &p, end);
4978 } else if (mod == MOD_KIND_STEP) {
4979 step_thread_id = decode_id (p, &p, end);
4980 size = decode_int (p, &p, end);
4981 depth = decode_int (p, &p, end);
4982 } else if (mod == MOD_KIND_THREAD_ONLY) {
4983 int id = decode_id (p, &p, end);
4985 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
4990 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
4991 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
4995 req->modifiers [i].caught = decode_byte (p, &p, end);
4996 req->modifiers [i].uncaught = decode_byte (p, &p, end);
4998 req->modifiers [i].data.exc_class = exc_class;
5000 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
5002 return ERR_INVALID_ARGUMENT;
5005 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
5006 int n = decode_int (p, &p, end);
5009 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
5010 for (j = 0; j < n; ++j) {
5011 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
5013 g_free (req->modifiers [i].data.assemblies);
5019 return ERR_NOT_IMPLEMENTED;
5023 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5026 req->info = set_breakpoint (method, location, req);
5027 } else if (req->event_kind == EVENT_KIND_STEP) {
5028 g_assert (step_thread_id);
5030 err = get_object (step_thread_id, (MonoObject**)&step_thread);
5036 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
5041 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
5042 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req);
5043 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
5044 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req);
5045 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
5047 if (req->nmodifiers) {
5049 return ERR_NOT_IMPLEMENTED;
5053 mono_loader_lock ();
5054 g_ptr_array_add (event_requests, req);
5055 mono_loader_unlock ();
5057 buffer_add_int (buf, req->id);
5060 case CMD_EVENT_REQUEST_CLEAR: {
5061 int etype = decode_byte (p, &p, end);
5062 int req_id = decode_int (p, &p, end);
5064 // FIXME: Make a faster mapping from req_id to request
5065 mono_loader_lock ();
5066 clear_event_request (req_id, etype);
5067 mono_loader_unlock ();
5070 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
5073 mono_loader_lock ();
5075 while (i < event_requests->len) {
5076 EventRequest *req = g_ptr_array_index (event_requests, i);
5078 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5079 clear_breakpoint (req->info);
5081 g_ptr_array_remove_index_fast (event_requests, i);
5087 mono_loader_unlock ();
5091 return ERR_NOT_IMPLEMENTED;
5098 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5104 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
5105 buffer_add_domainid (buf, mono_get_root_domain ());
5108 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
5109 domain = decode_domainid (p, &p, end, NULL, &err);
5112 buffer_add_string (buf, domain->friendly_name);
5115 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
5120 domain = decode_domainid (p, &p, end, NULL, &err);
5123 mono_loader_lock ();
5125 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5128 buffer_add_int (buf, count);
5129 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5131 buffer_add_assemblyid (buf, domain, ass);
5133 mono_loader_unlock ();
5136 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
5137 domain = decode_domainid (p, &p, end, NULL, &err);
5141 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
5144 case CMD_APPDOMAIN_GET_CORLIB: {
5145 domain = decode_domainid (p, &p, end, NULL, &err);
5149 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
5152 case CMD_APPDOMAIN_CREATE_STRING: {
5156 domain = decode_domainid (p, &p, end, NULL, &err);
5159 s = decode_string (p, &p, end);
5161 o = mono_string_new (domain, s);
5162 buffer_add_objid (buf, (MonoObject*)o);
5165 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
5167 MonoDomain *domain2;
5170 domain = decode_domainid (p, &p, end, NULL, &err);
5173 klass = decode_typeid (p, &p, end, &domain2, &err);
5178 g_assert (domain == domain2);
5180 o = mono_object_new (domain, klass);
5182 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
5186 buffer_add_objid (buf, o);
5190 return ERR_NOT_IMPLEMENTED;
5197 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5203 ass = decode_assemblyid (p, &p, end, &domain, &err);
5208 case CMD_ASSEMBLY_GET_LOCATION: {
5209 buffer_add_string (buf, mono_image_get_filename (ass->image));
5212 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
5216 if (ass->image->dynamic) {
5217 buffer_add_id (buf, 0);
5219 token = mono_image_get_entry_point (ass->image);
5221 buffer_add_id (buf, 0);
5223 m = mono_get_method (ass->image, token, NULL);
5224 buffer_add_methodid (buf, domain, m);
5229 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5230 buffer_add_moduleid (buf, domain, ass->image);
5233 case CMD_ASSEMBLY_GET_OBJECT: {
5234 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5235 buffer_add_objid (buf, o);
5238 case CMD_ASSEMBLY_GET_TYPE: {
5239 char *s = decode_string (p, &p, end);
5240 gboolean ignorecase = decode_byte (p, &p, end);
5241 MonoTypeNameParse info;
5243 gboolean type_resolve;
5245 if (!mono_reflection_parse_type (s, &info)) {
5248 if (info.assembly.name)
5250 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5252 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5253 mono_reflection_free_type_info (&info);
5258 case CMD_ASSEMBLY_GET_NAME: {
5260 MonoAssembly *mass = ass;
5262 name = g_strdup_printf (
5263 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5265 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5266 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5267 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5268 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5270 buffer_add_string (buf, name);
5275 return ERR_NOT_IMPLEMENTED;
5282 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5288 case CMD_MODULE_GET_INFO: {
5289 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
5292 basename = g_path_get_basename (image->name);
5293 buffer_add_string (buf, basename); // name
5294 buffer_add_string (buf, image->module_name); // scopename
5295 buffer_add_string (buf, image->name); // fqname
5296 buffer_add_string (buf, mono_image_get_guid (image)); // guid
5297 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
5302 return ERR_NOT_IMPLEMENTED;
5309 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
5311 if (val && val->vtable->klass == mono_defaults.monotype_class) {
5312 /* Special case these so the client doesn't have to handle Type objects */
5314 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
5315 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
5316 } else if (MONO_TYPE_IS_REFERENCE (t))
5317 buffer_add_value (buf, t, &val, domain);
5319 buffer_add_value (buf, t, mono_object_unbox (val), domain);
5323 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
5329 buffer_add_int (buf, 0);
5333 for (i = 0; i < cinfo->num_attrs; ++i) {
5334 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
5337 buffer_add_int (buf, nattrs);
5339 for (i = 0; i < cinfo->num_attrs; ++i) {
5340 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
5341 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
5342 MonoArray *typed_args, *named_args;
5344 CattrNamedArg *arginfo;
5346 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
5348 buffer_add_methodid (buf, domain, attr->ctor);
5352 buffer_add_int (buf, mono_array_length (typed_args));
5353 for (j = 0; j < mono_array_length (typed_args); ++j) {
5354 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
5356 t = mono_method_signature (attr->ctor)->params [j];
5358 buffer_add_cattr_arg (buf, t, domain, val);
5361 buffer_add_int (buf, 0);
5366 buffer_add_int (buf, mono_array_length (named_args));
5368 for (j = 0; j < mono_array_length (named_args); ++j) {
5369 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
5371 if (arginfo [j].prop) {
5372 buffer_add_byte (buf, 0x54);
5373 buffer_add_propertyid (buf, domain, arginfo [j].prop);
5374 } else if (arginfo [j].field) {
5375 buffer_add_byte (buf, 0x53);
5377 g_assert_not_reached ();
5380 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
5383 buffer_add_int (buf, 0);
5390 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5401 klass = decode_typeid (p, &p, end, &domain, &err);
5406 case CMD_TYPE_GET_INFO: {
5407 buffer_add_string (buf, klass->name_space);
5408 buffer_add_string (buf, klass->name);
5410 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
5411 buffer_add_string (buf, name);
5413 buffer_add_assemblyid (buf, domain, klass->image->assembly);
5414 buffer_add_moduleid (buf, domain, klass->image);
5415 buffer_add_typeid (buf, domain, klass->parent);
5416 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
5417 buffer_add_typeid (buf, domain, klass->element_class);
5419 buffer_add_id (buf, 0);
5420 buffer_add_int (buf, klass->type_token);
5421 buffer_add_byte (buf, klass->rank);
5422 buffer_add_int (buf, klass->flags);
5424 type = &klass->byval_arg;
5425 // FIXME: Can't decide whenever a class represents a byref type
5428 if (type->type == MONO_TYPE_PTR)
5430 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
5432 if (type->type == MONO_TYPE_VALUETYPE)
5434 if (klass->enumtype)
5436 buffer_add_byte (buf, b);
5439 while ((nested = mono_class_get_nested_types (klass, &iter)))
5441 buffer_add_int (buf, nnested);
5443 while ((nested = mono_class_get_nested_types (klass, &iter)))
5444 buffer_add_typeid (buf, domain, nested);
5447 case CMD_TYPE_GET_METHODS: {
5450 gpointer iter = NULL;
5453 nmethods = mono_class_num_methods (klass);
5455 buffer_add_int (buf, nmethods);
5457 while ((m = mono_class_get_methods (klass, &iter))) {
5458 buffer_add_methodid (buf, domain, m);
5461 g_assert (i == nmethods);
5464 case CMD_TYPE_GET_FIELDS: {
5467 gpointer iter = NULL;
5470 nfields = mono_class_num_fields (klass);
5472 buffer_add_int (buf, nfields);
5474 while ((f = mono_class_get_fields (klass, &iter))) {
5475 buffer_add_fieldid (buf, domain, f);
5476 buffer_add_string (buf, f->name);
5477 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
5478 buffer_add_int (buf, f->type->attrs);
5481 g_assert (i == nfields);
5484 case CMD_TYPE_GET_PROPERTIES: {
5487 gpointer iter = NULL;
5490 nprops = mono_class_num_properties (klass);
5492 buffer_add_int (buf, nprops);
5494 while ((p = mono_class_get_properties (klass, &iter))) {
5495 buffer_add_propertyid (buf, domain, p);
5496 buffer_add_string (buf, p->name);
5497 buffer_add_methodid (buf, domain, p->get);
5498 buffer_add_methodid (buf, domain, p->set);
5499 buffer_add_int (buf, p->attrs);
5502 g_assert (i == nprops);
5505 case CMD_TYPE_GET_CATTRS: {
5506 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
5507 MonoCustomAttrInfo *cinfo;
5509 cinfo = mono_custom_attrs_from_class (klass);
5511 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5514 case CMD_TYPE_GET_FIELD_CATTRS: {
5515 MonoClass *attr_klass;
5516 MonoCustomAttrInfo *cinfo;
5517 MonoClassField *field;
5519 field = decode_fieldid (p, &p, end, NULL, &err);
5522 attr_klass = decode_typeid (p, &p, end, NULL, &err);
5526 cinfo = mono_custom_attrs_from_field (klass, field);
5528 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5531 case CMD_TYPE_GET_PROPERTY_CATTRS: {
5532 MonoClass *attr_klass;
5533 MonoCustomAttrInfo *cinfo;
5536 prop = decode_propertyid (p, &p, end, NULL, &err);
5539 attr_klass = decode_typeid (p, &p, end, NULL, &err);
5543 cinfo = mono_custom_attrs_from_property (klass, prop);
5545 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
5548 case CMD_TYPE_GET_VALUES: {
5556 len = decode_int (p, &p, end);
5557 for (i = 0; i < len; ++i) {
5558 f = decode_fieldid (p, &p, end, NULL, &err);
5562 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
5563 return ERR_INVALID_FIELDID;
5564 if (mono_class_field_is_special_static (f))
5565 return ERR_INVALID_FIELDID;
5567 /* Check that the field belongs to the object */
5569 for (k = klass; k; k = k->parent) {
5570 if (k == f->parent) {
5576 return ERR_INVALID_FIELDID;
5578 vtable = mono_class_vtable (domain, f->parent);
5579 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5580 mono_field_static_get_value (vtable, f, val);
5581 buffer_add_value (buf, f->type, val, domain);
5586 case CMD_TYPE_SET_VALUES: {
5594 len = decode_int (p, &p, end);
5595 for (i = 0; i < len; ++i) {
5596 f = decode_fieldid (p, &p, end, NULL, &err);
5600 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
5601 return ERR_INVALID_FIELDID;
5602 if (mono_class_field_is_special_static (f))
5603 return ERR_INVALID_FIELDID;
5605 /* Check that the field belongs to the object */
5607 for (k = klass; k; k = k->parent) {
5608 if (k == f->parent) {
5614 return ERR_INVALID_FIELDID;
5616 // FIXME: Check for literal/const
5618 vtable = mono_class_vtable (domain, f->parent);
5619 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5620 err = decode_value (f->type, domain, val, p, &p, end);
5625 if (MONO_TYPE_IS_REFERENCE (f->type))
5626 mono_field_static_set_value (vtable, f, *(gpointer*)val);
5628 mono_field_static_set_value (vtable, f, val);
5633 case CMD_TYPE_GET_OBJECT: {
5634 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
5635 buffer_add_objid (buf, o);
5638 case CMD_TYPE_GET_SOURCE_FILES: {
5639 gpointer iter = NULL;
5641 char *source_file, *base;
5645 files = g_ptr_array_new ();
5647 while ((method = mono_class_get_methods (klass, &iter))) {
5648 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
5651 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
5655 for (i = 0; i < files->len; ++i)
5656 if (!strcmp (g_ptr_array_index (files, i), source_file))
5658 if (i == files->len)
5659 g_ptr_array_add (files, g_strdup (source_file));
5660 g_free (source_file);
5664 buffer_add_int (buf, files->len);
5665 for (i = 0; i < files->len; ++i) {
5666 source_file = g_ptr_array_index (files, i);
5667 base = g_path_get_basename (source_file);
5668 buffer_add_string (buf, base);
5670 g_free (source_file);
5672 g_ptr_array_free (files, TRUE);
5675 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
5676 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
5680 if (mono_class_is_assignable_from (klass, oklass))
5681 buffer_add_byte (buf, 1);
5683 buffer_add_byte (buf, 0);
5687 return ERR_NOT_IMPLEMENTED;
5694 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5699 MonoMethodHeader *header;
5701 method = decode_methodid (p, &p, end, &domain, &err);
5706 case CMD_METHOD_GET_NAME: {
5707 buffer_add_string (buf, method->name);
5710 case CMD_METHOD_GET_DECLARING_TYPE: {
5711 buffer_add_typeid (buf, domain, method->klass);
5714 case CMD_METHOD_GET_DEBUG_INFO: {
5715 MonoDebugMethodInfo *minfo;
5717 int i, n_il_offsets;
5721 header = mono_method_get_header (method);
5723 buffer_add_int (buf, 0);
5724 buffer_add_string (buf, "");
5725 buffer_add_int (buf, 0);
5729 minfo = mono_debug_lookup_method (method);
5731 buffer_add_int (buf, header->code_size);
5732 buffer_add_string (buf, "");
5733 buffer_add_int (buf, 0);
5734 mono_metadata_free_mh (header);
5738 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
5739 buffer_add_int (buf, header->code_size);
5740 buffer_add_string (buf, source_file);
5741 buffer_add_int (buf, n_il_offsets);
5742 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
5743 for (i = 0; i < n_il_offsets; ++i) {
5744 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
5745 buffer_add_int (buf, il_offsets [i]);
5746 buffer_add_int (buf, line_numbers [i]);
5748 g_free (source_file);
5749 g_free (il_offsets);
5750 g_free (line_numbers);
5751 mono_metadata_free_mh (header);
5754 case CMD_METHOD_GET_PARAM_INFO: {
5755 MonoMethodSignature *sig = mono_method_signature (method);
5759 /* FIXME: mono_class_from_mono_type () and byrefs */
5761 /* FIXME: Use a smaller encoding */
5762 buffer_add_int (buf, sig->call_convention);
5763 buffer_add_int (buf, sig->param_count);
5764 buffer_add_int (buf, sig->generic_param_count);
5765 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
5766 for (i = 0; i < sig->param_count; ++i) {
5768 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
5771 /* Emit parameter names */
5772 names = g_new (char *, sig->param_count);
5773 mono_method_get_param_names (method, (const char **) names);
5774 for (i = 0; i < sig->param_count; ++i)
5775 buffer_add_string (buf, names [i]);
5780 case CMD_METHOD_GET_LOCALS_INFO: {
5781 int i, j, num_locals;
5785 header = mono_method_get_header (method);
5788 buffer_add_int (buf, header->num_locals);
5791 for (i = 0; i < header->num_locals; ++i)
5792 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
5795 num_locals = mono_debug_lookup_locals (method, &local_names, &local_indexes);
5796 for (i = 0; i < header->num_locals; ++i) {
5797 for (j = 0; j < num_locals; ++j)
5798 if (local_indexes [j] == i)
5801 buffer_add_string (buf, local_names [j]);
5803 buffer_add_string (buf, "");
5805 g_free (local_names);
5806 g_free (local_indexes);
5809 /* FIXME: This works because we set debug_options.mdb_optimizations */
5810 for (i = 0; i < header->num_locals; ++i) {
5811 buffer_add_int (buf, 0);
5812 buffer_add_int (buf, header->code_size);
5814 mono_metadata_free_mh (header);
5818 case CMD_METHOD_GET_INFO:
5819 buffer_add_int (buf, method->flags);
5820 buffer_add_int (buf, method->iflags);
5821 buffer_add_int (buf, method->token);
5823 case CMD_METHOD_GET_BODY: {
5826 header = mono_method_get_header (method);
5828 buffer_add_int (buf, 0);
5830 buffer_add_int (buf, header->code_size);
5831 for (i = 0; i < header->code_size; ++i)
5832 buffer_add_byte (buf, header->code [i]);
5834 mono_metadata_free_mh (header);
5837 case CMD_METHOD_RESOLVE_TOKEN: {
5838 guint32 token = decode_int (p, &p, end);
5841 switch (mono_metadata_token_code (token)) {
5842 case MONO_TOKEN_STRING: {
5846 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
5849 s2 = mono_string_to_utf8 (s);
5851 buffer_add_byte (buf, TOKEN_TYPE_STRING);
5852 buffer_add_string (buf, s2);
5858 MonoClass *handle_class;
5860 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
5861 val = mono_method_get_wrapper_data (method, token);
5862 handle_class = mono_method_get_wrapper_data (method, token + 1);
5864 if (handle_class == NULL) {
5865 // Can't figure out the token type
5866 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
5870 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
5874 if (handle_class == mono_defaults.typehandle_class) {
5875 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
5876 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
5877 } else if (handle_class == mono_defaults.fieldhandle_class) {
5878 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
5879 buffer_add_fieldid (buf, domain, val);
5880 } else if (handle_class == mono_defaults.methodhandle_class) {
5881 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
5882 buffer_add_methodid (buf, domain, val);
5883 } else if (handle_class == mono_defaults.string_class) {
5886 s = mono_string_to_utf8 (val);
5887 buffer_add_byte (buf, TOKEN_TYPE_STRING);
5888 buffer_add_string (buf, s);
5891 g_assert_not_reached ();
5899 return ERR_NOT_IMPLEMENTED;
5906 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5908 int objid = decode_objid (p, &p, end);
5910 MonoThread *thread_obj;
5911 MonoInternalThread *thread;
5913 err = get_object (objid, (MonoObject**)&thread_obj);
5917 thread = THREAD_TO_INTERNAL (thread_obj);
5920 case CMD_THREAD_GET_NAME: {
5922 gunichar2 *s = mono_thread_get_name (thread, &name_len);
5925 buffer_add_int (buf, 0);
5930 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
5932 buffer_add_int (buf, len);
5933 buffer_add_data (buf, (guint8*)name, len);
5938 case CMD_THREAD_GET_FRAME_INFO: {
5939 DebuggerTlsData *tls;
5940 int i, start_frame, length;
5942 // Wait for suspending if it already started
5944 wait_for_suspend ();
5945 if (!is_suspended ())
5946 return ERR_NOT_SUSPENDED;
5948 start_frame = decode_int (p, &p, end);
5949 length = decode_int (p, &p, end);
5951 if (start_frame != 0 || length != -1)
5952 return ERR_NOT_IMPLEMENTED;
5954 mono_loader_lock ();
5955 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5956 mono_loader_unlock ();
5959 compute_frame_info (thread, tls);
5961 buffer_add_int (buf, tls->frame_count);
5962 for (i = 0; i < tls->frame_count; ++i) {
5963 buffer_add_int (buf, tls->frames [i]->id);
5964 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->method);
5965 buffer_add_int (buf, tls->frames [i]->il_offset);
5967 * Instead of passing the frame type directly to the client, we associate
5968 * it with the previous frame using a set of flags. This avoids lots of
5969 * conditional code in the client, since a frame whose type isn't
5970 * FRAME_TYPE_MANAGED has no method, location, etc.
5972 buffer_add_byte (buf, tls->frames [i]->flags);
5977 case CMD_THREAD_GET_STATE:
5978 buffer_add_int (buf, thread->state);
5980 case CMD_THREAD_GET_INFO:
5981 buffer_add_byte (buf, thread->threadpool_thread);
5984 return ERR_NOT_IMPLEMENTED;
5991 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5995 MonoThread *thread_obj;
5996 MonoInternalThread *thread;
5998 DebuggerTlsData *tls;
6000 MonoDebugMethodJitInfo *jit;
6001 MonoDebugVarInfo *var;
6002 MonoMethodSignature *sig;
6004 MonoMethodHeader *header;
6006 objid = decode_objid (p, &p, end);
6007 err = get_object (objid, (MonoObject**)&thread_obj);
6011 thread = THREAD_TO_INTERNAL (thread_obj);
6013 id = decode_id (p, &p, end);
6015 mono_loader_lock ();
6016 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6017 mono_loader_unlock ();
6020 for (i = 0; i < tls->frame_count; ++i) {
6021 if (tls->frames [i]->id == id)
6024 if (i == tls->frame_count)
6025 return ERR_INVALID_FRAMEID;
6027 frame = tls->frames [i];
6029 if (!frame->has_ctx)
6031 return ERR_INVALID_FRAMEID;
6034 frame->jit = mono_debug_find_method (frame->method, frame->domain);
6035 g_assert (frame->jit);
6039 sig = mono_method_signature (frame->method);
6042 case CMD_STACK_FRAME_GET_VALUES: {
6043 len = decode_int (p, &p, end);
6044 header = mono_method_get_header (frame->method);
6046 for (i = 0; i < len; ++i) {
6047 pos = decode_int (p, &p, end);
6052 g_assert (pos >= 0 && pos < jit->num_params);
6054 var = &jit->params [pos];
6056 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
6058 g_assert (pos >= 0 && pos < jit->num_locals);
6060 var = &jit->locals [pos];
6062 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
6065 mono_metadata_free_mh (header);
6068 case CMD_STACK_FRAME_GET_THIS: {
6069 if (frame->method->klass->valuetype) {
6070 if (!sig->hasthis) {
6071 MonoObject *p = NULL;
6072 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
6074 add_var (buf, &frame->method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6077 if (!sig->hasthis) {
6078 MonoObject *p = NULL;
6079 buffer_add_value (buf, &frame->method->klass->byval_arg, &p, frame->domain);
6081 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6086 case CMD_STACK_FRAME_SET_VALUES: {
6089 MonoDebugVarInfo *var;
6091 len = decode_int (p, &p, end);
6092 header = mono_method_get_header (frame->method);
6094 for (i = 0; i < len; ++i) {
6095 pos = decode_int (p, &p, end);
6100 g_assert (pos >= 0 && pos < jit->num_params);
6102 t = sig->params [pos];
6103 var = &jit->params [pos];
6105 g_assert (pos >= 0 && pos < jit->num_locals);
6107 t = header->locals [pos];
6108 var = &jit->locals [pos];
6111 if (MONO_TYPE_IS_REFERENCE (t))
6112 val_buf = g_alloca (sizeof (MonoObject*));
6114 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
6115 err = decode_value (t, frame->domain, val_buf, p, &p, end);
6119 set_var (t, var, &frame->ctx, frame->domain, val_buf);
6121 mono_metadata_free_mh (header);
6125 return ERR_NOT_IMPLEMENTED;
6132 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6135 int objid, err, index, len, i, esize;
6138 objid = decode_objid (p, &p, end);
6139 err = get_object (objid, (MonoObject**)&arr);
6144 case CMD_ARRAY_REF_GET_LENGTH:
6145 buffer_add_int (buf, arr->obj.vtable->klass->rank);
6147 buffer_add_int (buf, arr->max_length);
6148 buffer_add_int (buf, 0);
6150 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
6151 buffer_add_int (buf, arr->bounds [i].length);
6152 buffer_add_int (buf, arr->bounds [i].lower_bound);
6156 case CMD_ARRAY_REF_GET_VALUES:
6157 index = decode_int (p, &p, end);
6158 len = decode_int (p, &p, end);
6160 g_assert (index >= 0 && len >= 0);
6161 // Reordered to avoid integer overflow
6162 g_assert (!(index > arr->max_length - len));
6164 esize = mono_array_element_size (arr->obj.vtable->klass);
6165 for (i = index; i < index + len; ++i) {
6166 elem = (gpointer*)((char*)arr->vector + (i * esize));
6167 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
6170 case CMD_ARRAY_REF_SET_VALUES:
6171 index = decode_int (p, &p, end);
6172 len = decode_int (p, &p, end);
6174 g_assert (index >= 0 && len >= 0);
6175 // Reordered to avoid integer overflow
6176 g_assert (!(index > arr->max_length - len));
6178 esize = mono_array_element_size (arr->obj.vtable->klass);
6179 for (i = index; i < index + len; ++i) {
6180 elem = (gpointer*)((char*)arr->vector + (i * esize));
6182 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
6186 return ERR_NOT_IMPLEMENTED;
6193 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6199 objid = decode_objid (p, &p, end);
6200 err = get_object (objid, (MonoObject**)&str);
6205 case CMD_STRING_REF_GET_VALUE:
6206 s = mono_string_to_utf8 (str);
6207 buffer_add_string (buf, s);
6211 return ERR_NOT_IMPLEMENTED;
6218 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6227 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
6228 objid = decode_objid (p, &p, end);
6229 err = get_object (objid, &obj);
6231 buffer_add_int (buf, 1);
6233 buffer_add_int (buf, 0);
6237 objid = decode_objid (p, &p, end);
6238 err = get_object (objid, &obj);
6243 case CMD_OBJECT_REF_GET_TYPE:
6244 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
6246 case CMD_OBJECT_REF_GET_VALUES:
6247 len = decode_int (p, &p, end);
6249 for (i = 0; i < len; ++i) {
6250 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
6254 /* Check that the field belongs to the object */
6256 for (k = obj->vtable->klass; k; k = k->parent) {
6257 if (k == f->parent) {
6263 return ERR_INVALID_FIELDID;
6265 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6269 if (mono_class_field_is_special_static (f))
6270 return ERR_INVALID_FIELDID;
6272 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6273 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6274 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6275 mono_field_static_get_value (vtable, f, val);
6276 buffer_add_value (buf, f->type, val, obj->vtable->domain);
6279 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
6283 case CMD_OBJECT_REF_SET_VALUES:
6284 len = decode_int (p, &p, end);
6286 for (i = 0; i < len; ++i) {
6287 f = decode_fieldid (p, &p, end, NULL, &err);
6291 /* Check that the field belongs to the object */
6293 for (k = obj->vtable->klass; k; k = k->parent) {
6294 if (k == f->parent) {
6300 return ERR_INVALID_FIELDID;
6302 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
6306 if (mono_class_field_is_special_static (f))
6307 return ERR_INVALID_FIELDID;
6309 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
6310 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
6312 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6313 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
6318 mono_field_static_set_value (vtable, f, val);
6321 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
6327 case CMD_OBJECT_REF_GET_ADDRESS:
6328 buffer_add_long (buf, (gssize)obj);
6330 case CMD_OBJECT_REF_GET_DOMAIN:
6331 buffer_add_domainid (buf, obj->vtable->domain);
6334 return ERR_NOT_IMPLEMENTED;
6341 command_set_to_string (CommandSet command_set)
6343 switch (command_set) {
6346 case CMD_SET_OBJECT_REF:
6347 return "OBJECT_REF";
6348 case CMD_SET_STRING_REF:
6349 return "STRING_REF";
6350 case CMD_SET_THREAD:
6352 case CMD_SET_ARRAY_REF:
6354 case CMD_SET_EVENT_REQUEST:
6355 return "EVENT_REQUEST";
6356 case CMD_SET_STACK_FRAME:
6357 return "STACK_FRAME";
6358 case CMD_SET_APPDOMAIN:
6360 case CMD_SET_ASSEMBLY:
6362 case CMD_SET_METHOD:
6366 case CMD_SET_MODULE:
6378 * This thread handles communication with the debugger client using a JDWP
6381 static guint32 WINAPI
6382 debugger_thread (void *arg)
6384 int res, len, id, flags, command_set, command;
6385 guint8 header [HEADER_LENGTH];
6386 guint8 *data, *p, *end;
6391 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
6393 debugger_thread_id = GetCurrentThreadId ();
6395 mono_jit_thread_attach (mono_get_root_domain ());
6397 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
6399 mono_set_is_debugger_attached (TRUE);
6402 res = recv_length (conn_fd, header, HEADER_LENGTH, 0);
6404 /* This will break if the socket is closed during shutdown too */
6405 if (res != HEADER_LENGTH)
6409 end = header + HEADER_LENGTH;
6411 len = decode_int (p, &p, end);
6412 id = decode_int (p, &p, end);
6413 flags = decode_byte (p, &p, end);
6414 command_set = decode_byte (p, &p, end);
6415 command = decode_byte (p, &p, end);
6417 g_assert (flags == 0);
6419 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%d), id=%d.\n", command_set_to_string (command_set), command, id));
6421 data = g_malloc (len - HEADER_LENGTH);
6422 if (len - HEADER_LENGTH > 0)
6424 res = recv_length (conn_fd, data, len - HEADER_LENGTH, 0);
6425 if (res != len - HEADER_LENGTH)
6430 end = data + (len - HEADER_LENGTH);
6432 buffer_init (&buf, 128);
6437 /* Process the request */
6438 switch (command_set) {
6440 err = vm_commands (command, id, p, end, &buf);
6441 if (!err && command == CMD_VM_INVOKE_METHOD)
6442 /* Sent after the invoke is complete */
6445 case CMD_SET_EVENT_REQUEST:
6446 err = event_commands (command, p, end, &buf);
6448 case CMD_SET_APPDOMAIN:
6449 err = domain_commands (command, p, end, &buf);
6451 case CMD_SET_ASSEMBLY:
6452 err = assembly_commands (command, p, end, &buf);
6454 case CMD_SET_MODULE:
6455 err = module_commands (command, p, end, &buf);
6458 err = type_commands (command, p, end, &buf);
6460 case CMD_SET_METHOD:
6461 err = method_commands (command, p, end, &buf);
6463 case CMD_SET_THREAD:
6464 err = thread_commands (command, p, end, &buf);
6466 case CMD_SET_STACK_FRAME:
6467 err = frame_commands (command, p, end, &buf);
6469 case CMD_SET_ARRAY_REF:
6470 err = array_commands (command, p, end, &buf);
6472 case CMD_SET_STRING_REF:
6473 err = string_commands (command, p, end, &buf);
6475 case CMD_SET_OBJECT_REF:
6476 err = object_commands (command, p, end, &buf);
6479 err = ERR_NOT_IMPLEMENTED;
6483 send_reply_packet (id, err, &buf);
6488 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
6492 mono_set_is_debugger_attached (FALSE);
6494 mono_mutex_lock (&debugger_thread_exited_mutex);
6495 debugger_thread_exited = TRUE;
6496 mono_cond_signal (&debugger_thread_exited_cond);
6497 mono_mutex_unlock (&debugger_thread_exited_mutex);
6499 DEBUG (1, printf ("[dbg] Debugger thread exited.\n"));
6504 #else /* DISABLE_DEBUGGER_AGENT */
6507 mono_debugger_agent_parse_options (char *options)
6509 g_error ("This runtime is configure with the debugger agent disabled.");
6513 mono_debugger_agent_init (void)
6518 mono_debugger_agent_breakpoint_hit (void *sigctx)
6523 mono_debugger_agent_single_step_event (void *sigctx)
6528 mono_debugger_agent_free_domain_info (MonoDomain *domain)
6533 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
6539 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
6540 MonoContext *catch_ctx)