2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
43 #ifdef HAVE_UCONTEXT_H
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
62 #ifdef PLATFORM_ANDROID
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/environment.h>
73 #include <mono/metadata/threads-types.h>
74 #include <mono/metadata/socket-io.h>
75 #include <mono/metadata/assembly.h>
76 #include <mono/metadata/runtime.h>
77 #include <mono/metadata/threadpool.h>
78 #include <mono/metadata/verify-internals.h>
79 #include <mono/utils/mono-semaphore.h>
80 #include <mono/utils/mono-error-internals.h>
81 #include <mono/utils/mono-stack-unwinding.h>
82 #include <mono/utils/mono-time.h>
83 #include <mono/utils/mono-threads.h>
84 #include "debugger-agent.h"
88 On iOS we can't use System.Environment.Exit () as it will do the wrong
91 #if !defined (TARGET_IOS)
92 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
96 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
97 #define DISABLE_DEBUGGER_AGENT 1
100 #ifdef DISABLE_SOFT_DEBUG
101 #define DISABLE_DEBUGGER_AGENT 1
104 #ifndef DISABLE_DEBUGGER_AGENT
106 #include <mono/utils/mono-mutex.h>
108 /* Definitions to make backporting to 2.6 easier */
109 //#define MonoInternalThread MonoThread
110 //#define mono_thread_internal_current mono_thread_current
111 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
133 guint32 il_offset, native_offset;
137 * If method is gshared, this is the actual instance, otherwise this is equal to
140 MonoMethod *actual_method;
142 * This is the method which is visible to debugger clients. Same as method,
143 * except for native-to-managed wrappers.
145 MonoMethod *api_method;
147 MonoDebugMethodJitInfo *jit;
150 mgreg_t *reg_locations [MONO_MAX_IREGS];
152 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
153 * the frame can become invalid.
158 typedef struct _InvokeData InvokeData;
166 /* This is the context which needs to be restored after the invoke */
170 * If this is set, invoke this method with the arguments given by ARGS.
174 guint32 suspend_count;
177 InvokeData *last_invoke;
181 MonoThreadUnwindState context;
183 /* This is computed on demand when it is requested using the wire protocol */
184 /* It is freed up when the thread is resumed */
188 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
191 gboolean frames_up_to_date;
193 * Points to data about a pending invoke which needs to be executed after the thread
196 InvokeData *pending_invoke;
198 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
203 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
204 * within a finite amount of time.
208 * Set to TRUE if this thread is suspended in suspend_current ().
210 gboolean really_suspended;
211 /* Used to pass the context to the breakpoint/single step handler */
212 MonoContext handler_ctx;
213 /* Whenever thread_stop () was called for this thread */
216 /* Number of thread interruptions not yet processed */
217 gint32 interrupt_count;
219 /* Whenever to disable breakpoints (used during invokes) */
220 gboolean disable_breakpoints;
223 * Number of times this thread has been resumed using resume_thread ().
225 guint32 resume_count;
227 MonoInternalThread *thread;
230 * Information about the frame which transitioned to native code for running
233 StackFrameInfo async_last_frame;
236 * The context where the stack walk can be started for running threads.
238 MonoThreadUnwindState async_state;
241 * The context used for filter clauses
243 MonoThreadUnwindState filter_state;
246 * The callee address of the last mono_runtime_invoke call
248 gpointer invoke_addr;
250 gboolean abort_requested;
253 * The current mono_runtime_invoke invocation.
258 * The context where single stepping should resume while the thread is suspended because
259 * of an EXCEPTION event.
261 MonoThreadUnwindState catch_state;
264 * The context which needs to be restored after handling a single step/breakpoint
265 * event. This is the same as the ctx at step/breakpoint site, but includes changes
266 * to caller saved registers done by set_var ().
268 MonoContext restore_ctx;
273 void (*connect) (const char *address);
274 void (*close1) (void);
275 void (*close2) (void);
276 gboolean (*send) (void *buf, int len);
277 int (*recv) (void *buf, int len);
281 * Wire Protocol definitions
284 #define HEADER_LENGTH 11
286 #define MAJOR_VERSION 2
287 #define MINOR_VERSION 27
291 CMD_SET_OBJECT_REF = 9,
292 CMD_SET_STRING_REF = 10,
294 CMD_SET_ARRAY_REF = 13,
295 CMD_SET_EVENT_REQUEST = 15,
296 CMD_SET_STACK_FRAME = 16,
297 CMD_SET_APPDOMAIN = 20,
298 CMD_SET_ASSEMBLY = 21,
306 EVENT_KIND_VM_START = 0,
307 EVENT_KIND_VM_DEATH = 1,
308 EVENT_KIND_THREAD_START = 2,
309 EVENT_KIND_THREAD_DEATH = 3,
310 EVENT_KIND_APPDOMAIN_CREATE = 4,
311 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
312 EVENT_KIND_METHOD_ENTRY = 6,
313 EVENT_KIND_METHOD_EXIT = 7,
314 EVENT_KIND_ASSEMBLY_LOAD = 8,
315 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
316 EVENT_KIND_BREAKPOINT = 10,
317 EVENT_KIND_STEP = 11,
318 EVENT_KIND_TYPE_LOAD = 12,
319 EVENT_KIND_EXCEPTION = 13,
320 EVENT_KIND_KEEPALIVE = 14,
321 EVENT_KIND_USER_BREAK = 15,
322 EVENT_KIND_USER_LOG = 16
326 SUSPEND_POLICY_NONE = 0,
327 SUSPEND_POLICY_EVENT_THREAD = 1,
328 SUSPEND_POLICY_ALL = 2
333 ERR_INVALID_OBJECT = 20,
334 ERR_INVALID_FIELDID = 25,
335 ERR_INVALID_FRAMEID = 30,
336 ERR_NOT_IMPLEMENTED = 100,
337 ERR_NOT_SUSPENDED = 101,
338 ERR_INVALID_ARGUMENT = 102,
340 ERR_NO_INVOCATION = 104,
341 ERR_ABSENT_INFORMATION = 105,
342 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
343 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
348 MOD_KIND_THREAD_ONLY = 3,
349 MOD_KIND_LOCATION_ONLY = 7,
350 MOD_KIND_EXCEPTION_ONLY = 8,
352 MOD_KIND_ASSEMBLY_ONLY = 11,
353 MOD_KIND_SOURCE_FILE_ONLY = 12,
354 MOD_KIND_TYPE_NAME_ONLY = 13
369 STEP_FILTER_NONE = 0,
370 STEP_FILTER_STATIC_CTOR = 1,
371 STEP_FILTER_DEBUGGER_HIDDEN = 2,
372 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4
376 TOKEN_TYPE_STRING = 0,
378 TOKEN_TYPE_FIELD = 2,
379 TOKEN_TYPE_METHOD = 3,
380 TOKEN_TYPE_UNKNOWN = 4
384 VALUE_TYPE_ID_NULL = 0xf0,
385 VALUE_TYPE_ID_TYPE = 0xf1
389 FRAME_FLAG_DEBUGGER_INVOKE = 1,
390 FRAME_FLAG_NATIVE_TRANSITION = 2
394 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
395 INVOKE_FLAG_SINGLE_THREADED = 2
399 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
400 } BindingFlagsExtensions;
404 CMD_VM_ALL_THREADS = 2,
409 CMD_VM_INVOKE_METHOD = 7,
410 CMD_VM_SET_PROTOCOL_VERSION = 8,
411 CMD_VM_ABORT_INVOKE = 9,
412 CMD_VM_SET_KEEPALIVE = 10,
413 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
414 CMD_VM_GET_TYPES = 12,
415 CMD_VM_INVOKE_METHODS = 13
419 CMD_THREAD_GET_FRAME_INFO = 1,
420 CMD_THREAD_GET_NAME = 2,
421 CMD_THREAD_GET_STATE = 3,
422 CMD_THREAD_GET_INFO = 4,
423 CMD_THREAD_GET_ID = 5,
424 CMD_THREAD_GET_TID = 6
428 CMD_EVENT_REQUEST_SET = 1,
429 CMD_EVENT_REQUEST_CLEAR = 2,
430 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
438 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
439 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
440 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
441 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
442 CMD_APPDOMAIN_CREATE_STRING = 5,
443 CMD_APPDOMAIN_GET_CORLIB = 6,
444 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
448 CMD_ASSEMBLY_GET_LOCATION = 1,
449 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
450 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
451 CMD_ASSEMBLY_GET_OBJECT = 4,
452 CMD_ASSEMBLY_GET_TYPE = 5,
453 CMD_ASSEMBLY_GET_NAME = 6
457 CMD_MODULE_GET_INFO = 1,
461 CMD_METHOD_GET_NAME = 1,
462 CMD_METHOD_GET_DECLARING_TYPE = 2,
463 CMD_METHOD_GET_DEBUG_INFO = 3,
464 CMD_METHOD_GET_PARAM_INFO = 4,
465 CMD_METHOD_GET_LOCALS_INFO = 5,
466 CMD_METHOD_GET_INFO = 6,
467 CMD_METHOD_GET_BODY = 7,
468 CMD_METHOD_RESOLVE_TOKEN = 8,
469 CMD_METHOD_GET_CATTRS = 9,
470 CMD_METHOD_MAKE_GENERIC_METHOD = 10
474 CMD_TYPE_GET_INFO = 1,
475 CMD_TYPE_GET_METHODS = 2,
476 CMD_TYPE_GET_FIELDS = 3,
477 CMD_TYPE_GET_VALUES = 4,
478 CMD_TYPE_GET_OBJECT = 5,
479 CMD_TYPE_GET_SOURCE_FILES = 6,
480 CMD_TYPE_SET_VALUES = 7,
481 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
482 CMD_TYPE_GET_PROPERTIES = 9,
483 CMD_TYPE_GET_CATTRS = 10,
484 CMD_TYPE_GET_FIELD_CATTRS = 11,
485 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
486 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
487 CMD_TYPE_GET_VALUES_2 = 14,
488 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
489 CMD_TYPE_GET_INTERFACES = 16,
490 CMD_TYPE_GET_INTERFACE_MAP = 17,
491 CMD_TYPE_IS_INITIALIZED = 18
495 CMD_STACK_FRAME_GET_VALUES = 1,
496 CMD_STACK_FRAME_GET_THIS = 2,
497 CMD_STACK_FRAME_SET_VALUES = 3
501 CMD_ARRAY_REF_GET_LENGTH = 1,
502 CMD_ARRAY_REF_GET_VALUES = 2,
503 CMD_ARRAY_REF_SET_VALUES = 3,
507 CMD_STRING_REF_GET_VALUE = 1,
508 CMD_STRING_REF_GET_LENGTH = 2,
509 CMD_STRING_REF_GET_CHARS = 3
513 CMD_OBJECT_REF_GET_TYPE = 1,
514 CMD_OBJECT_REF_GET_VALUES = 2,
515 CMD_OBJECT_REF_IS_COLLECTED = 3,
516 CMD_OBJECT_REF_GET_ADDRESS = 4,
517 CMD_OBJECT_REF_GET_DOMAIN = 5,
518 CMD_OBJECT_REF_SET_VALUES = 6,
519 CMD_OBJECT_REF_GET_INFO = 7,
525 int count; /* For kind == MOD_KIND_COUNT */
526 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
527 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
528 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
529 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
530 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
531 StepFilter filter; /* For kind == MOD_KIND_STEP */
533 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
542 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
546 * Describes a single step request.
550 MonoInternalThread *thread;
556 MonoMethod *last_method;
558 /* Whenever single stepping is performed using start/stop_single_stepping () */
560 /* The list of breakpoints used to implement step-over */
562 /* The number of frames at the start of a step-over */
567 * Contains additional information for an event
570 /* For EVENT_KIND_EXCEPTION */
572 MonoContext catch_ctx;
574 /* For EVENT_KIND_USER_LOG */
576 char *category, *message;
577 /* For EVENT_KIND_TYPE_LOAD */
581 /* Dummy structure used for the profiler callbacks */
586 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
589 #define get_last_sock_error() WSAGetLastError()
590 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
591 #define MONO_EINTR WSAEINTR
593 #define get_last_sock_error() errno
594 #define MONO_EWOULDBLOCK EWOULDBLOCK
595 #define MONO_EINTR EINTR
598 #define CHECK_PROTOCOL_VERSION(major,minor) \
599 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
605 static AgentConfig agent_config;
608 * Whenever the agent is fully initialized.
609 * When using the onuncaught or onthrow options, only some parts of the agent are
610 * initialized on startup, and the full initialization which includes connection
611 * establishment and the startup of the agent thread is only done in response to
614 static gint32 inited;
616 #ifndef DISABLE_SOCKET_TRANSPORT
618 static int listen_fd;
621 static int packet_id = 0;
623 static int objref_id = 0;
625 static int event_request_id = 0;
627 static int frame_id = 0;
629 static GPtrArray *event_requests;
631 static MonoNativeTlsKey debugger_tls_id;
633 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
635 /* Maps MonoInternalThread -> DebuggerTlsData */
636 static MonoGHashTable *thread_to_tls;
638 /* Maps tid -> MonoInternalThread */
639 static MonoGHashTable *tid_to_thread;
641 /* Maps tid -> MonoThread (not MonoInternalThread) */
642 static MonoGHashTable *tid_to_thread_obj;
644 static gsize debugger_thread_id;
646 static HANDLE debugger_thread_handle;
648 static int log_level;
650 static gboolean embedding;
652 static FILE *log_file;
654 /* Assemblies whose assembly load event has no been sent yet */
655 static GPtrArray *pending_assembly_loads;
657 /* Whenever the debugger thread has exited */
658 static gboolean debugger_thread_exited;
660 /* Cond variable used to wait for debugger_thread_exited becoming true */
661 static mono_cond_t debugger_thread_exited_cond;
663 /* Mutex for the cond var above */
664 static mono_mutex_t debugger_thread_exited_mutex;
666 static DebuggerProfiler debugger_profiler;
668 /* The single step request instance */
669 static SingleStepReq *ss_req = NULL;
670 static gpointer ss_invoke_addr = NULL;
672 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
673 /* Number of single stepping operations in progress */
677 /* The protocol version of the client */
678 static int major_version, minor_version;
680 /* Whenever the variables above are set by the client */
681 static gboolean protocol_version_set;
683 /* A hash table containing all active domains */
684 static GHashTable *domains;
686 /* The number of times the runtime is suspended */
687 static gint32 suspend_count;
689 static void transport_init (void);
690 static void transport_connect (const char *address);
691 static gboolean transport_handshake (void);
692 static void register_transport (DebuggerTransport *trans);
694 static guint32 WINAPI debugger_thread (void *arg);
696 static void runtime_initialized (MonoProfiler *prof);
698 static void runtime_shutdown (MonoProfiler *prof);
700 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
702 static void thread_end (MonoProfiler *prof, uintptr_t tid);
704 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
706 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
708 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
710 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
712 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
714 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
716 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
718 static void emit_assembly_load (gpointer assembly, gpointer user_data);
720 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
722 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
724 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
726 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
728 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
730 static void start_single_stepping (void);
732 static void stop_single_stepping (void);
734 static void suspend_current (void);
736 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
738 static void clear_types_for_assembly (MonoAssembly *assembly);
740 static void clear_breakpoints_for_domain (MonoDomain *domain);
742 static void process_profiler_event (EventKind event, gpointer arg);
744 /* Submodule init/cleanup */
745 static void breakpoints_init (void);
746 static void breakpoints_cleanup (void);
748 static void objrefs_init (void);
749 static void objrefs_cleanup (void);
751 static void ids_init (void);
752 static void ids_cleanup (void);
754 static void suspend_init (void);
756 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
757 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
758 static void ss_destroy (SingleStepReq *req);
760 static void start_debugger_thread (void);
761 static void stop_debugger_thread (void);
763 static void finish_agent_init (gboolean on_startup);
765 static void process_profiler_event (EventKind event, gpointer arg);
767 static void invalidate_frames (DebuggerTlsData *tls);
769 #ifndef DISABLE_SOCKET_TRANSPORT
771 register_socket_transport (void);
775 parse_address (char *address, char **host, int *port)
777 char *pos = strchr (address, ':');
779 if (pos == NULL || pos == address)
782 *host = g_malloc (pos - address + 1);
783 strncpy (*host, address, pos - address);
784 (*host) [pos - address] = '\0';
786 *port = atoi (pos + 1);
794 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
795 fprintf (stderr, "Available options:\n");
796 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
797 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
798 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
799 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
800 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
801 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
802 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
803 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
804 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
808 parse_flag (const char *option, char *flag)
810 if (!strcmp (flag, "y"))
812 else if (!strcmp (flag, "n"))
815 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
822 mono_debugger_agent_parse_options (char *options)
829 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
830 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
834 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
836 options = g_strdup_printf ("%s,%s", options, extra);
838 agent_config.enabled = TRUE;
839 agent_config.suspend = TRUE;
840 agent_config.server = FALSE;
841 agent_config.defer = FALSE;
842 agent_config.address = NULL;
844 args = g_strsplit (options, ",", -1);
845 for (ptr = args; ptr && *ptr; ptr ++) {
848 if (strncmp (arg, "transport=", 10) == 0) {
849 agent_config.transport = g_strdup (arg + 10);
850 } else if (strncmp (arg, "address=", 8) == 0) {
851 agent_config.address = g_strdup (arg + 8);
852 } else if (strncmp (arg, "loglevel=", 9) == 0) {
853 agent_config.log_level = atoi (arg + 9);
854 } else if (strncmp (arg, "logfile=", 8) == 0) {
855 agent_config.log_file = g_strdup (arg + 8);
856 } else if (strncmp (arg, "suspend=", 8) == 0) {
857 agent_config.suspend = parse_flag ("suspend", arg + 8);
858 } else if (strncmp (arg, "server=", 7) == 0) {
859 agent_config.server = parse_flag ("server", arg + 7);
860 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
861 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
862 } else if (strncmp (arg, "onthrow=", 8) == 0) {
863 /* We support multiple onthrow= options */
864 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
865 } else if (strncmp (arg, "onthrow", 7) == 0) {
866 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
867 } else if (strncmp (arg, "help", 4) == 0) {
870 } else if (strncmp (arg, "timeout=", 8) == 0) {
871 agent_config.timeout = atoi (arg + 8);
872 } else if (strncmp (arg, "launch=", 7) == 0) {
873 agent_config.launch = g_strdup (arg + 7);
874 } else if (strncmp (arg, "embedding=", 10) == 0) {
875 agent_config.embedding = atoi (arg + 10) == 1;
876 } else if (strncmp (arg, "keepalive=", 10) == 0) {
877 agent_config.keepalive = atoi (arg + 10);
884 if (agent_config.server && !agent_config.suspend) {
885 /* Waiting for deferred attachment */
886 agent_config.defer = TRUE;
887 if (agent_config.address == NULL) {
888 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
892 //agent_config.log_level = 0;
894 if (agent_config.transport == NULL) {
895 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
899 if (agent_config.address == NULL && !agent_config.server) {
900 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
905 if (!strcmp (agent_config.transport, "dt_socket")) {
906 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
907 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
914 mono_debugger_agent_init (void)
916 if (!agent_config.enabled)
921 /* Need to know whenever a thread has acquired the loader mutex */
922 mono_loader_lock_track_ownership (TRUE);
924 event_requests = g_ptr_array_new ();
926 mono_mutex_init (&debugger_thread_exited_mutex);
927 mono_cond_init (&debugger_thread_exited_cond, NULL);
929 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
930 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
931 mono_profiler_install_runtime_initialized (runtime_initialized);
932 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
933 mono_profiler_install_thread (thread_startup, thread_end);
934 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
935 mono_profiler_install_jit_end (jit_end);
936 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
938 mono_native_tls_alloc (&debugger_tls_id, NULL);
940 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
941 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
943 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
944 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
946 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
947 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
949 pending_assembly_loads = g_ptr_array_new ();
950 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
952 log_level = agent_config.log_level;
954 embedding = agent_config.embedding;
957 if (agent_config.log_file) {
958 log_file = fopen (agent_config.log_file, "w+");
960 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
972 mini_get_debug_options ()->gen_seq_points = TRUE;
974 * This is needed because currently we don't handle liveness info.
976 mini_get_debug_options ()->mdb_optimizations = TRUE;
978 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
979 /* This is needed because we can't set local variables in registers yet */
980 mono_disable_optimizations (MONO_OPT_LINEARS);
984 * The stack walk done from thread_interrupt () needs to be signal safe, but it
985 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
986 * safe (#3411). So load AOT info eagerly when the debugger is running as a
989 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
991 if (!agent_config.onuncaught && !agent_config.onthrow)
992 finish_agent_init (TRUE);
998 * Finish the initialization of the agent. This involves connecting the transport
999 * and starting the agent thread. This is either done at startup, or
1000 * in response to some event like an unhandled exception.
1003 finish_agent_init (gboolean on_startup)
1007 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1010 if (agent_config.launch) {
1013 // FIXME: Generated address
1014 // FIXME: Races with transport_connect ()
1016 argv [0] = agent_config.launch;
1017 argv [1] = agent_config.transport;
1018 argv [2] = agent_config.address;
1021 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1023 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1028 transport_connect (agent_config.address);
1031 /* Do some which is usually done after sending the VMStart () event */
1032 vm_start_event_sent = TRUE;
1033 start_debugger_thread ();
1038 mono_debugger_agent_cleanup (void)
1043 stop_debugger_thread ();
1045 breakpoints_cleanup ();
1049 mono_mutex_destroy (&debugger_thread_exited_mutex);
1050 mono_cond_destroy (&debugger_thread_exited_cond);
1057 #ifndef DISABLE_SOCKET_TRANSPORT
1062 * recv() + handle incomplete reads and EINTR
1065 socket_transport_recv (void *buf, int len)
1071 static gint32 last_keepalive;
1076 res = recv (fd, (char *) buf + total, len - total, flags);
1079 if (agent_config.keepalive) {
1080 gboolean need_keepalive = FALSE;
1081 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1082 need_keepalive = TRUE;
1083 } else if (res == -1) {
1084 /* This could happen if recv () is interrupted repeatedly */
1085 msecs = mono_msec_ticks ();
1086 if (msecs - last_keepalive >= agent_config.keepalive) {
1087 need_keepalive = TRUE;
1088 last_keepalive = msecs;
1091 if (need_keepalive) {
1092 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1096 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1101 #define HAVE_GETADDRINFO 1
1105 set_keepalive (void)
1110 if (!agent_config.keepalive || !conn_fd)
1113 tv.tv_sec = agent_config.keepalive / 1000;
1114 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1116 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1117 g_assert (result >= 0);
1121 socket_transport_accept (int socket_fd)
1123 conn_fd = accept (socket_fd, NULL, NULL);
1124 if (conn_fd == -1) {
1125 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1127 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1134 socket_transport_send (void *data, int len)
1139 res = send (conn_fd, data, len, 0);
1140 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1148 * socket_transport_connect:
1150 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1153 socket_transport_connect (const char *address)
1155 #ifdef HAVE_GETADDRINFO
1156 struct addrinfo hints;
1157 struct addrinfo *result, *rp;
1159 struct hostent *result;
1161 int sfd = -1, s, res;
1162 char port_string [128];
1166 if (agent_config.address) {
1167 res = parse_address (agent_config.address, &host, &port);
1168 g_assert (res == 0);
1178 sprintf (port_string, "%d", port);
1180 mono_network_init ();
1182 /* Obtain address(es) matching host/port */
1183 #ifdef HAVE_GETADDRINFO
1184 memset (&hints, 0, sizeof (struct addrinfo));
1185 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1186 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1188 hints.ai_protocol = 0; /* Any protocol */
1190 s = getaddrinfo (host, port_string, &hints, &result);
1192 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1196 /* The PS3 doesn't even have _r or hstrerror () */
1197 result = gethostbyname (host);
1199 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1204 if (agent_config.server) {
1205 #ifdef HAVE_GETADDRINFO
1206 /* Wait for a connection */
1208 struct sockaddr_in addr;
1211 /* No address, generate one */
1212 sfd = socket (AF_INET, SOCK_STREAM, 0);
1215 /* This will bind the socket to a random port */
1216 res = listen (sfd, 16);
1218 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1223 addrlen = sizeof (addr);
1224 memset (&addr, 0, sizeof (addr));
1225 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1226 g_assert (res == 0);
1228 host = (char*)"127.0.0.1";
1229 port = ntohs (addr.sin_port);
1231 /* Emit the address to stdout */
1232 /* FIXME: Should print another interface, not localhost */
1233 printf ("%s:%d\n", host, port);
1235 /* Listen on the provided address */
1236 for (rp = result; rp != NULL; rp = rp->ai_next) {
1239 sfd = socket (rp->ai_family, rp->ai_socktype,
1244 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1247 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1251 res = listen (sfd, 16);
1260 * this function is not present on win2000 which we still support, and the
1261 * workaround described here:
1262 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1263 * only works with MSVC.
1265 #ifdef HAVE_GETADDRINFO
1266 freeaddrinfo (result);
1271 if (agent_config.defer)
1274 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1276 if (agent_config.timeout) {
1281 tv.tv_usec = agent_config.timeout * 1000;
1283 FD_SET (sfd, &readfds);
1284 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1286 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1291 conn_fd = socket_transport_accept (sfd);
1295 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1298 #endif /* HAVE_GETADDRINFO */
1300 /* Connect to the specified address */
1301 #ifdef HAVE_GETADDRINFO
1302 /* FIXME: Respect the timeout */
1303 for (rp = result; rp != NULL; rp = rp->ai_next) {
1304 sfd = socket (rp->ai_family, rp->ai_socktype,
1309 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1310 break; /* Success */
1316 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1320 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1322 g_assert_not_reached ();
1323 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1325 g_assert_not_reached ();
1331 /* See the comment above */
1332 #ifdef HAVE_GETADDRINFO
1333 freeaddrinfo (result);
1338 if (!transport_handshake ())
1343 socket_transport_close1 (void)
1345 /* This will interrupt the agent thread */
1346 /* Close the read part only so it can still send back replies */
1347 /* Also shut down the connection listener so that we can exit normally */
1349 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1350 shutdown (conn_fd, SD_BOTH);
1351 shutdown (listen_fd, SD_BOTH);
1352 closesocket (listen_fd);
1354 shutdown (conn_fd, SHUT_RD);
1355 shutdown (listen_fd, SHUT_RDWR);
1361 socket_transport_close2 (void)
1364 shutdown (conn_fd, SD_BOTH);
1366 shutdown (conn_fd, SHUT_RDWR);
1371 register_socket_transport (void)
1373 DebuggerTransport trans;
1375 trans.name = "dt_socket";
1376 trans.connect = socket_transport_connect;
1377 trans.close1 = socket_transport_close1;
1378 trans.close2 = socket_transport_close2;
1379 trans.send = socket_transport_send;
1380 trans.recv = socket_transport_recv;
1382 register_transport (&trans);
1385 #endif /* DISABLE_SOCKET_TRANSPORT */
1391 #define MAX_TRANSPORTS 16
1393 static DebuggerTransport *transport;
1395 static DebuggerTransport transports [MAX_TRANSPORTS];
1396 static int ntransports;
1399 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1402 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1404 register_transport (trans);
1408 register_transport (DebuggerTransport *trans)
1410 g_assert (ntransports < MAX_TRANSPORTS);
1412 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1417 transport_init (void)
1421 #ifndef DISABLE_SOCKET_TRANSPORT
1422 register_socket_transport ();
1425 for (i = 0; i < ntransports; ++i) {
1426 if (!strcmp (agent_config.transport, transports [i].name))
1429 if (i == ntransports) {
1430 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1431 for (i = 0; i < ntransports; ++i)
1432 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1433 fprintf (stderr, "\n");
1436 transport = &transports [i];
1440 transport_connect (const char *address)
1442 transport->connect (address);
1446 transport_close1 (void)
1448 transport->close1 ();
1452 transport_close2 (void)
1454 transport->close2 ();
1458 transport_send (void *buf, int len)
1460 return transport->send (buf, len);
1464 transport_recv (void *buf, int len)
1466 return transport->recv (buf, len);
1470 mono_debugger_agent_transport_handshake (void)
1472 return transport_handshake ();
1476 transport_handshake (void)
1478 char handshake_msg [128];
1482 disconnected = TRUE;
1484 /* Write handshake message */
1485 sprintf (handshake_msg, "DWP-Handshake");
1487 res = transport_send (handshake_msg, strlen (handshake_msg));
1488 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1489 g_assert (res != -1);
1492 res = transport_recv (buf, strlen (handshake_msg));
1493 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1494 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1499 * To support older clients, the client sends its protocol version after connecting
1500 * using a command. Until that is received, default to our protocol version.
1502 major_version = MAJOR_VERSION;
1503 minor_version = MINOR_VERSION;
1504 protocol_version_set = FALSE;
1506 #ifndef DISABLE_SOCKET_TRANSPORT
1507 // FIXME: Move this somewhere else
1509 * Set TCP_NODELAY on the socket so the client receives events/command
1510 * results immediately.
1514 int result = setsockopt (conn_fd,
1519 g_assert (result >= 0);
1525 disconnected = FALSE;
1530 stop_debugger_thread (void)
1535 transport_close1 ();
1538 * Wait for the thread to exit.
1540 * If we continue with the shutdown without waiting for it, then the client might
1541 * not receive an answer to its last command like a resume.
1542 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1545 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1546 if (GetCurrentThreadId () != debugger_thread_id) {
1548 mono_mutex_lock (&debugger_thread_exited_mutex);
1549 if (!debugger_thread_exited) {
1551 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1552 mono_mutex_unlock (&debugger_thread_exited_mutex);
1554 mono_mutex_lock (&debugger_thread_exited_mutex);
1557 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1560 mono_mutex_unlock (&debugger_thread_exited_mutex);
1561 } while (!debugger_thread_exited);
1564 transport_close2 ();
1568 start_debugger_thread (void)
1572 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1573 g_assert (debugger_thread_handle);
1577 * Functions to decode protocol data
1581 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1584 g_assert (*endbuf <= limit);
1589 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1592 g_assert (*endbuf <= limit);
1594 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1597 static inline gint64
1598 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1600 guint32 high = decode_int (buf, &buf, limit);
1601 guint32 low = decode_int (buf, &buf, limit);
1605 return ((((guint64)high) << 32) | ((guint64)low));
1609 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1611 return decode_int (buf, endbuf, limit);
1615 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1617 int len = decode_int (buf, &buf, limit);
1625 s = g_malloc (len + 1);
1628 memcpy (s, buf, len);
1637 * Functions to encode protocol data
1641 guint8 *buf, *p, *end;
1645 buffer_init (Buffer *buf, int size)
1647 buf->buf = g_malloc (size);
1649 buf->end = buf->buf + size;
1653 buffer_make_room (Buffer *buf, int size)
1655 if (buf->end - buf->p < size) {
1656 int new_size = buf->end - buf->buf + size + 32;
1657 guint8 *p = g_realloc (buf->buf, new_size);
1658 size = buf->p - buf->buf;
1661 buf->end = buf->buf + new_size;
1666 buffer_add_byte (Buffer *buf, guint8 val)
1668 buffer_make_room (buf, 1);
1674 buffer_add_short (Buffer *buf, guint32 val)
1676 buffer_make_room (buf, 2);
1677 buf->p [0] = (val >> 8) & 0xff;
1678 buf->p [1] = (val >> 0) & 0xff;
1683 buffer_add_int (Buffer *buf, guint32 val)
1685 buffer_make_room (buf, 4);
1686 buf->p [0] = (val >> 24) & 0xff;
1687 buf->p [1] = (val >> 16) & 0xff;
1688 buf->p [2] = (val >> 8) & 0xff;
1689 buf->p [3] = (val >> 0) & 0xff;
1694 buffer_add_long (Buffer *buf, guint64 l)
1696 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1697 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1701 buffer_add_id (Buffer *buf, int id)
1703 buffer_add_int (buf, (guint64)id);
1707 buffer_add_data (Buffer *buf, guint8 *data, int len)
1709 buffer_make_room (buf, len);
1710 memcpy (buf->p, data, len);
1715 buffer_add_string (Buffer *buf, const char *str)
1720 buffer_add_int (buf, 0);
1723 buffer_add_int (buf, len);
1724 buffer_add_data (buf, (guint8*)str, len);
1729 buffer_free (Buffer *buf)
1735 send_packet (int command_set, int command, Buffer *data)
1741 id = InterlockedIncrement (&packet_id);
1743 len = data->p - data->buf + 11;
1744 buffer_init (&buf, len);
1745 buffer_add_int (&buf, len);
1746 buffer_add_int (&buf, id);
1747 buffer_add_byte (&buf, 0); /* flags */
1748 buffer_add_byte (&buf, command_set);
1749 buffer_add_byte (&buf, command);
1750 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1752 res = transport_send (buf.buf, len);
1760 send_reply_packet (int id, int error, Buffer *data)
1766 len = data->p - data->buf + 11;
1767 buffer_init (&buf, len);
1768 buffer_add_int (&buf, len);
1769 buffer_add_int (&buf, id);
1770 buffer_add_byte (&buf, 0x80); /* flags */
1771 buffer_add_byte (&buf, (error >> 8) & 0xff);
1772 buffer_add_byte (&buf, error);
1773 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1775 res = transport_send (buf.buf, len);
1787 * Represents an object accessible by the debugger client.
1790 /* Unique id used in the wire protocol to refer to objects */
1793 * A weakref gc handle pointing to the object. The gc handle is used to
1794 * detect if the object was garbage collected.
1799 /* Maps objid -> ObjRef */
1800 static GHashTable *objrefs;
1803 free_objref (gpointer value)
1807 mono_gchandle_free (o->handle);
1815 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1819 objrefs_cleanup (void)
1821 g_hash_table_destroy (objrefs);
1825 static GHashTable *obj_to_objref;
1826 static MonoGHashTable *suspended_objs;
1829 * Return an ObjRef for OBJ.
1832 get_objref (MonoObject *obj)
1835 GSList *reflist = NULL, *l;
1841 mono_loader_lock ();
1843 if (!obj_to_objref) {
1844 obj_to_objref = g_hash_table_new (NULL, NULL);
1845 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1846 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1849 if (suspend_count) {
1851 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1853 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1856 /* FIXME: The tables can grow indefinitely */
1858 if (mono_gc_is_moving ()) {
1860 * Objects can move, so use a hash table mapping hash codes to lists of
1861 * ObjRef structures.
1863 hash = mono_object_hash (obj);
1865 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1866 for (l = reflist; l; l = l->next) {
1868 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1869 mono_loader_unlock ();
1874 /* Use a hash table with masked pointers to internalize object references */
1875 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1876 /* ref might refer to a different object with the same addr which was GCd */
1877 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1878 mono_loader_unlock ();
1883 ref = g_new0 (ObjRef, 1);
1884 ref->id = InterlockedIncrement (&objref_id);
1885 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1887 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1889 if (mono_gc_is_moving ()) {
1890 reflist = g_slist_append (reflist, ref);
1891 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1893 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1896 mono_loader_unlock ();
1902 true_pred (gpointer key, gpointer value, gpointer user_data)
1908 clear_suspended_objs (void)
1910 mono_loader_lock ();
1911 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
1912 mono_loader_unlock ();
1916 get_objid (MonoObject *obj)
1918 return get_objref (obj)->id;
1922 * Set OBJ to the object identified by OBJID.
1923 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1927 get_object_allow_null (int objid, MonoObject **obj)
1937 return ERR_INVALID_OBJECT;
1939 mono_loader_lock ();
1941 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1944 *obj = mono_gchandle_get_target (ref->handle);
1945 mono_loader_unlock ();
1947 return ERR_INVALID_OBJECT;
1950 mono_loader_unlock ();
1951 return ERR_INVALID_OBJECT;
1956 get_object (int objid, MonoObject **obj)
1958 int err = get_object_allow_null (objid, obj);
1963 return ERR_INVALID_OBJECT;
1968 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1970 return decode_id (buf, endbuf, limit);
1974 buffer_add_objid (Buffer *buf, MonoObject *o)
1976 buffer_add_id (buf, get_objid (o));
1995 * Represents a runtime structure accessible to the debugger client
1998 /* Unique id used in the wire protocol */
2000 /* Domain of the runtime structure, NULL if the domain was unloaded */
2007 MonoAssembly *assembly;
2008 MonoClassField *field;
2010 MonoProperty *property;
2015 /* Maps runtime structure -> Id */
2016 GHashTable *val_to_id [ID_NUM];
2017 /* Classes whose class load event has been sent */
2018 GHashTable *loaded_classes;
2019 /* Maps MonoClass->GPtrArray of file names */
2020 GHashTable *source_files;
2021 /* Maps source file basename -> GSList of classes */
2022 GHashTable *source_file_to_class;
2023 /* Same with ignore-case */
2024 GHashTable *source_file_to_class_ignorecase;
2028 static GPtrArray *ids [ID_NUM];
2035 for (i = 0; i < ID_NUM; ++i)
2036 ids [i] = g_ptr_array_new ();
2044 for (i = 0; i < ID_NUM; ++i) {
2046 for (j = 0; j < ids [i]->len; ++j)
2047 g_free (g_ptr_array_index (ids [i], j));
2048 g_ptr_array_free (ids [i], TRUE);
2055 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2057 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2059 GHashTableIter iter;
2060 GPtrArray *file_names;
2065 for (i = 0; i < ID_NUM; ++i)
2066 if (info->val_to_id [i])
2067 g_hash_table_destroy (info->val_to_id [i]);
2068 g_hash_table_destroy (info->loaded_classes);
2070 g_hash_table_iter_init (&iter, info->source_files);
2071 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2072 for (i = 0; i < file_names->len; ++i)
2073 g_free (g_ptr_array_index (file_names, i));
2074 g_ptr_array_free (file_names, TRUE);
2077 g_hash_table_iter_init (&iter, info->source_file_to_class);
2078 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2083 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2084 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2092 domain_jit_info (domain)->agent_info = NULL;
2094 /* Clear ids referencing structures in the domain */
2095 for (i = 0; i < ID_NUM; ++i) {
2097 for (j = 0; j < ids [i]->len; ++j) {
2098 Id *id = g_ptr_array_index (ids [i], j);
2099 if (id->domain == domain)
2105 mono_loader_lock ();
2106 g_hash_table_remove (domains, domain);
2107 mono_loader_unlock ();
2110 static AgentDomainInfo*
2111 get_agent_domain_info (MonoDomain *domain)
2113 AgentDomainInfo *info = NULL;
2115 mono_domain_lock (domain);
2117 info = domain_jit_info (domain)->agent_info;
2119 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2120 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2121 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2122 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2123 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2126 mono_domain_unlock (domain);
2132 get_id (MonoDomain *domain, IdType type, gpointer val)
2135 AgentDomainInfo *info;
2140 mono_loader_lock ();
2142 mono_domain_lock (domain);
2144 info = get_agent_domain_info (domain);
2146 if (info->val_to_id [type] == NULL)
2147 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2149 id = g_hash_table_lookup (info->val_to_id [type], val);
2151 mono_domain_unlock (domain);
2152 mono_loader_unlock ();
2156 id = g_new0 (Id, 1);
2158 id->id = ids [type]->len + 1;
2159 id->domain = domain;
2162 g_hash_table_insert (info->val_to_id [type], val, id);
2164 mono_domain_unlock (domain);
2166 g_ptr_array_add (ids [type], id);
2168 mono_loader_unlock ();
2173 static inline gpointer
2174 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2178 int id = decode_id (buf, endbuf, limit);
2187 // FIXME: error handling
2188 mono_loader_lock ();
2189 g_assert (id > 0 && id <= ids [type]->len);
2191 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2192 mono_loader_unlock ();
2194 if (res->domain == NULL) {
2195 *err = ERR_UNLOADED;
2200 *domain = res->domain;
2202 return res->data.val;
2206 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2208 buffer_add_id (buf, get_id (domain, type, val));
2211 static inline MonoClass*
2212 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2216 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2217 if (G_UNLIKELY (log_level >= 2) && klass) {
2220 s = mono_type_full_name (&klass->byval_arg);
2221 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2227 static inline MonoAssembly*
2228 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2230 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2233 static inline MonoImage*
2234 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2236 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2239 static inline MonoMethod*
2240 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2244 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2245 if (G_UNLIKELY (log_level >= 2) && m) {
2248 s = mono_method_full_name (m, TRUE);
2249 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2255 static inline MonoClassField*
2256 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2258 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2261 static inline MonoDomain*
2262 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2264 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2267 static inline MonoProperty*
2268 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2270 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2274 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2276 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2277 if (G_UNLIKELY (log_level >= 2) && klass) {
2280 s = mono_type_full_name (&klass->byval_arg);
2281 if (GetCurrentThreadId () == debugger_thread_id)
2282 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2284 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2290 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2292 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2293 if (G_UNLIKELY (log_level >= 2) && method) {
2296 s = mono_method_full_name (method, 1);
2297 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2303 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2305 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2309 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2311 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2315 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2317 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2321 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2323 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2327 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2329 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2332 static void invoke_method (void);
2339 * save_thread_context:
2341 * Set CTX as the current threads context which is used for computing stack traces.
2342 * This function is signal-safe.
2345 save_thread_context (MonoContext *ctx)
2347 DebuggerTlsData *tls;
2349 tls = mono_native_tls_get_value (debugger_tls_id);
2353 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2355 mono_thread_state_init_from_current (&tls->context);
2358 /* Number of threads suspended */
2360 * If this is equal to the size of thread_to_tls, the runtime is considered
2363 static gint32 threads_suspend_count;
2365 static mono_mutex_t suspend_mutex;
2367 /* Cond variable used to wait for suspend_count becoming 0 */
2368 static mono_cond_t suspend_cond;
2370 /* Semaphore used to wait for a thread becoming suspended */
2371 static MonoSemType suspend_sem;
2376 mono_mutex_init (&suspend_mutex);
2377 mono_cond_init (&suspend_cond, NULL);
2378 MONO_SEM_INIT (&suspend_sem, 0);
2383 StackFrameInfo last_frame;
2384 gboolean last_frame_set;
2387 } GetLastFrameUserData;
2390 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2392 GetLastFrameUserData *data = user_data;
2394 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2397 if (!data->last_frame_set) {
2398 /* Store the last frame */
2399 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2400 data->last_frame_set = TRUE;
2403 /* Store the context/lmf for the frame above the last frame */
2404 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2405 data->lmf = info->lmf;
2413 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2414 * INFO is set, process the thread described by INFO.
2415 * This should be signal safe.
2418 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2422 MonoNativeThreadId tid;
2425 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2426 * guarantee the signal handler will be called that many times. Instead of tracking
2427 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2428 * has been requested that hasn't been handled yet, otherwise we can have threads
2429 * refuse to die when VM_EXIT is called
2431 #if defined(__APPLE__)
2432 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2436 * We use interrupt_count to determine whenever this interrupt should be processed
2437 * by us or the normal interrupt processing code in the signal handler.
2438 * There is no race here with notify_thread (), since the signal is sent after
2439 * incrementing interrupt_count.
2441 if (tls->interrupt_count == 0)
2444 InterlockedDecrement (&tls->interrupt_count);
2448 ip = mono_arch_ip_from_context (sigctx);
2450 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2455 tid = mono_thread_info_get_tid (info);
2457 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2459 // FIXME: Races when the thread leaves managed code before hitting a single step
2463 /* Running managed code, will be suspended by the single step code */
2464 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2468 * Running native code, will be suspended when it returns to/enters
2469 * managed code. Treat it as already suspended.
2470 * This might interrupt the code in process_single_step_inner (), we use the
2471 * tls->suspending flag to avoid races when that happens.
2473 if (!tls->suspended && !tls->suspending) {
2475 GetLastFrameUserData data;
2477 // FIXME: printf is not signal safe, but this is only used during
2478 // debugger debugging
2480 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2481 //save_thread_context (&ctx);
2484 /* Already terminated */
2488 * We are in a difficult position: we want to be able to provide stack
2489 * traces for this thread, but we can't use the current ctx+lmf, since
2490 * the thread is still running, so it might return to managed code,
2491 * making these invalid.
2492 * So we start a stack walk and save the first frame, along with the
2493 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2494 * suspended when it returns to managed code, so the parent's ctx should
2497 data.last_frame_set = FALSE;
2499 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2501 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2502 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2503 * since we are not in a JITted method.
2505 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2507 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2509 if (data.last_frame_set) {
2510 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2511 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2513 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2516 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2517 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2518 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2520 tls->async_state.valid = FALSE;
2523 mono_memory_barrier ();
2525 tls->suspended = TRUE;
2526 MONO_SEM_POST (&suspend_sem);
2533 * mono_debugger_agent_thread_interrupt:
2535 * Called by the abort signal handler.
2536 * Should be signal safe.
2539 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2541 DebuggerTlsData *tls;
2546 tls = mono_native_tls_get_value (debugger_tls_id);
2548 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2552 return thread_interrupt (tls, NULL, sigctx, ji);
2556 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2559 mono_debugger_agent_thread_interrupt (NULL, NULL);
2561 #endif /* HOST_WIN32 */
2564 * reset_native_thread_suspend_state:
2566 * Reset the suspended flag and state on native threads
2569 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2571 DebuggerTlsData *tls = value;
2573 if (!tls->really_suspended && tls->suspended) {
2574 tls->suspended = FALSE;
2576 * The thread might still be running if it was executing native code, so the state won't be invalided by
2577 * suspend_current ().
2579 tls->context.valid = FALSE;
2580 tls->async_state.valid = FALSE;
2581 invalidate_frames (tls);
2588 * Notify a thread that it needs to suspend.
2591 notify_thread (gpointer key, gpointer value, gpointer user_data)
2593 MonoInternalThread *thread = key;
2594 DebuggerTlsData *tls = value;
2595 gsize tid = thread->tid;
2598 if (GetCurrentThreadId () == tid || tls->terminated)
2601 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2604 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2605 * guarantee the signal handler will be called that many times. Instead of tracking
2606 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2607 * has been requested that hasn't been handled yet, otherwise we can have threads
2608 * refuse to die when VM_EXIT is called
2610 #if defined(__APPLE__)
2611 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2615 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2616 * of things like breaking waits etc. which we don't want.
2618 InterlockedIncrement (&tls->interrupt_count);
2621 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2623 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2625 if (mono_thread_info_new_interrupt_enabled ()) {
2626 MonoThreadInfo *info;
2629 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2631 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2633 * Attached thread which died without detaching.
2635 tls->terminated = TRUE;
2637 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2639 thread_interrupt (tls, info, NULL, ji);
2641 mono_thread_info_resume (mono_thread_info_get_tid (info));
2644 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2646 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2648 * Attached thread which died without detaching.
2650 tls->terminated = TRUE;
2657 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2659 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2663 if (mono_loader_lock_is_owned_by_self ()) {
2665 * Shortcut for the check in suspend_current (). This speeds up processing
2666 * when executing long running code inside the loader lock, i.e. assembly load
2672 if (debugger_thread_id == GetCurrentThreadId ())
2675 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2676 if (suspend_count - tls->resume_count > 0)
2677 tls->suspending = TRUE;
2679 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2681 if (suspend_count - tls->resume_count == 0) {
2683 * We are executing a single threaded invoke but the single step for
2684 * suspending is still active.
2685 * FIXME: This slows down single threaded invokes.
2687 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2691 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2693 /* Can't suspend in these methods */
2694 method = jinfo_get_method (ji);
2695 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2698 save_thread_context (ctx);
2706 * Increase the suspend count of the VM. While the suspend count is greater
2707 * than 0, runtime threads are suspended at certain points during execution.
2712 mono_loader_lock ();
2714 mono_mutex_lock (&suspend_mutex);
2718 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2720 if (suspend_count == 1) {
2721 // FIXME: Is it safe to call this inside the lock ?
2722 start_single_stepping ();
2723 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2726 mono_mutex_unlock (&suspend_mutex);
2728 if (suspend_count == 1)
2730 * Suspend creation of new threadpool threads, since they cannot run
2732 mono_thread_pool_suspend ();
2734 mono_loader_unlock ();
2740 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2748 g_assert (debugger_thread_id == GetCurrentThreadId ());
2750 mono_loader_lock ();
2752 mono_mutex_lock (&suspend_mutex);
2754 g_assert (suspend_count > 0);
2757 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2759 if (suspend_count == 0) {
2760 // FIXME: Is it safe to call this inside the lock ?
2761 stop_single_stepping ();
2762 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2765 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2766 err = mono_cond_broadcast (&suspend_cond);
2767 g_assert (err == 0);
2769 mono_mutex_unlock (&suspend_mutex);
2770 //g_assert (err == 0);
2772 if (suspend_count == 0)
2773 mono_thread_pool_resume ();
2775 mono_loader_unlock ();
2781 * Resume just one thread.
2784 resume_thread (MonoInternalThread *thread)
2787 DebuggerTlsData *tls;
2789 g_assert (debugger_thread_id == GetCurrentThreadId ());
2791 mono_loader_lock ();
2793 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2796 mono_mutex_lock (&suspend_mutex);
2798 g_assert (suspend_count > 0);
2800 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2802 tls->resume_count += suspend_count;
2805 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2806 * but only the one whose resume_count field is > 0 will be resumed.
2808 err = mono_cond_broadcast (&suspend_cond);
2809 g_assert (err == 0);
2811 mono_mutex_unlock (&suspend_mutex);
2812 //g_assert (err == 0);
2814 mono_loader_unlock ();
2818 invalidate_frames (DebuggerTlsData *tls)
2823 tls = mono_native_tls_get_value (debugger_tls_id);
2826 for (i = 0; i < tls->frame_count; ++i) {
2827 if (tls->frames [i]->jit)
2828 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2829 g_free (tls->frames [i]);
2831 g_free (tls->frames);
2832 tls->frame_count = 0;
2839 * Suspend the current thread until the runtime is resumed. If the thread has a
2840 * pending invoke, then the invoke is executed before this function returns.
2843 suspend_current (void)
2846 DebuggerTlsData *tls;
2848 g_assert (debugger_thread_id != GetCurrentThreadId ());
2850 if (mono_loader_lock_is_owned_by_self ()) {
2852 * If we own the loader mutex, can't suspend until we release it, since the
2853 * whole runtime can deadlock otherwise.
2858 tls = mono_native_tls_get_value (debugger_tls_id);
2861 mono_mutex_lock (&suspend_mutex);
2863 tls->suspending = FALSE;
2864 tls->really_suspended = TRUE;
2866 if (!tls->suspended) {
2867 tls->suspended = TRUE;
2868 MONO_SEM_POST (&suspend_sem);
2871 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2873 while (suspend_count - tls->resume_count > 0) {
2875 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2877 mono_mutex_unlock (&suspend_mutex);
2879 mono_mutex_lock (&suspend_mutex);
2885 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2886 g_assert (err == 0);
2890 tls->suspended = FALSE;
2891 tls->really_suspended = FALSE;
2893 threads_suspend_count --;
2895 mono_mutex_unlock (&suspend_mutex);
2897 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2899 if (tls->pending_invoke) {
2900 /* Save the original context */
2901 tls->pending_invoke->has_ctx = TRUE;
2902 tls->pending_invoke->ctx = tls->context.ctx;
2907 /* The frame info becomes invalid after a resume */
2908 tls->context.valid = FALSE;
2909 tls->async_state.valid = FALSE;
2910 invalidate_frames (tls);
2914 count_thread (gpointer key, gpointer value, gpointer user_data)
2916 DebuggerTlsData *tls = value;
2918 if (!tls->suspended && !tls->terminated)
2919 *(int*)user_data = *(int*)user_data + 1;
2923 count_threads_to_wait_for (void)
2927 mono_loader_lock ();
2928 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2929 mono_loader_unlock ();
2937 * Wait until the runtime is completely suspended.
2940 wait_for_suspend (void)
2942 int nthreads, nwait, err;
2943 gboolean waited = FALSE;
2945 // FIXME: Threads starting/stopping ?
2946 mono_loader_lock ();
2947 nthreads = mono_g_hash_table_size (thread_to_tls);
2948 mono_loader_unlock ();
2951 nwait = count_threads_to_wait_for ();
2953 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2954 err = MONO_SEM_WAIT (&suspend_sem);
2955 g_assert (err == 0);
2963 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2969 * Return whenever the runtime is suspended.
2974 return count_threads_to_wait_for () == 0;
2977 static MonoSeqPointInfo*
2978 get_seq_points (MonoDomain *domain, MonoMethod *method)
2980 MonoSeqPointInfo *seq_points;
2982 mono_domain_lock (domain);
2983 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2984 if (!seq_points && method->is_inflated) {
2985 /* generic sharing + aot */
2986 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2988 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2990 mono_domain_unlock (domain);
2996 no_seq_points_found (MonoMethod *method)
2999 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3001 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3005 * find_next_seq_point_for_native_offset:
3007 * Find the first sequence point after NATIVE_OFFSET.
3010 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3012 MonoSeqPointInfo *seq_points;
3015 seq_points = get_seq_points (domain, method);
3021 g_assert (seq_points);
3025 for (i = 0; i < seq_points->len; ++i) {
3026 if (seq_points->seq_points [i].native_offset >= native_offset)
3027 return &seq_points->seq_points [i];
3034 * find_prev_seq_point_for_native_offset:
3036 * Find the first sequence point before NATIVE_OFFSET.
3039 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3041 MonoSeqPointInfo *seq_points;
3044 seq_points = get_seq_points (domain, method);
3050 for (i = seq_points->len - 1; i >= 0; --i) {
3051 if (seq_points->seq_points [i].native_offset <= native_offset)
3052 return &seq_points->seq_points [i];
3061 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3062 * should be the location of a sequence point.
3064 static G_GNUC_UNUSED SeqPoint*
3065 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3067 MonoSeqPointInfo *seq_points;
3072 seq_points = get_seq_points (domain, method);
3077 for (i = 0; i < seq_points->len; ++i) {
3078 if (seq_points->seq_points [i].il_offset == il_offset)
3079 return &seq_points->seq_points [i];
3086 DebuggerTlsData *tls;
3088 } ComputeFramesUserData;
3091 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3093 ComputeFramesUserData *ud = user_data;
3095 MonoMethod *method, *actual_method, *api_method;
3099 if (info->type != FRAME_TYPE_MANAGED) {
3100 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3101 /* Mark the last frame as an invoke frame */
3103 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3109 method = jinfo_get_method (info->ji);
3111 method = info->method;
3112 actual_method = info->actual_method;
3113 api_method = method;
3118 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3121 if (info->il_offset == -1) {
3122 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3123 if (ud->frames == NULL) {
3124 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3126 info->il_offset = sp->il_offset;
3128 if (info->il_offset == -1)
3129 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3132 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));
3134 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3135 if (!CHECK_PROTOCOL_VERSION (2, 17))
3136 /* Older clients can't handle this flag */
3138 api_method = mono_marshal_method_from_wrapper (method);
3141 actual_method = api_method;
3142 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3145 frame = g_new0 (StackFrame, 1);
3146 frame->method = method;
3147 frame->actual_method = actual_method;
3148 frame->api_method = api_method;
3149 frame->il_offset = info->il_offset;
3150 frame->native_offset = info->native_offset;
3151 frame->flags = flags;
3152 frame->ji = info->ji;
3153 if (info->reg_locations)
3154 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3157 frame->has_ctx = TRUE;
3159 frame->domain = info->domain;
3161 ud->frames = g_slist_append (ud->frames, frame);
3167 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3169 ComputeFramesUserData *ud = user_data;
3172 * 'tls->filter_ctx' is the location of the throw site.
3174 * mono_walk_stack() will never actually hit the throw site, but unwind
3175 * directly from the filter to the call site; we abort stack unwinding here
3176 * once this happens and resume from the throw site.
3179 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3182 return process_frame (info, ctx, user_data);
3186 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3188 ComputeFramesUserData user_data;
3190 int i, findex, new_frame_count;
3191 StackFrame **new_frames, *f;
3192 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3194 // FIXME: Locking on tls
3195 if (tls->frames && tls->frames_up_to_date)
3198 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3200 user_data.tls = tls;
3201 user_data.frames = NULL;
3202 if (tls->terminated) {
3203 tls->frame_count = 0;
3205 } if (!tls->really_suspended && tls->async_state.valid) {
3206 /* Have to use the state saved by the signal handler */
3207 process_frame (&tls->async_last_frame, NULL, &user_data);
3208 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3209 } else if (tls->filter_state.valid) {
3211 * We are inside an exception filter.
3213 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3215 if (tls->context.valid)
3216 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3218 * After that, we resume unwinding from the location where the exception has been thrown.
3220 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3221 } else if (tls->context.valid) {
3222 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3225 tls->frame_count = 0;
3229 new_frame_count = g_slist_length (user_data.frames);
3230 new_frames = g_new0 (StackFrame*, new_frame_count);
3232 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3236 * Reuse the id for already existing stack frames, so invokes don't invalidate
3237 * the still valid stack frames.
3239 for (i = 0; i < tls->frame_count; ++i) {
3240 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3241 f->id = tls->frames [i]->id;
3246 if (i >= tls->frame_count)
3247 f->id = InterlockedIncrement (&frame_id);
3249 new_frames [findex ++] = f;
3252 g_slist_free (user_data.frames);
3254 invalidate_frames (tls);
3256 tls->frames = new_frames;
3257 tls->frame_count = new_frame_count;
3258 tls->frames_up_to_date = TRUE;
3262 * GHFunc to emit an appdomain creation event
3263 * @param key Don't care
3264 * @param value A loaded appdomain
3265 * @param user_data Don't care
3268 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3270 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3271 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3275 * GHFunc to emit a thread start event
3276 * @param key A thread id
3277 * @param value A thread object
3278 * @param user_data Don't care
3281 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3283 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3284 process_profiler_event (EVENT_KIND_THREAD_START, value);
3288 * GFunc to emit an assembly load event
3289 * @param value A loaded assembly
3290 * @param user_data Don't care
3293 emit_assembly_load (gpointer value, gpointer user_data)
3295 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3299 * GFunc to emit a type load event
3300 * @param value A loaded type
3301 * @param user_data Don't care
3304 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3306 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3310 strdup_tolower (char *s)
3315 for (p = s2; *p; ++p)
3325 * create_event_list:
3327 * Return a list of event request ids matching EVENT, starting from REQS, which
3328 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3330 * We return request ids, instead of requests, to simplify threading, since
3331 * requests could be deleted anytime when the loader lock is not held.
3332 * LOCKING: Assumes the loader lock is held.
3335 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3338 GSList *events = NULL;
3340 *suspend_policy = SUSPEND_POLICY_NONE;
3343 reqs = event_requests;
3348 for (i = 0; i < reqs->len; ++i) {
3349 EventRequest *req = g_ptr_array_index (reqs, i);
3350 if (req->event_kind == event) {
3351 gboolean filtered = FALSE;
3354 for (j = 0; j < req->nmodifiers; ++j) {
3355 Modifier *mod = &req->modifiers [j];
3357 if (mod->kind == MOD_KIND_COUNT) {
3359 if (mod->data.count > 0) {
3360 if (mod->data.count > 0) {
3362 if (mod->data.count == 0)
3366 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3367 if (mod->data.thread != mono_thread_internal_current ())
3369 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3370 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3372 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3374 if (ei->caught && !mod->caught)
3376 if (!ei->caught && !mod->uncaught)
3378 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3380 gboolean found = FALSE;
3381 MonoAssembly **assemblies = mod->data.assemblies;
3384 for (k = 0; assemblies [k]; ++k)
3385 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3390 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3391 gpointer iter = NULL;
3393 MonoDebugSourceInfo *sinfo;
3394 char *source_file, *s;
3395 gboolean found = FALSE;
3397 GPtrArray *source_file_list;
3399 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3400 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3403 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3404 for (i = 0; i < source_file_list->len; ++i) {
3405 sinfo = g_ptr_array_index (source_file_list, i);
3407 * Do a case-insesitive match by converting the file name to
3410 s = strdup_tolower (sinfo->source_file);
3411 if (g_hash_table_lookup (mod->data.source_files, s))
3414 char *s2 = g_path_get_basename (sinfo->source_file);
3415 char *s3 = strdup_tolower (s2);
3417 if (g_hash_table_lookup (mod->data.source_files, s3))
3424 g_ptr_array_free (source_file_list, TRUE);
3429 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3432 s = mono_type_full_name (&ei->klass->byval_arg);
3433 if (!g_hash_table_lookup (mod->data.type_names, s))
3436 } else if (mod->kind == MOD_KIND_STEP) {
3437 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3438 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3439 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3441 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3442 MonoCustomAttrInfo *ainfo;
3443 static MonoClass *klass;
3446 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3449 if (!ji->dbg_hidden_inited) {
3450 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3452 if (mono_custom_attrs_has_attr (ainfo, klass))
3453 ji->dbg_hidden = TRUE;
3454 mono_custom_attrs_free (ainfo);
3456 ji->dbg_hidden_inited = TRUE;
3461 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3462 MonoCustomAttrInfo *ainfo;
3463 static MonoClass *klass;
3466 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3469 if (!ji->dbg_step_through_inited) {
3470 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3472 if (mono_custom_attrs_has_attr (ainfo, klass))
3473 ji->dbg_step_through = TRUE;
3474 mono_custom_attrs_free (ainfo);
3476 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3478 if (mono_custom_attrs_has_attr (ainfo, klass))
3479 ji->dbg_step_through = TRUE;
3480 mono_custom_attrs_free (ainfo);
3482 ji->dbg_step_through_inited = TRUE;
3484 if (ji->dbg_step_through)
3491 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3492 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3497 /* Send a VM START/DEATH event by default */
3498 if (event == EVENT_KIND_VM_START)
3499 events = g_slist_append (events, GINT_TO_POINTER (0));
3500 if (event == EVENT_KIND_VM_DEATH)
3501 events = g_slist_append (events, GINT_TO_POINTER (0));
3506 static G_GNUC_UNUSED const char*
3507 event_to_string (EventKind event)
3510 case EVENT_KIND_VM_START: return "VM_START";
3511 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3512 case EVENT_KIND_THREAD_START: return "THREAD_START";
3513 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3514 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3515 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3516 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3517 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3518 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3519 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3520 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3521 case EVENT_KIND_STEP: return "STEP";
3522 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3523 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3524 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3525 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3526 case EVENT_KIND_USER_LOG: return "USER_LOG";
3528 g_assert_not_reached ();
3536 * Send an event to the client, suspending the vm if needed.
3537 * LOCKING: Since this can suspend the calling thread, no locks should be held
3539 * The EVENTS list is freed by this function.
3542 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3546 MonoDomain *domain = mono_domain_get ();
3547 MonoThread *thread = NULL;
3548 MonoObject *keepalive_obj = NULL;
3549 gboolean send_success = FALSE;
3554 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3558 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3559 // FIXME: We miss those events
3560 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3564 if (vm_death_event_sent) {
3565 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3569 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3570 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3575 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3579 if (event == EVENT_KIND_KEEPALIVE)
3580 suspend_policy = SUSPEND_POLICY_NONE;
3585 if (agent_config.defer) {
3586 /* Make sure the thread id is always set when doing deferred debugging */
3587 if (debugger_thread_id == GetCurrentThreadId ()) {
3588 /* Don't suspend on events from the debugger thread */
3589 suspend_policy = SUSPEND_POLICY_NONE;
3590 thread = mono_thread_get_main ();
3592 else thread = mono_thread_current ();
3594 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3595 // FIXME: Send these with a NULL thread, don't suspend the current thread
3600 nevents = g_slist_length (events);
3601 buffer_init (&buf, 128);
3602 buffer_add_byte (&buf, suspend_policy);
3603 buffer_add_int (&buf, nevents);
3605 for (l = events; l; l = l->next) {
3606 buffer_add_byte (&buf, event); // event kind
3607 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3612 thread = mono_thread_current ();
3614 if (event == EVENT_KIND_VM_START && arg != NULL)
3617 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3620 case EVENT_KIND_THREAD_START:
3621 case EVENT_KIND_THREAD_DEATH:
3623 case EVENT_KIND_APPDOMAIN_CREATE:
3624 case EVENT_KIND_APPDOMAIN_UNLOAD:
3625 buffer_add_domainid (&buf, arg);
3627 case EVENT_KIND_METHOD_ENTRY:
3628 case EVENT_KIND_METHOD_EXIT:
3629 buffer_add_methodid (&buf, domain, arg);
3631 case EVENT_KIND_ASSEMBLY_LOAD:
3632 case EVENT_KIND_ASSEMBLY_UNLOAD:
3633 buffer_add_assemblyid (&buf, domain, arg);
3635 case EVENT_KIND_TYPE_LOAD:
3636 buffer_add_typeid (&buf, domain, arg);
3638 case EVENT_KIND_BREAKPOINT:
3639 case EVENT_KIND_STEP:
3640 buffer_add_methodid (&buf, domain, arg);
3641 buffer_add_long (&buf, il_offset);
3643 case EVENT_KIND_VM_START:
3644 buffer_add_domainid (&buf, mono_get_root_domain ());
3646 case EVENT_KIND_VM_DEATH:
3647 if (CHECK_PROTOCOL_VERSION (2, 27))
3648 buffer_add_int (&buf, mono_environment_exitcode_get ());
3650 case EVENT_KIND_EXCEPTION: {
3651 EventInfo *ei = arg;
3652 buffer_add_objid (&buf, ei->exc);
3654 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3655 * later after the suspension. (#12494).
3657 keepalive_obj = ei->exc;
3660 case EVENT_KIND_USER_BREAK:
3662 case EVENT_KIND_USER_LOG: {
3663 EventInfo *ei = arg;
3664 buffer_add_int (&buf, ei->level);
3665 buffer_add_string (&buf, ei->category ? ei->category : "");
3666 buffer_add_string (&buf, ei->message ? ei->message : "");
3669 case EVENT_KIND_KEEPALIVE:
3670 suspend_policy = SUSPEND_POLICY_NONE;
3673 g_assert_not_reached ();
3677 if (event == EVENT_KIND_VM_START) {
3678 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3679 if (!agent_config.defer)
3680 start_debugger_thread ();
3683 if (event == EVENT_KIND_VM_DEATH) {
3684 vm_death_event_sent = TRUE;
3685 suspend_policy = SUSPEND_POLICY_NONE;
3688 if (mono_runtime_is_shutting_down ())
3689 suspend_policy = SUSPEND_POLICY_NONE;
3691 if (suspend_policy != SUSPEND_POLICY_NONE) {
3693 * Save the thread context and start suspending before sending the packet,
3694 * since we could be receiving the resume request before send_packet ()
3697 save_thread_context (ctx);
3701 /* This will keep this object alive */
3702 get_objref (keepalive_obj);
3705 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3709 g_slist_free (events);
3712 if (!send_success) {
3713 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3717 if (event == EVENT_KIND_VM_START) {
3718 vm_start_event_sent = TRUE;
3721 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3723 switch (suspend_policy) {
3724 case SUSPEND_POLICY_NONE:
3726 case SUSPEND_POLICY_ALL:
3729 case SUSPEND_POLICY_EVENT_THREAD:
3733 g_assert_not_reached ();
3738 process_profiler_event (EventKind event, gpointer arg)
3742 EventInfo ei, *ei_arg = NULL;
3744 if (event == EVENT_KIND_TYPE_LOAD) {
3749 mono_loader_lock ();
3750 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3751 mono_loader_unlock ();
3753 process_event (event, arg, 0, NULL, events, suspend_policy);
3757 runtime_initialized (MonoProfiler *prof)
3759 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3760 if (agent_config.defer)
3761 start_debugger_thread ();
3765 runtime_shutdown (MonoProfiler *prof)
3767 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3769 mono_debugger_agent_cleanup ();
3773 thread_startup (MonoProfiler *prof, uintptr_t tid)
3775 MonoInternalThread *thread = mono_thread_internal_current ();
3776 MonoInternalThread *old_thread;
3777 DebuggerTlsData *tls;
3779 if (tid == debugger_thread_id)
3782 g_assert (thread->tid == tid);
3784 mono_loader_lock ();
3785 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3786 mono_loader_unlock ();
3788 if (thread == old_thread) {
3790 * For some reason, thread_startup () might be called for the same thread
3791 * multiple times (attach ?).
3793 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3797 * thread_end () might not be called for some threads, and the tid could
3800 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3801 mono_loader_lock ();
3802 mono_g_hash_table_remove (thread_to_tls, old_thread);
3803 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3804 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3805 mono_loader_unlock ();
3809 tls = mono_native_tls_get_value (debugger_tls_id);
3811 // FIXME: Free this somewhere
3812 tls = g_new0 (DebuggerTlsData, 1);
3813 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3814 tls->thread = thread;
3815 mono_native_tls_set_value (debugger_tls_id, tls);
3817 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3819 mono_loader_lock ();
3820 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3821 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3822 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3823 mono_loader_unlock ();
3825 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3828 * suspend_vm () could have missed this thread, so wait for a resume.
3834 thread_end (MonoProfiler *prof, uintptr_t tid)
3836 MonoInternalThread *thread;
3837 DebuggerTlsData *tls = NULL;
3839 mono_loader_lock ();
3840 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3842 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3843 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3845 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3846 tls->terminated = TRUE;
3847 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3848 MONO_GC_UNREGISTER_ROOT (tls->thread);
3852 mono_loader_unlock ();
3854 /* We might be called for threads started before we registered the start callback */
3856 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3857 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3862 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3864 mono_loader_lock ();
3865 g_hash_table_insert (domains, domain, domain);
3866 mono_loader_unlock ();
3868 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3872 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3874 clear_breakpoints_for_domain (domain);
3876 mono_loader_lock ();
3877 /* Invalidate each thread's frame stack */
3878 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3879 mono_loader_unlock ();
3881 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3885 * invalidate_each_thread:
3887 * A GHFunc to invalidate frames.
3888 * value must be a DebuggerTlsData*
3891 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3893 invalidate_frames (value);
3897 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3899 /* Sent later in jit_end () */
3900 mono_loader_lock ();
3901 g_ptr_array_add (pending_assembly_loads, assembly);
3902 mono_loader_unlock ();
3906 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3908 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3910 clear_event_requests_for_assembly (assembly);
3911 clear_types_for_assembly (assembly);
3915 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3917 #if defined(HOST_WIN32) && !defined(__GNUC__)
3918 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3920 gpointer stackptr = __builtin_frame_address (1);
3922 MonoInternalThread *thread = mono_thread_internal_current ();
3923 DebuggerTlsData *tls;
3925 mono_loader_lock ();
3927 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3928 /* Could be the debugger thread with assembly/type load hooks */
3930 tls->invoke_addr = stackptr;
3932 mono_loader_unlock ();
3936 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3939 #if defined(HOST_WIN32) && !defined(__GNUC__)
3940 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3942 gpointer stackptr = __builtin_frame_address (1);
3945 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3949 * We need to stop single stepping when exiting a runtime invoke, since if it is
3950 * a step out, it may return to native code, and thus never end.
3952 mono_loader_lock ();
3953 ss_invoke_addr = NULL;
3955 for (i = 0; i < event_requests->len; ++i) {
3956 EventRequest *req = g_ptr_array_index (event_requests, i);
3958 if (req->event_kind == EVENT_KIND_STEP) {
3959 ss_destroy (req->info);
3960 g_ptr_array_remove_index_fast (event_requests, i);
3965 mono_loader_unlock ();
3969 send_type_load (MonoClass *klass)
3971 gboolean type_load = FALSE;
3972 MonoDomain *domain = mono_domain_get ();
3973 AgentDomainInfo *info = NULL;
3975 mono_loader_lock ();
3976 mono_domain_lock (domain);
3978 info = get_agent_domain_info (domain);
3980 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3982 g_hash_table_insert (info->loaded_classes, klass, klass);
3985 mono_domain_unlock (domain);
3986 mono_loader_unlock ();
3988 emit_type_load (klass, klass, NULL);
3992 * Emit load events for all types currently loaded in the domain.
3993 * Takes the loader and domain locks.
3994 * user_data is unused.
3997 send_types_for_domain (MonoDomain *domain, void *user_data)
3999 AgentDomainInfo *info = NULL;
4001 mono_loader_lock ();
4002 mono_domain_lock (domain);
4003 info = get_agent_domain_info (domain);
4005 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4006 mono_domain_unlock (domain);
4007 mono_loader_unlock ();
4011 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4014 * We emit type load events when the first method of the type is JITted,
4015 * since the class load profiler callbacks might be called with the
4016 * loader lock held. They could also occur in the debugger thread.
4017 * Same for assembly load events.
4020 MonoAssembly *assembly = NULL;
4022 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4023 mono_loader_lock ();
4024 if (pending_assembly_loads->len > 0) {
4025 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4026 g_ptr_array_remove_index (pending_assembly_loads, 0);
4028 mono_loader_unlock ();
4031 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4037 send_type_load (method->klass);
4040 add_pending_breakpoints (method, jinfo);
4044 * BREAKPOINTS/SINGLE STEPPING
4048 * Contains information about an inserted breakpoint.
4051 long il_offset, native_offset;
4056 } BreakpointInstance;
4059 * Contains generic information about a breakpoint.
4063 * The method where the breakpoint is placed. Can be NULL in which case it
4064 * is inserted into every method. This is used to implement method entry/
4065 * exit events. Can be a generic method definition, in which case the
4066 * breakpoint is inserted into every instance.
4072 * A list of BreakpointInstance structures describing where the breakpoint
4073 * was inserted. There could be more than one because of
4074 * generics/appdomains/method entry/exit.
4076 GPtrArray *children;
4079 /* List of breakpoints */
4080 static GPtrArray *breakpoints;
4081 /* Maps breakpoint locations to the number of breakpoints at that location */
4082 static GHashTable *bp_locs;
4085 breakpoints_init (void)
4087 breakpoints = g_ptr_array_new ();
4088 bp_locs = g_hash_table_new (NULL, NULL);
4092 * insert_breakpoint:
4094 * Insert the breakpoint described by BP into the method described by
4098 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4101 BreakpointInstance *inst;
4102 SeqPoint *sp = NULL;
4105 mono_error_init (error);
4107 for (i = 0; i < seq_points->len; ++i) {
4108 sp = &seq_points->seq_points [i];
4110 if (sp->il_offset == bp->il_offset)
4114 if (i == seq_points->len) {
4116 * The set of IL offsets with seq points doesn't completely match the
4117 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4119 for (i = 0; i < seq_points->len; ++i) {
4120 sp = &seq_points->seq_points [i];
4122 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4127 if (i == seq_points->len) {
4128 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset, seq_points->len);
4130 for (i = 0; i < seq_points->len; ++i)
4131 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4134 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4135 g_warning ("%s", s);
4139 g_warning ("%s", s);
4145 inst = g_new0 (BreakpointInstance, 1);
4147 inst->native_offset = sp->native_offset;
4148 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4150 inst->domain = domain;
4152 mono_loader_lock ();
4154 g_ptr_array_add (bp->children, inst);
4156 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4157 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4158 mono_loader_unlock ();
4160 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4161 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4162 } else if (count == 0) {
4163 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4164 mono_arch_set_breakpoint (ji, inst->ip);
4170 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (jinfo_get_method (ji), TRUE), (int)sp->il_offset));
4174 remove_breakpoint (BreakpointInstance *inst)
4176 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4178 MonoJitInfo *ji = inst->ji;
4179 guint8 *ip = inst->ip;
4181 mono_loader_lock ();
4182 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4183 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4184 mono_loader_unlock ();
4186 g_assert (count > 0);
4188 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4189 mono_arch_clear_breakpoint (ji, ip);
4196 static inline gboolean
4197 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4203 if (method == bp->method)
4205 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4208 if (bp->method->is_inflated && method->is_inflated) {
4209 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4210 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4212 /* Open generic methods should match closed generic methods of the same class */
4213 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4214 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4215 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4217 /* FIXME: Handle !mvar */
4218 if (t1->type != MONO_TYPE_MVAR)
4229 * add_pending_breakpoints:
4231 * Insert pending breakpoints into the newly JITted method METHOD.
4234 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4237 MonoSeqPointInfo *seq_points;
4239 MonoMethod *jmethod;
4244 domain = mono_domain_get ();
4246 mono_loader_lock ();
4248 for (i = 0; i < breakpoints->len; ++i) {
4249 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4250 gboolean found = FALSE;
4252 if (!bp_matches_method (bp, method))
4255 for (j = 0; j < bp->children->len; ++j) {
4256 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4263 jmethod = jinfo_get_method (ji);
4264 mono_domain_lock (domain);
4265 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4266 if (!seq_points && jmethod->is_inflated)
4267 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4268 mono_domain_unlock (domain);
4270 /* Could be AOT code */
4272 g_assert (seq_points);
4274 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4278 mono_loader_unlock ();
4282 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4288 mono_error_init (error);
4290 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4292 /* Might be AOTed code */
4293 code = mono_aot_get_method (domain, method);
4295 ji = mono_jit_info_table_find (domain, code);
4300 insert_breakpoint (seq_points, domain, ji, bp, error);
4304 clear_breakpoint (MonoBreakpoint *bp);
4309 * Set a breakpoint at IL_OFFSET in METHOD.
4310 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4311 * METHOD can also be a generic method definition, in which case a breakpoint
4312 * is placed in all instances of the method.
4313 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4316 static MonoBreakpoint*
4317 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4320 GHashTableIter iter, iter2;
4323 MonoSeqPointInfo *seq_points;
4326 mono_error_init (error);
4329 // - suspend/resume the vm to prevent code patching problems
4330 // - multiple breakpoints on the same location
4331 // - dynamic methods
4334 bp = g_new0 (MonoBreakpoint, 1);
4335 bp->method = method;
4336 bp->il_offset = il_offset;
4338 bp->children = g_ptr_array_new ();
4340 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));
4342 mono_loader_lock ();
4344 g_hash_table_iter_init (&iter, domains);
4345 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4346 mono_domain_lock (domain);
4348 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4349 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4350 if (bp_matches_method (bp, m))
4351 set_bp_in_method (domain, m, seq_points, bp, error);
4354 mono_domain_unlock (domain);
4357 mono_loader_unlock ();
4359 mono_loader_lock ();
4360 g_ptr_array_add (breakpoints, bp);
4361 mono_loader_unlock ();
4363 if (error && !mono_error_ok (error)) {
4364 clear_breakpoint (bp);
4372 clear_breakpoint (MonoBreakpoint *bp)
4376 // FIXME: locking, races
4377 for (i = 0; i < bp->children->len; ++i) {
4378 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4380 remove_breakpoint (inst);
4385 mono_loader_lock ();
4386 g_ptr_array_remove (breakpoints, bp);
4387 mono_loader_unlock ();
4389 g_ptr_array_free (bp->children, TRUE);
4394 breakpoints_cleanup (void)
4398 mono_loader_lock ();
4400 while (i < event_requests->len) {
4401 EventRequest *req = g_ptr_array_index (event_requests, i);
4403 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4404 clear_breakpoint (req->info);
4405 g_ptr_array_remove_index_fast (event_requests, i);
4412 for (i = 0; i < breakpoints->len; ++i)
4413 g_free (g_ptr_array_index (breakpoints, i));
4415 g_ptr_array_free (breakpoints, TRUE);
4416 g_hash_table_destroy (bp_locs);
4421 mono_loader_unlock ();
4425 * clear_breakpoints_for_domain:
4427 * Clear breakpoint instances which reference DOMAIN.
4430 clear_breakpoints_for_domain (MonoDomain *domain)
4434 /* This could be called after shutdown */
4438 mono_loader_lock ();
4439 for (i = 0; i < breakpoints->len; ++i) {
4440 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4443 while (j < bp->children->len) {
4444 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4446 if (inst->domain == domain) {
4447 remove_breakpoint (inst);
4451 g_ptr_array_remove_index_fast (bp->children, j);
4457 mono_loader_unlock ();
4463 * Return FALSE if single stepping needs to continue.
4466 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4468 MonoDebugMethodInfo *minfo;
4469 MonoDebugSourceLocation *loc = NULL;
4470 gboolean hit = TRUE;
4473 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4475 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4477 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4481 if (req->depth == STEP_DEPTH_OVER && hit) {
4482 if (!tls->context.valid)
4483 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4484 compute_frame_info (tls->thread, tls);
4485 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4486 /* Hit the breakpoint in a recursive call */
4487 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4492 if (req->size != STEP_SIZE_LINE)
4495 /* Have to check whenever a different source line was reached */
4496 method = jinfo_get_method (ji);
4497 minfo = mono_debug_lookup_method (method);
4500 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4502 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4503 /* Have to continue single stepping */
4505 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4507 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4512 ss_req->last_method = method;
4513 ss_req->last_line = loc->row;
4514 mono_debug_free_source_location (loc);
4521 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4523 return bp->method && bp->method->klass->image->assembly == assembly;
4527 process_breakpoint_inner (DebuggerTlsData *tls)
4531 int i, j, suspend_policy;
4532 guint32 native_offset;
4534 BreakpointInstance *inst;
4535 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4536 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4537 EventKind kind = EVENT_KIND_BREAKPOINT;
4538 MonoContext *ctx = &tls->restore_ctx;
4540 MonoSeqPointInfo *info;
4543 // FIXME: Speed this up
4545 ip = MONO_CONTEXT_GET_IP (ctx);
4546 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4548 method = jinfo_get_method (ji);
4550 /* Compute the native offset of the breakpoint from the ip */
4551 native_offset = ip - (guint8*)ji->code_start;
4554 * Skip the instruction causing the breakpoint signal.
4556 mono_arch_skip_breakpoint (ctx, ji);
4558 if (method->wrapper_type || tls->disable_breakpoints)
4561 bp_reqs = g_ptr_array_new ();
4562 ss_reqs = g_ptr_array_new ();
4563 ss_reqs_orig = g_ptr_array_new ();
4565 mono_loader_lock ();
4568 * The ip points to the instruction causing the breakpoint event, which is after
4569 * the offset recorded in the seq point map, so find the prev seq point before ip.
4571 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4573 no_seq_points_found (method);
4576 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), method->name, ip, native_offset, sp ? sp->il_offset : -1));
4579 for (i = 0; i < breakpoints->len; ++i) {
4580 bp = g_ptr_array_index (breakpoints, i);
4585 for (j = 0; j < bp->children->len; ++j) {
4586 inst = g_ptr_array_index (bp->children, j);
4587 if (inst->ji == ji && inst->sp == sp) {
4588 if (bp->req->event_kind == EVENT_KIND_STEP) {
4589 g_ptr_array_add (ss_reqs_orig, bp->req);
4591 g_ptr_array_add (bp_reqs, bp->req);
4596 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4597 /* Maybe a method entry/exit event */
4598 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4599 kind = EVENT_KIND_METHOD_ENTRY;
4600 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4601 kind = EVENT_KIND_METHOD_EXIT;
4604 /* Process single step requests */
4605 for (i = 0; i < ss_reqs_orig->len; ++i) {
4606 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4607 SingleStepReq *ss_req = req->info;
4610 if (mono_thread_internal_current () != ss_req->thread)
4613 hit = ss_update (ss_req, ji, sp, tls, ctx);
4615 g_ptr_array_add (ss_reqs, req);
4617 /* Start single stepping again from the current sequence point */
4618 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4621 if (ss_reqs->len > 0)
4622 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4623 if (bp_reqs->len > 0)
4624 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4625 if (kind != EVENT_KIND_BREAKPOINT)
4626 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4628 mono_loader_unlock ();
4630 g_ptr_array_free (bp_reqs, TRUE);
4631 g_ptr_array_free (ss_reqs, TRUE);
4634 * FIXME: The first event will suspend, so the second will only be sent after the
4638 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4640 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4641 if (enter_leave_events)
4642 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4645 /* Process a breakpoint/single step event after resuming from a signal handler */
4647 process_signal_event (void (*func) (DebuggerTlsData*))
4649 DebuggerTlsData *tls;
4650 MonoContext orig_restore_ctx, ctx;
4652 tls = mono_native_tls_get_value (debugger_tls_id);
4653 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4654 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4655 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4659 /* This is called when resuming from a signal handler, so it shouldn't return */
4660 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4661 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4662 mono_restore_context (&ctx);
4663 g_assert_not_reached ();
4667 process_breakpoint (void)
4669 process_signal_event (process_breakpoint_inner);
4673 resume_from_signal_handler (void *sigctx, void *func)
4675 DebuggerTlsData *tls;
4678 /* Save the original context in TLS */
4679 // FIXME: This might not work on an altstack ?
4680 tls = mono_native_tls_get_value (debugger_tls_id);
4682 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4685 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4686 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4687 // clob:c could be added to op_seq_point.
4689 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4690 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4691 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4692 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4694 MONO_CONTEXT_SET_IP (&ctx, func);
4696 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4698 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4699 mono_ppc_set_func_into_sigctx (sigctx, func);
4704 mono_debugger_agent_breakpoint_hit (void *sigctx)
4707 * We are called from a signal handler, and running code there causes all kinds of
4708 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4709 * So set up the signal context to return to the real breakpoint handler function.
4711 resume_from_signal_handler (sigctx, process_breakpoint);
4715 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4717 if (frame->managed) {
4718 *(MonoContext*)data = *ctx;
4727 * Called by System.Diagnostics.Debugger:Break ().
4730 mono_debugger_agent_user_break (void)
4732 if (agent_config.enabled) {
4737 /* Obtain a context */
4738 MONO_CONTEXT_SET_IP (&ctx, NULL);
4739 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4740 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4742 mono_loader_lock ();
4743 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4744 mono_loader_unlock ();
4746 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4753 ss_depth_to_string (StepDepth depth)
4756 case STEP_DEPTH_OVER:
4758 case STEP_DEPTH_OUT:
4760 case STEP_DEPTH_INTO:
4763 g_assert_not_reached ();
4769 process_single_step_inner (DebuggerTlsData *tls)
4774 int il_offset, suspend_policy;
4777 MonoContext *ctx = &tls->restore_ctx;
4780 MonoSeqPointInfo *info;
4782 ip = MONO_CONTEXT_GET_IP (ctx);
4784 /* Skip the instruction causing the single step */
4785 mono_arch_skip_single_step (ctx);
4787 if (suspend_count > 0) {
4788 process_suspend (tls, ctx);
4793 // FIXME: A suspend race
4796 if (mono_thread_internal_current () != ss_req->thread)
4799 if (log_level > 0) {
4800 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4802 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 (jinfo_get_method (ji), TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4805 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4807 method = jinfo_get_method (ji);
4810 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4815 * Stopping in memset makes half-initialized vtypes visible.
4816 * Stopping in memcpy makes half-copied vtypes visible.
4818 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4822 * The ip points to the instruction causing the single step event, which is before
4823 * the offset recorded in the seq point map, so find the next seq point after ip.
4825 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
4828 il_offset = sp->il_offset;
4830 if (!ss_update (ss_req, ji, sp, tls, ctx))
4833 /* Start single stepping again from the current sequence point */
4834 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4836 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4837 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4838 !strcmp (method->name, ".cctor"))
4841 // FIXME: Has to lock earlier
4843 reqs = g_ptr_array_new ();
4845 mono_loader_lock ();
4847 g_ptr_array_add (reqs, ss_req->req);
4849 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4851 g_ptr_array_free (reqs, TRUE);
4853 mono_loader_unlock ();
4855 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4859 process_single_step (void)
4861 process_signal_event (process_single_step_inner);
4865 * mono_debugger_agent_single_step_event:
4867 * Called from a signal handler to handle a single step event.
4870 mono_debugger_agent_single_step_event (void *sigctx)
4872 /* Resume to process_single_step through the signal context */
4874 // FIXME: Since step out/over is implemented using step in, the step in case should
4875 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4878 if (GetCurrentThreadId () == debugger_thread_id) {
4880 * This could happen despite our best effors when the runtime calls
4881 * assembly/type resolve hooks.
4882 * FIXME: Breakpoints too.
4886 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4887 mono_arch_skip_single_step (&ctx);
4888 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4892 resume_from_signal_handler (sigctx, process_single_step);
4896 debugger_agent_single_step_from_context (MonoContext *ctx)
4898 DebuggerTlsData *tls;
4899 MonoContext orig_restore_ctx;
4901 tls = mono_native_tls_get_value (debugger_tls_id);
4904 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4905 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4906 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4908 process_single_step_inner (tls);
4910 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4911 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4915 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4917 DebuggerTlsData *tls;
4918 MonoContext orig_restore_ctx;
4920 tls = mono_native_tls_get_value (debugger_tls_id);
4922 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4923 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4925 process_breakpoint_inner (tls);
4927 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4928 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4932 * start_single_stepping:
4934 * Turn on single stepping. Can be called multiple times, for example,
4935 * by a single step event request + a suspend.
4938 start_single_stepping (void)
4940 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4941 int val = InterlockedIncrement (&ss_count);
4944 mono_arch_start_single_stepping ();
4946 if (ss_req != NULL && ss_invoke_addr == NULL) {
4947 DebuggerTlsData *tls;
4949 mono_loader_lock ();
4951 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4952 ss_invoke_addr = tls->invoke_addr;
4954 mono_loader_unlock ();
4957 g_assert_not_reached ();
4962 stop_single_stepping (void)
4964 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4965 int val = InterlockedDecrement (&ss_count);
4968 mono_arch_stop_single_stepping ();
4970 ss_invoke_addr = NULL;
4972 g_assert_not_reached ();
4979 * Stop the single stepping operation given by SS_REQ.
4982 ss_stop (SingleStepReq *ss_req)
4987 for (l = ss_req->bps; l; l = l->next) {
4988 clear_breakpoint (l->data);
4990 g_slist_free (ss_req->bps);
4994 if (ss_req->global) {
4995 stop_single_stepping ();
4996 ss_req->global = FALSE;
5003 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5004 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5005 * belong to the same thread as CTX.
5008 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5010 int i, j, frame_index;
5013 gboolean enable_global = FALSE;
5015 /* Stop the previous operation */
5019 * Implement single stepping using breakpoints if possible.
5021 if (step_to_catch) {
5022 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5023 ss_req->bps = g_slist_append (ss_req->bps, bp);
5027 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5028 /* Need parent frames */
5029 if (!tls->context.valid)
5030 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5031 compute_frame_info (tls->thread, tls);
5035 * Find the first sequence point in the current or in a previous frame which
5036 * is not the last in its method.
5038 if (ss_req->depth == STEP_DEPTH_OUT) {
5039 /* Ignore seq points in current method */
5040 while (frame_index < tls->frame_count) {
5041 StackFrame *frame = tls->frames [frame_index];
5043 method = frame->method;
5044 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5046 if (sp && sp->next_len != 0)
5049 // There could be method calls before the next seq point in the caller when using nested calls
5050 //enable_global = TRUE;
5052 if (sp && sp->next_len == 0) {
5054 while (frame_index < tls->frame_count) {
5055 StackFrame *frame = tls->frames [frame_index];
5057 method = frame->method;
5058 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5059 if (sp && sp->next_len != 0)
5067 if (sp && sp->next_len > 0) {
5068 for (i = 0; i < sp->next_len; ++i) {
5069 next_sp = &info->seq_points [sp->next [i]];
5071 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5072 ss_req->bps = g_slist_append (ss_req->bps, bp);
5076 if (ss_req->depth == STEP_DEPTH_OVER) {
5077 if (ss_req->nframes == 0)
5078 ss_req->nframes = tls->frame_count;
5079 /* Need to stop in catch clauses as well */
5080 for (i = 0; i < tls->frame_count; ++i) {
5081 StackFrame *frame = tls->frames [i];
5084 MonoJitInfo *jinfo = frame->ji;
5085 for (j = 0; j < jinfo->num_clauses; ++j) {
5086 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5088 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5090 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5091 ss_req->bps = g_slist_append (ss_req->bps, bp);
5099 if (ss_req->depth == STEP_DEPTH_INTO) {
5100 /* Enable global stepping so we stop at method entry too */
5101 enable_global = TRUE;
5105 * The ctx/frame info computed above will become invalid when we continue.
5107 tls->context.valid = FALSE;
5108 tls->async_state.valid = FALSE;
5109 invalidate_frames (tls);
5112 if (enable_global) {
5113 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5114 ss_req->global = TRUE;
5115 start_single_stepping ();
5116 } else if (!ss_req->bps) {
5117 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5118 ss_req->global = TRUE;
5119 start_single_stepping ();
5121 ss_req->global = FALSE;
5126 * Start single stepping of thread THREAD
5129 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5131 DebuggerTlsData *tls;
5132 MonoSeqPointInfo *info = NULL;
5133 SeqPoint *sp = NULL;
5134 MonoMethod *method = NULL;
5135 MonoDebugMethodInfo *minfo;
5136 gboolean step_to_catch = FALSE;
5138 if (suspend_count == 0)
5139 return ERR_NOT_SUSPENDED;
5141 wait_for_suspend ();
5143 // FIXME: Multiple requests
5145 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5146 return ERR_NOT_IMPLEMENTED;
5149 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5151 ss_req = g_new0 (SingleStepReq, 1);
5153 ss_req->thread = thread;
5154 ss_req->size = size;
5155 ss_req->depth = depth;
5158 mono_loader_lock ();
5159 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5160 mono_loader_unlock ();
5162 g_assert (tls->context.valid);
5163 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5165 if (tls->catch_state.valid) {
5167 StackFrameInfo frame;
5168 MonoContext new_ctx;
5169 MonoLMF *lmf = NULL;
5172 * We are stopped at a throw site. Stepping should go to the catch site.
5175 /* Find the the jit info for the catch context */
5176 res = mono_find_jit_info_ext (tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], thread->jit_data, NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5178 g_assert (frame.type == FRAME_TYPE_MANAGED);
5181 * Find the seq point corresponding to the landing site ip, which is the first seq
5184 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5186 no_seq_points_found (frame.method);
5189 method = frame.method;
5191 step_to_catch = TRUE;
5192 /* This make sure the seq point is not skipped by process_single_step () */
5193 ss_req->last_sp = NULL;
5196 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5199 /* Compute the initial line info */
5200 compute_frame_info (thread, tls);
5202 if (tls->frame_count) {
5203 frame = tls->frames [0];
5205 ss_req->last_method = frame->method;
5206 ss_req->last_line = -1;
5208 minfo = mono_debug_lookup_method (frame->method);
5209 if (minfo && frame->il_offset != -1) {
5210 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5213 ss_req->last_line = loc->row;
5220 if (!step_to_catch) {
5223 compute_frame_info (thread, tls);
5225 if (tls->frame_count) {
5226 frame = tls->frames [0];
5228 if (!method && frame->il_offset != -1) {
5229 /* FIXME: Sort the table and use a binary search */
5230 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5232 no_seq_points_found (frame->method);
5234 method = frame->method;
5239 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5245 ss_destroy (SingleStepReq *req)
5248 g_assert (ss_req == req);
5257 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5260 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5266 if (!agent_config.enabled)
5269 mono_loader_lock ();
5270 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5271 mono_loader_unlock ();
5274 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5275 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5277 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5279 g_free (ei.category);
5280 g_free (ei.message);
5284 mono_debugger_agent_debug_log_is_enabled (void)
5286 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5287 return agent_config.enabled;
5290 #ifdef PLATFORM_ANDROID
5292 mono_debugger_agent_unhandled_exception (MonoException *exc)
5301 memset (&ei, 0, sizeof (EventInfo));
5302 ei.exc = (MonoObject*)exc;
5304 mono_loader_lock ();
5305 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5306 mono_loader_unlock ();
5308 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5313 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5314 MonoContext *catch_ctx)
5316 int i, j, suspend_policy;
5318 MonoJitInfo *ji, *catch_ji;
5320 DebuggerTlsData *tls = NULL;
5322 if (thread_to_tls != NULL) {
5323 MonoInternalThread *thread = mono_thread_internal_current ();
5325 mono_loader_lock ();
5326 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5327 mono_loader_unlock ();
5329 if (tls && tls->abort_requested)
5331 if (tls && tls->disable_breakpoints)
5335 memset (&ei, 0, sizeof (EventInfo));
5337 /* Just-In-Time debugging */
5339 if (agent_config.onuncaught && !inited) {
5340 finish_agent_init (FALSE);
5343 * Send an unsolicited EXCEPTION event with a dummy request id.
5345 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5346 ei.exc = (MonoObject*)exc;
5347 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5350 } else if (agent_config.onthrow && !inited) {
5352 gboolean found = FALSE;
5354 for (l = agent_config.onthrow; l; l = l->next) {
5355 char *ex_type = l->data;
5356 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5358 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5365 finish_agent_init (FALSE);
5368 * Send an unsolicited EXCEPTION event with a dummy request id.
5370 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5371 ei.exc = (MonoObject*)exc;
5372 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5380 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5382 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5386 ei.exc = (MonoObject*)exc;
5387 ei.caught = catch_ctx != NULL;
5389 mono_loader_lock ();
5391 /* Treat exceptions which are caught in non-user code as unhandled */
5392 for (i = 0; i < event_requests->len; ++i) {
5393 EventRequest *req = g_ptr_array_index (event_requests, i);
5394 if (req->event_kind != EVENT_KIND_EXCEPTION)
5397 for (j = 0; j < req->nmodifiers; ++j) {
5398 Modifier *mod = &req->modifiers [j];
5400 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5402 gboolean found = FALSE;
5403 MonoAssembly **assemblies = mod->data.assemblies;
5406 for (k = 0; assemblies [k]; ++k)
5407 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5416 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5417 mono_loader_unlock ();
5419 if (tls && ei.caught && catch_ctx) {
5420 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5421 tls->catch_state.ctx = *catch_ctx;
5422 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5423 tls->catch_state.valid = TRUE;
5426 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5429 tls->catch_state.valid = FALSE;
5433 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5435 DebuggerTlsData *tls;
5440 tls = mono_native_tls_get_value (debugger_tls_id);
5445 * We're about to invoke an exception filter during the first pass of exception handling.
5447 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5448 * 'orig_ctx' is the context where the exception has been thrown.
5451 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5453 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5454 * the call site (line 37) and then continue to Main(), but it would never
5455 * include the throw site (line 32).
5457 * Since exception filters are invoked during the first pass of exception handling,
5458 * the stack frames of the throw site are still intact, so we should include them
5461 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5463 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5464 * but report the location of the 'throw' to the user.
5468 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5472 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5474 DebuggerTlsData *tls;
5479 tls = mono_native_tls_get_value (debugger_tls_id);
5483 tls->filter_state.valid = FALSE;
5487 * buffer_add_value_full:
5489 * Add the encoding of the value at ADDR described by T to the buffer.
5490 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5494 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5500 if (!(*(void**)addr)) {
5501 /* This can happen with compiler generated locals */
5502 //printf ("%s\n", mono_type_full_name (t));
5503 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5506 g_assert (*(void**)addr);
5507 addr = *(void**)addr;
5512 case MONO_TYPE_BOOLEAN:
5515 case MONO_TYPE_CHAR:
5535 case MONO_TYPE_VOID:
5536 buffer_add_byte (buf, t->type);
5538 case MONO_TYPE_BOOLEAN:
5541 buffer_add_byte (buf, t->type);
5542 buffer_add_int (buf, *(gint8*)addr);
5544 case MONO_TYPE_CHAR:
5547 buffer_add_byte (buf, t->type);
5548 buffer_add_int (buf, *(gint16*)addr);
5553 buffer_add_byte (buf, t->type);
5554 buffer_add_int (buf, *(gint32*)addr);
5559 buffer_add_byte (buf, t->type);
5560 buffer_add_long (buf, *(gint64*)addr);
5564 /* Treat it as a vtype */
5566 case MONO_TYPE_PTR: {
5567 gssize val = *(gssize*)addr;
5569 buffer_add_byte (buf, t->type);
5570 buffer_add_long (buf, val);
5574 case MONO_TYPE_STRING:
5575 case MONO_TYPE_SZARRAY:
5576 case MONO_TYPE_OBJECT:
5577 case MONO_TYPE_CLASS:
5578 case MONO_TYPE_ARRAY:
5579 obj = *(MonoObject**)addr;
5582 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5584 if (obj->vtable->klass->valuetype) {
5585 t = &obj->vtable->klass->byval_arg;
5586 addr = mono_object_unbox (obj);
5588 } else if (obj->vtable->klass->rank) {
5589 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5590 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5591 buffer_add_byte (buf, MONO_TYPE_CLASS);
5593 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5595 buffer_add_objid (buf, obj);
5599 case MONO_TYPE_VALUETYPE: {
5603 MonoClass *klass = mono_class_from_mono_type (t);
5605 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5606 buffer_add_byte (buf, klass->enumtype);
5607 buffer_add_typeid (buf, domain, klass);
5611 while ((f = mono_class_get_fields (klass, &iter))) {
5612 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5614 if (mono_field_is_deleted (f))
5618 buffer_add_int (buf, nfields);
5621 while ((f = mono_class_get_fields (klass, &iter))) {
5622 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5624 if (mono_field_is_deleted (f))
5626 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5630 case MONO_TYPE_GENERICINST:
5631 if (mono_type_generic_inst_is_valuetype (t)) {
5643 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5645 buffer_add_value_full (buf, t, addr, domain, FALSE);
5649 obj_is_of_type (MonoObject *obj, MonoType *t)
5651 MonoClass *klass = obj->vtable->klass;
5652 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5653 if (mono_class_is_transparent_proxy (klass)) {
5654 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5655 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5665 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5668 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5674 gpointer iter = NULL;
5678 is_enum = decode_byte (buf, &buf, limit);
5679 /* Enums are sent as a normal vtype */
5681 return ERR_NOT_IMPLEMENTED;
5682 klass = decode_typeid (buf, &buf, limit, &d, &err);
5686 if (t && klass != mono_class_from_mono_type (t)) {
5687 char *name = mono_type_full_name (t);
5688 char *name2 = mono_type_full_name (&klass->byval_arg);
5689 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5692 return ERR_INVALID_ARGUMENT;
5695 nfields = decode_int (buf, &buf, limit);
5696 while ((f = mono_class_get_fields (klass, &iter))) {
5697 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5699 if (mono_field_is_deleted (f))
5701 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5706 g_assert (nfields == 0);
5714 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5718 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5719 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5720 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5721 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5722 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5723 char *name = mono_type_full_name (t);
5724 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5726 return ERR_INVALID_ARGUMENT;
5730 case MONO_TYPE_BOOLEAN:
5731 *(guint8*)addr = decode_int (buf, &buf, limit);
5733 case MONO_TYPE_CHAR:
5734 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5737 *(gint8*)addr = decode_int (buf, &buf, limit);
5740 *(guint8*)addr = decode_int (buf, &buf, limit);
5743 *(gint16*)addr = decode_int (buf, &buf, limit);
5746 *(guint16*)addr = decode_int (buf, &buf, limit);
5749 *(gint32*)addr = decode_int (buf, &buf, limit);
5752 *(guint32*)addr = decode_int (buf, &buf, limit);
5755 *(gint64*)addr = decode_long (buf, &buf, limit);
5758 *(guint64*)addr = decode_long (buf, &buf, limit);
5761 *(guint32*)addr = decode_int (buf, &buf, limit);
5764 *(guint64*)addr = decode_long (buf, &buf, limit);
5767 /* We send these as I8, so we get them back as such */
5768 g_assert (type == MONO_TYPE_I8);
5769 *(gssize*)addr = decode_long (buf, &buf, limit);
5771 case MONO_TYPE_GENERICINST:
5772 if (MONO_TYPE_ISSTRUCT (t)) {
5773 /* The client sends these as a valuetype */
5781 /* We send these as vtypes, so we get them back as such */
5782 g_assert (type == MONO_TYPE_VALUETYPE);
5785 case MONO_TYPE_VALUETYPE:
5786 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5792 if (MONO_TYPE_IS_REFERENCE (t)) {
5793 if (type == MONO_TYPE_OBJECT) {
5794 int objid = decode_objid (buf, &buf, limit);
5798 err = get_object (objid, (MonoObject**)&obj);
5803 if (!obj_is_of_type (obj, t)) {
5804 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5805 return ERR_INVALID_ARGUMENT;
5808 if (obj && obj->vtable->domain != domain)
5809 return ERR_INVALID_ARGUMENT;
5811 mono_gc_wbarrier_generic_store (addr, obj);
5812 } else if (type == VALUE_TYPE_ID_NULL) {
5813 *(MonoObject**)addr = NULL;
5814 } else if (type == MONO_TYPE_VALUETYPE) {
5822 /* This can happen when round-tripping boxed vtypes */
5824 * Obtain vtype class.
5825 * Same as the beginning of the handle_vtype case above.
5828 is_enum = decode_byte (buf, &buf, limit);
5830 return ERR_NOT_IMPLEMENTED;
5831 klass = decode_typeid (buf, &buf, limit, &d, &err);
5835 /* Decode the vtype into a temporary buffer, then box it. */
5836 vtype_buf_size = mono_class_value_size (klass, NULL);
5837 vtype_buf = g_malloc0 (vtype_buf_size);
5838 g_assert (vtype_buf);
5841 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
5846 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
5849 char *name = mono_type_full_name (t);
5850 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5852 return ERR_INVALID_ARGUMENT;
5866 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5869 int type = decode_byte (buf, &buf, limit);
5871 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5872 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5873 guint8 *nullable_buf;
5876 * First try decoding it as a Nullable`1
5878 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5883 * Then try decoding as a primitive value or null.
5885 if (targ->type == type) {
5886 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5887 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5889 g_free (nullable_buf);
5892 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5893 g_free (nullable_buf);
5896 } else if (type == VALUE_TYPE_ID_NULL) {
5897 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5903 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5907 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5911 guint8 *addr, *gaddr;
5914 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5915 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5918 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5919 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5921 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5923 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5924 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5925 addr += (gint32)var->offset;
5927 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5929 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5931 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5934 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5935 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5936 /* Same as regoffset, but with an indirection */
5937 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5938 addr += (gint32)var->offset;
5940 gaddr = *(gpointer*)addr;
5942 buffer_add_value_full (buf, t, gaddr, domain, as_vtype);
5944 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5945 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5946 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5947 MonoGSharedVtMethodRuntimeInfo *info;
5953 g_assert (info_var);
5954 g_assert (locals_var);
5956 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5957 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5958 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5959 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5960 addr += (gint32)info_var->offset;
5961 info = *(gpointer*)addr;
5962 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5963 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5965 g_assert_not_reached ();
5969 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5970 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5971 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5972 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5973 addr += (gint32)locals_var->offset;
5974 locals = *(gpointer*)addr;
5975 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5976 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5978 g_assert_not_reached ();
5982 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5984 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5989 g_assert_not_reached ();
5994 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5998 guint8 *addr, *gaddr;
6000 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6001 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6003 if (MONO_TYPE_IS_REFERENCE (t))
6004 size = sizeof (gpointer);
6006 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6009 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6010 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6012 gboolean is_signed = FALSE;
6014 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6019 v = is_signed ? *(gint8*)val : *(guint8*)val;
6022 v = is_signed ? *(gint16*)val : *(guint16*)val;
6025 v = is_signed ? *(gint32*)val : *(guint32*)val;
6028 v = is_signed ? *(gint64*)val : *(guint64*)val;
6031 g_assert_not_reached ();
6037 /* Set value on the stack or in the return ctx */
6038 if (reg_locations [reg]) {
6039 /* Saved on the stack */
6040 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6041 *(reg_locations [reg]) = v;
6044 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6045 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6048 // FIXME: Move these to mono-context.h/c.
6049 mono_arch_context_set_int_reg (ctx, reg, v);
6051 // FIXME: Can't set registers, so we disable linears
6056 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6057 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6058 addr += (gint32)var->offset;
6060 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6063 addr = *(guint8**)addr;
6069 // FIXME: Write barriers
6070 mono_gc_memmove (addr, val, size);
6072 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6073 /* Same as regoffset, but with an indirection */
6074 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6075 addr += (gint32)var->offset;
6077 gaddr = *(gpointer*)addr;
6079 // FIXME: Write barriers
6080 mono_gc_memmove (gaddr, val, size);
6082 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6086 g_assert_not_reached ();
6091 clear_event_request (int req_id, int etype)
6095 mono_loader_lock ();
6096 for (i = 0; i < event_requests->len; ++i) {
6097 EventRequest *req = g_ptr_array_index (event_requests, i);
6099 if (req->id == req_id && req->event_kind == etype) {
6100 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6101 clear_breakpoint (req->info);
6102 if (req->event_kind == EVENT_KIND_STEP)
6103 ss_destroy (req->info);
6104 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6105 clear_breakpoint (req->info);
6106 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6107 clear_breakpoint (req->info);
6108 g_ptr_array_remove_index_fast (event_requests, i);
6113 mono_loader_unlock ();
6117 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
6119 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6120 return breakpoint_matches_assembly (req->info, assembly);
6124 for (i = 0; i < req->nmodifiers; ++i) {
6125 Modifier *m = &req->modifiers [i];
6127 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6129 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6130 for (j = 0; m->data.assemblies [j]; ++j)
6131 if (m->data.assemblies [j] == assembly)
6141 * clear_event_requests_for_assembly:
6143 * Clear all events requests which reference ASSEMBLY.
6146 clear_event_requests_for_assembly (MonoAssembly *assembly)
6151 mono_loader_lock ();
6155 for (i = 0; i < event_requests->len; ++i) {
6156 EventRequest *req = g_ptr_array_index (event_requests, i);
6158 if (event_req_matches_assembly (req, assembly)) {
6159 clear_event_request (req->id, req->event_kind);
6165 mono_loader_unlock ();
6169 * type_comes_from_assembly:
6171 * GHRFunc that returns TRUE if klass comes from assembly
6174 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6176 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6180 * clear_types_for_assembly:
6182 * Clears types from loaded_classes for a given assembly
6185 clear_types_for_assembly (MonoAssembly *assembly)
6187 MonoDomain *domain = mono_domain_get ();
6188 AgentDomainInfo *info = NULL;
6190 mono_loader_lock ();
6191 info = get_agent_domain_info (domain);
6192 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6193 mono_loader_unlock ();
6197 add_thread (gpointer key, gpointer value, gpointer user_data)
6199 MonoInternalThread *thread = value;
6200 Buffer *buf = user_data;
6202 buffer_add_objid (buf, (MonoObject*)thread);
6206 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6208 guint8 *end = invoke->endp;
6211 MonoMethodSignature *sig;
6214 MonoObject *this, *res, *exc;
6217 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6220 MonoStopwatch watch;
6222 if (invoke->method) {
6224 * Invoke this method directly, currently only Environment.Exit () is supported.
6227 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>"));
6228 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6229 g_assert_not_reached ();
6232 m = decode_methodid (p, &p, end, &domain, &err);
6235 sig = mono_method_signature (m);
6237 if (m->klass->valuetype)
6238 this_buf = g_alloca (mono_class_instance_size (m->klass));
6240 this_buf = g_alloca (sizeof (MonoObject*));
6241 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6242 /* Should be null */
6243 int type = decode_byte (p, &p, end);
6244 if (type != VALUE_TYPE_ID_NULL) {
6245 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6246 return ERR_INVALID_ARGUMENT;
6248 memset (this_buf, 0, mono_class_instance_size (m->klass));
6250 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6255 if (!m->klass->valuetype)
6256 this = *(MonoObject**)this_buf;
6260 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6262 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6263 return ERR_INVALID_ARGUMENT;
6265 m = mono_object_get_virtual_method (this, m);
6268 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>"));
6270 if (this && this->vtable->domain != domain)
6273 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6274 if (!strcmp (m->name, ".ctor")) {
6275 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6276 return ERR_INVALID_ARGUMENT;
6278 this = mono_object_new (domain, m->klass);
6280 return ERR_INVALID_ARGUMENT;
6284 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6285 return ERR_INVALID_ARGUMENT;
6287 nargs = decode_int (p, &p, end);
6288 if (nargs != sig->param_count)
6289 return ERR_INVALID_ARGUMENT;
6290 /* Use alloca to get gc tracking */
6291 arg_buf = g_alloca (nargs * sizeof (gpointer));
6292 memset (arg_buf, 0, nargs * sizeof (gpointer));
6293 args = g_alloca (nargs * sizeof (gpointer));
6294 for (i = 0; i < nargs; ++i) {
6295 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6296 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6300 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6303 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6304 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6307 args [i] = arg_buf [i];
6314 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6315 tls->disable_breakpoints = TRUE;
6317 tls->disable_breakpoints = FALSE;
6320 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6322 /* FIXME: Move this to arch specific code */
6323 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6324 if (invoke->has_ctx) {
6327 lmf_addr = mono_get_lmf_addr ();
6330 memset (&ext, 0, sizeof (ext));
6331 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6333 ext.debugger_invoke = TRUE;
6334 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6336 mono_set_lmf ((MonoLMF*)&ext);
6340 mono_stopwatch_start (&watch);
6341 if (m->klass->valuetype)
6342 res = mono_runtime_invoke (m, this_buf, args, &exc);
6344 res = mono_runtime_invoke (m, this, args, &exc);
6345 mono_stopwatch_stop (&watch);
6346 DEBUG (1, fprintf (log_file, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer)GetCurrentThreadId (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch)));
6348 buffer_add_byte (buf, 0);
6349 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6351 buffer_add_byte (buf, 1);
6352 if (sig->ret->type == MONO_TYPE_VOID) {
6353 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6354 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6357 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6358 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6359 buffer_add_value (buf, sig->ret, &res, domain);
6360 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6361 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6362 MonoClass *k = mono_class_from_mono_type (sig->ret);
6363 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6365 g_assert (nullable_buf);
6366 mono_nullable_init (nullable_buf, res, k);
6367 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6370 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6377 tls->disable_breakpoints = FALSE;
6379 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6380 if (invoke->has_ctx)
6381 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6385 // FIXME: byref arguments
6393 * Invoke the method given by tls->pending_invoke in the current thread.
6396 invoke_method (void)
6398 DebuggerTlsData *tls;
6403 MonoContext restore_ctx;
6406 tls = mono_native_tls_get_value (debugger_tls_id);
6410 * Store the `InvokeData *' in `tls->invoke' until we're done with
6411 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6414 mono_loader_lock ();
6416 invoke = tls->pending_invoke;
6418 tls->pending_invoke = NULL;
6420 invoke->last_invoke = tls->invoke;
6421 tls->invoke = invoke;
6423 mono_loader_unlock ();
6425 tls->frames_up_to_date = FALSE;
6431 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6432 buffer_init (&buf, 128);
6435 /* Fail the other invokes as well */
6437 err = do_invoke_method (tls, &buf, invoke, p, &p);
6440 /* Start suspending before sending the reply */
6441 if (mindex == invoke->nmethods - 1) {
6442 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6443 for (i = 0; i < invoke->suspend_count; ++i)
6448 send_reply_packet (id, err, &buf);
6453 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6455 if (invoke->has_ctx)
6456 save_thread_context (&restore_ctx);
6458 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6459 g_assert (tls->resume_count);
6460 tls->resume_count -= invoke->suspend_count;
6463 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6466 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6468 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6469 * after the mono_runtime_invoke() already returned, but it doesn't matter
6470 * because we reset the abort here.
6473 mono_loader_lock ();
6475 if (tls->abort_requested)
6476 mono_thread_internal_reset_abort (tls->thread);
6478 tls->invoke = tls->invoke->last_invoke;
6479 tls->abort_requested = FALSE;
6481 mono_loader_unlock ();
6490 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6492 MonoThread *thread = value;
6493 DebuggerTlsData *tls;
6496 mono_loader_lock ();
6497 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6499 res = tls->really_suspended;
6500 mono_loader_unlock ();
6506 get_source_files_for_type (MonoClass *klass)
6508 gpointer iter = NULL;
6510 MonoDebugSourceInfo *sinfo;
6514 files = g_ptr_array_new ();
6516 while ((method = mono_class_get_methods (klass, &iter))) {
6517 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6518 GPtrArray *source_file_list;
6521 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6522 for (j = 0; j < source_file_list->len; ++j) {
6523 sinfo = g_ptr_array_index (source_file_list, j);
6524 for (i = 0; i < files->len; ++i)
6525 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6527 if (i == files->len)
6528 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6530 g_ptr_array_free (source_file_list, TRUE);
6538 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6541 case CMD_VM_VERSION: {
6542 char *build_info, *version;
6544 build_info = mono_get_runtime_build_info ();
6545 version = g_strdup_printf ("mono %s", build_info);
6547 buffer_add_string (buf, version); /* vm version */
6548 buffer_add_int (buf, MAJOR_VERSION);
6549 buffer_add_int (buf, MINOR_VERSION);
6550 g_free (build_info);
6554 case CMD_VM_SET_PROTOCOL_VERSION: {
6555 major_version = decode_int (p, &p, end);
6556 minor_version = decode_int (p, &p, end);
6557 protocol_version_set = TRUE;
6558 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6561 case CMD_VM_ALL_THREADS: {
6563 mono_loader_lock ();
6564 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6565 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6566 mono_loader_unlock ();
6569 case CMD_VM_SUSPEND:
6571 wait_for_suspend ();
6574 if (suspend_count == 0)
6575 return ERR_NOT_SUSPENDED;
6577 clear_suspended_objs ();
6579 case CMD_VM_DISPOSE:
6580 /* Clear all event requests */
6581 mono_loader_lock ();
6582 while (event_requests->len > 0) {
6583 EventRequest *req = g_ptr_array_index (event_requests, 0);
6585 clear_event_request (req->id, req->event_kind);
6587 mono_loader_unlock ();
6589 while (suspend_count > 0)
6591 disconnected = TRUE;
6592 vm_start_event_sent = FALSE;
6595 MonoInternalThread *thread;
6596 DebuggerTlsData *tls;
6597 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6598 MonoClass *env_class;
6600 MonoMethod *exit_method = NULL;
6604 exit_code = decode_int (p, &p, end);
6606 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6608 /* Have to send a reply before exiting */
6609 send_reply_packet (id, 0, buf);
6611 /* Clear all event requests */
6612 mono_loader_lock ();
6613 while (event_requests->len > 0) {
6614 EventRequest *req = g_ptr_array_index (event_requests, 0);
6616 clear_event_request (req->id, req->event_kind);
6618 mono_loader_unlock ();
6621 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6622 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6623 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6624 * better than doing the shutdown ourselves, since it avoids various races.
6628 wait_for_suspend ();
6630 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6631 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6633 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6636 mono_loader_lock ();
6637 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6638 mono_loader_unlock ();
6640 if (thread && exit_method) {
6641 mono_loader_lock ();
6642 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6643 mono_loader_unlock ();
6645 args = g_new0 (gpointer, 1);
6646 args [0] = g_malloc (sizeof (int));
6647 *(int*)(args [0]) = exit_code;
6649 tls->pending_invoke = g_new0 (InvokeData, 1);
6650 tls->pending_invoke->method = exit_method;
6651 tls->pending_invoke->args = args;
6652 tls->pending_invoke->nmethods = 1;
6654 while (suspend_count > 0)
6658 * No thread found, do it ourselves.
6659 * FIXME: This can race with normal shutdown etc.
6661 while (suspend_count > 0)
6664 if (!mono_runtime_try_shutdown ())
6667 mono_environment_exitcode_set (exit_code);
6669 /* Suspend all managed threads since the runtime is going away */
6670 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6671 mono_thread_suspend_all_other_threads ();
6672 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6673 mono_runtime_quit ();
6674 transport_close2 ();
6675 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6681 case CMD_VM_INVOKE_METHOD:
6682 case CMD_VM_INVOKE_METHODS: {
6683 int objid = decode_objid (p, &p, end);
6685 DebuggerTlsData *tls;
6686 int i, count, err, flags, nmethods;
6688 err = get_object (objid, (MonoObject**)&thread);
6692 flags = decode_int (p, &p, end);
6694 if (command == CMD_VM_INVOKE_METHODS)
6695 nmethods = decode_int (p, &p, end);
6699 // Wait for suspending if it already started
6701 wait_for_suspend ();
6702 if (!is_suspended ())
6703 return ERR_NOT_SUSPENDED;
6705 mono_loader_lock ();
6706 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6707 mono_loader_unlock ();
6710 if (!tls->really_suspended)
6711 /* The thread is still running native code, can't do invokes */
6712 return ERR_NOT_SUSPENDED;
6715 * Store the invoke data into tls, the thread will execute it after it is
6718 if (tls->pending_invoke)
6719 return ERR_NOT_SUSPENDED;
6720 tls->pending_invoke = g_new0 (InvokeData, 1);
6721 tls->pending_invoke->id = id;
6722 tls->pending_invoke->flags = flags;
6723 tls->pending_invoke->p = g_malloc (end - p);
6724 memcpy (tls->pending_invoke->p, p, end - p);
6725 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6726 tls->pending_invoke->suspend_count = suspend_count;
6727 tls->pending_invoke->nmethods = nmethods;
6729 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6730 resume_thread (THREAD_TO_INTERNAL (thread));
6733 count = suspend_count;
6734 for (i = 0; i < count; ++i)
6739 case CMD_VM_ABORT_INVOKE: {
6740 int objid = decode_objid (p, &p, end);
6742 DebuggerTlsData *tls;
6745 err = get_object (objid, (MonoObject**)&thread);
6749 invoke_id = decode_int (p, &p, end);
6751 mono_loader_lock ();
6752 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6755 if (tls->abort_requested) {
6756 mono_loader_unlock ();
6761 * Check whether we're still inside the mono_runtime_invoke() and that it's
6762 * actually the correct invocation.
6764 * Careful, we do not stop the thread that's doing the invocation, so we can't
6765 * inspect its stack. However, invoke_method() also acquires the loader lock
6766 * when it's done, so we're safe here.
6770 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6771 mono_loader_unlock ();
6772 return ERR_NO_INVOCATION;
6775 tls->abort_requested = TRUE;
6777 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6778 mono_loader_unlock ();
6782 case CMD_VM_SET_KEEPALIVE: {
6783 int timeout = decode_int (p, &p, end);
6784 agent_config.keepalive = timeout;
6786 #ifndef DISABLE_SOCKET_TRANSPORT
6793 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6794 GHashTableIter iter, kiter;
6799 char *fname, *basename;
6800 gboolean ignore_case;
6801 GSList *class_list, *l;
6802 GPtrArray *res_classes, *res_domains;
6804 fname = decode_string (p, &p, end);
6805 ignore_case = decode_byte (p, &p, end);
6807 basename = g_path_get_basename (fname);
6809 res_classes = g_ptr_array_new ();
6810 res_domains = g_ptr_array_new ();
6812 mono_loader_lock ();
6813 g_hash_table_iter_init (&iter, domains);
6814 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6815 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6817 /* Update 'source_file_to_class' cache */
6818 g_hash_table_iter_init (&kiter, info->loaded_classes);
6819 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6820 if (!g_hash_table_lookup (info->source_files, klass)) {
6821 files = get_source_files_for_type (klass);
6822 g_hash_table_insert (info->source_files, klass, files);
6824 for (i = 0; i < files->len; ++i) {
6825 char *s = g_ptr_array_index (files, i);
6826 char *s2 = g_path_get_basename (s);
6829 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6831 class_list = g_slist_prepend (class_list, klass);
6832 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6834 class_list = g_slist_prepend (class_list, klass);
6835 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6838 /* The _ignorecase hash contains the lowercase path */
6839 s3 = strdup_tolower (s2);
6840 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6842 class_list = g_slist_prepend (class_list, klass);
6843 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6845 class_list = g_slist_prepend (class_list, klass);
6846 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6858 s = strdup_tolower (basename);
6859 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6862 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6865 for (l = class_list; l; l = l->next) {
6868 g_ptr_array_add (res_classes, klass);
6869 g_ptr_array_add (res_domains, domain);
6872 mono_loader_unlock ();
6877 buffer_add_int (buf, res_classes->len);
6878 for (i = 0; i < res_classes->len; ++i)
6879 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6880 g_ptr_array_free (res_classes, TRUE);
6881 g_ptr_array_free (res_domains, TRUE);
6884 case CMD_VM_GET_TYPES: {
6885 GHashTableIter iter;
6889 gboolean ignore_case;
6890 GPtrArray *res_classes, *res_domains;
6891 MonoTypeNameParse info;
6893 name = decode_string (p, &p, end);
6894 ignore_case = decode_byte (p, &p, end);
6896 if (!mono_reflection_parse_type (name, &info)) {
6898 mono_reflection_free_type_info (&info);
6899 return ERR_INVALID_ARGUMENT;
6902 res_classes = g_ptr_array_new ();
6903 res_domains = g_ptr_array_new ();
6905 mono_loader_lock ();
6906 g_hash_table_iter_init (&iter, domains);
6907 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6909 gboolean type_resolve;
6913 mono_domain_assemblies_lock (domain);
6914 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6918 type_resolve = TRUE;
6919 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6921 g_ptr_array_add (res_classes, mono_type_get_class (t));
6922 g_ptr_array_add (res_domains, domain);
6926 mono_domain_assemblies_unlock (domain);
6928 mono_loader_unlock ();
6931 mono_reflection_free_type_info (&info);
6933 buffer_add_int (buf, res_classes->len);
6934 for (i = 0; i < res_classes->len; ++i)
6935 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6936 g_ptr_array_free (res_classes, TRUE);
6937 g_ptr_array_free (res_domains, TRUE);
6942 return ERR_NOT_IMPLEMENTED;
6949 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6955 case CMD_EVENT_REQUEST_SET: {
6957 int i, event_kind, suspend_policy, nmodifiers, mod;
6960 MonoThread *step_thread;
6961 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6965 event_kind = decode_byte (p, &p, end);
6966 suspend_policy = decode_byte (p, &p, end);
6967 nmodifiers = decode_byte (p, &p, end);
6969 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6970 req->id = InterlockedIncrement (&event_request_id);
6971 req->event_kind = event_kind;
6972 req->suspend_policy = suspend_policy;
6973 req->nmodifiers = nmodifiers;
6976 for (i = 0; i < nmodifiers; ++i) {
6977 mod = decode_byte (p, &p, end);
6979 req->modifiers [i].kind = mod;
6980 if (mod == MOD_KIND_COUNT) {
6981 req->modifiers [i].data.count = decode_int (p, &p, end);
6982 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6983 method = decode_methodid (p, &p, end, &domain, &err);
6986 location = decode_long (p, &p, end);
6987 } else if (mod == MOD_KIND_STEP) {
6988 step_thread_id = decode_id (p, &p, end);
6989 size = decode_int (p, &p, end);
6990 depth = decode_int (p, &p, end);
6991 if (CHECK_PROTOCOL_VERSION (2, 16))
6992 filter = decode_int (p, &p, end);
6993 req->modifiers [i].data.filter = filter;
6994 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
6995 /* Treat STEP_THOUGH the same as HIDDEN */
6996 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
6997 } else if (mod == MOD_KIND_THREAD_ONLY) {
6998 int id = decode_id (p, &p, end);
7000 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7005 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7006 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7010 req->modifiers [i].caught = decode_byte (p, &p, end);
7011 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7012 if (CHECK_PROTOCOL_VERSION (2, 25))
7013 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7015 req->modifiers [i].subclasses = TRUE;
7016 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : "", req->modifiers [i].subclasses ? ", include-subclasses" : ""));
7018 req->modifiers [i].data.exc_class = exc_class;
7020 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7022 return ERR_INVALID_ARGUMENT;
7025 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7026 int n = decode_int (p, &p, end);
7029 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7030 for (j = 0; j < n; ++j) {
7031 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7033 g_free (req->modifiers [i].data.assemblies);
7037 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7038 int n = decode_int (p, &p, end);
7041 modifier = &req->modifiers [i];
7042 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7043 for (j = 0; j < n; ++j) {
7044 char *s = decode_string (p, &p, end);
7048 s2 = strdup_tolower (s);
7049 g_hash_table_insert (modifier->data.source_files, s2, s2);
7053 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7054 int n = decode_int (p, &p, end);
7057 modifier = &req->modifiers [i];
7058 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7059 for (j = 0; j < n; ++j) {
7060 char *s = decode_string (p, &p, end);
7063 g_hash_table_insert (modifier->data.type_names, s, s);
7067 return ERR_NOT_IMPLEMENTED;
7071 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7074 req->info = set_breakpoint (method, location, req, &error);
7075 if (!mono_error_ok (&error)) {
7077 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7078 mono_error_cleanup (&error);
7079 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7081 } else if (req->event_kind == EVENT_KIND_STEP) {
7082 g_assert (step_thread_id);
7084 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7090 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7095 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7096 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7097 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7098 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7099 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7100 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7102 if (req->nmodifiers) {
7104 return ERR_NOT_IMPLEMENTED;
7108 mono_loader_lock ();
7109 g_ptr_array_add (event_requests, req);
7111 if (agent_config.defer) {
7112 /* Transmit cached data to the client on receipt of the event request */
7113 switch (req->event_kind) {
7114 case EVENT_KIND_APPDOMAIN_CREATE:
7115 /* Emit load events for currently loaded domains */
7116 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7118 case EVENT_KIND_ASSEMBLY_LOAD:
7119 /* Emit load events for currently loaded assemblies */
7120 mono_assembly_foreach (emit_assembly_load, NULL);
7122 case EVENT_KIND_THREAD_START:
7123 /* Emit start events for currently started threads */
7124 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7126 case EVENT_KIND_TYPE_LOAD:
7127 /* Emit type load events for currently loaded types */
7128 mono_domain_foreach (send_types_for_domain, NULL);
7134 mono_loader_unlock ();
7136 buffer_add_int (buf, req->id);
7139 case CMD_EVENT_REQUEST_CLEAR: {
7140 int etype = decode_byte (p, &p, end);
7141 int req_id = decode_int (p, &p, end);
7143 // FIXME: Make a faster mapping from req_id to request
7144 mono_loader_lock ();
7145 clear_event_request (req_id, etype);
7146 mono_loader_unlock ();
7149 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7152 mono_loader_lock ();
7154 while (i < event_requests->len) {
7155 EventRequest *req = g_ptr_array_index (event_requests, i);
7157 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7158 clear_breakpoint (req->info);
7160 g_ptr_array_remove_index_fast (event_requests, i);
7166 mono_loader_unlock ();
7170 return ERR_NOT_IMPLEMENTED;
7177 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7183 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7184 buffer_add_domainid (buf, mono_get_root_domain ());
7187 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7188 domain = decode_domainid (p, &p, end, NULL, &err);
7191 buffer_add_string (buf, domain->friendly_name);
7194 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7199 domain = decode_domainid (p, &p, end, NULL, &err);
7202 mono_loader_lock ();
7204 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7207 buffer_add_int (buf, count);
7208 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7210 buffer_add_assemblyid (buf, domain, ass);
7212 mono_loader_unlock ();
7215 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7216 domain = decode_domainid (p, &p, end, NULL, &err);
7220 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7223 case CMD_APPDOMAIN_GET_CORLIB: {
7224 domain = decode_domainid (p, &p, end, NULL, &err);
7228 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7231 case CMD_APPDOMAIN_CREATE_STRING: {
7235 domain = decode_domainid (p, &p, end, NULL, &err);
7238 s = decode_string (p, &p, end);
7240 o = mono_string_new (domain, s);
7241 buffer_add_objid (buf, (MonoObject*)o);
7244 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7246 MonoDomain *domain2;
7249 domain = decode_domainid (p, &p, end, NULL, &err);
7252 klass = decode_typeid (p, &p, end, &domain2, &err);
7257 g_assert (domain == domain2);
7259 o = mono_object_new (domain, klass);
7261 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7265 buffer_add_objid (buf, o);
7269 return ERR_NOT_IMPLEMENTED;
7276 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7282 ass = decode_assemblyid (p, &p, end, &domain, &err);
7287 case CMD_ASSEMBLY_GET_LOCATION: {
7288 buffer_add_string (buf, mono_image_get_filename (ass->image));
7291 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7295 if (ass->image->dynamic) {
7296 buffer_add_id (buf, 0);
7298 token = mono_image_get_entry_point (ass->image);
7300 buffer_add_id (buf, 0);
7302 m = mono_get_method (ass->image, token, NULL);
7303 buffer_add_methodid (buf, domain, m);
7308 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7309 buffer_add_moduleid (buf, domain, ass->image);
7312 case CMD_ASSEMBLY_GET_OBJECT: {
7313 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7314 buffer_add_objid (buf, o);
7317 case CMD_ASSEMBLY_GET_TYPE: {
7318 char *s = decode_string (p, &p, end);
7319 gboolean ignorecase = decode_byte (p, &p, end);
7320 MonoTypeNameParse info;
7322 gboolean type_resolve, res;
7323 MonoDomain *d = mono_domain_get ();
7325 /* This is needed to be able to find referenced assemblies */
7326 res = mono_domain_set (domain, FALSE);
7329 if (!mono_reflection_parse_type (s, &info)) {
7332 if (info.assembly.name)
7334 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7336 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7337 mono_reflection_free_type_info (&info);
7340 mono_domain_set (d, TRUE);
7344 case CMD_ASSEMBLY_GET_NAME: {
7346 MonoAssembly *mass = ass;
7348 name = g_strdup_printf (
7349 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7351 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7352 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7353 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7354 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7356 buffer_add_string (buf, name);
7361 return ERR_NOT_IMPLEMENTED;
7368 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7374 case CMD_MODULE_GET_INFO: {
7375 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7378 basename = g_path_get_basename (image->name);
7379 buffer_add_string (buf, basename); // name
7380 buffer_add_string (buf, image->module_name); // scopename
7381 buffer_add_string (buf, image->name); // fqname
7382 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7383 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7388 return ERR_NOT_IMPLEMENTED;
7395 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7397 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7398 /* Special case these so the client doesn't have to handle Type objects */
7400 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7401 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7402 } else if (MONO_TYPE_IS_REFERENCE (t))
7403 buffer_add_value (buf, t, &val, domain);
7405 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7409 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7415 buffer_add_int (buf, 0);
7419 for (i = 0; i < cinfo->num_attrs; ++i) {
7420 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7423 buffer_add_int (buf, nattrs);
7425 for (i = 0; i < cinfo->num_attrs; ++i) {
7426 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7427 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7428 MonoArray *typed_args, *named_args;
7430 CattrNamedArg *arginfo = NULL;
7433 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7434 g_assert (mono_error_ok (&error));
7436 buffer_add_methodid (buf, domain, attr->ctor);
7440 buffer_add_int (buf, mono_array_length (typed_args));
7441 for (j = 0; j < mono_array_length (typed_args); ++j) {
7442 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7444 t = mono_method_signature (attr->ctor)->params [j];
7446 buffer_add_cattr_arg (buf, t, domain, val);
7449 buffer_add_int (buf, 0);
7454 buffer_add_int (buf, mono_array_length (named_args));
7456 for (j = 0; j < mono_array_length (named_args); ++j) {
7457 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7459 if (arginfo [j].prop) {
7460 buffer_add_byte (buf, 0x54);
7461 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7462 } else if (arginfo [j].field) {
7463 buffer_add_byte (buf, 0x53);
7464 buffer_add_fieldid (buf, domain, arginfo [j].field);
7466 g_assert_not_reached ();
7469 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7472 buffer_add_int (buf, 0);
7479 /* FIXME: Code duplication with icall.c */
7481 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7486 mono_class_setup_interfaces (klass, error);
7487 if (!mono_error_ok (error))
7490 for (i = 0; i < klass->interface_count; i++) {
7491 ic = klass->interfaces [i];
7492 g_hash_table_insert (ifaces, ic, ic);
7494 collect_interfaces (ic, ifaces, error);
7495 if (!mono_error_ok (error))
7501 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7511 case CMD_TYPE_GET_INFO: {
7512 buffer_add_string (buf, klass->name_space);
7513 buffer_add_string (buf, klass->name);
7515 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7516 buffer_add_string (buf, name);
7518 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7519 buffer_add_moduleid (buf, domain, klass->image);
7520 buffer_add_typeid (buf, domain, klass->parent);
7521 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7522 buffer_add_typeid (buf, domain, klass->element_class);
7524 buffer_add_id (buf, 0);
7525 buffer_add_int (buf, klass->type_token);
7526 buffer_add_byte (buf, klass->rank);
7527 buffer_add_int (buf, klass->flags);
7529 type = &klass->byval_arg;
7530 // FIXME: Can't decide whenever a class represents a byref type
7533 if (type->type == MONO_TYPE_PTR)
7535 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7537 if (type->type == MONO_TYPE_VALUETYPE)
7539 if (klass->enumtype)
7541 if (klass->generic_container)
7543 if (klass->generic_container || klass->generic_class)
7545 buffer_add_byte (buf, b);
7548 while ((nested = mono_class_get_nested_types (klass, &iter)))
7550 buffer_add_int (buf, nnested);
7552 while ((nested = mono_class_get_nested_types (klass, &iter)))
7553 buffer_add_typeid (buf, domain, nested);
7554 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7555 if (klass->generic_container)
7556 buffer_add_typeid (buf, domain, klass);
7557 else if (klass->generic_class)
7558 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7560 buffer_add_id (buf, 0);
7562 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7565 if (klass->generic_class) {
7566 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7568 count = inst->type_argc;
7569 buffer_add_int (buf, count);
7570 for (i = 0; i < count; i++)
7571 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7572 } else if (klass->generic_container) {
7573 MonoGenericContainer *container = klass->generic_container;
7576 count = container->type_argc;
7577 buffer_add_int (buf, count);
7578 for (i = 0; i < count; i++) {
7579 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7580 buffer_add_typeid (buf, domain, pklass);
7583 buffer_add_int (buf, 0);
7588 case CMD_TYPE_GET_METHODS: {
7591 gpointer iter = NULL;
7594 mono_class_setup_methods (klass);
7596 nmethods = mono_class_num_methods (klass);
7598 buffer_add_int (buf, nmethods);
7600 while ((m = mono_class_get_methods (klass, &iter))) {
7601 buffer_add_methodid (buf, domain, m);
7604 g_assert (i == nmethods);
7607 case CMD_TYPE_GET_FIELDS: {
7610 gpointer iter = NULL;
7613 nfields = mono_class_num_fields (klass);
7615 buffer_add_int (buf, nfields);
7617 while ((f = mono_class_get_fields (klass, &iter))) {
7618 buffer_add_fieldid (buf, domain, f);
7619 buffer_add_string (buf, f->name);
7620 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7621 buffer_add_int (buf, f->type->attrs);
7624 g_assert (i == nfields);
7627 case CMD_TYPE_GET_PROPERTIES: {
7630 gpointer iter = NULL;
7633 nprops = mono_class_num_properties (klass);
7635 buffer_add_int (buf, nprops);
7637 while ((p = mono_class_get_properties (klass, &iter))) {
7638 buffer_add_propertyid (buf, domain, p);
7639 buffer_add_string (buf, p->name);
7640 buffer_add_methodid (buf, domain, p->get);
7641 buffer_add_methodid (buf, domain, p->set);
7642 buffer_add_int (buf, p->attrs);
7645 g_assert (i == nprops);
7648 case CMD_TYPE_GET_CATTRS: {
7649 MonoClass *attr_klass;
7650 MonoCustomAttrInfo *cinfo;
7652 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7653 /* attr_klass can be NULL */
7657 cinfo = mono_custom_attrs_from_class (klass);
7659 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7662 case CMD_TYPE_GET_FIELD_CATTRS: {
7663 MonoClass *attr_klass;
7664 MonoCustomAttrInfo *cinfo;
7665 MonoClassField *field;
7667 field = decode_fieldid (p, &p, end, NULL, &err);
7670 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7674 cinfo = mono_custom_attrs_from_field (klass, field);
7676 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7679 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7680 MonoClass *attr_klass;
7681 MonoCustomAttrInfo *cinfo;
7684 prop = decode_propertyid (p, &p, end, NULL, &err);
7687 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7691 cinfo = mono_custom_attrs_from_property (klass, prop);
7693 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7696 case CMD_TYPE_GET_VALUES:
7697 case CMD_TYPE_GET_VALUES_2: {
7704 MonoThread *thread_obj;
7705 MonoInternalThread *thread = NULL;
7706 guint32 special_static_type;
7708 if (command == CMD_TYPE_GET_VALUES_2) {
7709 int objid = decode_objid (p, &p, end);
7712 err = get_object (objid, (MonoObject**)&thread_obj);
7716 thread = THREAD_TO_INTERNAL (thread_obj);
7719 len = decode_int (p, &p, end);
7720 for (i = 0; i < len; ++i) {
7721 f = decode_fieldid (p, &p, end, NULL, &err);
7725 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7726 return ERR_INVALID_FIELDID;
7727 special_static_type = mono_class_field_get_special_static_type (f);
7728 if (special_static_type != SPECIAL_STATIC_NONE) {
7729 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7730 return ERR_INVALID_FIELDID;
7733 /* Check that the field belongs to the object */
7735 for (k = klass; k; k = k->parent) {
7736 if (k == f->parent) {
7742 return ERR_INVALID_FIELDID;
7744 vtable = mono_class_vtable (domain, f->parent);
7745 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7746 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7747 buffer_add_value (buf, f->type, val, domain);
7752 case CMD_TYPE_SET_VALUES: {
7760 len = decode_int (p, &p, end);
7761 for (i = 0; i < len; ++i) {
7762 f = decode_fieldid (p, &p, end, NULL, &err);
7766 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7767 return ERR_INVALID_FIELDID;
7768 if (mono_class_field_is_special_static (f))
7769 return ERR_INVALID_FIELDID;
7771 /* Check that the field belongs to the object */
7773 for (k = klass; k; k = k->parent) {
7774 if (k == f->parent) {
7780 return ERR_INVALID_FIELDID;
7782 // FIXME: Check for literal/const
7784 vtable = mono_class_vtable (domain, f->parent);
7785 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7786 err = decode_value (f->type, domain, val, p, &p, end);
7791 if (MONO_TYPE_IS_REFERENCE (f->type))
7792 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7794 mono_field_static_set_value (vtable, f, val);
7799 case CMD_TYPE_GET_OBJECT: {
7800 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7801 buffer_add_objid (buf, o);
7804 case CMD_TYPE_GET_SOURCE_FILES:
7805 case CMD_TYPE_GET_SOURCE_FILES_2: {
7806 char *source_file, *base;
7810 files = get_source_files_for_type (klass);
7812 buffer_add_int (buf, files->len);
7813 for (i = 0; i < files->len; ++i) {
7814 source_file = g_ptr_array_index (files, i);
7815 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7816 buffer_add_string (buf, source_file);
7818 base = g_path_get_basename (source_file);
7819 buffer_add_string (buf, base);
7822 g_free (source_file);
7824 g_ptr_array_free (files, TRUE);
7827 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7828 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7832 if (mono_class_is_assignable_from (klass, oklass))
7833 buffer_add_byte (buf, 1);
7835 buffer_add_byte (buf, 0);
7838 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7839 char *name = decode_string (p, &p, end);
7840 int i, flags = decode_int (p, &p, end);
7841 MonoException *ex = NULL;
7842 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7845 return ERR_LOADER_ERROR;
7846 buffer_add_int (buf, array->len);
7847 for (i = 0; i < array->len; ++i) {
7848 MonoMethod *method = g_ptr_array_index (array, i);
7849 buffer_add_methodid (buf, domain, method);
7852 g_ptr_array_free (array, TRUE);
7856 case CMD_TYPE_GET_INTERFACES: {
7858 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7860 MonoClass *tclass, *iface;
7861 GHashTableIter iter;
7865 for (parent = tclass; parent; parent = parent->parent) {
7866 mono_class_setup_interfaces (parent, &error);
7867 if (!mono_error_ok (&error))
7868 return ERR_LOADER_ERROR;
7869 collect_interfaces (parent, iface_hash, &error);
7870 if (!mono_error_ok (&error))
7871 return ERR_LOADER_ERROR;
7874 buffer_add_int (buf, g_hash_table_size (iface_hash));
7876 g_hash_table_iter_init (&iter, iface_hash);
7877 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7878 buffer_add_typeid (buf, domain, iface);
7879 g_hash_table_destroy (iface_hash);
7882 case CMD_TYPE_GET_INTERFACE_MAP: {
7883 int tindex, ioffset;
7884 gboolean variance_used;
7886 int len, nmethods, i;
7890 len = decode_int (p, &p, end);
7891 mono_class_setup_vtable (klass);
7893 for (tindex = 0; tindex < len; ++tindex) {
7894 iclass = decode_typeid (p, &p, end, NULL, &err);
7898 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7900 return ERR_INVALID_ARGUMENT;
7902 nmethods = mono_class_num_methods (iclass);
7903 buffer_add_int (buf, nmethods);
7906 while ((method = mono_class_get_methods (iclass, &iter))) {
7907 buffer_add_methodid (buf, domain, method);
7909 for (i = 0; i < nmethods; ++i)
7910 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7914 case CMD_TYPE_IS_INITIALIZED: {
7915 MonoVTable *vtable = mono_class_vtable (domain, klass);
7918 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7920 buffer_add_int (buf, 0);
7924 return ERR_NOT_IMPLEMENTED;
7931 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7934 MonoDomain *old_domain;
7938 klass = decode_typeid (p, &p, end, &domain, &err);
7942 old_domain = mono_domain_get ();
7944 mono_domain_set (domain, TRUE);
7946 err = type_commands_internal (command, klass, domain, p, end, buf);
7948 mono_domain_set (old_domain, TRUE);
7954 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7956 MonoMethodHeader *header;
7960 case CMD_METHOD_GET_NAME: {
7961 buffer_add_string (buf, method->name);
7964 case CMD_METHOD_GET_DECLARING_TYPE: {
7965 buffer_add_typeid (buf, domain, method->klass);
7968 case CMD_METHOD_GET_DEBUG_INFO: {
7969 MonoDebugMethodInfo *minfo;
7971 int i, j, n_il_offsets;
7974 int *column_numbers;
7976 GPtrArray *source_file_list;
7978 header = mono_method_get_header (method);
7980 buffer_add_int (buf, 0);
7981 buffer_add_string (buf, "");
7982 buffer_add_int (buf, 0);
7986 minfo = mono_debug_lookup_method (method);
7988 buffer_add_int (buf, header->code_size);
7989 buffer_add_string (buf, "");
7990 buffer_add_int (buf, 0);
7991 mono_metadata_free_mh (header);
7995 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7996 buffer_add_int (buf, header->code_size);
7997 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7998 buffer_add_int (buf, source_file_list->len);
7999 for (i = 0; i < source_file_list->len; ++i) {
8000 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8001 buffer_add_string (buf, sinfo->source_file);
8002 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8003 for (j = 0; j < 16; ++j)
8004 buffer_add_byte (buf, sinfo->hash [j]);
8008 buffer_add_string (buf, source_file);
8010 buffer_add_int (buf, n_il_offsets);
8011 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8012 for (i = 0; i < n_il_offsets; ++i) {
8013 const char *srcfile = "";
8015 if (source_files [i] != -1) {
8016 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8017 srcfile = sinfo->source_file;
8019 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8020 buffer_add_int (buf, il_offsets [i]);
8021 buffer_add_int (buf, line_numbers [i]);
8022 if (CHECK_PROTOCOL_VERSION (2, 13))
8023 buffer_add_int (buf, source_files [i]);
8024 if (CHECK_PROTOCOL_VERSION (2, 19))
8025 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8027 g_free (source_file);
8028 g_free (il_offsets);
8029 g_free (line_numbers);
8030 g_free (source_files);
8031 g_ptr_array_free (source_file_list, TRUE);
8032 mono_metadata_free_mh (header);
8035 case CMD_METHOD_GET_PARAM_INFO: {
8036 MonoMethodSignature *sig = mono_method_signature (method);
8040 /* FIXME: mono_class_from_mono_type () and byrefs */
8042 /* FIXME: Use a smaller encoding */
8043 buffer_add_int (buf, sig->call_convention);
8044 buffer_add_int (buf, sig->param_count);
8045 buffer_add_int (buf, sig->generic_param_count);
8046 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8047 for (i = 0; i < sig->param_count; ++i) {
8049 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8052 /* Emit parameter names */
8053 names = g_new (char *, sig->param_count);
8054 mono_method_get_param_names (method, (const char **) names);
8055 for (i = 0; i < sig->param_count; ++i)
8056 buffer_add_string (buf, names [i]);
8061 case CMD_METHOD_GET_LOCALS_INFO: {
8062 int i, j, num_locals;
8063 MonoDebugLocalsInfo *locals;
8065 header = mono_method_get_header (method);
8067 return ERR_INVALID_ARGUMENT;
8069 buffer_add_int (buf, header->num_locals);
8072 for (i = 0; i < header->num_locals; ++i)
8073 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8076 locals = mono_debug_lookup_locals (method);
8078 num_locals = locals->num_locals;
8081 for (i = 0; i < header->num_locals; ++i) {
8082 for (j = 0; j < num_locals; ++j)
8083 if (locals->locals [j].index == i)
8086 buffer_add_string (buf, locals->locals [j].name);
8088 buffer_add_string (buf, "");
8092 for (i = 0; i < header->num_locals; ++i) {
8093 for (j = 0; j < num_locals; ++j)
8094 if (locals->locals [j].index == i)
8096 if (j < num_locals && locals->locals [j].block) {
8097 buffer_add_int (buf, locals->locals [j].block->start_offset);
8098 buffer_add_int (buf, locals->locals [j].block->end_offset);
8100 buffer_add_int (buf, 0);
8101 buffer_add_int (buf, header->code_size);
8104 mono_metadata_free_mh (header);
8107 mono_debug_symfile_free_locals (locals);
8111 case CMD_METHOD_GET_INFO:
8112 buffer_add_int (buf, method->flags);
8113 buffer_add_int (buf, method->iflags);
8114 buffer_add_int (buf, method->token);
8115 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8117 if (method->is_generic)
8119 if (mono_method_signature (method)->generic_param_count)
8121 buffer_add_byte (buf, attrs);
8122 if (method->is_generic || method->is_inflated) {
8125 if (method->is_generic) {
8128 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8130 result = imethod->declaring;
8131 if (imethod->context.class_inst) {
8132 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8133 /*Generic methods gets the context of the GTD.*/
8134 if (mono_class_get_context (klass))
8135 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8139 buffer_add_methodid (buf, domain, result);
8141 buffer_add_id (buf, 0);
8143 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8144 if (mono_method_signature (method)->generic_param_count) {
8147 if (method->is_inflated) {
8148 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8150 count = inst->type_argc;
8151 buffer_add_int (buf, count);
8153 for (i = 0; i < count; i++)
8154 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8156 buffer_add_int (buf, 0);
8158 } else if (method->is_generic) {
8159 MonoGenericContainer *container = mono_method_get_generic_container (method);
8161 count = mono_method_signature (method)->generic_param_count;
8162 buffer_add_int (buf, count);
8163 for (i = 0; i < count; i++) {
8164 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8165 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8166 buffer_add_typeid (buf, domain, pklass);
8169 buffer_add_int (buf, 0);
8172 buffer_add_int (buf, 0);
8177 case CMD_METHOD_GET_BODY: {
8180 header = mono_method_get_header (method);
8182 buffer_add_int (buf, 0);
8184 if (CHECK_PROTOCOL_VERSION (2, 18))
8185 buffer_add_int (buf, 0);
8187 buffer_add_int (buf, header->code_size);
8188 for (i = 0; i < header->code_size; ++i)
8189 buffer_add_byte (buf, header->code [i]);
8191 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8192 buffer_add_int (buf, header->num_clauses);
8193 for (i = 0; i < header->num_clauses; ++i) {
8194 MonoExceptionClause *clause = &header->clauses [i];
8196 buffer_add_int (buf, clause->flags);
8197 buffer_add_int (buf, clause->try_offset);
8198 buffer_add_int (buf, clause->try_len);
8199 buffer_add_int (buf, clause->handler_offset);
8200 buffer_add_int (buf, clause->handler_len);
8201 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8202 buffer_add_typeid (buf, domain, clause->data.catch_class);
8203 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8204 buffer_add_int (buf, clause->data.filter_offset);
8208 mono_metadata_free_mh (header);
8213 case CMD_METHOD_RESOLVE_TOKEN: {
8214 guint32 token = decode_int (p, &p, end);
8217 switch (mono_metadata_token_code (token)) {
8218 case MONO_TOKEN_STRING: {
8222 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8225 s2 = mono_string_to_utf8 (s);
8227 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8228 buffer_add_string (buf, s2);
8234 MonoClass *handle_class;
8236 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8237 val = mono_method_get_wrapper_data (method, token);
8238 handle_class = mono_method_get_wrapper_data (method, token + 1);
8240 if (handle_class == NULL) {
8241 // Can't figure out the token type
8242 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8246 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8250 if (handle_class == mono_defaults.typehandle_class) {
8251 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8252 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8253 buffer_add_typeid (buf, domain, (MonoClass *) val);
8255 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8256 } else if (handle_class == mono_defaults.fieldhandle_class) {
8257 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8258 buffer_add_fieldid (buf, domain, val);
8259 } else if (handle_class == mono_defaults.methodhandle_class) {
8260 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8261 buffer_add_methodid (buf, domain, val);
8262 } else if (handle_class == mono_defaults.string_class) {
8265 s = mono_string_to_utf8 (val);
8266 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8267 buffer_add_string (buf, s);
8270 g_assert_not_reached ();
8277 case CMD_METHOD_GET_CATTRS: {
8278 MonoClass *attr_klass;
8279 MonoCustomAttrInfo *cinfo;
8281 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8282 /* attr_klass can be NULL */
8286 cinfo = mono_custom_attrs_from_method (method);
8288 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8291 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8292 MonoType **type_argv;
8296 MonoGenericInst *ginst;
8297 MonoGenericContext tmp_context;
8298 MonoMethod *inflated;
8300 type_argc = decode_int (p, &p, end);
8301 type_argv = g_new0 (MonoType*, type_argc);
8302 for (i = 0; i < type_argc; ++i) {
8303 klass = decode_typeid (p, &p, end, &d, &err);
8310 return ERR_INVALID_ARGUMENT;
8312 type_argv [i] = &klass->byval_arg;
8314 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8316 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8317 tmp_context.method_inst = ginst;
8319 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8320 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8321 return ERR_INVALID_ARGUMENT;
8322 buffer_add_methodid (buf, domain, inflated);
8326 return ERR_NOT_IMPLEMENTED;
8333 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8336 MonoDomain *old_domain;
8340 method = decode_methodid (p, &p, end, &domain, &err);
8344 old_domain = mono_domain_get ();
8346 mono_domain_set (domain, TRUE);
8348 err = method_commands_internal (command, method, domain, p, end, buf);
8350 mono_domain_set (old_domain, TRUE);
8356 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8358 int objid = decode_objid (p, &p, end);
8360 MonoThread *thread_obj;
8361 MonoInternalThread *thread;
8363 err = get_object (objid, (MonoObject**)&thread_obj);
8367 thread = THREAD_TO_INTERNAL (thread_obj);
8370 case CMD_THREAD_GET_NAME: {
8372 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8375 buffer_add_int (buf, 0);
8380 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8382 buffer_add_int (buf, len);
8383 buffer_add_data (buf, (guint8*)name, len);
8388 case CMD_THREAD_GET_FRAME_INFO: {
8389 DebuggerTlsData *tls;
8390 int i, start_frame, length;
8392 // Wait for suspending if it already started
8393 // FIXME: Races with suspend_count
8394 while (!is_suspended ()) {
8396 wait_for_suspend ();
8400 wait_for_suspend ();
8401 if (!is_suspended ())
8402 return ERR_NOT_SUSPENDED;
8405 start_frame = decode_int (p, &p, end);
8406 length = decode_int (p, &p, end);
8408 if (start_frame != 0 || length != -1)
8409 return ERR_NOT_IMPLEMENTED;
8411 mono_loader_lock ();
8412 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8413 mono_loader_unlock ();
8416 compute_frame_info (thread, tls);
8418 buffer_add_int (buf, tls->frame_count);
8419 for (i = 0; i < tls->frame_count; ++i) {
8420 buffer_add_int (buf, tls->frames [i]->id);
8421 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8422 buffer_add_int (buf, tls->frames [i]->il_offset);
8424 * Instead of passing the frame type directly to the client, we associate
8425 * it with the previous frame using a set of flags. This avoids lots of
8426 * conditional code in the client, since a frame whose type isn't
8427 * FRAME_TYPE_MANAGED has no method, location, etc.
8429 buffer_add_byte (buf, tls->frames [i]->flags);
8434 case CMD_THREAD_GET_STATE:
8435 buffer_add_int (buf, thread->state);
8437 case CMD_THREAD_GET_INFO:
8438 buffer_add_byte (buf, thread->threadpool_thread);
8440 case CMD_THREAD_GET_ID:
8441 buffer_add_long (buf, (guint64)(gsize)thread);
8443 case CMD_THREAD_GET_TID:
8444 buffer_add_long (buf, (guint64)thread->tid);
8447 return ERR_NOT_IMPLEMENTED;
8454 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8458 MonoThread *thread_obj;
8459 MonoInternalThread *thread;
8460 int pos, i, len, frame_idx;
8461 DebuggerTlsData *tls;
8463 MonoDebugMethodJitInfo *jit;
8464 MonoDebugVarInfo *var;
8465 MonoMethodSignature *sig;
8467 MonoMethodHeader *header;
8469 objid = decode_objid (p, &p, end);
8470 err = get_object (objid, (MonoObject**)&thread_obj);
8474 thread = THREAD_TO_INTERNAL (thread_obj);
8476 id = decode_id (p, &p, end);
8478 mono_loader_lock ();
8479 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8480 mono_loader_unlock ();
8483 for (i = 0; i < tls->frame_count; ++i) {
8484 if (tls->frames [i]->id == id)
8487 if (i == tls->frame_count)
8488 return ERR_INVALID_FRAMEID;
8491 frame = tls->frames [frame_idx];
8493 if (!frame->has_ctx)
8494 return ERR_ABSENT_INFORMATION;
8497 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8498 if (!frame->jit && frame->api_method->is_inflated)
8499 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8503 /* This could happen for aot images with no jit debug info */
8504 s = mono_method_full_name (frame->api_method, TRUE);
8505 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8507 return ERR_ABSENT_INFORMATION;
8512 sig = mono_method_signature (frame->actual_method);
8514 if (!get_seq_points (frame->domain, frame->actual_method))
8516 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8518 return ERR_ABSENT_INFORMATION;
8521 case CMD_STACK_FRAME_GET_VALUES: {
8522 len = decode_int (p, &p, end);
8523 header = mono_method_get_header (frame->actual_method);
8525 for (i = 0; i < len; ++i) {
8526 pos = decode_int (p, &p, end);
8531 g_assert (pos >= 0 && pos < jit->num_params);
8533 var = &jit->params [pos];
8535 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8537 g_assert (pos >= 0 && pos < jit->num_locals);
8539 var = &jit->locals [pos];
8541 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8544 mono_metadata_free_mh (header);
8547 case CMD_STACK_FRAME_GET_THIS: {
8548 if (frame->api_method->klass->valuetype) {
8549 if (!sig->hasthis) {
8550 MonoObject *p = NULL;
8551 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8553 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8556 if (!sig->hasthis) {
8557 MonoObject *p = NULL;
8558 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8560 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8565 case CMD_STACK_FRAME_SET_VALUES: {
8568 MonoDebugVarInfo *var;
8570 len = decode_int (p, &p, end);
8571 header = mono_method_get_header (frame->actual_method);
8573 for (i = 0; i < len; ++i) {
8574 pos = decode_int (p, &p, end);
8579 g_assert (pos >= 0 && pos < jit->num_params);
8581 t = sig->params [pos];
8582 var = &jit->params [pos];
8584 g_assert (pos >= 0 && pos < jit->num_locals);
8586 t = header->locals [pos];
8587 var = &jit->locals [pos];
8590 if (MONO_TYPE_IS_REFERENCE (t))
8591 val_buf = g_alloca (sizeof (MonoObject*));
8593 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8594 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8598 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8600 mono_metadata_free_mh (header);
8604 return ERR_NOT_IMPLEMENTED;
8611 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8614 int objid, err, index, len, i, esize;
8617 objid = decode_objid (p, &p, end);
8618 err = get_object (objid, (MonoObject**)&arr);
8623 case CMD_ARRAY_REF_GET_LENGTH:
8624 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8626 buffer_add_int (buf, arr->max_length);
8627 buffer_add_int (buf, 0);
8629 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8630 buffer_add_int (buf, arr->bounds [i].length);
8631 buffer_add_int (buf, arr->bounds [i].lower_bound);
8635 case CMD_ARRAY_REF_GET_VALUES:
8636 index = decode_int (p, &p, end);
8637 len = decode_int (p, &p, end);
8639 g_assert (index >= 0 && len >= 0);
8640 // Reordered to avoid integer overflow
8641 g_assert (!(index > arr->max_length - len));
8643 esize = mono_array_element_size (arr->obj.vtable->klass);
8644 for (i = index; i < index + len; ++i) {
8645 elem = (gpointer*)((char*)arr->vector + (i * esize));
8646 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8649 case CMD_ARRAY_REF_SET_VALUES:
8650 index = decode_int (p, &p, end);
8651 len = decode_int (p, &p, end);
8653 g_assert (index >= 0 && len >= 0);
8654 // Reordered to avoid integer overflow
8655 g_assert (!(index > arr->max_length - len));
8657 esize = mono_array_element_size (arr->obj.vtable->klass);
8658 for (i = index; i < index + len; ++i) {
8659 elem = (gpointer*)((char*)arr->vector + (i * esize));
8661 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8665 return ERR_NOT_IMPLEMENTED;
8672 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8677 int i, index, length;
8680 objid = decode_objid (p, &p, end);
8681 err = get_object (objid, (MonoObject**)&str);
8686 case CMD_STRING_REF_GET_VALUE:
8687 s = mono_string_to_utf8 (str);
8688 buffer_add_string (buf, s);
8691 case CMD_STRING_REF_GET_LENGTH:
8692 buffer_add_long (buf, mono_string_length (str));
8694 case CMD_STRING_REF_GET_CHARS:
8695 index = decode_long (p, &p, end);
8696 length = decode_long (p, &p, end);
8697 if (index > mono_string_length (str) - length)
8698 return ERR_INVALID_ARGUMENT;
8699 c = mono_string_chars (str) + index;
8700 for (i = 0; i < length; ++i)
8701 buffer_add_short (buf, c [i]);
8704 return ERR_NOT_IMPLEMENTED;
8711 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8720 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8721 objid = decode_objid (p, &p, end);
8722 err = get_object (objid, &obj);
8724 buffer_add_int (buf, 1);
8726 buffer_add_int (buf, 0);
8730 objid = decode_objid (p, &p, end);
8731 err = get_object (objid, &obj);
8736 case CMD_OBJECT_REF_GET_TYPE:
8737 /* This handles transparent proxies too */
8738 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8740 case CMD_OBJECT_REF_GET_VALUES:
8741 len = decode_int (p, &p, end);
8743 for (i = 0; i < len; ++i) {
8744 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8748 /* Check that the field belongs to the object */
8750 for (k = obj->vtable->klass; k; k = k->parent) {
8751 if (k == f->parent) {
8757 return ERR_INVALID_FIELDID;
8759 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8763 if (mono_class_field_is_special_static (f))
8764 return ERR_INVALID_FIELDID;
8766 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8767 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8768 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8769 mono_field_static_get_value (vtable, f, val);
8770 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8773 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8777 case CMD_OBJECT_REF_SET_VALUES:
8778 len = decode_int (p, &p, end);
8780 for (i = 0; i < len; ++i) {
8781 f = decode_fieldid (p, &p, end, NULL, &err);
8785 /* Check that the field belongs to the object */
8787 for (k = obj->vtable->klass; k; k = k->parent) {
8788 if (k == f->parent) {
8794 return ERR_INVALID_FIELDID;
8796 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8800 if (mono_class_field_is_special_static (f))
8801 return ERR_INVALID_FIELDID;
8803 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8804 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8806 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8807 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8812 mono_field_static_set_value (vtable, f, val);
8815 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8821 case CMD_OBJECT_REF_GET_ADDRESS:
8822 buffer_add_long (buf, (gssize)obj);
8824 case CMD_OBJECT_REF_GET_DOMAIN:
8825 buffer_add_domainid (buf, obj->vtable->domain);
8827 case CMD_OBJECT_REF_GET_INFO:
8828 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8829 buffer_add_domainid (buf, obj->vtable->domain);
8832 return ERR_NOT_IMPLEMENTED;
8839 command_set_to_string (CommandSet command_set)
8841 switch (command_set) {
8844 case CMD_SET_OBJECT_REF:
8845 return "OBJECT_REF";
8846 case CMD_SET_STRING_REF:
8847 return "STRING_REF";
8848 case CMD_SET_THREAD:
8850 case CMD_SET_ARRAY_REF:
8852 case CMD_SET_EVENT_REQUEST:
8853 return "EVENT_REQUEST";
8854 case CMD_SET_STACK_FRAME:
8855 return "STACK_FRAME";
8856 case CMD_SET_APPDOMAIN:
8858 case CMD_SET_ASSEMBLY:
8860 case CMD_SET_METHOD:
8864 case CMD_SET_MODULE:
8873 static const char* vm_cmds_str [] = {
8881 "SET_PROTOCOL_VERSION",
8884 "GET_TYPES_FOR_SOURCE_FILE",
8889 static const char* thread_cmds_str[] = {
8898 static const char* event_cmds_str[] = {
8901 "REQUEST_CLEAR_ALL_BREAKPOINTS"
8904 static const char* appdomain_cmds_str[] = {
8906 "GET_FRIENDLY_NAME",
8908 "GET_ENTRY_ASSEMBLY",
8911 "CREATE_BOXED_VALUE"
8914 static const char* assembly_cmds_str[] = {
8917 "GET_MANIFEST_MODULE",
8923 static const char* module_cmds_str[] = {
8927 static const char* method_cmds_str[] = {
8929 "GET_DECLARING_TYPE",
8937 "MAKE_GENERIC_METHOD"
8940 static const char* type_cmds_str[] = {
8948 "IS_ASSIGNABLE_FROM",
8952 "GET_PROPERTY_CATTRS",
8953 "GET_SOURCE_FILES_2",
8955 "GET_METHODS_BY_NAME_FLAGS",
8957 "GET_INTERFACE_MAP",
8961 static const char* stack_frame_cmds_str[] = {
8967 static const char* array_cmds_str[] = {
8973 static const char* string_cmds_str[] = {
8979 static const char* object_cmds_str[] = {
8990 cmd_to_string (CommandSet set, int command)
8998 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9000 case CMD_SET_OBJECT_REF:
9001 cmds = object_cmds_str;
9002 cmds_len = G_N_ELEMENTS (object_cmds_str);
9004 case CMD_SET_STRING_REF:
9005 cmds = string_cmds_str;
9006 cmds_len = G_N_ELEMENTS (string_cmds_str);
9008 case CMD_SET_THREAD:
9009 cmds = thread_cmds_str;
9010 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9012 case CMD_SET_ARRAY_REF:
9013 cmds = array_cmds_str;
9014 cmds_len = G_N_ELEMENTS (array_cmds_str);
9016 case CMD_SET_EVENT_REQUEST:
9017 cmds = event_cmds_str;
9018 cmds_len = G_N_ELEMENTS (event_cmds_str);
9020 case CMD_SET_STACK_FRAME:
9021 cmds = stack_frame_cmds_str;
9022 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9024 case CMD_SET_APPDOMAIN:
9025 cmds = appdomain_cmds_str;
9026 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9028 case CMD_SET_ASSEMBLY:
9029 cmds = assembly_cmds_str;
9030 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9032 case CMD_SET_METHOD:
9033 cmds = method_cmds_str;
9034 cmds_len = G_N_ELEMENTS (method_cmds_str);
9037 cmds = type_cmds_str;
9038 cmds_len = G_N_ELEMENTS (type_cmds_str);
9040 case CMD_SET_MODULE:
9041 cmds = module_cmds_str;
9042 cmds_len = G_N_ELEMENTS (module_cmds_str);
9045 cmds = event_cmds_str;
9046 cmds_len = G_N_ELEMENTS (event_cmds_str);
9051 if (command > 0 && command <= cmds_len)
9052 return cmds [command - 1];
9058 wait_for_attach (void)
9060 #ifndef DISABLE_SOCKET_TRANSPORT
9061 if (listen_fd == -1) {
9062 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9066 /* Block and wait for client connection */
9067 conn_fd = socket_transport_accept (listen_fd);
9068 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9069 if (conn_fd == -1) {
9070 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9074 g_assert_not_reached ();
9078 disconnected = !transport_handshake ();
9080 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9090 * This thread handles communication with the debugger client using a JDWP
9093 static guint32 WINAPI
9094 debugger_thread (void *arg)
9096 int res, len, id, flags, command_set = 0, command = 0;
9097 guint8 header [HEADER_LENGTH];
9098 guint8 *data, *p, *end;
9102 gboolean attach_failed = FALSE;
9104 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9106 debugger_thread_id = GetCurrentThreadId ();
9108 mono_jit_thread_attach (mono_get_root_domain ());
9110 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9112 mono_set_is_debugger_attached (TRUE);
9114 if (agent_config.defer) {
9115 if (!wait_for_attach ()) {
9116 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9117 attach_failed = TRUE; // Don't abort process when we can't listen
9119 /* Send start event to client */
9120 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9124 while (!attach_failed) {
9125 res = transport_recv (header, HEADER_LENGTH);
9127 /* This will break if the socket is closed during shutdown too */
9128 if (res != HEADER_LENGTH) {
9129 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9134 end = header + HEADER_LENGTH;
9136 len = decode_int (p, &p, end);
9137 id = decode_int (p, &p, end);
9138 flags = decode_byte (p, &p, end);
9139 command_set = decode_byte (p, &p, end);
9140 command = decode_byte (p, &p, end);
9142 g_assert (flags == 0);
9145 const char *cmd_str;
9148 cmd_str = cmd_to_string (command_set, command);
9150 sprintf (cmd_num, "%d", command);
9154 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d].\n", command_set_to_string (command_set), cmd_str, id));
9157 data = g_malloc (len - HEADER_LENGTH);
9158 if (len - HEADER_LENGTH > 0)
9160 res = transport_recv (data, len - HEADER_LENGTH);
9161 if (res != len - HEADER_LENGTH) {
9162 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9168 end = data + (len - HEADER_LENGTH);
9170 buffer_init (&buf, 128);
9175 /* Process the request */
9176 switch (command_set) {
9178 err = vm_commands (command, id, p, end, &buf);
9179 if (!err && command == CMD_VM_INVOKE_METHOD)
9180 /* Sent after the invoke is complete */
9183 case CMD_SET_EVENT_REQUEST:
9184 err = event_commands (command, p, end, &buf);
9186 case CMD_SET_APPDOMAIN:
9187 err = domain_commands (command, p, end, &buf);
9189 case CMD_SET_ASSEMBLY:
9190 err = assembly_commands (command, p, end, &buf);
9192 case CMD_SET_MODULE:
9193 err = module_commands (command, p, end, &buf);
9196 err = type_commands (command, p, end, &buf);
9198 case CMD_SET_METHOD:
9199 err = method_commands (command, p, end, &buf);
9201 case CMD_SET_THREAD:
9202 err = thread_commands (command, p, end, &buf);
9204 case CMD_SET_STACK_FRAME:
9205 err = frame_commands (command, p, end, &buf);
9207 case CMD_SET_ARRAY_REF:
9208 err = array_commands (command, p, end, &buf);
9210 case CMD_SET_STRING_REF:
9211 err = string_commands (command, p, end, &buf);
9213 case CMD_SET_OBJECT_REF:
9214 err = object_commands (command, p, end, &buf);
9217 err = ERR_NOT_IMPLEMENTED;
9221 send_reply_packet (id, err, &buf);
9226 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9230 mono_set_is_debugger_attached (FALSE);
9232 mono_mutex_lock (&debugger_thread_exited_mutex);
9233 debugger_thread_exited = TRUE;
9234 mono_cond_signal (&debugger_thread_exited_cond);
9235 mono_mutex_unlock (&debugger_thread_exited_mutex);
9237 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9239 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9240 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9241 start_debugger_thread ();
9247 #else /* DISABLE_DEBUGGER_AGENT */
9250 mono_debugger_agent_parse_options (char *options)
9252 g_error ("This runtime is configured with the debugger agent disabled.");
9256 mono_debugger_agent_init (void)
9261 mono_debugger_agent_breakpoint_hit (void *sigctx)
9266 mono_debugger_agent_single_step_event (void *sigctx)
9271 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9276 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9282 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9283 MonoContext *catch_ctx)
9288 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9293 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9298 mono_debugger_agent_user_break (void)
9304 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9309 mono_debugger_agent_debug_log_is_enabled (void)