2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
14 #ifdef HAVE_SYS_TYPES_H
15 #include <sys/types.h>
17 #ifdef HAVE_SYS_SELECT_H
18 #include <sys/select.h>
20 #ifdef HAVE_SYS_SOCKET_H
21 #include <sys/socket.h>
23 #ifdef HAVE_NETINET_TCP_H
24 #include <netinet/tcp.h>
26 #ifdef HAVE_NETINET_IN_H
27 #include <netinet/in.h>
42 #ifdef HAVE_UCONTEXT_H
52 /* cygwin's headers do not seem to define these */
53 void WSAAPI freeaddrinfo (struct addrinfo*);
54 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
56 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
61 #ifdef PLATFORM_ANDROID
63 #include <linux/tcp.h>
64 #include <sys/endian.h>
67 #include <mono/metadata/mono-debug.h>
68 #include <mono/metadata/mono-debug-debugger.h>
69 #include <mono/metadata/debug-mono-symfile.h>
70 #include <mono/metadata/gc-internal.h>
71 #include <mono/metadata/threads-types.h>
72 #include <mono/metadata/socket-io.h>
73 #include <mono/metadata/assembly.h>
74 #include <mono/utils/mono-semaphore.h>
75 #include <mono/utils/mono-error-internals.h>
76 #include <mono/utils/mono-stack-unwinding.h>
77 #include "debugger-agent.h"
80 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
81 #define DISABLE_DEBUGGER_AGENT 1
84 #ifdef DISABLE_SOFT_DEBUG
85 #define DISABLE_DEBUGGER_AGENT 1
88 #ifndef DISABLE_DEBUGGER_AGENT
90 #include <mono/io-layer/mono-mutex.h>
92 /* Definitions to make backporting to 2.6 easier */
93 //#define MonoInternalThread MonoThread
94 //#define mono_thread_internal_current mono_thread_current
95 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
116 guint32 il_offset, native_offset;
120 * If method is gshared, this is the actual instance, otherwise this is equal to
123 MonoMethod *actual_method;
125 MonoDebugMethodJitInfo *jit;
128 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
129 * the frame can become invalid.
134 typedef struct _InvokeData InvokeData;
142 /* This is the context which needs to be restored after the invoke */
146 * If this is set, invoke this method with the arguments given by ARGS.
150 guint32 suspend_count;
152 InvokeData *last_invoke;
156 MonoThreadUnwindState context;
158 gpointer resume_event;
159 /* This is computed on demand when it is requested using the wire protocol */
160 /* It is freed up when the thread is resumed */
164 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
167 gboolean frames_up_to_date;
169 * Points to data about a pending invoke which needs to be executed after the thread
172 InvokeData *pending_invoke;
174 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
179 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
180 * within a finite amount of time.
184 * Set to TRUE if this thread is suspended in suspend_current ().
186 gboolean really_suspended;
187 /* Used to pass the context to the breakpoint/single step handler */
188 MonoContext handler_ctx;
189 /* Whenever thread_stop () was called for this thread */
192 /* Number of thread interruptions not yet processed */
193 gint32 interrupt_count;
195 /* Whenever to disable breakpoints (used during invokes) */
196 gboolean disable_breakpoints;
199 * Number of times this thread has been resumed using resume_thread ().
201 guint32 resume_count;
203 MonoInternalThread *thread;
206 * Information about the frame which transitioned to native code for running
209 StackFrameInfo async_last_frame;
212 * The context where the stack walk can be started for running threads.
214 MonoThreadUnwindState async_state;
217 * The context used for filter clauses
219 MonoThreadUnwindState filter_state;
222 * The callee address of the last mono_runtime_invoke call
224 gpointer invoke_addr;
226 gboolean abort_requested;
229 * The current mono_runtime_invoke invocation.
234 * The context where single stepping should resume while the thread is suspended because
235 * of an EXCEPTION event.
237 MonoContext catch_ctx;
239 gboolean has_catch_ctx;
243 * Wire Protocol definitions
246 #define HEADER_LENGTH 11
248 #define MAJOR_VERSION 2
249 #define MINOR_VERSION 3
253 CMD_SET_OBJECT_REF = 9,
254 CMD_SET_STRING_REF = 10,
256 CMD_SET_ARRAY_REF = 13,
257 CMD_SET_EVENT_REQUEST = 15,
258 CMD_SET_STACK_FRAME = 16,
259 CMD_SET_APPDOMAIN = 20,
260 CMD_SET_ASSEMBLY = 21,
268 EVENT_KIND_VM_START = 0,
269 EVENT_KIND_VM_DEATH = 1,
270 EVENT_KIND_THREAD_START = 2,
271 EVENT_KIND_THREAD_DEATH = 3,
272 EVENT_KIND_APPDOMAIN_CREATE = 4,
273 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
274 EVENT_KIND_METHOD_ENTRY = 6,
275 EVENT_KIND_METHOD_EXIT = 7,
276 EVENT_KIND_ASSEMBLY_LOAD = 8,
277 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
278 EVENT_KIND_BREAKPOINT = 10,
279 EVENT_KIND_STEP = 11,
280 EVENT_KIND_TYPE_LOAD = 12,
281 EVENT_KIND_EXCEPTION = 13
285 SUSPEND_POLICY_NONE = 0,
286 SUSPEND_POLICY_EVENT_THREAD = 1,
287 SUSPEND_POLICY_ALL = 2
292 ERR_INVALID_OBJECT = 20,
293 ERR_INVALID_FIELDID = 25,
294 ERR_INVALID_FRAMEID = 30,
295 ERR_NOT_IMPLEMENTED = 100,
296 ERR_NOT_SUSPENDED = 101,
297 ERR_INVALID_ARGUMENT = 102,
299 ERR_NO_INVOCATION = 104,
300 ERR_ABSENT_INFORMATION = 105,
301 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106
306 MOD_KIND_THREAD_ONLY = 3,
307 MOD_KIND_LOCATION_ONLY = 7,
308 MOD_KIND_EXCEPTION_ONLY = 8,
310 MOD_KIND_ASSEMBLY_ONLY = 11
325 TOKEN_TYPE_STRING = 0,
327 TOKEN_TYPE_FIELD = 2,
328 TOKEN_TYPE_METHOD = 3,
329 TOKEN_TYPE_UNKNOWN = 4
333 VALUE_TYPE_ID_NULL = 0xf0,
334 VALUE_TYPE_ID_TYPE = 0xf1
338 FRAME_FLAG_DEBUGGER_INVOKE = 1
342 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
343 INVOKE_FLAG_SINGLE_THREADED = 2
348 CMD_VM_ALL_THREADS = 2,
353 CMD_VM_INVOKE_METHOD = 7,
354 CMD_VM_SET_PROTOCOL_VERSION = 8,
355 CMD_VM_ABORT_INVOKE = 9
359 CMD_THREAD_GET_FRAME_INFO = 1,
360 CMD_THREAD_GET_NAME = 2,
361 CMD_THREAD_GET_STATE = 3,
362 CMD_THREAD_GET_INFO = 4,
363 CMD_THREAD_GET_ID = 5,
364 CMD_THREAD_GET_TID = 6
368 CMD_EVENT_REQUEST_SET = 1,
369 CMD_EVENT_REQUEST_CLEAR = 2,
370 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
378 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
379 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
380 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
381 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
382 CMD_APPDOMAIN_CREATE_STRING = 5,
383 CMD_APPDOMAIN_GET_CORLIB = 6,
384 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
388 CMD_ASSEMBLY_GET_LOCATION = 1,
389 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
390 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
391 CMD_ASSEMBLY_GET_OBJECT = 4,
392 CMD_ASSEMBLY_GET_TYPE = 5,
393 CMD_ASSEMBLY_GET_NAME = 6
397 CMD_MODULE_GET_INFO = 1,
401 CMD_METHOD_GET_NAME = 1,
402 CMD_METHOD_GET_DECLARING_TYPE = 2,
403 CMD_METHOD_GET_DEBUG_INFO = 3,
404 CMD_METHOD_GET_PARAM_INFO = 4,
405 CMD_METHOD_GET_LOCALS_INFO = 5,
406 CMD_METHOD_GET_INFO = 6,
407 CMD_METHOD_GET_BODY = 7,
408 CMD_METHOD_RESOLVE_TOKEN = 8,
412 CMD_TYPE_GET_INFO = 1,
413 CMD_TYPE_GET_METHODS = 2,
414 CMD_TYPE_GET_FIELDS = 3,
415 CMD_TYPE_GET_VALUES = 4,
416 CMD_TYPE_GET_OBJECT = 5,
417 CMD_TYPE_GET_SOURCE_FILES = 6,
418 CMD_TYPE_SET_VALUES = 7,
419 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
420 CMD_TYPE_GET_PROPERTIES = 9,
421 CMD_TYPE_GET_CATTRS = 10,
422 CMD_TYPE_GET_FIELD_CATTRS = 11,
423 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
424 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
425 CMD_TYPE_GET_VALUES_2 = 14
429 CMD_STACK_FRAME_GET_VALUES = 1,
430 CMD_STACK_FRAME_GET_THIS = 2,
431 CMD_STACK_FRAME_SET_VALUES = 3
435 CMD_ARRAY_REF_GET_LENGTH = 1,
436 CMD_ARRAY_REF_GET_VALUES = 2,
437 CMD_ARRAY_REF_SET_VALUES = 3,
441 CMD_STRING_REF_GET_VALUE = 1,
445 CMD_OBJECT_REF_GET_TYPE = 1,
446 CMD_OBJECT_REF_GET_VALUES = 2,
447 CMD_OBJECT_REF_IS_COLLECTED = 3,
448 CMD_OBJECT_REF_GET_ADDRESS = 4,
449 CMD_OBJECT_REF_GET_DOMAIN = 5,
450 CMD_OBJECT_REF_SET_VALUES = 6
456 int count; /* For kind == MOD_KIND_COUNT */
457 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
458 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
459 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
461 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
470 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
474 * Describes a single step request.
478 MonoInternalThread *thread;
483 MonoMethod *last_method;
485 /* Whenever single stepping is performed using start/stop_single_stepping () */
487 /* The list of breakpoints used to implement step-over */
492 * Contains additional information for an event
495 /* For EVENT_KIND_EXCEPTION */
497 MonoContext catch_ctx;
501 /* Dummy structure used for the profiler callbacks */
506 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
512 static AgentConfig agent_config;
515 * Whenever the agent is fully initialized.
516 * When using the onuncaught or onthrow options, only some parts of the agent are
517 * initialized on startup, and the full initialization which includes connection
518 * establishment and the startup of the agent thread is only done in response to
521 static gint32 inited;
524 static int listen_fd;
526 static int packet_id = 0;
528 static int objref_id = 0;
530 static int event_request_id = 0;
532 static int frame_id = 0;
534 static GPtrArray *event_requests;
536 static guint32 debugger_tls_id;
538 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
540 /* Maps MonoInternalThread -> DebuggerTlsData */
541 static MonoGHashTable *thread_to_tls;
543 /* Maps tid -> MonoInternalThread */
544 static MonoGHashTable *tid_to_thread;
546 /* Maps tid -> MonoThread (not MonoInternalThread) */
547 static MonoGHashTable *tid_to_thread_obj;
549 static gsize debugger_thread_id;
551 static HANDLE debugger_thread_handle;
553 static int log_level;
555 static gboolean embedding;
557 static FILE *log_file;
559 /* Assemblies whose assembly load event has no been sent yet */
560 static GPtrArray *pending_assembly_loads;
562 /* Whenever the debugger thread has exited */
563 static gboolean debugger_thread_exited;
565 /* Cond variable used to wait for debugger_thread_exited becoming true */
566 static mono_cond_t debugger_thread_exited_cond;
568 /* Mutex for the cond var above */
569 static mono_mutex_t debugger_thread_exited_mutex;
571 static DebuggerProfiler debugger_profiler;
573 /* The single step request instance */
574 static SingleStepReq *ss_req = NULL;
575 static gpointer ss_invoke_addr = NULL;
577 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
578 /* Number of single stepping operations in progress */
582 /* The protocol version of the client */
583 static int major_version, minor_version;
585 /* Whenever the variables above are set by the client */
586 static gboolean protocol_version_set;
588 /* A hash table containing all active domains */
589 static GHashTable *domains;
591 static void transport_connect (const char *host, int port);
593 static guint32 WINAPI debugger_thread (void *arg);
595 static void runtime_initialized (MonoProfiler *prof);
597 static void runtime_shutdown (MonoProfiler *prof);
599 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
601 static void thread_end (MonoProfiler *prof, uintptr_t tid);
603 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
605 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
607 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
609 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
611 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
613 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
615 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
617 static void emit_assembly_load (gpointer assembly, gpointer user_data);
619 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
621 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
623 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
625 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
627 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
629 static void start_single_stepping (void);
631 static void stop_single_stepping (void);
633 static void suspend_current (void);
635 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
637 static void clear_types_for_assembly (MonoAssembly *assembly);
639 static void clear_breakpoints_for_domain (MonoDomain *domain);
641 static void process_profiler_event (EventKind event, gpointer arg);
643 /* Submodule init/cleanup */
644 static void breakpoints_init (void);
645 static void breakpoints_cleanup (void);
647 static void objrefs_init (void);
648 static void objrefs_cleanup (void);
650 static void ids_init (void);
651 static void ids_cleanup (void);
653 static void suspend_init (void);
655 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
656 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
657 static void ss_destroy (SingleStepReq *req);
659 static void start_debugger_thread (void);
660 static void stop_debugger_thread (void);
662 static void finish_agent_init (gboolean on_startup);
665 parse_address (char *address, char **host, int *port)
667 char *pos = strchr (address, ':');
669 if (pos == NULL || pos == address)
672 *host = g_malloc (pos - address + 1);
673 strncpy (*host, address, pos - address);
674 (*host) [pos - address] = '\0';
676 *port = atoi (pos + 1);
684 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
685 fprintf (stderr, "Available options:\n");
686 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
687 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
688 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
689 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
690 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
691 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
692 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
693 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
697 parse_flag (const char *option, char *flag)
699 if (!strcmp (flag, "y"))
701 else if (!strcmp (flag, "n"))
704 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
711 mono_debugger_agent_parse_options (char *options)
717 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
718 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
722 agent_config.enabled = TRUE;
723 agent_config.suspend = TRUE;
724 agent_config.server = FALSE;
725 agent_config.defer = FALSE;
726 agent_config.address = NULL;
728 args = g_strsplit (options, ",", -1);
729 for (ptr = args; ptr && *ptr; ptr ++) {
732 if (strncmp (arg, "transport=", 10) == 0) {
733 agent_config.transport = g_strdup (arg + 10);
734 } else if (strncmp (arg, "address=", 8) == 0) {
735 agent_config.address = g_strdup (arg + 8);
736 } else if (strncmp (arg, "loglevel=", 9) == 0) {
737 agent_config.log_level = atoi (arg + 9);
738 } else if (strncmp (arg, "logfile=", 8) == 0) {
739 agent_config.log_file = g_strdup (arg + 8);
740 } else if (strncmp (arg, "suspend=", 8) == 0) {
741 agent_config.suspend = parse_flag ("suspend", arg + 8);
742 } else if (strncmp (arg, "server=", 7) == 0) {
743 agent_config.server = parse_flag ("server", arg + 7);
744 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
745 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
746 } else if (strncmp (arg, "onthrow=", 8) == 0) {
747 /* We support multiple onthrow= options */
748 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
749 } else if (strncmp (arg, "onthrow", 7) == 0) {
750 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
751 } else if (strncmp (arg, "help", 4) == 0) {
754 } else if (strncmp (arg, "timeout=", 8) == 0) {
755 agent_config.timeout = atoi (arg + 8);
756 } else if (strncmp (arg, "launch=", 7) == 0) {
757 agent_config.launch = g_strdup (arg + 7);
758 } else if (strncmp (arg, "embedding=", 10) == 0) {
759 agent_config.embedding = atoi (arg + 10) == 1;
766 if (agent_config.server && !agent_config.suspend) {
767 /* Waiting for deferred attachment */
768 agent_config.defer = TRUE;
769 if (agent_config.address == NULL) {
770 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
774 if (agent_config.transport == NULL) {
775 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
778 if (strcmp (agent_config.transport, "dt_socket") != 0) {
779 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
783 if (agent_config.address == NULL && !agent_config.server) {
784 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
788 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
789 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
795 mono_debugger_agent_init (void)
797 if (!agent_config.enabled)
800 /* Need to know whenever a thread has acquired the loader mutex */
801 mono_loader_lock_track_ownership (TRUE);
803 event_requests = g_ptr_array_new ();
805 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
806 mono_cond_init (&debugger_thread_exited_cond, NULL);
808 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
809 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
810 mono_profiler_install_runtime_initialized (runtime_initialized);
811 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
812 mono_profiler_install_thread (thread_startup, thread_end);
813 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
814 mono_profiler_install_jit_end (jit_end);
815 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
817 debugger_tls_id = TlsAlloc ();
819 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
820 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
822 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
823 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
825 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
826 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
828 pending_assembly_loads = g_ptr_array_new ();
829 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
831 log_level = agent_config.log_level;
833 embedding = agent_config.embedding;
836 if (agent_config.log_file) {
837 log_file = fopen (agent_config.log_file, "w+");
839 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
851 mini_get_debug_options ()->gen_seq_points = TRUE;
853 * This is needed because currently we don't handle liveness info.
855 mini_get_debug_options ()->mdb_optimizations = TRUE;
857 /* This is needed because we can't set local variables in registers yet */
858 mono_disable_optimizations (MONO_OPT_LINEARS);
860 if (!agent_config.onuncaught && !agent_config.onthrow)
861 finish_agent_init (TRUE);
867 * Finish the initialization of the agent. This involves connecting the transport
868 * and starting the agent thread. This is either done at startup, or
869 * in response to some event like an unhandled exception.
872 finish_agent_init (gboolean on_startup)
878 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
881 if (agent_config.launch) {
884 // FIXME: Generated address
885 // FIXME: Races with transport_connect ()
887 argv [0] = agent_config.launch;
888 argv [1] = agent_config.transport;
889 argv [2] = agent_config.address;
892 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
894 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
899 if (agent_config.address) {
900 res = parse_address (agent_config.address, &host, &port);
907 transport_connect (host, port);
910 /* Do some which is usually done after sending the VMStart () event */
911 vm_start_event_sent = TRUE;
912 start_debugger_thread ();
917 mono_debugger_agent_cleanup (void)
922 stop_debugger_thread ();
924 breakpoints_cleanup ();
928 mono_mutex_destroy (&debugger_thread_exited_mutex);
929 mono_cond_destroy (&debugger_thread_exited_cond);
935 * recv() + handle incomplete reads and EINTR
938 recv_length (int fd, void *buf, int len, int flags)
944 res = recv (fd, (char *) buf + total, len - total, flags);
947 } while ((res > 0 && total < len) || (res == -1 && errno == EINTR));
952 #define HAVE_GETADDRINFO 1
956 transport_accept (int socket_fd)
958 conn_fd = accept (socket_fd, NULL, NULL);
960 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
962 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
969 transport_handshake (void)
971 char handshake_msg [128];
975 /* Write handshake message */
976 sprintf (handshake_msg, "DWP-Handshake");
978 res = send (conn_fd, handshake_msg, strlen (handshake_msg), 0);
979 } while (res == -1 && errno == EINTR);
980 g_assert (res != -1);
983 res = recv_length (conn_fd, buf, strlen (handshake_msg), 0);
984 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
985 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
990 * To support older clients, the client sends its protocol version after connecting
991 * using a command. Until that is received, default to our protocol version.
993 major_version = MAJOR_VERSION;
994 minor_version = MINOR_VERSION;
995 protocol_version_set = FALSE;
998 * Set TCP_NODELAY on the socket so the client receives events/command
999 * results immediately.
1003 int result = setsockopt (conn_fd,
1008 g_assert (result >= 0);
1015 * transport_connect:
1017 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1020 transport_connect (const char *host, int port)
1022 #ifdef HAVE_GETADDRINFO
1023 struct addrinfo hints;
1024 struct addrinfo *result, *rp;
1026 struct hostent *result;
1029 char port_string [128];
1035 sprintf (port_string, "%d", port);
1037 mono_network_init ();
1039 /* Obtain address(es) matching host/port */
1040 #ifdef HAVE_GETADDRINFO
1041 memset (&hints, 0, sizeof (struct addrinfo));
1042 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1043 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1045 hints.ai_protocol = 0; /* Any protocol */
1047 s = getaddrinfo (host, port_string, &hints, &result);
1049 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1053 /* The PS3 doesn't even have _r or hstrerror () */
1054 result = gethostbyname (host);
1056 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1061 if (agent_config.server) {
1062 #ifdef HAVE_GETADDRINFO
1063 /* Wait for a connection */
1065 struct sockaddr_in addr;
1068 /* No address, generate one */
1069 sfd = socket (AF_INET, SOCK_STREAM, 0);
1072 /* This will bind the socket to a random port */
1073 res = listen (sfd, 16);
1075 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
1080 addrlen = sizeof (addr);
1081 memset (&addr, 0, sizeof (addr));
1082 res = getsockname (sfd, &addr, &addrlen);
1083 g_assert (res == 0);
1086 port = ntohs (addr.sin_port);
1088 /* Emit the address to stdout */
1089 /* FIXME: Should print another interface, not localhost */
1090 printf ("%s:%d\n", host, port);
1092 /* Listen on the provided address */
1093 for (rp = result; rp != NULL; rp = rp->ai_next) {
1094 sfd = socket (rp->ai_family, rp->ai_socktype,
1099 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1103 res = listen (sfd, 16);
1112 * this function is not present on win2000 which we still support, and the
1113 * workaround described here:
1114 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1115 * only works with MSVC.
1117 #ifdef HAVE_GETADDRINFO
1118 freeaddrinfo (result);
1123 if (agent_config.defer)
1126 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1128 if (agent_config.timeout) {
1133 tv.tv_usec = agent_config.timeout * 1000;
1135 FD_SET (sfd, &readfds);
1136 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1138 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1143 conn_fd = transport_accept (sfd);
1147 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1150 #endif /* HAVE_GETADDRINFO */
1152 /* Connect to the specified address */
1153 #ifdef HAVE_GETADDRINFO
1154 /* FIXME: Respect the timeout */
1155 for (rp = result; rp != NULL; rp = rp->ai_next) {
1156 sfd = socket (rp->ai_family, rp->ai_socktype,
1161 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1162 break; /* Success */
1168 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1172 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1174 g_assert_not_reached ();
1175 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1177 g_assert_not_reached ();
1183 /* See the comment above */
1184 #ifdef HAVE_GETADDRINFO
1185 freeaddrinfo (result);
1190 disconnected = !transport_handshake ();
1196 transport_send (guint8 *data, int len)
1201 res = send (conn_fd, data, len, 0);
1202 } while (res == -1 && errno == EINTR);
1210 stop_debugger_thread (void)
1215 /* This will interrupt the agent thread */
1216 /* Close the read part only so it can still send back replies */
1217 /* Also shut down the connection listener so that we can exit normally */
1219 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1220 shutdown (conn_fd, SD_BOTH);
1221 shutdown (listen_fd, SD_BOTH);
1222 closesocket (listen_fd);
1224 shutdown (conn_fd, SHUT_RD);
1225 shutdown (listen_fd, SHUT_RDWR);
1230 * Wait for the thread to exit.
1232 * If we continue with the shutdown without waiting for it, then the client might
1233 * not receive an answer to its last command like a resume.
1234 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1237 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1238 if (GetCurrentThreadId () != debugger_thread_id) {
1240 mono_mutex_lock (&debugger_thread_exited_mutex);
1241 if (!debugger_thread_exited) {
1243 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1244 mono_mutex_unlock (&debugger_thread_exited_mutex);
1246 mono_mutex_lock (&debugger_thread_exited_mutex);
1249 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1252 mono_mutex_unlock (&debugger_thread_exited_mutex);
1253 } while (!debugger_thread_exited);
1257 shutdown (conn_fd, SD_BOTH);
1259 shutdown (conn_fd, SHUT_RDWR);
1264 start_debugger_thread (void)
1268 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1269 g_assert (debugger_thread_handle);
1273 * Functions to decode protocol data
1277 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1280 g_assert (*endbuf <= limit);
1285 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1288 g_assert (*endbuf <= limit);
1290 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1293 static inline gint64
1294 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1296 guint32 high = decode_int (buf, &buf, limit);
1297 guint32 low = decode_int (buf, &buf, limit);
1301 return ((((guint64)high) << 32) | ((guint64)low));
1305 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1307 return decode_int (buf, endbuf, limit);
1311 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1313 int len = decode_int (buf, &buf, limit);
1316 s = g_malloc (len + 1);
1319 memcpy (s, buf, len);
1328 * Functions to encode protocol data
1332 guint8 *buf, *p, *end;
1336 buffer_init (Buffer *buf, int size)
1338 buf->buf = g_malloc (size);
1340 buf->end = buf->buf + size;
1344 buffer_make_room (Buffer *buf, int size)
1346 if (buf->end - buf->p < size) {
1347 int new_size = buf->end - buf->buf + size + 32;
1348 guint8 *p = g_realloc (buf->buf, new_size);
1349 size = buf->p - buf->buf;
1352 buf->end = buf->buf + new_size;
1357 buffer_add_byte (Buffer *buf, guint8 val)
1359 buffer_make_room (buf, 1);
1365 buffer_add_int (Buffer *buf, guint32 val)
1367 buffer_make_room (buf, 4);
1368 buf->p [0] = (val >> 24) & 0xff;
1369 buf->p [1] = (val >> 16) & 0xff;
1370 buf->p [2] = (val >> 8) & 0xff;
1371 buf->p [3] = (val >> 0) & 0xff;
1376 buffer_add_long (Buffer *buf, guint64 l)
1378 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1379 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1383 buffer_add_id (Buffer *buf, int id)
1385 buffer_add_int (buf, (guint64)id);
1389 buffer_add_data (Buffer *buf, guint8 *data, int len)
1391 buffer_make_room (buf, len);
1392 memcpy (buf->p, data, len);
1397 buffer_add_string (Buffer *buf, const char *str)
1402 buffer_add_int (buf, 0);
1405 buffer_add_int (buf, len);
1406 buffer_add_data (buf, (guint8*)str, len);
1411 buffer_free (Buffer *buf)
1417 send_packet (int command_set, int command, Buffer *data)
1423 id = InterlockedIncrement (&packet_id);
1425 len = data->p - data->buf + 11;
1426 buffer_init (&buf, len);
1427 buffer_add_int (&buf, len);
1428 buffer_add_int (&buf, id);
1429 buffer_add_byte (&buf, 0); /* flags */
1430 buffer_add_byte (&buf, command_set);
1431 buffer_add_byte (&buf, command);
1432 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1434 res = transport_send (buf.buf, len);
1442 send_reply_packet (int id, int error, Buffer *data)
1448 len = data->p - data->buf + 11;
1449 buffer_init (&buf, len);
1450 buffer_add_int (&buf, len);
1451 buffer_add_int (&buf, id);
1452 buffer_add_byte (&buf, 0x80); /* flags */
1453 buffer_add_byte (&buf, (error >> 8) & 0xff);
1454 buffer_add_byte (&buf, error);
1455 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1457 res = transport_send (buf.buf, len);
1469 * Represents an object accessible by the debugger client.
1472 /* Unique id used in the wire protocol to refer to objects */
1475 * A weakref gc handle pointing to the object. The gc handle is used to
1476 * detect if the object was garbage collected.
1481 /* Maps objid -> ObjRef */
1482 static GHashTable *objrefs;
1485 free_objref (gpointer value)
1489 mono_gchandle_free (o->handle);
1497 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1501 objrefs_cleanup (void)
1503 g_hash_table_destroy (objrefs);
1507 static GHashTable *obj_to_objref;
1510 * Return an ObjRef for OBJ.
1513 get_objref (MonoObject *obj)
1516 GSList *reflist = NULL, *l;
1522 mono_loader_lock ();
1525 obj_to_objref = g_hash_table_new (NULL, NULL);
1527 /* FIXME: The tables can grow indefinitely */
1529 if (mono_gc_is_moving ()) {
1531 * Objects can move, so use a hash table mapping hash codes to lists of
1532 * ObjRef structures.
1534 hash = mono_object_hash (obj);
1536 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1537 for (l = reflist; l; l = l->next) {
1539 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1540 mono_loader_unlock ();
1545 /* Use a hash table with masked pointers to internalize object references */
1546 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1547 /* ref might refer to a different object with the same addr which was GCd */
1548 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1549 mono_loader_unlock ();
1554 ref = g_new0 (ObjRef, 1);
1555 ref->id = InterlockedIncrement (&objref_id);
1556 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1558 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1560 if (mono_gc_is_moving ()) {
1561 reflist = g_slist_append (reflist, ref);
1562 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1564 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1567 mono_loader_unlock ();
1573 get_objid (MonoObject *obj)
1575 return get_objref (obj)->id;
1579 * Set OBJ to the object identified by OBJID.
1580 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1584 get_object_allow_null (int objid, MonoObject **obj)
1594 return ERR_INVALID_OBJECT;
1596 mono_loader_lock ();
1598 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1601 *obj = mono_gchandle_get_target (ref->handle);
1602 mono_loader_unlock ();
1604 return ERR_INVALID_OBJECT;
1607 mono_loader_unlock ();
1608 return ERR_INVALID_OBJECT;
1613 get_object (int objid, MonoObject **obj)
1615 int err = get_object_allow_null (objid, obj);
1620 return ERR_INVALID_OBJECT;
1625 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1627 return decode_id (buf, endbuf, limit);
1631 buffer_add_objid (Buffer *buf, MonoObject *o)
1633 buffer_add_id (buf, get_objid (o));
1652 * Represents a runtime structure accessible to the debugger client
1655 /* Unique id used in the wire protocol */
1657 /* Domain of the runtime structure, NULL if the domain was unloaded */
1664 MonoAssembly *assembly;
1665 MonoClassField *field;
1667 MonoProperty *property;
1672 /* Maps runtime structure -> Id */
1673 GHashTable *val_to_id [ID_NUM];
1674 /* Classes whose class load event has been sent */
1675 GHashTable *loaded_classes;
1679 static GPtrArray *ids [ID_NUM];
1686 for (i = 0; i < ID_NUM; ++i)
1687 ids [i] = g_ptr_array_new ();
1695 for (i = 0; i < ID_NUM; ++i) {
1697 for (j = 0; j < ids [i]->len; ++j)
1698 g_free (g_ptr_array_index (ids [i], j));
1699 g_ptr_array_free (ids [i], TRUE);
1706 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1708 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1712 for (i = 0; i < ID_NUM; ++i)
1713 if (info->val_to_id [i])
1714 g_hash_table_destroy (info->val_to_id [i]);
1715 g_hash_table_destroy (info->loaded_classes);
1719 domain_jit_info (domain)->agent_info = NULL;
1721 /* Clear ids referencing structures in the domain */
1722 for (i = 0; i < ID_NUM; ++i) {
1724 for (j = 0; j < ids [i]->len; ++j) {
1725 Id *id = g_ptr_array_index (ids [i], j);
1726 if (id->domain == domain)
1732 mono_loader_lock ();
1733 g_hash_table_remove (domains, domain);
1734 mono_loader_unlock ();
1738 * Called when deferred debugger session is attached,
1739 * after the VM start event has been sent successfully
1742 mono_debugger_agent_on_attach (void)
1744 /* Emit load events for currently loaded appdomains, assemblies, and types */
1745 mono_loader_lock ();
1746 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
1747 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
1748 mono_assembly_foreach (emit_assembly_load, NULL);
1749 mono_loader_unlock ();
1752 static AgentDomainInfo*
1753 get_agent_domain_info (MonoDomain *domain)
1755 AgentDomainInfo *info = NULL;
1757 mono_domain_lock (domain);
1759 info = domain_jit_info (domain)->agent_info;
1761 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1762 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
1765 mono_domain_unlock (domain);
1771 get_id (MonoDomain *domain, IdType type, gpointer val)
1774 AgentDomainInfo *info;
1779 mono_loader_lock ();
1781 mono_domain_lock (domain);
1783 info = get_agent_domain_info (domain);
1785 if (info->val_to_id [type] == NULL)
1786 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1788 id = g_hash_table_lookup (info->val_to_id [type], val);
1790 mono_domain_unlock (domain);
1791 mono_loader_unlock ();
1795 id = g_new0 (Id, 1);
1797 id->id = ids [type]->len + 1;
1798 id->domain = domain;
1801 g_hash_table_insert (info->val_to_id [type], val, id);
1803 mono_domain_unlock (domain);
1805 g_ptr_array_add (ids [type], id);
1807 mono_loader_unlock ();
1812 static inline gpointer
1813 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1817 int id = decode_id (buf, endbuf, limit);
1826 // FIXME: error handling
1827 mono_loader_lock ();
1828 g_assert (id > 0 && id <= ids [type]->len);
1830 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1831 mono_loader_unlock ();
1833 if (res->domain == NULL) {
1834 *err = ERR_UNLOADED;
1839 *domain = res->domain;
1841 return res->data.val;
1845 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1847 buffer_add_id (buf, get_id (domain, type, val));
1850 static inline MonoClass*
1851 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1853 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1856 static inline MonoAssembly*
1857 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1859 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1862 static inline MonoImage*
1863 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1865 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1868 static inline MonoMethod*
1869 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1871 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1874 static inline MonoClassField*
1875 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1877 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1880 static inline MonoDomain*
1881 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1883 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1886 static inline MonoProperty*
1887 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1889 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1893 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1895 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1899 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1901 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1905 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1907 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1911 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1913 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1917 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1919 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1923 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1925 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1929 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1931 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1934 static void invoke_method (void);
1941 * save_thread_context:
1943 * Set CTX as the current threads context which is used for computing stack traces.
1944 * This function is signal-safe.
1947 save_thread_context (MonoContext *ctx)
1949 DebuggerTlsData *tls;
1951 tls = TlsGetValue (debugger_tls_id);
1955 mono_thread_state_init_from_monoctx (&tls->context, ctx);
1957 mono_thread_state_init_from_current (&tls->context);
1960 /* The number of times the runtime is suspended */
1961 static gint32 suspend_count;
1963 /* Number of threads suspended */
1965 * If this is equal to the size of thread_to_tls, the runtime is considered
1968 static gint32 threads_suspend_count;
1970 static mono_mutex_t suspend_mutex;
1972 /* Cond variable used to wait for suspend_count becoming 0 */
1973 static mono_cond_t suspend_cond;
1975 /* Semaphore used to wait for a thread becoming suspended */
1976 static MonoSemType suspend_sem;
1981 mono_mutex_init (&suspend_mutex, NULL);
1982 mono_cond_init (&suspend_cond, NULL);
1983 MONO_SEM_INIT (&suspend_sem, 0);
1988 StackFrameInfo last_frame;
1989 gboolean last_frame_set;
1992 } GetLastFrameUserData;
1995 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
1997 GetLastFrameUserData *data = user_data;
1999 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2002 if (!data->last_frame_set) {
2003 /* Store the last frame */
2004 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2005 data->last_frame_set = TRUE;
2008 /* Store the context/lmf for the frame above the last frame */
2009 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2010 data->lmf = info->lmf;
2017 * mono_debugger_agent_thread_interrupt:
2019 * Called by the abort signal handler.
2020 * Should be signal safe.
2023 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2025 DebuggerTlsData *tls;
2030 tls = TlsGetValue (debugger_tls_id);
2035 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2036 * guarantee the signal handler will be called that many times. Instead of tracking
2037 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2038 * has been requested that hasn't been handled yet, otherwise we can have threads
2039 * refuse to die when VM_EXIT is called
2041 #if defined(__APPLE__)
2042 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2046 * We use interrupt_count to determine whenever this interrupt should be processed
2047 * by us or the normal interrupt processing code in the signal handler.
2048 * There is no race here with notify_thread (), since the signal is sent after
2049 * incrementing interrupt_count.
2051 if (tls->interrupt_count == 0)
2054 InterlockedDecrement (&tls->interrupt_count);
2057 // FIXME: Races when the thread leaves managed code before hitting a single step
2061 /* Running managed code, will be suspended by the single step code */
2062 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)GetCurrentThreadId (), ji->method->name, mono_arch_ip_from_context (sigctx)));
2066 * Running native code, will be suspended when it returns to/enters
2067 * managed code. Treat it as already suspended.
2068 * This might interrupt the code in process_single_step_inner (), we use the
2069 * tls->suspending flag to avoid races when that happens.
2071 if (!tls->suspended && !tls->suspending) {
2073 GetLastFrameUserData data;
2075 // FIXME: printf is not signal safe, but this is only used during
2076 // debugger debugging
2078 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)GetCurrentThreadId (), mono_arch_ip_from_context (sigctx)));
2079 //save_thread_context (&ctx);
2082 /* Already terminated */
2086 * We are in a difficult position: we want to be able to provide stack
2087 * traces for this thread, but we can't use the current ctx+lmf, since
2088 * the thread is still running, so it might return to managed code,
2089 * making these invalid.
2090 * So we start a stack walk and save the first frame, along with the
2091 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2092 * suspended when it returns to managed code, so the parent's ctx should
2095 data.last_frame_set = FALSE;
2097 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2098 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_DEFAULT, &data);
2100 if (data.last_frame_set) {
2101 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2102 g_assert (mono_thread_state_init_from_monoctx (&tls->async_state, sigctx));
2103 g_assert (mono_thread_state_init_from_monoctx (&tls->context, sigctx));
2105 tls->async_state.valid = FALSE;
2108 mono_memory_barrier ();
2110 tls->suspended = TRUE;
2111 MONO_SEM_POST (&suspend_sem);
2118 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2121 mono_debugger_agent_thread_interrupt (NULL, NULL);
2123 #endif /* HOST_WIN32 */
2126 * reset_native_thread_suspend_state:
2128 * Reset the suspended flag on native threads
2131 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2133 DebuggerTlsData *tls = value;
2135 if (!tls->really_suspended && tls->suspended)
2136 tls->suspended = FALSE;
2142 * Notify a thread that it needs to suspend.
2145 notify_thread (gpointer key, gpointer value, gpointer user_data)
2147 MonoInternalThread *thread = key;
2148 DebuggerTlsData *tls = value;
2149 gsize tid = thread->tid;
2151 if (GetCurrentThreadId () == tid || tls->terminated)
2154 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2157 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2158 * guarantee the signal handler will be called that many times. Instead of tracking
2159 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2160 * has been requested that hasn't been handled yet, otherwise we can have threads
2161 * refuse to die when VM_EXIT is called
2163 #if defined(__APPLE__)
2164 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2168 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2169 * of things like breaking waits etc. which we don't want.
2171 InterlockedIncrement (&tls->interrupt_count);
2174 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2176 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2178 mono_thread_kill (thread, mono_thread_get_abort_signal ());
2183 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2185 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2188 if (mono_loader_lock_is_owned_by_self ()) {
2190 * Shortcut for the check in suspend_current (). This speeds up processing
2191 * when executing long running code inside the loader lock, i.e. assembly load
2197 if (debugger_thread_id == GetCurrentThreadId ())
2200 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2201 if (suspend_count - tls->resume_count > 0)
2202 tls->suspending = TRUE;
2204 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2206 if (suspend_count - tls->resume_count == 0) {
2208 * We are executing a single threaded invoke but the single step for
2209 * suspending is still active.
2210 * FIXME: This slows down single threaded invokes.
2212 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2216 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2218 /* Can't suspend in these methods */
2219 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2222 save_thread_context (ctx);
2230 * Increase the suspend count of the VM. While the suspend count is greater
2231 * than 0, runtime threads are suspended at certain points during execution.
2236 mono_loader_lock ();
2238 mono_mutex_lock (&suspend_mutex);
2242 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2244 if (suspend_count == 1) {
2245 // FIXME: Is it safe to call this inside the lock ?
2246 start_single_stepping ();
2247 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2250 mono_mutex_unlock (&suspend_mutex);
2252 mono_loader_unlock ();
2258 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2266 g_assert (debugger_thread_id == GetCurrentThreadId ());
2268 mono_loader_lock ();
2270 mono_mutex_lock (&suspend_mutex);
2272 g_assert (suspend_count > 0);
2275 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2277 if (suspend_count == 0) {
2278 // FIXME: Is it safe to call this inside the lock ?
2279 stop_single_stepping ();
2280 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2283 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2284 err = mono_cond_broadcast (&suspend_cond);
2285 g_assert (err == 0);
2287 mono_mutex_unlock (&suspend_mutex);
2288 //g_assert (err == 0);
2290 mono_loader_unlock ();
2296 * Resume just one thread.
2299 resume_thread (MonoInternalThread *thread)
2302 DebuggerTlsData *tls;
2304 g_assert (debugger_thread_id == GetCurrentThreadId ());
2306 mono_loader_lock ();
2308 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2311 mono_mutex_lock (&suspend_mutex);
2313 g_assert (suspend_count > 0);
2315 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2317 tls->resume_count += suspend_count;
2320 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2321 * but only the one whose resume_count field is > 0 will be resumed.
2323 err = mono_cond_broadcast (&suspend_cond);
2324 g_assert (err == 0);
2326 mono_mutex_unlock (&suspend_mutex);
2327 //g_assert (err == 0);
2329 mono_loader_unlock ();
2333 invalidate_frames (DebuggerTlsData *tls)
2338 tls = TlsGetValue (debugger_tls_id);
2341 for (i = 0; i < tls->frame_count; ++i) {
2342 if (tls->frames [i]->jit)
2343 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2344 g_free (tls->frames [i]);
2346 g_free (tls->frames);
2347 tls->frame_count = 0;
2354 * Suspend the current thread until the runtime is resumed. If the thread has a
2355 * pending invoke, then the invoke is executed before this function returns.
2358 suspend_current (void)
2361 DebuggerTlsData *tls;
2363 g_assert (debugger_thread_id != GetCurrentThreadId ());
2365 if (mono_loader_lock_is_owned_by_self ()) {
2367 * If we own the loader mutex, can't suspend until we release it, since the
2368 * whole runtime can deadlock otherwise.
2373 tls = TlsGetValue (debugger_tls_id);
2376 mono_mutex_lock (&suspend_mutex);
2378 tls->suspending = FALSE;
2379 tls->really_suspended = TRUE;
2381 if (!tls->suspended) {
2382 tls->suspended = TRUE;
2383 MONO_SEM_POST (&suspend_sem);
2386 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2388 while (suspend_count - tls->resume_count > 0) {
2390 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2392 mono_mutex_unlock (&suspend_mutex);
2394 mono_mutex_lock (&suspend_mutex);
2400 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2401 g_assert (err == 0);
2405 tls->suspended = FALSE;
2406 tls->really_suspended = FALSE;
2408 threads_suspend_count --;
2410 mono_mutex_unlock (&suspend_mutex);
2412 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2414 if (tls->pending_invoke) {
2415 /* Save the original context */
2416 tls->pending_invoke->has_ctx = TRUE;
2417 tls->pending_invoke->ctx = tls->context.ctx;
2422 /* The frame info becomes invalid after a resume */
2423 tls->context.valid = FALSE;
2424 tls->async_state.valid = FALSE;
2425 invalidate_frames (NULL);
2429 count_thread (gpointer key, gpointer value, gpointer user_data)
2431 DebuggerTlsData *tls = value;
2433 if (!tls->suspended && !tls->terminated)
2434 *(int*)user_data = *(int*)user_data + 1;
2438 count_threads_to_wait_for (void)
2442 mono_loader_lock ();
2443 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2444 mono_loader_unlock ();
2452 * Wait until the runtime is completely suspended.
2455 wait_for_suspend (void)
2457 int nthreads, nwait, err;
2458 gboolean waited = FALSE;
2460 // FIXME: Threads starting/stopping ?
2461 mono_loader_lock ();
2462 nthreads = mono_g_hash_table_size (thread_to_tls);
2463 mono_loader_unlock ();
2466 nwait = count_threads_to_wait_for ();
2468 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2469 err = MONO_SEM_WAIT (&suspend_sem);
2470 g_assert (err == 0);
2478 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2484 * Return whenever the runtime is suspended.
2489 return count_threads_to_wait_for () == 0;
2493 * find_seq_point_for_native_offset:
2495 * Find the sequence point corresponding to the native offset NATIVE_OFFSET, which
2496 * should be the location of a sequence point.
2499 find_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2501 MonoSeqPointInfo *seq_points;
2504 mono_domain_lock (domain);
2505 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2506 mono_domain_unlock (domain);
2507 g_assert (seq_points);
2511 for (i = 0; i < seq_points->len; ++i) {
2512 if (seq_points->seq_points [i].native_offset == native_offset)
2513 return &seq_points->seq_points [i];
2520 * find_next_seq_point_for_native_offset:
2522 * Find the first sequence point after NATIVE_OFFSET.
2525 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2527 MonoSeqPointInfo *seq_points;
2530 mono_domain_lock (domain);
2531 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2532 mono_domain_unlock (domain);
2533 g_assert (seq_points);
2537 for (i = 0; i < seq_points->len; ++i) {
2538 if (seq_points->seq_points [i].native_offset >= native_offset)
2539 return &seq_points->seq_points [i];
2546 * find_prev_seq_point_for_native_offset:
2548 * Find the first sequence point before NATIVE_OFFSET.
2551 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2553 MonoSeqPointInfo *seq_points;
2556 mono_domain_lock (domain);
2557 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2558 mono_domain_unlock (domain);
2559 g_assert (seq_points);
2563 for (i = seq_points->len - 1; i >= 0; --i) {
2564 if (seq_points->seq_points [i].native_offset <= native_offset)
2565 return &seq_points->seq_points [i];
2574 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2575 * should be the location of a sequence point.
2578 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2580 MonoSeqPointInfo *seq_points;
2583 mono_domain_lock (domain);
2584 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2585 mono_domain_unlock (domain);
2586 g_assert (seq_points);
2590 for (i = 0; i < seq_points->len; ++i) {
2591 if (seq_points->seq_points [i].il_offset == il_offset)
2592 return &seq_points->seq_points [i];
2599 * compute_il_offset:
2601 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
2602 * a location of a sequence point.
2603 * We use this function instead of mono_debug_il_offset_from_address () etc,
2604 * which doesn't seem to work in a lot of cases.
2607 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
2609 MonoSeqPointInfo *seq_points;
2610 int i, last_il_offset, seq_il_offset, seq_native_offset;
2612 mono_domain_lock (domain);
2613 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2614 mono_domain_unlock (domain);
2615 g_assert (seq_points);
2617 last_il_offset = -1;
2619 /* Find the sequence point */
2620 for (i = 0; i < seq_points->len; ++i) {
2621 seq_il_offset = seq_points->seq_points [i].il_offset;
2622 seq_native_offset = seq_points->seq_points [i].native_offset;
2624 if (seq_native_offset > native_offset)
2626 last_il_offset = seq_il_offset;
2629 return last_il_offset;
2633 DebuggerTlsData *tls;
2635 } ComputeFramesUserData;
2638 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2640 ComputeFramesUserData *ud = user_data;
2642 MonoMethod *method, *actual_method;
2644 if (info->type != FRAME_TYPE_MANAGED) {
2645 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2646 /* Mark the last frame as an invoke frame */
2648 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2654 method = info->ji->method;
2656 method = info->method;
2657 actual_method = info->actual_method;
2659 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2662 if (info->il_offset == -1) {
2663 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2664 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2667 DEBUG (1, fprintf (log_file, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed));
2669 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2671 * mono_arch_find_jit_info () returns the context stored in the LMF for
2672 * native frames, but it should unwind once. This is why we have duplicate
2673 * frames on the stack sometimes.
2674 * !managed also seems to be set for dynamic methods.
2679 frame = g_new0 (StackFrame, 1);
2680 frame->method = method;
2681 frame->actual_method = actual_method;
2682 frame->il_offset = info->il_offset;
2683 frame->native_offset = info->native_offset;
2686 frame->has_ctx = TRUE;
2688 frame->domain = info->domain;
2690 ud->frames = g_slist_append (ud->frames, frame);
2696 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2698 ComputeFramesUserData *ud = user_data;
2701 * 'tls->filter_ctx' is the location of the throw site.
2703 * mono_walk_stack() will never actually hit the throw site, but unwind
2704 * directly from the filter to the call site; we abort stack unwinding here
2705 * once this happens and resume from the throw site.
2708 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
2711 return process_frame (info, ctx, user_data);
2715 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2717 ComputeFramesUserData user_data;
2719 int i, findex, new_frame_count;
2720 StackFrame **new_frames, *f;
2722 // FIXME: Locking on tls
2723 if (tls->frames && tls->frames_up_to_date)
2726 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2728 user_data.tls = tls;
2729 user_data.frames = NULL;
2730 if (tls->terminated) {
2731 tls->frame_count = 0;
2733 } if (!tls->really_suspended && tls->async_state.valid) {
2734 /* Have to use the state saved by the signal handler */
2735 process_frame (&tls->async_last_frame, NULL, &user_data);
2736 mono_walk_stack_with_state (process_frame, &tls->async_state, MONO_UNWIND_DEFAULT, &user_data);
2737 } else if (tls->filter_state.valid) {
2739 * We are inside an exception filter.
2741 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
2743 if (tls->context.valid)
2744 mono_walk_stack_with_state (process_filter_frame, &tls->context, MONO_UNWIND_DEFAULT, &user_data);
2746 * After that, we resume unwinding from the location where the exception has been thrown.
2748 mono_walk_stack_with_state (process_frame, &tls->filter_state, MONO_UNWIND_DEFAULT, &user_data);
2749 } else if (tls->context.valid) {
2750 mono_walk_stack_with_state (process_frame, &tls->context, MONO_UNWIND_DEFAULT, &user_data);
2753 tls->frame_count = 0;
2757 new_frame_count = g_slist_length (user_data.frames);
2758 new_frames = g_new0 (StackFrame*, new_frame_count);
2760 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2764 * Reuse the id for already existing stack frames, so invokes don't invalidate
2765 * the still valid stack frames.
2767 for (i = 0; i < tls->frame_count; ++i) {
2768 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2769 f->id = tls->frames [i]->id;
2774 if (i >= tls->frame_count)
2775 f->id = InterlockedIncrement (&frame_id);
2777 new_frames [findex ++] = f;
2780 g_slist_free (user_data.frames);
2782 invalidate_frames (tls);
2784 tls->frames = new_frames;
2785 tls->frame_count = new_frame_count;
2786 tls->frames_up_to_date = TRUE;
2790 * GHFunc to emit an appdomain creation event
2791 * @param key Don't care
2792 * @param value A loaded appdomain
2793 * @param user_data Don't care
2796 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
2798 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
2799 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
2803 * GHFunc to emit a thread start event
2804 * @param key A thread id
2805 * @param value A thread object
2806 * @param user_data Don't care
2809 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
2811 if (GPOINTER_TO_INT (key) != debugger_thread_id)
2812 process_profiler_event (EVENT_KIND_THREAD_START, value);
2816 * GFunc to emit an assembly load event
2817 * @param value A loaded assembly
2818 * @param user_data Don't care
2821 emit_assembly_load (gpointer value, gpointer user_data)
2823 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
2827 * GFunc to emit a type load event
2828 * @param value A loaded type
2829 * @param user_data Don't care
2832 emit_type_load (gpointer key, gpointer value, gpointer user_data)
2834 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
2843 * create_event_list:
2845 * Return a list of event request ids matching EVENT, starting from REQS, which
2846 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2848 * We return request ids, instead of requests, to simplify threading, since
2849 * requests could be deleted anytime when the loader lock is not held.
2850 * LOCKING: Assumes the loader lock is held.
2853 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
2856 GSList *events = NULL;
2858 *suspend_policy = SUSPEND_POLICY_NONE;
2861 reqs = event_requests;
2866 for (i = 0; i < reqs->len; ++i) {
2867 EventRequest *req = g_ptr_array_index (reqs, i);
2868 if (req->event_kind == event) {
2869 gboolean filtered = FALSE;
2872 for (j = 0; j < req->nmodifiers; ++j) {
2873 Modifier *mod = &req->modifiers [j];
2875 if (mod->kind == MOD_KIND_COUNT) {
2877 if (mod->data.count > 0) {
2878 if (mod->data.count > 0) {
2880 if (mod->data.count == 0)
2884 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2885 if (mod->data.thread != mono_thread_internal_current ())
2887 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
2888 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
2890 if (ei->caught && !mod->caught)
2892 if (!ei->caught && !mod->uncaught)
2894 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2896 gboolean found = FALSE;
2897 MonoAssembly **assemblies = mod->data.assemblies;
2900 for (k = 0; assemblies [k]; ++k)
2901 if (assemblies [k] == ji->method->klass->image->assembly)
2910 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2911 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2916 /* Send a VM START/DEATH event by default */
2917 if (event == EVENT_KIND_VM_START)
2918 events = g_slist_append (events, GINT_TO_POINTER (0));
2919 if (event == EVENT_KIND_VM_DEATH)
2920 events = g_slist_append (events, GINT_TO_POINTER (0));
2925 static G_GNUC_UNUSED const char*
2926 event_to_string (EventKind event)
2929 case EVENT_KIND_VM_START: return "VM_START";
2930 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2931 case EVENT_KIND_THREAD_START: return "THREAD_START";
2932 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2933 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2934 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2935 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2936 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2937 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2938 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2939 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2940 case EVENT_KIND_STEP: return "STEP";
2941 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2942 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2944 g_assert_not_reached ();
2951 * Send an event to the client, suspending the vm if needed.
2952 * LOCKING: Since this can suspend the calling thread, no locks should be held
2954 * The EVENTS list is freed by this function.
2957 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2961 MonoDomain *domain = mono_domain_get ();
2962 MonoThread *thread = NULL;
2963 gboolean send_success = FALSE;
2966 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
2970 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
2971 // FIXME: We miss those events
2972 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
2976 if (vm_death_event_sent) {
2977 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
2981 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
2982 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
2987 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
2994 if (agent_config.defer) {
2995 /* Make sure the thread id is always set when doing deferred debugging */
2996 if (debugger_thread_id == GetCurrentThreadId ())
2997 thread = mono_thread_get_main ();
2998 else thread = mono_thread_current ();
3000 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3001 // FIXME: Send these with a NULL thread, don't suspend the current thread
3005 buffer_init (&buf, 128);
3006 buffer_add_byte (&buf, suspend_policy);
3007 buffer_add_int (&buf, g_slist_length (events)); // n of events
3009 for (l = events; l; l = l->next) {
3010 buffer_add_byte (&buf, event); // event kind
3011 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3014 thread = mono_thread_current ();
3016 if (event == EVENT_KIND_VM_START && arg != NULL)
3019 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3022 case EVENT_KIND_THREAD_START:
3023 case EVENT_KIND_THREAD_DEATH:
3025 case EVENT_KIND_APPDOMAIN_CREATE:
3026 case EVENT_KIND_APPDOMAIN_UNLOAD:
3027 buffer_add_domainid (&buf, arg);
3029 case EVENT_KIND_METHOD_ENTRY:
3030 case EVENT_KIND_METHOD_EXIT:
3031 buffer_add_methodid (&buf, domain, arg);
3033 case EVENT_KIND_ASSEMBLY_LOAD:
3034 case EVENT_KIND_ASSEMBLY_UNLOAD:
3035 buffer_add_assemblyid (&buf, domain, arg);
3037 case EVENT_KIND_TYPE_LOAD:
3038 buffer_add_typeid (&buf, domain, arg);
3040 case EVENT_KIND_BREAKPOINT:
3041 case EVENT_KIND_STEP:
3042 buffer_add_methodid (&buf, domain, arg);
3043 buffer_add_long (&buf, il_offset);
3045 case EVENT_KIND_VM_START:
3046 buffer_add_domainid (&buf, mono_get_root_domain ());
3048 case EVENT_KIND_VM_DEATH:
3050 case EVENT_KIND_EXCEPTION: {
3051 EventInfo *ei = arg;
3052 buffer_add_objid (&buf, ei->exc);
3056 g_assert_not_reached ();
3060 if (event == EVENT_KIND_VM_START) {
3061 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3062 if (!agent_config.defer)
3063 start_debugger_thread ();
3066 if (event == EVENT_KIND_VM_DEATH) {
3067 vm_death_event_sent = TRUE;
3068 suspend_policy = SUSPEND_POLICY_NONE;
3071 if (mono_runtime_is_shutting_down ())
3072 suspend_policy = SUSPEND_POLICY_NONE;
3074 if (suspend_policy != SUSPEND_POLICY_NONE) {
3076 * Save the thread context and start suspending before sending the packet,
3077 * since we could be receiving the resume request before send_packet ()
3080 save_thread_context (ctx);
3084 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3088 g_slist_free (events);
3091 if (!send_success) {
3092 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3096 if (event == EVENT_KIND_VM_START) {
3097 vm_start_event_sent = TRUE;
3098 if (agent_config.defer)
3099 mono_debugger_agent_on_attach ();
3102 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
3105 switch (suspend_policy) {
3106 case SUSPEND_POLICY_NONE:
3108 case SUSPEND_POLICY_ALL:
3111 case SUSPEND_POLICY_EVENT_THREAD:
3115 g_assert_not_reached ();
3120 process_profiler_event (EventKind event, gpointer arg)
3125 mono_loader_lock ();
3126 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
3127 mono_loader_unlock ();
3129 process_event (event, arg, 0, NULL, events, suspend_policy);
3133 runtime_initialized (MonoProfiler *prof)
3135 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3136 if (agent_config.defer)
3137 start_debugger_thread ();
3141 runtime_shutdown (MonoProfiler *prof)
3143 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3145 mono_debugger_agent_cleanup ();
3149 thread_startup (MonoProfiler *prof, uintptr_t tid)
3151 MonoInternalThread *thread = mono_thread_internal_current ();
3152 MonoInternalThread *old_thread;
3153 DebuggerTlsData *tls;
3155 if (tid == debugger_thread_id)
3158 g_assert (thread->tid == tid);
3160 mono_loader_lock ();
3161 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3162 mono_loader_unlock ();
3164 if (thread == old_thread) {
3166 * For some reason, thread_startup () might be called for the same thread
3167 * multiple times (attach ?).
3169 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3173 * thread_end () might not be called for some threads, and the tid could
3176 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3177 mono_loader_lock ();
3178 mono_g_hash_table_remove (thread_to_tls, old_thread);
3179 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3180 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3181 mono_loader_unlock ();
3185 tls = TlsGetValue (debugger_tls_id);
3187 // FIXME: Free this somewhere
3188 tls = g_new0 (DebuggerTlsData, 1);
3189 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3190 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3191 tls->thread = thread;
3192 TlsSetValue (debugger_tls_id, tls);
3194 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3196 mono_loader_lock ();
3197 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3198 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3199 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3200 mono_loader_unlock ();
3202 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3205 * suspend_vm () could have missed this thread, so wait for a resume.
3211 thread_end (MonoProfiler *prof, uintptr_t tid)
3213 MonoInternalThread *thread;
3214 DebuggerTlsData *tls = NULL;
3216 mono_loader_lock ();
3217 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3219 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3220 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3221 tls->terminated = TRUE;
3222 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3223 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3224 MONO_GC_UNREGISTER_ROOT (tls->thread);
3227 mono_loader_unlock ();
3229 /* We might be called for threads started before we registered the start callback */
3231 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3232 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3237 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3239 mono_loader_lock ();
3240 g_hash_table_insert (domains, domain, domain);
3241 mono_loader_unlock ();
3243 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3247 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3249 clear_breakpoints_for_domain (domain);
3251 mono_loader_lock ();
3252 /* Invalidate each thread's frame stack */
3253 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3254 mono_loader_unlock ();
3256 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3260 * invalidate_each_thread:
3262 * A GHFunc to invalidate frames.
3263 * value must be a DebuggerTlsData*
3266 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3268 invalidate_frames (value);
3272 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3274 /* Sent later in jit_end () */
3275 mono_loader_lock ();
3276 g_ptr_array_add (pending_assembly_loads, assembly);
3277 mono_loader_unlock ();
3281 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3283 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3285 clear_event_requests_for_assembly (assembly);
3286 clear_types_for_assembly (assembly);
3290 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3292 #if defined(HOST_WIN32) && !defined(__GNUC__)
3293 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3295 gpointer stackptr = __builtin_frame_address (1);
3297 MonoInternalThread *thread = mono_thread_internal_current ();
3298 DebuggerTlsData *tls;
3300 mono_loader_lock ();
3302 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3303 /* Could be the debugger thread with assembly/type load hooks */
3305 tls->invoke_addr = stackptr;
3307 mono_loader_unlock ();
3311 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3314 #if defined(HOST_WIN32) && !defined(__GNUC__)
3315 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3317 gpointer stackptr = __builtin_frame_address (1);
3320 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3324 * We need to stop single stepping when exiting a runtime invoke, since if it is
3325 * a step out, it may return to native code, and thus never end.
3327 mono_loader_lock ();
3328 ss_invoke_addr = NULL;
3330 for (i = 0; i < event_requests->len; ++i) {
3331 EventRequest *req = g_ptr_array_index (event_requests, i);
3333 if (req->event_kind == EVENT_KIND_STEP) {
3334 ss_destroy (req->info);
3335 g_ptr_array_remove_index_fast (event_requests, i);
3340 mono_loader_unlock ();
3344 send_type_load (MonoClass *klass)
3346 gboolean type_load = FALSE;
3347 MonoDomain *domain = mono_domain_get ();
3348 AgentDomainInfo *info = NULL;
3350 mono_loader_lock ();
3351 mono_domain_lock (domain);
3353 info = get_agent_domain_info (domain);
3355 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3357 g_hash_table_insert (info->loaded_classes, klass, klass);
3360 mono_domain_unlock (domain);
3361 mono_loader_unlock ();
3363 emit_type_load (klass, klass, NULL);
3367 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3370 * We emit type load events when the first method of the type is JITted,
3371 * since the class load profiler callbacks might be called with the
3372 * loader lock held. They could also occur in the debugger thread.
3373 * Same for assembly load events.
3376 MonoAssembly *assembly = NULL;
3378 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3379 mono_loader_lock ();
3380 if (pending_assembly_loads->len > 0) {
3381 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3382 g_ptr_array_remove_index (pending_assembly_loads, 0);
3384 mono_loader_unlock ();
3387 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3393 send_type_load (method->klass);
3396 add_pending_breakpoints (method, jinfo);
3400 * BREAKPOINTS/SINGLE STEPPING
3404 * Contains information about an inserted breakpoint.
3407 long il_offset, native_offset;
3411 } BreakpointInstance;
3414 * Contains generic information about a breakpoint.
3418 * The method where the breakpoint is placed. Can be NULL in which case it
3419 * is inserted into every method. This is used to implement method entry/
3420 * exit events. Can be a generic method definition, in which case the
3421 * breakpoint is inserted into every instance.
3427 * A list of BreakpointInstance structures describing where the breakpoint
3428 * was inserted. There could be more than one because of
3429 * generics/appdomains/method entry/exit.
3431 GPtrArray *children;
3434 /* List of breakpoints */
3435 static GPtrArray *breakpoints;
3436 /* Maps breakpoint locations to the number of breakpoints at that location */
3437 static GHashTable *bp_locs;
3440 breakpoints_init (void)
3442 breakpoints = g_ptr_array_new ();
3443 bp_locs = g_hash_table_new (NULL, NULL);
3447 * insert_breakpoint:
3449 * Insert the breakpoint described by BP into the method described by
3453 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3456 gint32 il_offset = -1, native_offset;
3457 BreakpointInstance *inst;
3460 mono_error_init (error);
3463 for (i = 0; i < seq_points->len; ++i) {
3464 il_offset = seq_points->seq_points [i].il_offset;
3465 native_offset = seq_points->seq_points [i].native_offset;
3467 if (il_offset == bp->il_offset)
3471 if (i == seq_points->len) {
3472 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (ji->method, TRUE), bp->il_offset, seq_points->len);
3474 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3483 inst = g_new0 (BreakpointInstance, 1);
3484 inst->native_offset = native_offset;
3485 inst->ip = (guint8*)ji->code_start + native_offset;
3487 inst->domain = domain;
3489 mono_loader_lock ();
3491 g_ptr_array_add (bp->children, inst);
3493 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3494 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3495 mono_loader_unlock ();
3498 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3499 mono_arch_set_breakpoint (ji, inst->ip);
3505 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)il_offset));
3509 remove_breakpoint (BreakpointInstance *inst)
3511 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3513 MonoJitInfo *ji = inst->ji;
3514 guint8 *ip = inst->ip;
3516 mono_loader_lock ();
3517 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3518 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3519 mono_loader_unlock ();
3521 g_assert (count > 0);
3524 mono_arch_clear_breakpoint (ji, ip);
3531 static inline gboolean
3532 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3534 return (!bp->method || method == bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method));
3538 * add_pending_breakpoints:
3540 * Insert pending breakpoints into the newly JITted method METHOD.
3543 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3546 MonoSeqPointInfo *seq_points;
3552 domain = mono_domain_get ();
3554 mono_loader_lock ();
3556 for (i = 0; i < breakpoints->len; ++i) {
3557 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3558 gboolean found = FALSE;
3560 if (!bp_matches_method (bp, method))
3563 for (j = 0; j < bp->children->len; ++j) {
3564 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3571 mono_domain_lock (domain);
3572 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3573 mono_domain_unlock (domain);
3575 /* Could be AOT code */
3577 g_assert (seq_points);
3579 insert_breakpoint (seq_points, domain, ji, bp, NULL);
3583 mono_loader_unlock ();
3587 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
3593 mono_error_init (error);
3595 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3597 /* Might be AOTed code */
3598 code = mono_aot_get_method (domain, method);
3600 ji = mono_jit_info_table_find (domain, code);
3605 insert_breakpoint (seq_points, domain, ji, bp, error);
3609 clear_breakpoint (MonoBreakpoint *bp);
3614 * Set a breakpoint at IL_OFFSET in METHOD.
3615 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3616 * METHOD can also be a generic method definition, in which case a breakpoint
3617 * is placed in all instances of the method.
3618 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
3621 static MonoBreakpoint*
3622 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
3625 GHashTableIter iter, iter2;
3628 MonoSeqPointInfo *seq_points;
3631 mono_error_init (error);
3634 // - suspend/resume the vm to prevent code patching problems
3635 // - multiple breakpoints on the same location
3636 // - dynamic methods
3639 bp = g_new0 (MonoBreakpoint, 1);
3640 bp->method = method;
3641 bp->il_offset = il_offset;
3643 bp->children = g_ptr_array_new ();
3645 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));
3647 mono_loader_lock ();
3649 g_hash_table_iter_init (&iter, domains);
3650 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
3651 mono_domain_lock (domain);
3653 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
3654 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
3655 if (bp_matches_method (bp, m))
3656 set_bp_in_method (domain, m, seq_points, bp, error);
3659 mono_domain_unlock (domain);
3662 mono_loader_unlock ();
3664 mono_loader_lock ();
3665 g_ptr_array_add (breakpoints, bp);
3666 mono_loader_unlock ();
3668 if (error && !mono_error_ok (error)) {
3669 clear_breakpoint (bp);
3677 clear_breakpoint (MonoBreakpoint *bp)
3681 // FIXME: locking, races
3682 for (i = 0; i < bp->children->len; ++i) {
3683 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
3685 remove_breakpoint (inst);
3690 mono_loader_lock ();
3691 g_ptr_array_remove (breakpoints, bp);
3692 mono_loader_unlock ();
3694 g_ptr_array_free (bp->children, TRUE);
3699 breakpoints_cleanup (void)
3703 mono_loader_lock ();
3705 while (i < event_requests->len) {
3706 EventRequest *req = g_ptr_array_index (event_requests, i);
3708 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
3709 clear_breakpoint (req->info);
3710 g_ptr_array_remove_index_fast (event_requests, i);
3717 for (i = 0; i < breakpoints->len; ++i)
3718 g_free (g_ptr_array_index (breakpoints, i));
3720 g_ptr_array_free (breakpoints, TRUE);
3721 g_hash_table_destroy (bp_locs);
3726 mono_loader_unlock ();
3730 * clear_breakpoints_for_domain:
3732 * Clear breakpoint instances which reference DOMAIN.
3735 clear_breakpoints_for_domain (MonoDomain *domain)
3739 /* This could be called after shutdown */
3743 mono_loader_lock ();
3744 for (i = 0; i < breakpoints->len; ++i) {
3745 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3748 while (j < bp->children->len) {
3749 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3751 if (inst->domain == domain) {
3752 remove_breakpoint (inst);
3756 g_ptr_array_remove_index_fast (bp->children, j);
3762 mono_loader_unlock ();
3766 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
3768 return bp->method && bp->method->klass->image->assembly == assembly;
3772 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
3775 guint8 *orig_ip, *ip;
3776 int i, j, suspend_policy;
3777 guint32 native_offset;
3779 BreakpointInstance *inst;
3780 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
3781 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
3782 EventKind kind = EVENT_KIND_BREAKPOINT;
3784 // FIXME: Speed this up
3786 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
3787 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
3789 g_assert (ji->method);
3791 /* Compute the native offset of the breakpoint from the ip */
3792 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3793 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
3794 native_offset = ip - (guint8*)ji->code_start;
3800 * Skip the instruction causing the breakpoint signal.
3802 mono_arch_skip_breakpoint (ctx);
3804 if (ji->method->wrapper_type || tls->disable_breakpoints)
3807 bp_reqs = g_ptr_array_new ();
3808 ss_reqs = g_ptr_array_new ();
3809 ss_reqs_orig = g_ptr_array_new ();
3811 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
3813 mono_loader_lock ();
3816 for (i = 0; i < breakpoints->len; ++i) {
3817 bp = g_ptr_array_index (breakpoints, i);
3822 for (j = 0; j < bp->children->len; ++j) {
3823 inst = g_ptr_array_index (bp->children, j);
3824 if (inst->ji == ji && inst->native_offset == native_offset) {
3825 if (bp->req->event_kind == EVENT_KIND_STEP) {
3826 g_ptr_array_add (ss_reqs_orig, bp->req);
3828 g_ptr_array_add (bp_reqs, bp->req);
3833 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
3834 MonoSeqPointInfo *seq_points;
3835 int seq_il_offset, seq_native_offset;
3836 MonoDomain *domain = mono_domain_get ();
3838 /* Maybe a method entry/exit event */
3839 mono_domain_lock (domain);
3840 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3841 mono_domain_unlock (domain);
3843 // FIXME: Generic sharing */
3844 mono_loader_unlock ();
3847 g_assert (seq_points);
3849 for (i = 0; i < seq_points->len; ++i) {
3850 seq_il_offset = seq_points->seq_points [i].il_offset;
3851 seq_native_offset = seq_points->seq_points [i].native_offset;
3853 if (native_offset == seq_native_offset) {
3854 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
3855 kind = EVENT_KIND_METHOD_ENTRY;
3856 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
3857 kind = EVENT_KIND_METHOD_EXIT;
3863 /* Process single step requests */
3864 for (i = 0; i < ss_reqs_orig->len; ++i) {
3865 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
3866 SingleStepReq *ss_req = req->info;
3867 gboolean hit = TRUE;
3868 MonoSeqPointInfo *info;
3871 sp = find_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
3874 if (ss_req->size == STEP_SIZE_LINE) {
3875 /* Have to check whenever a different source line was reached */
3876 MonoDebugMethodInfo *minfo;
3877 MonoDebugSourceLocation *loc = NULL;
3879 minfo = mono_debug_lookup_method (ji->method);
3882 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
3884 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
3885 /* Have to continue single stepping */
3889 ss_req->last_method = ji->method;
3890 ss_req->last_line = loc->row;
3891 mono_debug_free_source_location (loc);
3896 g_ptr_array_add (ss_reqs, req);
3898 /* Start single stepping again from the current sequence point */
3899 ss_start (ss_req, ji->method, sp, info, ctx, NULL, FALSE);
3902 if (ss_reqs->len > 0)
3903 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
3904 if (bp_reqs->len > 0)
3905 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
3906 if (kind != EVENT_KIND_BREAKPOINT)
3907 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
3909 mono_loader_unlock ();
3911 g_ptr_array_free (bp_reqs, TRUE);
3912 g_ptr_array_free (ss_reqs, TRUE);
3915 * FIXME: The first event will suspend, so the second will only be sent after the
3919 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
3921 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
3922 if (enter_leave_events)
3923 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
3927 process_breakpoint (void)
3929 DebuggerTlsData *tls;
3931 static void (*restore_context) (void *);
3933 if (!restore_context)
3934 restore_context = mono_get_restore_context ();
3936 tls = TlsGetValue (debugger_tls_id);
3937 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3939 process_breakpoint_inner (tls, &ctx);
3941 /* This is called when resuming from a signal handler, so it shouldn't return */
3942 restore_context (&ctx);
3943 g_assert_not_reached ();
3947 resume_from_signal_handler (void *sigctx, void *func)
3949 DebuggerTlsData *tls;
3952 /* Save the original context in TLS */
3953 // FIXME: This might not work on an altstack ?
3954 tls = TlsGetValue (debugger_tls_id);
3957 // FIXME: MonoContext usually doesn't include the fp registers, so these are
3958 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
3959 // clob:c could be added to op_seq_point.
3961 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3962 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
3963 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
3964 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
3966 MONO_CONTEXT_SET_IP (&ctx, func);
3968 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3970 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
3971 mono_ppc_set_func_into_sigctx (sigctx, func);
3976 mono_debugger_agent_breakpoint_hit (void *sigctx)
3979 * We are called from a signal handler, and running code there causes all kinds of
3980 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
3981 * So set up the signal context to return to the real breakpoint handler function.
3984 resume_from_signal_handler (sigctx, process_breakpoint);
3988 ss_depth_to_string (StepDepth depth)
3991 case STEP_DEPTH_OVER:
3993 case STEP_DEPTH_OUT:
3995 case STEP_DEPTH_INTO:
3998 g_assert_not_reached ();
4004 process_single_step_inner (DebuggerTlsData *tls, MonoContext *ctx)
4009 int il_offset, suspend_policy;
4013 // FIXME: Speed this up
4015 ip = MONO_CONTEXT_GET_IP (ctx);
4017 /* Skip the instruction causing the single step */
4018 mono_arch_skip_single_step (ctx);
4020 if (suspend_count > 0) {
4021 process_suspend (tls, ctx);
4026 // FIXME: A suspend race
4029 if (mono_thread_internal_current () != ss_req->thread)
4032 if (log_level > 0) {
4033 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4035 DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_depth_to_string (ss_req->depth), mono_method_full_name (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4039 * We implement step over/out by single stepping until we reach the same
4040 * frame/parent frame.
4043 * - stack growing upward
4047 if (ss_req->depth != STEP_DEPTH_INTO) {
4048 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
4050 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
4053 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
4056 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4058 g_assert (ji->method);
4060 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4065 * Stopping in memset makes half-initialized vtypes visible.
4066 * Stopping in memcpy makes half-copied vtypes visible.
4068 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4072 * The ip points to the instruction causing the single step event, convert it
4073 * to the offset stored in seq_points.
4075 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4076 ip = mono_arch_get_ip_for_single_step (ji, ctx);
4078 g_assert_not_reached ();
4082 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
4083 * example, so do things by hand.
4085 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
4087 if (il_offset == -1)
4090 if (ss_req->size == STEP_SIZE_LINE) {
4091 /* Step until a different source line is reached */
4092 MonoDebugMethodInfo *minfo;
4094 minfo = mono_debug_lookup_method (ji->method);
4097 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4099 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4100 mono_debug_free_source_location (loc);
4105 * Step until we reach a location with line number info,
4106 * otherwise the client can't show a location.
4107 * This can happen for example with statics initialized inline
4108 * outside of a cctor.
4113 ss_req->last_method = ji->method;
4114 ss_req->last_line = loc->row;
4115 mono_debug_free_source_location (loc);
4120 // FIXME: Has to lock earlier
4122 reqs = g_ptr_array_new ();
4124 mono_loader_lock ();
4126 g_ptr_array_add (reqs, ss_req->req);
4128 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4130 g_ptr_array_free (reqs, TRUE);
4132 mono_loader_unlock ();
4134 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4138 process_single_step (void)
4140 DebuggerTlsData *tls;
4142 static void (*restore_context) (void *);
4144 if (!restore_context)
4145 restore_context = mono_get_restore_context ();
4147 tls = TlsGetValue (debugger_tls_id);
4148 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
4150 process_single_step_inner (tls, &ctx);
4152 /* This is called when resuming from a signal handler, so it shouldn't return */
4153 restore_context (&ctx);
4154 g_assert_not_reached ();
4158 * mono_debugger_agent_single_step_event:
4160 * Called from a signal handler to handle a single step event.
4163 mono_debugger_agent_single_step_event (void *sigctx)
4165 /* Resume to process_single_step through the signal context */
4167 // FIXME: Since step out/over is implemented using step in, the step in case should
4168 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4171 if (GetCurrentThreadId () == debugger_thread_id) {
4173 * This could happen despite our best effors when the runtime calls
4174 * assembly/type resolve hooks.
4175 * FIXME: Breakpoints too.
4179 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4180 mono_arch_skip_single_step (&ctx);
4181 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4185 resume_from_signal_handler (sigctx, process_single_step);
4189 * start_single_stepping:
4191 * Turn on single stepping. Can be called multiple times, for example,
4192 * by a single step event request + a suspend.
4195 start_single_stepping (void)
4197 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4198 int val = InterlockedIncrement (&ss_count);
4201 mono_arch_start_single_stepping ();
4203 if (ss_req != NULL && ss_invoke_addr == NULL) {
4204 DebuggerTlsData *tls;
4206 mono_loader_lock ();
4208 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4209 ss_invoke_addr = tls->invoke_addr;
4211 mono_loader_unlock ();
4214 g_assert_not_reached ();
4219 stop_single_stepping (void)
4221 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4222 int val = InterlockedDecrement (&ss_count);
4225 mono_arch_stop_single_stepping ();
4227 g_assert_not_reached ();
4234 * Stop the single stepping operation given by SS_REQ.
4237 ss_stop (SingleStepReq *ss_req)
4239 gboolean use_bps = FALSE;
4246 for (l = ss_req->bps; l; l = l->next) {
4247 clear_breakpoint (l->data);
4249 g_slist_free (ss_req->bps);
4253 if (ss_req->global) {
4254 stop_single_stepping ();
4255 ss_req->global = FALSE;
4262 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4265 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4271 /* Stop the previous operation */
4275 * Implement single stepping using breakpoints if possible.
4277 if (step_to_catch) {
4278 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4279 ss_req->bps = g_slist_append (ss_req->bps, bp);
4280 } else if (ss_req->depth == STEP_DEPTH_OVER) {
4283 * Find the first sequence point in the current or in a previous frame which
4284 * is not the last in its method.
4286 while (sp && sp->next_len == 0) {
4288 if (tls && frame_index < tls->frame_count) {
4289 StackFrame *frame = tls->frames [frame_index];
4291 method = frame->method;
4292 if (frame->il_offset != -1) {
4293 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
4299 if (sp && sp->next_len > 0) {
4300 for (i = 0; i < sp->next_len; ++i) {
4301 next_sp = &info->seq_points [sp->next [i]];
4303 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4304 ss_req->bps = g_slist_append (ss_req->bps, bp);
4310 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4311 ss_req->global = TRUE;
4312 start_single_stepping ();
4314 ss_req->global = FALSE;
4319 * Start single stepping of thread THREAD
4322 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4324 DebuggerTlsData *tls;
4325 MonoSeqPointInfo *info = NULL;
4326 SeqPoint *sp = NULL;
4327 MonoMethod *method = NULL;
4328 MonoDebugMethodInfo *minfo;
4329 gboolean step_to_catch = FALSE;
4331 if (suspend_count == 0)
4332 return ERR_NOT_SUSPENDED;
4334 wait_for_suspend ();
4336 // FIXME: Multiple requests
4338 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4339 return ERR_NOT_IMPLEMENTED;
4342 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4344 ss_req = g_new0 (SingleStepReq, 1);
4346 ss_req->thread = thread;
4347 ss_req->size = size;
4348 ss_req->depth = depth;
4351 mono_loader_lock ();
4352 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4353 mono_loader_unlock ();
4355 g_assert (tls->context.valid);
4356 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4358 if (tls->has_catch_ctx) {
4360 StackFrameInfo frame;
4361 MonoContext new_ctx;
4362 MonoLMF *lmf = NULL;
4365 * We are stopped at a throw site. Stepping should go to the catch site.
4368 /* Find the the jit info for the catch context */
4369 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4371 g_assert (frame.type == FRAME_TYPE_MANAGED);
4374 * Find the seq point corresponding to the landing site ip, which is the first seq
4377 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4380 method = frame.method;
4382 step_to_catch = TRUE;
4383 /* This make sure the seq point is not skipped by process_single_step () */
4384 ss_req->last_sp = NULL;
4387 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4390 /* Compute the initial line info */
4391 compute_frame_info (thread, tls);
4393 g_assert (tls->frame_count);
4394 frame = tls->frames [0];
4396 ss_req->last_method = frame->method;
4397 ss_req->last_line = -1;
4399 minfo = mono_debug_lookup_method (frame->method);
4400 if (minfo && frame->il_offset != -1) {
4401 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4404 ss_req->last_line = loc->row;
4410 if (!step_to_catch && ss_req->depth == STEP_DEPTH_OVER) {
4413 compute_frame_info (thread, tls);
4415 g_assert (tls->frame_count);
4416 frame = tls->frames [0];
4418 if (!method && frame->il_offset != -1) {
4419 /* FIXME: Sort the table and use a binary search */
4420 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4422 method = frame->method;
4426 ss_start (ss_req, method, sp, info, NULL, tls, step_to_catch);
4432 ss_destroy (SingleStepReq *req)
4435 g_assert (ss_req == req);
4444 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
4445 MonoContext *catch_ctx)
4451 DebuggerTlsData *tls = NULL;
4453 if (thread_to_tls != NULL) {
4454 MonoInternalThread *thread = mono_thread_internal_current ();
4456 mono_loader_lock ();
4457 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4458 mono_loader_unlock ();
4460 if (tls && tls->abort_requested)
4462 if (tls && tls->disable_breakpoints)
4466 memset (&ei, 0, sizeof (EventInfo));
4468 /* Just-In-Time debugging */
4470 if (agent_config.onuncaught && !inited) {
4471 finish_agent_init (FALSE);
4474 * Send an unsolicited EXCEPTION event with a dummy request id.
4476 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4477 ei.exc = (MonoObject*)exc;
4478 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4481 } else if (agent_config.onthrow && !inited) {
4483 gboolean found = FALSE;
4485 for (l = agent_config.onthrow; l; l = l->next) {
4486 char *ex_type = l->data;
4487 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
4489 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
4496 finish_agent_init (FALSE);
4499 * Send an unsolicited EXCEPTION event with a dummy request id.
4501 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4502 ei.exc = (MonoObject*)exc;
4503 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4511 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
4513 ei.exc = (MonoObject*)exc;
4514 ei.caught = catch_ctx != NULL;
4516 mono_loader_lock ();
4517 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
4518 mono_loader_unlock ();
4520 if (tls && catch_ctx) {
4521 tls->catch_ctx = *catch_ctx;
4522 tls->has_catch_ctx = TRUE;
4525 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
4528 tls->has_catch_ctx = FALSE;
4532 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4534 DebuggerTlsData *tls;
4539 tls = TlsGetValue (debugger_tls_id);
4544 * We're about to invoke an exception filter during the first pass of exception handling.
4546 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
4547 * 'orig_ctx' is the context where the exception has been thrown.
4550 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
4552 * If we're stopped in Filter(), normal stack unwinding would first unwind to
4553 * the call site (line 37) and then continue to Main(), but it would never
4554 * include the throw site (line 32).
4556 * Since exception filters are invoked during the first pass of exception handling,
4557 * the stack frames of the throw site are still intact, so we should include them
4560 * We do this here by saving the context of the throw site in 'tls->filter_state'.
4562 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
4563 * but report the location of the 'throw' to the user.
4567 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
4571 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4573 DebuggerTlsData *tls;
4578 tls = TlsGetValue (debugger_tls_id);
4582 tls->filter_state.valid = FALSE;
4586 * buffer_add_value_full:
4588 * Add the encoding of the value at ADDR described by T to the buffer.
4589 * AS_VTYPE determines whenever to treat primitive types as primitive types or
4593 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
4599 g_assert (*(void**)addr);
4600 addr = *(void**)addr;
4605 case MONO_TYPE_BOOLEAN:
4608 case MONO_TYPE_CHAR:
4628 case MONO_TYPE_VOID:
4629 buffer_add_byte (buf, t->type);
4631 case MONO_TYPE_BOOLEAN:
4634 buffer_add_byte (buf, t->type);
4635 buffer_add_int (buf, *(gint8*)addr);
4637 case MONO_TYPE_CHAR:
4640 buffer_add_byte (buf, t->type);
4641 buffer_add_int (buf, *(gint16*)addr);
4646 buffer_add_byte (buf, t->type);
4647 buffer_add_int (buf, *(gint32*)addr);
4652 buffer_add_byte (buf, t->type);
4653 buffer_add_long (buf, *(gint64*)addr);
4657 /* Treat it as a vtype */
4659 case MONO_TYPE_PTR: {
4660 gssize val = *(gssize*)addr;
4662 buffer_add_byte (buf, t->type);
4663 buffer_add_long (buf, val);
4667 case MONO_TYPE_STRING:
4668 case MONO_TYPE_SZARRAY:
4669 case MONO_TYPE_OBJECT:
4670 case MONO_TYPE_CLASS:
4671 case MONO_TYPE_ARRAY:
4672 obj = *(MonoObject**)addr;
4675 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
4677 if (obj->vtable->klass->valuetype) {
4678 t = &obj->vtable->klass->byval_arg;
4679 addr = mono_object_unbox (obj);
4681 } else if (obj->vtable->klass->rank) {
4682 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4683 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
4684 buffer_add_byte (buf, MONO_TYPE_CLASS);
4686 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
4688 buffer_add_objid (buf, obj);
4692 case MONO_TYPE_VALUETYPE: {
4696 MonoClass *klass = mono_class_from_mono_type (t);
4698 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
4699 buffer_add_byte (buf, klass->enumtype);
4700 buffer_add_typeid (buf, domain, klass);
4704 while ((f = mono_class_get_fields (klass, &iter))) {
4705 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4707 if (mono_field_is_deleted (f))
4711 buffer_add_int (buf, nfields);
4714 while ((f = mono_class_get_fields (klass, &iter))) {
4715 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4717 if (mono_field_is_deleted (f))
4719 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
4723 case MONO_TYPE_GENERICINST:
4724 if (mono_type_generic_inst_is_valuetype (t)) {
4736 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
4738 buffer_add_value_full (buf, t, addr, domain, FALSE);
4742 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
4745 int type = decode_byte (buf, &buf, limit);
4747 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
4748 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
4749 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
4750 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
4751 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
4752 char *name = mono_type_full_name (t);
4753 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
4755 return ERR_INVALID_ARGUMENT;
4759 case MONO_TYPE_BOOLEAN:
4760 *(guint8*)addr = decode_int (buf, &buf, limit);
4762 case MONO_TYPE_CHAR:
4763 *(gunichar2*)addr = decode_int (buf, &buf, limit);
4766 *(gint8*)addr = decode_int (buf, &buf, limit);
4769 *(guint8*)addr = decode_int (buf, &buf, limit);
4772 *(gint16*)addr = decode_int (buf, &buf, limit);
4775 *(guint16*)addr = decode_int (buf, &buf, limit);
4778 *(gint32*)addr = decode_int (buf, &buf, limit);
4781 *(guint32*)addr = decode_int (buf, &buf, limit);
4784 *(gint64*)addr = decode_long (buf, &buf, limit);
4787 *(guint64*)addr = decode_long (buf, &buf, limit);
4790 *(guint32*)addr = decode_int (buf, &buf, limit);
4793 *(guint64*)addr = decode_long (buf, &buf, limit);
4796 /* We send these as I8, so we get them back as such */
4797 g_assert (type == MONO_TYPE_I8);
4798 *(gssize*)addr = decode_long (buf, &buf, limit);
4800 case MONO_TYPE_GENERICINST:
4801 if (MONO_TYPE_ISSTRUCT (t)) {
4802 /* The client sends these as a valuetype */
4810 /* We send these as vtypes, so we get them back as such */
4811 g_assert (type == MONO_TYPE_VALUETYPE);
4814 case MONO_TYPE_VALUETYPE: {
4815 gboolean is_enum = decode_byte (buf, &buf, limit);
4819 gpointer iter = NULL;
4822 /* Enums are sent as a normal vtype */
4824 return ERR_NOT_IMPLEMENTED;
4825 klass = decode_typeid (buf, &buf, limit, &d, &err);
4829 if (klass != mono_class_from_mono_type (t))
4830 return ERR_INVALID_ARGUMENT;
4832 nfields = decode_int (buf, &buf, limit);
4833 while ((f = mono_class_get_fields (klass, &iter))) {
4834 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
4836 if (mono_field_is_deleted (f))
4838 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
4843 g_assert (nfields == 0);
4848 if (MONO_TYPE_IS_REFERENCE (t)) {
4849 if (type == MONO_TYPE_OBJECT) {
4850 int objid = decode_objid (buf, &buf, limit);
4854 err = get_object (objid, (MonoObject**)&obj);
4858 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
4859 return ERR_INVALID_ARGUMENT;
4860 if (obj && obj->vtable->domain != domain)
4861 return ERR_INVALID_ARGUMENT;
4863 mono_gc_wbarrier_generic_store (addr, obj);
4864 } else if (type == VALUE_TYPE_ID_NULL) {
4865 *(MonoObject**)addr = NULL;
4867 return ERR_INVALID_ARGUMENT;
4881 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
4888 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4889 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4892 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4893 reg_val = mono_arch_context_get_int_reg (ctx, reg);
4895 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
4897 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4898 addr = mono_arch_context_get_int_reg (ctx, reg);
4899 addr += (gint32)var->offset;
4901 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4903 buffer_add_value_full (buf, t, addr, domain, as_vtype);
4905 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4909 g_assert_not_reached ();
4914 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
4920 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4921 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
4923 if (MONO_TYPE_IS_REFERENCE (t))
4924 size = sizeof (gpointer);
4926 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
4929 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
4930 // FIXME: Can't set registers, so we disable linears
4933 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
4934 addr = mono_arch_context_get_int_reg (ctx, reg);
4935 addr += (gint32)var->offset;
4937 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
4939 // FIXME: Write barriers
4940 memcpy (addr, val, size);
4942 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
4946 g_assert_not_reached ();
4951 clear_event_request (int req_id, int etype)
4955 mono_loader_lock ();
4956 for (i = 0; i < event_requests->len; ++i) {
4957 EventRequest *req = g_ptr_array_index (event_requests, i);
4959 if (req->id == req_id && req->event_kind == etype) {
4960 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4961 clear_breakpoint (req->info);
4962 if (req->event_kind == EVENT_KIND_STEP)
4963 ss_destroy (req->info);
4964 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
4965 clear_breakpoint (req->info);
4966 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
4967 clear_breakpoint (req->info);
4968 g_ptr_array_remove_index_fast (event_requests, i);
4973 mono_loader_unlock ();
4977 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
4979 if (req->event_kind == EVENT_KIND_BREAKPOINT)
4980 return breakpoint_matches_assembly (req->info, assembly);
4984 for (i = 0; i < req->nmodifiers; ++i) {
4985 Modifier *m = &req->modifiers [i];
4987 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
4989 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
4990 for (j = 0; m->data.assemblies [j]; ++j)
4991 if (m->data.assemblies [j] == assembly)
5001 * clear_event_requests_for_assembly:
5003 * Clear all events requests which reference ASSEMBLY.
5006 clear_event_requests_for_assembly (MonoAssembly *assembly)
5011 mono_loader_lock ();
5015 for (i = 0; i < event_requests->len; ++i) {
5016 EventRequest *req = g_ptr_array_index (event_requests, i);
5018 if (event_req_matches_assembly (req, assembly)) {
5019 clear_event_request (req->id, req->event_kind);
5025 mono_loader_unlock ();
5029 * type_comes_from_assembly:
5031 * GHRFunc that returns TRUE if klass comes from assembly
5034 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5036 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5040 * clear_types_for_assembly:
5042 * Clears types from loaded_classes for a given assembly
5045 clear_types_for_assembly (MonoAssembly *assembly)
5047 MonoDomain *domain = mono_domain_get ();
5048 AgentDomainInfo *info = NULL;
5050 mono_loader_lock ();
5051 info = get_agent_domain_info (domain);
5052 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5053 mono_loader_unlock ();
5057 add_thread (gpointer key, gpointer value, gpointer user_data)
5059 MonoInternalThread *thread = value;
5060 Buffer *buf = user_data;
5062 buffer_add_objid (buf, (MonoObject*)thread);
5066 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5068 guint8 *p = invoke->p;
5069 guint8 *end = invoke->endp;
5072 MonoMethodSignature *sig;
5075 MonoObject *this, *res, *exc;
5078 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5082 if (invoke->method) {
5084 * Invoke this method directly, currently only Environment.Exit () is supported.
5087 DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this ? this->vtable->klass->name : "<null>"));
5088 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5089 g_assert_not_reached ();
5092 m = decode_methodid (p, &p, end, &domain, &err);
5095 sig = mono_method_signature (m);
5097 if (m->klass->valuetype)
5098 this_buf = g_alloca (mono_class_instance_size (m->klass));
5100 this_buf = g_alloca (sizeof (MonoObject*));
5101 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5102 /* Should be null */
5103 int type = decode_byte (p, &p, end);
5104 if (type != VALUE_TYPE_ID_NULL)
5105 return ERR_INVALID_ARGUMENT;
5106 memset (this_buf, 0, mono_class_instance_size (m->klass));
5108 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5113 if (!m->klass->valuetype)
5114 this = *(MonoObject**)this_buf;
5118 DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this ? this->vtable->klass->name : "<null>"));
5120 if (this && this->vtable->domain != domain)
5123 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5124 if (!strcmp (m->name, ".ctor")) {
5125 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5126 return ERR_INVALID_ARGUMENT;
5128 this = mono_object_new (domain, m->klass);
5130 return ERR_INVALID_ARGUMENT;
5134 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5135 return ERR_INVALID_ARGUMENT;
5137 nargs = decode_int (p, &p, end);
5138 if (nargs != sig->param_count)
5139 return ERR_INVALID_ARGUMENT;
5140 /* Use alloca to get gc tracking */
5141 arg_buf = g_alloca (nargs * sizeof (gpointer));
5142 memset (arg_buf, 0, nargs * sizeof (gpointer));
5143 args = g_alloca (nargs * sizeof (gpointer));
5144 for (i = 0; i < nargs; ++i) {
5145 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5146 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5150 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5153 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5154 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5157 args [i] = arg_buf [i];
5164 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5165 tls->disable_breakpoints = TRUE;
5167 tls->disable_breakpoints = FALSE;
5170 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5172 /* FIXME: Move this to arch specific code */
5173 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5174 if (invoke->has_ctx) {
5177 lmf_addr = mono_get_lmf_addr ();
5180 memset (&ext, 0, sizeof (ext));
5182 ext.lmf.previous_lmf = *(lmf_addr);
5183 /* Mark that this is a MonoLMFExt */
5184 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5185 ext.lmf.rsp = (gssize)&ext;
5186 #elif defined(TARGET_X86)
5187 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5188 /* Mark that this is a MonoLMFExt */
5189 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5190 ext.lmf.ebp = (gssize)&ext;
5191 #elif defined(TARGET_ARM)
5192 ext.lmf.previous_lmf = *(lmf_addr);
5193 /* Mark that this is a MonoLMFExt */
5194 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5195 #elif defined(TARGET_POWERPC)
5196 ext.lmf.previous_lmf = *(lmf_addr);
5197 /* Mark that this is a MonoLMFExt */
5198 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5199 ext.lmf.ebp = (gssize)&ext;
5201 g_assert_not_reached ();
5204 ext.debugger_invoke = TRUE;
5205 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5207 mono_set_lmf ((MonoLMF*)&ext);
5211 if (m->klass->valuetype)
5212 res = mono_runtime_invoke (m, this_buf, args, &exc);
5214 res = mono_runtime_invoke (m, this, args, &exc);
5216 buffer_add_byte (buf, 0);
5217 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5219 buffer_add_byte (buf, 1);
5220 if (sig->ret->type == MONO_TYPE_VOID) {
5221 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5222 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5225 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5226 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5227 buffer_add_value (buf, sig->ret, &res, domain);
5228 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5229 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5231 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &res, domain);
5233 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5236 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5243 tls->disable_breakpoints = FALSE;
5245 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5246 if (invoke->has_ctx)
5247 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5250 // FIXME: byref arguments
5258 * Invoke the method given by tls->pending_invoke in the current thread.
5261 invoke_method (void)
5263 DebuggerTlsData *tls;
5268 static void (*restore_context) (void *);
5269 MonoContext restore_ctx;
5271 if (!restore_context)
5272 restore_context = mono_get_restore_context ();
5274 tls = TlsGetValue (debugger_tls_id);
5278 * Store the `InvokeData *' in `tls->invoke' until we're done with
5279 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5282 mono_loader_lock ();
5284 invoke = tls->pending_invoke;
5286 tls->pending_invoke = NULL;
5288 invoke->last_invoke = tls->invoke;
5289 tls->invoke = invoke;
5291 mono_loader_unlock ();
5293 tls->frames_up_to_date = FALSE;
5297 buffer_init (&buf, 128);
5299 err = do_invoke_method (tls, &buf, invoke);
5301 /* Start suspending before sending the reply */
5302 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5305 send_reply_packet (id, err, &buf);
5309 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5311 if (invoke->has_ctx)
5312 save_thread_context (&restore_ctx);
5314 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5315 g_assert (tls->resume_count);
5316 tls->resume_count -= invoke->suspend_count;
5319 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5322 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5324 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5325 * after the mono_runtime_invoke() already returned, but it doesn't matter
5326 * because we reset the abort here.
5329 mono_loader_lock ();
5331 if (tls->abort_requested)
5332 mono_thread_internal_reset_abort (tls->thread);
5334 tls->invoke = tls->invoke->last_invoke;
5335 tls->abort_requested = FALSE;
5337 mono_loader_unlock ();
5346 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5348 MonoThread *thread = value;
5349 DebuggerTlsData *tls;
5352 mono_loader_lock ();
5353 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5355 res = tls->really_suspended;
5356 mono_loader_unlock ();
5362 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
5365 case CMD_VM_VERSION: {
5366 char *build_info, *version;
5368 build_info = mono_get_runtime_build_info ();
5369 version = g_strdup_printf ("mono %s", build_info);
5371 buffer_add_string (buf, version); /* vm version */
5372 buffer_add_int (buf, MAJOR_VERSION);
5373 buffer_add_int (buf, MINOR_VERSION);
5374 g_free (build_info);
5378 case CMD_VM_SET_PROTOCOL_VERSION: {
5379 major_version = decode_int (p, &p, end);
5380 minor_version = decode_int (p, &p, end);
5381 protocol_version_set = TRUE;
5382 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
5385 case CMD_VM_ALL_THREADS: {
5387 mono_loader_lock ();
5388 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
5389 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
5390 mono_loader_unlock ();
5393 case CMD_VM_SUSPEND:
5395 wait_for_suspend ();
5398 if (suspend_count == 0)
5399 return ERR_NOT_SUSPENDED;
5402 case CMD_VM_DISPOSE:
5403 /* Clear all event requests */
5404 mono_loader_lock ();
5405 while (event_requests->len > 0) {
5406 EventRequest *req = g_ptr_array_index (event_requests, 0);
5408 clear_event_request (req->id, req->event_kind);
5410 mono_loader_unlock ();
5412 while (suspend_count > 0)
5414 disconnected = TRUE;
5415 vm_start_event_sent = FALSE;
5418 MonoInternalThread *thread;
5419 DebuggerTlsData *tls;
5420 MonoClass *env_class;
5421 MonoMethod *exit_method;
5425 exit_code = decode_int (p, &p, end);
5427 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
5429 /* Have to send a reply before exiting */
5430 send_reply_packet (id, 0, buf);
5432 /* Clear all event requests */
5433 mono_loader_lock ();
5434 while (event_requests->len > 0) {
5435 EventRequest *req = g_ptr_array_index (event_requests, 0);
5437 clear_event_request (req->id, req->event_kind);
5439 mono_loader_unlock ();
5442 * The JDWP documentation says that the shutdown is not orderly. It doesn't
5443 * specify whenever a VM_DEATH event is sent. We currently do an orderly
5444 * shutdown by hijacking a thread to execute Environment.Exit (). This is
5445 * better than doing the shutdown ourselves, since it avoids various races.
5449 wait_for_suspend ();
5451 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
5453 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
5455 mono_loader_lock ();
5456 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
5457 mono_loader_unlock ();
5459 if (thread && exit_method) {
5460 mono_loader_lock ();
5461 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5462 mono_loader_unlock ();
5464 args = g_new0 (gpointer, 1);
5465 args [0] = g_malloc (sizeof (int));
5466 *(int*)(args [0]) = exit_code;
5468 tls->pending_invoke = g_new0 (InvokeData, 1);
5469 tls->pending_invoke->method = exit_method;
5470 tls->pending_invoke->args = args;
5472 while (suspend_count > 0)
5476 * No thread found, do it ourselves.
5477 * FIXME: This can race with normal shutdown etc.
5479 while (suspend_count > 0)
5482 mono_runtime_set_shutting_down ();
5484 mono_threads_set_shutting_down ();
5486 /* Suspend all managed threads since the runtime is going away */
5487 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
5488 mono_thread_suspend_all_other_threads ();
5489 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
5490 mono_runtime_quit ();
5492 shutdown (conn_fd, SD_BOTH);
5494 shutdown (conn_fd, SHUT_RDWR);
5496 DEBUG(1, fprintf (log_file, "Exiting...\n"));
5502 case CMD_VM_INVOKE_METHOD: {
5503 int objid = decode_objid (p, &p, end);
5505 DebuggerTlsData *tls;
5508 err = get_object (objid, (MonoObject**)&thread);
5512 flags = decode_int (p, &p, end);
5514 // Wait for suspending if it already started
5516 wait_for_suspend ();
5517 if (!is_suspended ())
5518 return ERR_NOT_SUSPENDED;
5520 mono_loader_lock ();
5521 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5522 mono_loader_unlock ();
5525 if (!tls->really_suspended)
5526 /* The thread is still running native code, can't do invokes */
5527 return ERR_NOT_SUSPENDED;
5530 * Store the invoke data into tls, the thread will execute it after it is
5533 if (tls->pending_invoke)
5535 tls->pending_invoke = g_new0 (InvokeData, 1);
5536 tls->pending_invoke->id = id;
5537 tls->pending_invoke->flags = flags;
5538 tls->pending_invoke->p = g_malloc (end - p);
5539 memcpy (tls->pending_invoke->p, p, end - p);
5540 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
5541 tls->pending_invoke->suspend_count = suspend_count;
5543 if (flags & INVOKE_FLAG_SINGLE_THREADED)
5544 resume_thread (THREAD_TO_INTERNAL (thread));
5549 case CMD_VM_ABORT_INVOKE: {
5550 int objid = decode_objid (p, &p, end);
5552 DebuggerTlsData *tls;
5555 err = get_object (objid, (MonoObject**)&thread);
5559 invoke_id = decode_int (p, &p, end);
5561 mono_loader_lock ();
5562 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
5565 if (tls->abort_requested) {
5566 mono_loader_unlock ();
5571 * Check whether we're still inside the mono_runtime_invoke() and that it's
5572 * actually the correct invocation.
5574 * Careful, we do not stop the thread that's doing the invocation, so we can't
5575 * inspect its stack. However, invoke_method() also acquires the loader lock
5576 * when it's done, so we're safe here.
5580 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
5581 mono_loader_unlock ();
5582 return ERR_NO_INVOCATION;
5585 tls->abort_requested = TRUE;
5587 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
5588 mono_loader_unlock ();
5593 return ERR_NOT_IMPLEMENTED;
5600 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5606 case CMD_EVENT_REQUEST_SET: {
5608 int i, event_kind, suspend_policy, nmodifiers, mod;
5611 MonoThread *step_thread;
5612 int size = 0, depth = 0, step_thread_id = 0;
5615 event_kind = decode_byte (p, &p, end);
5616 suspend_policy = decode_byte (p, &p, end);
5617 nmodifiers = decode_byte (p, &p, end);
5619 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
5620 req->id = InterlockedIncrement (&event_request_id);
5621 req->event_kind = event_kind;
5622 req->suspend_policy = suspend_policy;
5623 req->nmodifiers = nmodifiers;
5626 for (i = 0; i < nmodifiers; ++i) {
5627 mod = decode_byte (p, &p, end);
5629 req->modifiers [i].kind = mod;
5630 if (mod == MOD_KIND_COUNT) {
5631 req->modifiers [i].data.count = decode_int (p, &p, end);
5632 } else if (mod == MOD_KIND_LOCATION_ONLY) {
5633 method = decode_methodid (p, &p, end, &domain, &err);
5636 location = decode_long (p, &p, end);
5637 } else if (mod == MOD_KIND_STEP) {
5638 step_thread_id = decode_id (p, &p, end);
5639 size = decode_int (p, &p, end);
5640 depth = decode_int (p, &p, end);
5641 } else if (mod == MOD_KIND_THREAD_ONLY) {
5642 int id = decode_id (p, &p, end);
5644 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
5649 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
5650 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
5654 req->modifiers [i].caught = decode_byte (p, &p, end);
5655 req->modifiers [i].uncaught = decode_byte (p, &p, end);
5656 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : ""));
5658 req->modifiers [i].data.exc_class = exc_class;
5660 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
5662 return ERR_INVALID_ARGUMENT;
5665 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
5666 int n = decode_int (p, &p, end);
5669 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
5670 for (j = 0; j < n; ++j) {
5671 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
5673 g_free (req->modifiers [i].data.assemblies);
5679 return ERR_NOT_IMPLEMENTED;
5683 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5686 req->info = set_breakpoint (method, location, req, &error);
5687 if (!mono_error_ok (&error)) {
5689 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
5690 mono_error_cleanup (&error);
5691 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
5693 } else if (req->event_kind == EVENT_KIND_STEP) {
5694 g_assert (step_thread_id);
5696 err = get_object (step_thread_id, (MonoObject**)&step_thread);
5702 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
5707 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
5708 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
5709 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
5710 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
5711 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
5713 if (req->nmodifiers) {
5715 return ERR_NOT_IMPLEMENTED;
5719 mono_loader_lock ();
5720 g_ptr_array_add (event_requests, req);
5721 mono_loader_unlock ();
5723 buffer_add_int (buf, req->id);
5726 case CMD_EVENT_REQUEST_CLEAR: {
5727 int etype = decode_byte (p, &p, end);
5728 int req_id = decode_int (p, &p, end);
5730 // FIXME: Make a faster mapping from req_id to request
5731 mono_loader_lock ();
5732 clear_event_request (req_id, etype);
5733 mono_loader_unlock ();
5736 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
5739 mono_loader_lock ();
5741 while (i < event_requests->len) {
5742 EventRequest *req = g_ptr_array_index (event_requests, i);
5744 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
5745 clear_breakpoint (req->info);
5747 g_ptr_array_remove_index_fast (event_requests, i);
5753 mono_loader_unlock ();
5757 return ERR_NOT_IMPLEMENTED;
5764 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5770 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
5771 buffer_add_domainid (buf, mono_get_root_domain ());
5774 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
5775 domain = decode_domainid (p, &p, end, NULL, &err);
5778 buffer_add_string (buf, domain->friendly_name);
5781 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
5786 domain = decode_domainid (p, &p, end, NULL, &err);
5789 mono_loader_lock ();
5791 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5794 buffer_add_int (buf, count);
5795 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
5797 buffer_add_assemblyid (buf, domain, ass);
5799 mono_loader_unlock ();
5802 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
5803 domain = decode_domainid (p, &p, end, NULL, &err);
5807 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
5810 case CMD_APPDOMAIN_GET_CORLIB: {
5811 domain = decode_domainid (p, &p, end, NULL, &err);
5815 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
5818 case CMD_APPDOMAIN_CREATE_STRING: {
5822 domain = decode_domainid (p, &p, end, NULL, &err);
5825 s = decode_string (p, &p, end);
5827 o = mono_string_new (domain, s);
5828 buffer_add_objid (buf, (MonoObject*)o);
5831 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
5833 MonoDomain *domain2;
5836 domain = decode_domainid (p, &p, end, NULL, &err);
5839 klass = decode_typeid (p, &p, end, &domain2, &err);
5844 g_assert (domain == domain2);
5846 o = mono_object_new (domain, klass);
5848 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
5852 buffer_add_objid (buf, o);
5856 return ERR_NOT_IMPLEMENTED;
5863 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5869 ass = decode_assemblyid (p, &p, end, &domain, &err);
5874 case CMD_ASSEMBLY_GET_LOCATION: {
5875 buffer_add_string (buf, mono_image_get_filename (ass->image));
5878 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
5882 if (ass->image->dynamic) {
5883 buffer_add_id (buf, 0);
5885 token = mono_image_get_entry_point (ass->image);
5887 buffer_add_id (buf, 0);
5889 m = mono_get_method (ass->image, token, NULL);
5890 buffer_add_methodid (buf, domain, m);
5895 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
5896 buffer_add_moduleid (buf, domain, ass->image);
5899 case CMD_ASSEMBLY_GET_OBJECT: {
5900 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
5901 buffer_add_objid (buf, o);
5904 case CMD_ASSEMBLY_GET_TYPE: {
5905 char *s = decode_string (p, &p, end);
5906 gboolean ignorecase = decode_byte (p, &p, end);
5907 MonoTypeNameParse info;
5909 gboolean type_resolve;
5911 if (!mono_reflection_parse_type (s, &info)) {
5914 if (info.assembly.name)
5916 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
5918 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
5919 mono_reflection_free_type_info (&info);
5924 case CMD_ASSEMBLY_GET_NAME: {
5926 MonoAssembly *mass = ass;
5928 name = g_strdup_printf (
5929 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
5931 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
5932 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
5933 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
5934 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
5936 buffer_add_string (buf, name);
5941 return ERR_NOT_IMPLEMENTED;
5948 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5954 case CMD_MODULE_GET_INFO: {
5955 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
5958 basename = g_path_get_basename (image->name);
5959 buffer_add_string (buf, basename); // name
5960 buffer_add_string (buf, image->module_name); // scopename
5961 buffer_add_string (buf, image->name); // fqname
5962 buffer_add_string (buf, mono_image_get_guid (image)); // guid
5963 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
5968 return ERR_NOT_IMPLEMENTED;
5975 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
5977 if (val && val->vtable->klass == mono_defaults.monotype_class) {
5978 /* Special case these so the client doesn't have to handle Type objects */
5980 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
5981 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
5982 } else if (MONO_TYPE_IS_REFERENCE (t))
5983 buffer_add_value (buf, t, &val, domain);
5985 buffer_add_value (buf, t, mono_object_unbox (val), domain);
5989 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
5995 buffer_add_int (buf, 0);
5999 for (i = 0; i < cinfo->num_attrs; ++i) {
6000 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6003 buffer_add_int (buf, nattrs);
6005 for (i = 0; i < cinfo->num_attrs; ++i) {
6006 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6007 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6008 MonoArray *typed_args, *named_args;
6010 CattrNamedArg *arginfo;
6012 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6014 buffer_add_methodid (buf, domain, attr->ctor);
6018 buffer_add_int (buf, mono_array_length (typed_args));
6019 for (j = 0; j < mono_array_length (typed_args); ++j) {
6020 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6022 t = mono_method_signature (attr->ctor)->params [j];
6024 buffer_add_cattr_arg (buf, t, domain, val);
6027 buffer_add_int (buf, 0);
6032 buffer_add_int (buf, mono_array_length (named_args));
6034 for (j = 0; j < mono_array_length (named_args); ++j) {
6035 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
6037 if (arginfo [j].prop) {
6038 buffer_add_byte (buf, 0x54);
6039 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6040 } else if (arginfo [j].field) {
6041 buffer_add_byte (buf, 0x53);
6043 g_assert_not_reached ();
6046 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6049 buffer_add_int (buf, 0);
6056 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6066 case CMD_TYPE_GET_INFO: {
6067 buffer_add_string (buf, klass->name_space);
6068 buffer_add_string (buf, klass->name);
6070 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
6071 buffer_add_string (buf, name);
6073 buffer_add_assemblyid (buf, domain, klass->image->assembly);
6074 buffer_add_moduleid (buf, domain, klass->image);
6075 buffer_add_typeid (buf, domain, klass->parent);
6076 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
6077 buffer_add_typeid (buf, domain, klass->element_class);
6079 buffer_add_id (buf, 0);
6080 buffer_add_int (buf, klass->type_token);
6081 buffer_add_byte (buf, klass->rank);
6082 buffer_add_int (buf, klass->flags);
6084 type = &klass->byval_arg;
6085 // FIXME: Can't decide whenever a class represents a byref type
6088 if (type->type == MONO_TYPE_PTR)
6090 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
6092 if (type->type == MONO_TYPE_VALUETYPE)
6094 if (klass->enumtype)
6096 buffer_add_byte (buf, b);
6099 while ((nested = mono_class_get_nested_types (klass, &iter)))
6101 buffer_add_int (buf, nnested);
6103 while ((nested = mono_class_get_nested_types (klass, &iter)))
6104 buffer_add_typeid (buf, domain, nested);
6107 case CMD_TYPE_GET_METHODS: {
6110 gpointer iter = NULL;
6113 mono_class_setup_methods (klass);
6115 nmethods = mono_class_num_methods (klass);
6117 buffer_add_int (buf, nmethods);
6119 while ((m = mono_class_get_methods (klass, &iter))) {
6120 buffer_add_methodid (buf, domain, m);
6123 g_assert (i == nmethods);
6126 case CMD_TYPE_GET_FIELDS: {
6129 gpointer iter = NULL;
6132 nfields = mono_class_num_fields (klass);
6134 buffer_add_int (buf, nfields);
6136 while ((f = mono_class_get_fields (klass, &iter))) {
6137 buffer_add_fieldid (buf, domain, f);
6138 buffer_add_string (buf, f->name);
6139 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
6140 buffer_add_int (buf, f->type->attrs);
6143 g_assert (i == nfields);
6146 case CMD_TYPE_GET_PROPERTIES: {
6149 gpointer iter = NULL;
6152 nprops = mono_class_num_properties (klass);
6154 buffer_add_int (buf, nprops);
6156 while ((p = mono_class_get_properties (klass, &iter))) {
6157 buffer_add_propertyid (buf, domain, p);
6158 buffer_add_string (buf, p->name);
6159 buffer_add_methodid (buf, domain, p->get);
6160 buffer_add_methodid (buf, domain, p->set);
6161 buffer_add_int (buf, p->attrs);
6164 g_assert (i == nprops);
6167 case CMD_TYPE_GET_CATTRS: {
6168 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
6169 MonoCustomAttrInfo *cinfo;
6171 cinfo = mono_custom_attrs_from_class (klass);
6173 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6176 case CMD_TYPE_GET_FIELD_CATTRS: {
6177 MonoClass *attr_klass;
6178 MonoCustomAttrInfo *cinfo;
6179 MonoClassField *field;
6181 field = decode_fieldid (p, &p, end, NULL, &err);
6184 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6188 cinfo = mono_custom_attrs_from_field (klass, field);
6190 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6193 case CMD_TYPE_GET_PROPERTY_CATTRS: {
6194 MonoClass *attr_klass;
6195 MonoCustomAttrInfo *cinfo;
6198 prop = decode_propertyid (p, &p, end, NULL, &err);
6201 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6205 cinfo = mono_custom_attrs_from_property (klass, prop);
6207 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6210 case CMD_TYPE_GET_VALUES:
6211 case CMD_TYPE_GET_VALUES_2: {
6218 MonoThread *thread_obj;
6219 MonoInternalThread *thread = NULL;
6220 guint32 special_static_type;
6222 if (command == CMD_TYPE_GET_VALUES_2) {
6223 int objid = decode_objid (p, &p, end);
6226 err = get_object (objid, (MonoObject**)&thread_obj);
6230 thread = THREAD_TO_INTERNAL (thread_obj);
6233 len = decode_int (p, &p, end);
6234 for (i = 0; i < len; ++i) {
6235 f = decode_fieldid (p, &p, end, NULL, &err);
6239 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6240 return ERR_INVALID_FIELDID;
6241 special_static_type = mono_class_field_get_special_static_type (f);
6242 if (special_static_type != SPECIAL_STATIC_NONE) {
6243 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
6244 return ERR_INVALID_FIELDID;
6247 /* Check that the field belongs to the object */
6249 for (k = klass; k; k = k->parent) {
6250 if (k == f->parent) {
6256 return ERR_INVALID_FIELDID;
6258 vtable = mono_class_vtable (domain, f->parent);
6259 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6260 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
6261 buffer_add_value (buf, f->type, val, domain);
6266 case CMD_TYPE_SET_VALUES: {
6274 len = decode_int (p, &p, end);
6275 for (i = 0; i < len; ++i) {
6276 f = decode_fieldid (p, &p, end, NULL, &err);
6280 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6281 return ERR_INVALID_FIELDID;
6282 if (mono_class_field_is_special_static (f))
6283 return ERR_INVALID_FIELDID;
6285 /* Check that the field belongs to the object */
6287 for (k = klass; k; k = k->parent) {
6288 if (k == f->parent) {
6294 return ERR_INVALID_FIELDID;
6296 // FIXME: Check for literal/const
6298 vtable = mono_class_vtable (domain, f->parent);
6299 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6300 err = decode_value (f->type, domain, val, p, &p, end);
6305 if (MONO_TYPE_IS_REFERENCE (f->type))
6306 mono_field_static_set_value (vtable, f, *(gpointer*)val);
6308 mono_field_static_set_value (vtable, f, val);
6313 case CMD_TYPE_GET_OBJECT: {
6314 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
6315 buffer_add_objid (buf, o);
6318 case CMD_TYPE_GET_SOURCE_FILES:
6319 case CMD_TYPE_GET_SOURCE_FILES_2: {
6320 gpointer iter = NULL;
6322 char *source_file, *base;
6326 files = g_ptr_array_new ();
6328 while ((method = mono_class_get_methods (klass, &iter))) {
6329 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6332 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
6336 for (i = 0; i < files->len; ++i)
6337 if (!strcmp (g_ptr_array_index (files, i), source_file))
6339 if (i == files->len)
6340 g_ptr_array_add (files, g_strdup (source_file));
6341 g_free (source_file);
6345 buffer_add_int (buf, files->len);
6346 for (i = 0; i < files->len; ++i) {
6347 source_file = g_ptr_array_index (files, i);
6348 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
6349 buffer_add_string (buf, source_file);
6351 base = g_path_get_basename (source_file);
6352 buffer_add_string (buf, base);
6355 g_free (source_file);
6357 g_ptr_array_free (files, TRUE);
6360 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
6361 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
6365 if (mono_class_is_assignable_from (klass, oklass))
6366 buffer_add_byte (buf, 1);
6368 buffer_add_byte (buf, 0);
6372 return ERR_NOT_IMPLEMENTED;
6379 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6382 MonoDomain *old_domain;
6386 klass = decode_typeid (p, &p, end, &domain, &err);
6390 old_domain = mono_domain_get ();
6392 mono_domain_set (domain, TRUE);
6394 err = type_commands_internal (command, klass, domain, p, end, buf);
6396 mono_domain_set (old_domain, TRUE);
6402 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6404 MonoMethodHeader *header;
6407 case CMD_METHOD_GET_NAME: {
6408 buffer_add_string (buf, method->name);
6411 case CMD_METHOD_GET_DECLARING_TYPE: {
6412 buffer_add_typeid (buf, domain, method->klass);
6415 case CMD_METHOD_GET_DEBUG_INFO: {
6416 MonoDebugMethodInfo *minfo;
6418 int i, n_il_offsets;
6422 header = mono_method_get_header (method);
6424 buffer_add_int (buf, 0);
6425 buffer_add_string (buf, "");
6426 buffer_add_int (buf, 0);
6430 minfo = mono_debug_lookup_method (method);
6432 buffer_add_int (buf, header->code_size);
6433 buffer_add_string (buf, "");
6434 buffer_add_int (buf, 0);
6435 mono_metadata_free_mh (header);
6439 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
6440 buffer_add_int (buf, header->code_size);
6441 buffer_add_string (buf, source_file);
6442 buffer_add_int (buf, n_il_offsets);
6443 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
6444 for (i = 0; i < n_il_offsets; ++i) {
6445 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
6446 buffer_add_int (buf, il_offsets [i]);
6447 buffer_add_int (buf, line_numbers [i]);
6449 g_free (source_file);
6450 g_free (il_offsets);
6451 g_free (line_numbers);
6452 mono_metadata_free_mh (header);
6455 case CMD_METHOD_GET_PARAM_INFO: {
6456 MonoMethodSignature *sig = mono_method_signature (method);
6460 /* FIXME: mono_class_from_mono_type () and byrefs */
6462 /* FIXME: Use a smaller encoding */
6463 buffer_add_int (buf, sig->call_convention);
6464 buffer_add_int (buf, sig->param_count);
6465 buffer_add_int (buf, sig->generic_param_count);
6466 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
6467 for (i = 0; i < sig->param_count; ++i) {
6469 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
6472 /* Emit parameter names */
6473 names = g_new (char *, sig->param_count);
6474 mono_method_get_param_names (method, (const char **) names);
6475 for (i = 0; i < sig->param_count; ++i)
6476 buffer_add_string (buf, names [i]);
6481 case CMD_METHOD_GET_LOCALS_INFO: {
6482 int i, j, num_locals;
6483 MonoDebugLocalsInfo *locals;
6485 header = mono_method_get_header (method);
6488 buffer_add_int (buf, header->num_locals);
6491 for (i = 0; i < header->num_locals; ++i)
6492 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
6495 locals = mono_debug_lookup_locals (method);
6497 num_locals = locals->num_locals;
6500 for (i = 0; i < header->num_locals; ++i) {
6501 for (j = 0; j < num_locals; ++j)
6502 if (locals->locals [j].index == i)
6505 buffer_add_string (buf, locals->locals [j].name);
6507 buffer_add_string (buf, "");
6511 for (i = 0; i < header->num_locals; ++i) {
6512 for (j = 0; j < num_locals; ++j)
6513 if (locals->locals [j].index == i)
6515 if (j < num_locals && locals->locals [j].block) {
6516 buffer_add_int (buf, locals->locals [j].block->start_offset);
6517 buffer_add_int (buf, locals->locals [j].block->end_offset);
6519 buffer_add_int (buf, 0);
6520 buffer_add_int (buf, header->code_size);
6523 mono_metadata_free_mh (header);
6526 mono_debug_symfile_free_locals (locals);
6530 case CMD_METHOD_GET_INFO:
6531 buffer_add_int (buf, method->flags);
6532 buffer_add_int (buf, method->iflags);
6533 buffer_add_int (buf, method->token);
6535 case CMD_METHOD_GET_BODY: {
6538 header = mono_method_get_header (method);
6540 buffer_add_int (buf, 0);
6542 buffer_add_int (buf, header->code_size);
6543 for (i = 0; i < header->code_size; ++i)
6544 buffer_add_byte (buf, header->code [i]);
6546 mono_metadata_free_mh (header);
6549 case CMD_METHOD_RESOLVE_TOKEN: {
6550 guint32 token = decode_int (p, &p, end);
6553 switch (mono_metadata_token_code (token)) {
6554 case MONO_TOKEN_STRING: {
6558 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
6561 s2 = mono_string_to_utf8 (s);
6563 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6564 buffer_add_string (buf, s2);
6570 MonoClass *handle_class;
6572 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6573 val = mono_method_get_wrapper_data (method, token);
6574 handle_class = mono_method_get_wrapper_data (method, token + 1);
6576 if (handle_class == NULL) {
6577 // Can't figure out the token type
6578 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
6582 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
6586 if (handle_class == mono_defaults.typehandle_class) {
6587 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
6588 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
6589 buffer_add_typeid (buf, domain, (MonoClass *) val);
6591 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
6592 } else if (handle_class == mono_defaults.fieldhandle_class) {
6593 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
6594 buffer_add_fieldid (buf, domain, val);
6595 } else if (handle_class == mono_defaults.methodhandle_class) {
6596 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
6597 buffer_add_methodid (buf, domain, val);
6598 } else if (handle_class == mono_defaults.string_class) {
6601 s = mono_string_to_utf8 (val);
6602 buffer_add_byte (buf, TOKEN_TYPE_STRING);
6603 buffer_add_string (buf, s);
6606 g_assert_not_reached ();
6614 return ERR_NOT_IMPLEMENTED;
6621 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6624 MonoDomain *old_domain;
6628 method = decode_methodid (p, &p, end, &domain, &err);
6632 old_domain = mono_domain_get ();
6634 mono_domain_set (domain, TRUE);
6636 err = method_commands_internal (command, method, domain, p, end, buf);
6638 mono_domain_set (old_domain, TRUE);
6644 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6646 int objid = decode_objid (p, &p, end);
6648 MonoThread *thread_obj;
6649 MonoInternalThread *thread;
6651 err = get_object (objid, (MonoObject**)&thread_obj);
6655 thread = THREAD_TO_INTERNAL (thread_obj);
6658 case CMD_THREAD_GET_NAME: {
6660 gunichar2 *s = mono_thread_get_name (thread, &name_len);
6663 buffer_add_int (buf, 0);
6668 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
6670 buffer_add_int (buf, len);
6671 buffer_add_data (buf, (guint8*)name, len);
6676 case CMD_THREAD_GET_FRAME_INFO: {
6677 DebuggerTlsData *tls;
6678 int i, start_frame, length;
6680 // Wait for suspending if it already started
6682 wait_for_suspend ();
6683 if (!is_suspended ())
6684 return ERR_NOT_SUSPENDED;
6686 start_frame = decode_int (p, &p, end);
6687 length = decode_int (p, &p, end);
6689 if (start_frame != 0 || length != -1)
6690 return ERR_NOT_IMPLEMENTED;
6692 mono_loader_lock ();
6693 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6694 mono_loader_unlock ();
6697 compute_frame_info (thread, tls);
6699 buffer_add_int (buf, tls->frame_count);
6700 for (i = 0; i < tls->frame_count; ++i) {
6701 buffer_add_int (buf, tls->frames [i]->id);
6702 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
6703 buffer_add_int (buf, tls->frames [i]->il_offset);
6705 * Instead of passing the frame type directly to the client, we associate
6706 * it with the previous frame using a set of flags. This avoids lots of
6707 * conditional code in the client, since a frame whose type isn't
6708 * FRAME_TYPE_MANAGED has no method, location, etc.
6710 buffer_add_byte (buf, tls->frames [i]->flags);
6715 case CMD_THREAD_GET_STATE:
6716 buffer_add_int (buf, thread->state);
6718 case CMD_THREAD_GET_INFO:
6719 buffer_add_byte (buf, thread->threadpool_thread);
6721 case CMD_THREAD_GET_ID:
6722 buffer_add_long (buf, (guint64)(gsize)thread);
6724 case CMD_THREAD_GET_TID:
6725 buffer_add_long (buf, (guint64)thread->tid);
6728 return ERR_NOT_IMPLEMENTED;
6735 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6739 MonoThread *thread_obj;
6740 MonoInternalThread *thread;
6742 DebuggerTlsData *tls;
6744 MonoDebugMethodJitInfo *jit;
6745 MonoDebugVarInfo *var;
6746 MonoMethodSignature *sig;
6748 MonoMethodHeader *header;
6750 objid = decode_objid (p, &p, end);
6751 err = get_object (objid, (MonoObject**)&thread_obj);
6755 thread = THREAD_TO_INTERNAL (thread_obj);
6757 id = decode_id (p, &p, end);
6759 mono_loader_lock ();
6760 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6761 mono_loader_unlock ();
6764 for (i = 0; i < tls->frame_count; ++i) {
6765 if (tls->frames [i]->id == id)
6768 if (i == tls->frame_count)
6769 return ERR_INVALID_FRAMEID;
6771 frame = tls->frames [i];
6773 if (!frame->has_ctx)
6775 return ERR_INVALID_FRAMEID;
6778 frame->jit = mono_debug_find_method (frame->method, frame->domain);
6780 /* This could happen for aot images with no jit debug info */
6781 return ERR_ABSENT_INFORMATION;
6785 sig = mono_method_signature (frame->actual_method);
6788 case CMD_STACK_FRAME_GET_VALUES: {
6789 len = decode_int (p, &p, end);
6790 header = mono_method_get_header (frame->actual_method);
6792 for (i = 0; i < len; ++i) {
6793 pos = decode_int (p, &p, end);
6798 g_assert (pos >= 0 && pos < jit->num_params);
6800 var = &jit->params [pos];
6802 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
6804 g_assert (pos >= 0 && pos < jit->num_locals);
6806 var = &jit->locals [pos];
6808 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
6811 mono_metadata_free_mh (header);
6814 case CMD_STACK_FRAME_GET_THIS: {
6815 if (frame->method->klass->valuetype) {
6816 if (!sig->hasthis) {
6817 MonoObject *p = NULL;
6818 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
6820 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6823 if (!sig->hasthis) {
6824 MonoObject *p = NULL;
6825 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
6827 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
6832 case CMD_STACK_FRAME_SET_VALUES: {
6835 MonoDebugVarInfo *var;
6837 len = decode_int (p, &p, end);
6838 header = mono_method_get_header (frame->actual_method);
6840 for (i = 0; i < len; ++i) {
6841 pos = decode_int (p, &p, end);
6846 g_assert (pos >= 0 && pos < jit->num_params);
6848 t = sig->params [pos];
6849 var = &jit->params [pos];
6851 g_assert (pos >= 0 && pos < jit->num_locals);
6853 t = header->locals [pos];
6854 var = &jit->locals [pos];
6857 if (MONO_TYPE_IS_REFERENCE (t))
6858 val_buf = g_alloca (sizeof (MonoObject*));
6860 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
6861 err = decode_value (t, frame->domain, val_buf, p, &p, end);
6865 set_var (t, var, &frame->ctx, frame->domain, val_buf);
6867 mono_metadata_free_mh (header);
6871 return ERR_NOT_IMPLEMENTED;
6878 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6881 int objid, err, index, len, i, esize;
6884 objid = decode_objid (p, &p, end);
6885 err = get_object (objid, (MonoObject**)&arr);
6890 case CMD_ARRAY_REF_GET_LENGTH:
6891 buffer_add_int (buf, arr->obj.vtable->klass->rank);
6893 buffer_add_int (buf, arr->max_length);
6894 buffer_add_int (buf, 0);
6896 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
6897 buffer_add_int (buf, arr->bounds [i].length);
6898 buffer_add_int (buf, arr->bounds [i].lower_bound);
6902 case CMD_ARRAY_REF_GET_VALUES:
6903 index = decode_int (p, &p, end);
6904 len = decode_int (p, &p, end);
6906 g_assert (index >= 0 && len >= 0);
6907 // Reordered to avoid integer overflow
6908 g_assert (!(index > arr->max_length - len));
6910 esize = mono_array_element_size (arr->obj.vtable->klass);
6911 for (i = index; i < index + len; ++i) {
6912 elem = (gpointer*)((char*)arr->vector + (i * esize));
6913 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
6916 case CMD_ARRAY_REF_SET_VALUES:
6917 index = decode_int (p, &p, end);
6918 len = decode_int (p, &p, end);
6920 g_assert (index >= 0 && len >= 0);
6921 // Reordered to avoid integer overflow
6922 g_assert (!(index > arr->max_length - len));
6924 esize = mono_array_element_size (arr->obj.vtable->klass);
6925 for (i = index; i < index + len; ++i) {
6926 elem = (gpointer*)((char*)arr->vector + (i * esize));
6928 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
6932 return ERR_NOT_IMPLEMENTED;
6939 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6945 objid = decode_objid (p, &p, end);
6946 err = get_object (objid, (MonoObject**)&str);
6951 case CMD_STRING_REF_GET_VALUE:
6952 s = mono_string_to_utf8 (str);
6953 buffer_add_string (buf, s);
6957 return ERR_NOT_IMPLEMENTED;
6964 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6973 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
6974 objid = decode_objid (p, &p, end);
6975 err = get_object (objid, &obj);
6977 buffer_add_int (buf, 1);
6979 buffer_add_int (buf, 0);
6983 objid = decode_objid (p, &p, end);
6984 err = get_object (objid, &obj);
6989 case CMD_OBJECT_REF_GET_TYPE:
6990 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
6992 case CMD_OBJECT_REF_GET_VALUES:
6993 len = decode_int (p, &p, end);
6995 for (i = 0; i < len; ++i) {
6996 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
7000 /* Check that the field belongs to the object */
7002 for (k = obj->vtable->klass; k; k = k->parent) {
7003 if (k == f->parent) {
7009 return ERR_INVALID_FIELDID;
7011 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
7015 if (mono_class_field_is_special_static (f))
7016 return ERR_INVALID_FIELDID;
7018 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
7019 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
7020 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7021 mono_field_static_get_value (vtable, f, val);
7022 buffer_add_value (buf, f->type, val, obj->vtable->domain);
7025 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
7029 case CMD_OBJECT_REF_SET_VALUES:
7030 len = decode_int (p, &p, end);
7032 for (i = 0; i < len; ++i) {
7033 f = decode_fieldid (p, &p, end, NULL, &err);
7037 /* Check that the field belongs to the object */
7039 for (k = obj->vtable->klass; k; k = k->parent) {
7040 if (k == f->parent) {
7046 return ERR_INVALID_FIELDID;
7048 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
7052 if (mono_class_field_is_special_static (f))
7053 return ERR_INVALID_FIELDID;
7055 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
7056 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
7058 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7059 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
7064 mono_field_static_set_value (vtable, f, val);
7067 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
7073 case CMD_OBJECT_REF_GET_ADDRESS:
7074 buffer_add_long (buf, (gssize)obj);
7076 case CMD_OBJECT_REF_GET_DOMAIN:
7077 buffer_add_domainid (buf, obj->vtable->domain);
7080 return ERR_NOT_IMPLEMENTED;
7087 command_set_to_string (CommandSet command_set)
7089 switch (command_set) {
7092 case CMD_SET_OBJECT_REF:
7093 return "OBJECT_REF";
7094 case CMD_SET_STRING_REF:
7095 return "STRING_REF";
7096 case CMD_SET_THREAD:
7098 case CMD_SET_ARRAY_REF:
7100 case CMD_SET_EVENT_REQUEST:
7101 return "EVENT_REQUEST";
7102 case CMD_SET_STACK_FRAME:
7103 return "STACK_FRAME";
7104 case CMD_SET_APPDOMAIN:
7106 case CMD_SET_ASSEMBLY:
7108 case CMD_SET_METHOD:
7112 case CMD_SET_MODULE:
7122 cmd_to_string (CommandSet set, int command)
7127 case CMD_VM_VERSION:
7129 case CMD_VM_ALL_THREADS:
7130 return "ALL_THREADS";
7131 case CMD_VM_SUSPEND:
7137 case CMD_VM_DISPOSE:
7139 case CMD_VM_INVOKE_METHOD:
7140 return "INVOKE_METHOD";
7141 case CMD_VM_SET_PROTOCOL_VERSION:
7142 return "SET_PROTOCOL_VERSION";
7143 case CMD_VM_ABORT_INVOKE:
7144 return "ABORT_INVOKE";
7157 wait_for_attach (void)
7159 if (listen_fd == -1) {
7160 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
7164 /* Block and wait for client connection */
7165 conn_fd = transport_accept (listen_fd);
7166 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
7167 if (conn_fd == -1) {
7168 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
7173 disconnected = !transport_handshake ();
7175 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
7185 * This thread handles communication with the debugger client using a JDWP
7188 static guint32 WINAPI
7189 debugger_thread (void *arg)
7191 int res, len, id, flags, command_set, command;
7192 guint8 header [HEADER_LENGTH];
7193 guint8 *data, *p, *end;
7197 gboolean attach_failed = FALSE;
7199 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
7201 debugger_thread_id = GetCurrentThreadId ();
7203 mono_jit_thread_attach (mono_get_root_domain ());
7205 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
7207 mono_set_is_debugger_attached (TRUE);
7209 if (agent_config.defer) {
7210 if (!wait_for_attach ()) {
7211 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
7212 attach_failed = TRUE; // Don't abort process when we can't listen
7214 /* Send start event to client */
7215 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
7219 while (!attach_failed) {
7220 res = recv_length (conn_fd, header, HEADER_LENGTH, 0);
7222 /* This will break if the socket is closed during shutdown too */
7223 if (res != HEADER_LENGTH)
7227 end = header + HEADER_LENGTH;
7229 len = decode_int (p, &p, end);
7230 id = decode_int (p, &p, end);
7231 flags = decode_byte (p, &p, end);
7232 command_set = decode_byte (p, &p, end);
7233 command = decode_byte (p, &p, end);
7235 g_assert (flags == 0);
7238 const char *cmd_str;
7241 cmd_str = cmd_to_string (command_set, command);
7243 sprintf (cmd_num, "%d", command);
7247 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
7250 data = g_malloc (len - HEADER_LENGTH);
7251 if (len - HEADER_LENGTH > 0)
7253 res = recv_length (conn_fd, data, len - HEADER_LENGTH, 0);
7254 if (res != len - HEADER_LENGTH)
7259 end = data + (len - HEADER_LENGTH);
7261 buffer_init (&buf, 128);
7266 /* Process the request */
7267 switch (command_set) {
7269 err = vm_commands (command, id, p, end, &buf);
7270 if (!err && command == CMD_VM_INVOKE_METHOD)
7271 /* Sent after the invoke is complete */
7274 case CMD_SET_EVENT_REQUEST:
7275 err = event_commands (command, p, end, &buf);
7277 case CMD_SET_APPDOMAIN:
7278 err = domain_commands (command, p, end, &buf);
7280 case CMD_SET_ASSEMBLY:
7281 err = assembly_commands (command, p, end, &buf);
7283 case CMD_SET_MODULE:
7284 err = module_commands (command, p, end, &buf);
7287 err = type_commands (command, p, end, &buf);
7289 case CMD_SET_METHOD:
7290 err = method_commands (command, p, end, &buf);
7292 case CMD_SET_THREAD:
7293 err = thread_commands (command, p, end, &buf);
7295 case CMD_SET_STACK_FRAME:
7296 err = frame_commands (command, p, end, &buf);
7298 case CMD_SET_ARRAY_REF:
7299 err = array_commands (command, p, end, &buf);
7301 case CMD_SET_STRING_REF:
7302 err = string_commands (command, p, end, &buf);
7304 case CMD_SET_OBJECT_REF:
7305 err = object_commands (command, p, end, &buf);
7308 err = ERR_NOT_IMPLEMENTED;
7312 send_reply_packet (id, err, &buf);
7317 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
7321 mono_set_is_debugger_attached (FALSE);
7323 mono_mutex_lock (&debugger_thread_exited_mutex);
7324 debugger_thread_exited = TRUE;
7325 mono_cond_signal (&debugger_thread_exited_cond);
7326 mono_mutex_unlock (&debugger_thread_exited_mutex);
7328 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
7330 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
7331 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
7332 start_debugger_thread ();
7338 #else /* DISABLE_DEBUGGER_AGENT */
7341 mono_debugger_agent_parse_options (char *options)
7343 g_error ("This runtime is configured with the debugger agent disabled.");
7347 mono_debugger_agent_init (void)
7352 mono_debugger_agent_breakpoint_hit (void *sigctx)
7357 mono_debugger_agent_single_step_event (void *sigctx)
7362 mono_debugger_agent_free_domain_info (MonoDomain *domain)
7367 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
7373 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
7374 MonoContext *catch_ctx)
7379 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
7384 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)