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 */
565 * Contains additional information for an event
568 /* For EVENT_KIND_EXCEPTION */
570 MonoContext catch_ctx;
572 /* For EVENT_KIND_USER_LOG */
574 char *category, *message;
575 /* For EVENT_KIND_TYPE_LOAD */
579 /* Dummy structure used for the profiler callbacks */
584 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
587 #define get_last_sock_error() WSAGetLastError()
588 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
589 #define MONO_EINTR WSAEINTR
591 #define get_last_sock_error() errno
592 #define MONO_EWOULDBLOCK EWOULDBLOCK
593 #define MONO_EINTR EINTR
596 #define CHECK_PROTOCOL_VERSION(major,minor) \
597 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
603 static AgentConfig agent_config;
606 * Whenever the agent is fully initialized.
607 * When using the onuncaught or onthrow options, only some parts of the agent are
608 * initialized on startup, and the full initialization which includes connection
609 * establishment and the startup of the agent thread is only done in response to
612 static gint32 inited;
614 #ifndef DISABLE_SOCKET_TRANSPORT
616 static int listen_fd;
619 static int packet_id = 0;
621 static int objref_id = 0;
623 static int event_request_id = 0;
625 static int frame_id = 0;
627 static GPtrArray *event_requests;
629 static MonoNativeTlsKey debugger_tls_id;
631 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
633 /* Maps MonoInternalThread -> DebuggerTlsData */
634 static MonoGHashTable *thread_to_tls;
636 /* Maps tid -> MonoInternalThread */
637 static MonoGHashTable *tid_to_thread;
639 /* Maps tid -> MonoThread (not MonoInternalThread) */
640 static MonoGHashTable *tid_to_thread_obj;
642 static gsize debugger_thread_id;
644 static HANDLE debugger_thread_handle;
646 static int log_level;
648 static gboolean embedding;
650 static FILE *log_file;
652 /* Assemblies whose assembly load event has no been sent yet */
653 static GPtrArray *pending_assembly_loads;
655 /* Whenever the debugger thread has exited */
656 static gboolean debugger_thread_exited;
658 /* Cond variable used to wait for debugger_thread_exited becoming true */
659 static mono_cond_t debugger_thread_exited_cond;
661 /* Mutex for the cond var above */
662 static mono_mutex_t debugger_thread_exited_mutex;
664 static DebuggerProfiler debugger_profiler;
666 /* The single step request instance */
667 static SingleStepReq *ss_req = NULL;
668 static gpointer ss_invoke_addr = NULL;
670 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
671 /* Number of single stepping operations in progress */
675 /* The protocol version of the client */
676 static int major_version, minor_version;
678 /* Whenever the variables above are set by the client */
679 static gboolean protocol_version_set;
681 /* A hash table containing all active domains */
682 static GHashTable *domains;
684 /* The number of times the runtime is suspended */
685 static gint32 suspend_count;
687 static void transport_init (void);
688 static void transport_connect (const char *address);
689 static gboolean transport_handshake (void);
690 static void register_transport (DebuggerTransport *trans);
692 static guint32 WINAPI debugger_thread (void *arg);
694 static void runtime_initialized (MonoProfiler *prof);
696 static void runtime_shutdown (MonoProfiler *prof);
698 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
700 static void thread_end (MonoProfiler *prof, uintptr_t tid);
702 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
704 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
706 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
708 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
710 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
712 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
714 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
716 static void emit_assembly_load (gpointer assembly, gpointer user_data);
718 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
720 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
722 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
724 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
726 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
728 static void start_single_stepping (void);
730 static void stop_single_stepping (void);
732 static void suspend_current (void);
734 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
736 static void clear_types_for_assembly (MonoAssembly *assembly);
738 static void clear_breakpoints_for_domain (MonoDomain *domain);
740 static void process_profiler_event (EventKind event, gpointer arg);
742 /* Submodule init/cleanup */
743 static void breakpoints_init (void);
744 static void breakpoints_cleanup (void);
746 static void objrefs_init (void);
747 static void objrefs_cleanup (void);
749 static void ids_init (void);
750 static void ids_cleanup (void);
752 static void suspend_init (void);
754 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
755 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
756 static void ss_destroy (SingleStepReq *req);
758 static void start_debugger_thread (void);
759 static void stop_debugger_thread (void);
761 static void finish_agent_init (gboolean on_startup);
763 static void process_profiler_event (EventKind event, gpointer arg);
765 static void invalidate_frames (DebuggerTlsData *tls);
767 #ifndef DISABLE_SOCKET_TRANSPORT
769 register_socket_transport (void);
773 parse_address (char *address, char **host, int *port)
775 char *pos = strchr (address, ':');
777 if (pos == NULL || pos == address)
780 *host = g_malloc (pos - address + 1);
781 strncpy (*host, address, pos - address);
782 (*host) [pos - address] = '\0';
784 *port = atoi (pos + 1);
792 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
793 fprintf (stderr, "Available options:\n");
794 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
795 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
796 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
797 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
798 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
799 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
800 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
801 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
802 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
806 parse_flag (const char *option, char *flag)
808 if (!strcmp (flag, "y"))
810 else if (!strcmp (flag, "n"))
813 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
820 mono_debugger_agent_parse_options (char *options)
827 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
828 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
832 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
834 options = g_strdup_printf ("%s,%s", options, extra);
836 agent_config.enabled = TRUE;
837 agent_config.suspend = TRUE;
838 agent_config.server = FALSE;
839 agent_config.defer = FALSE;
840 agent_config.address = NULL;
842 args = g_strsplit (options, ",", -1);
843 for (ptr = args; ptr && *ptr; ptr ++) {
846 if (strncmp (arg, "transport=", 10) == 0) {
847 agent_config.transport = g_strdup (arg + 10);
848 } else if (strncmp (arg, "address=", 8) == 0) {
849 agent_config.address = g_strdup (arg + 8);
850 } else if (strncmp (arg, "loglevel=", 9) == 0) {
851 agent_config.log_level = atoi (arg + 9);
852 } else if (strncmp (arg, "logfile=", 8) == 0) {
853 agent_config.log_file = g_strdup (arg + 8);
854 } else if (strncmp (arg, "suspend=", 8) == 0) {
855 agent_config.suspend = parse_flag ("suspend", arg + 8);
856 } else if (strncmp (arg, "server=", 7) == 0) {
857 agent_config.server = parse_flag ("server", arg + 7);
858 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
859 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
860 } else if (strncmp (arg, "onthrow=", 8) == 0) {
861 /* We support multiple onthrow= options */
862 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
863 } else if (strncmp (arg, "onthrow", 7) == 0) {
864 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
865 } else if (strncmp (arg, "help", 4) == 0) {
868 } else if (strncmp (arg, "timeout=", 8) == 0) {
869 agent_config.timeout = atoi (arg + 8);
870 } else if (strncmp (arg, "launch=", 7) == 0) {
871 agent_config.launch = g_strdup (arg + 7);
872 } else if (strncmp (arg, "embedding=", 10) == 0) {
873 agent_config.embedding = atoi (arg + 10) == 1;
874 } else if (strncmp (arg, "keepalive=", 10) == 0) {
875 agent_config.keepalive = atoi (arg + 10);
882 if (agent_config.server && !agent_config.suspend) {
883 /* Waiting for deferred attachment */
884 agent_config.defer = TRUE;
885 if (agent_config.address == NULL) {
886 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
890 //agent_config.log_level = 0;
892 if (agent_config.transport == NULL) {
893 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
897 if (agent_config.address == NULL && !agent_config.server) {
898 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
903 if (!strcmp (agent_config.transport, "dt_socket")) {
904 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
905 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
912 mono_debugger_agent_init (void)
914 if (!agent_config.enabled)
919 /* Need to know whenever a thread has acquired the loader mutex */
920 mono_loader_lock_track_ownership (TRUE);
922 event_requests = g_ptr_array_new ();
924 mono_mutex_init (&debugger_thread_exited_mutex);
925 mono_cond_init (&debugger_thread_exited_cond, NULL);
927 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
928 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
929 mono_profiler_install_runtime_initialized (runtime_initialized);
930 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
931 mono_profiler_install_thread (thread_startup, thread_end);
932 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
933 mono_profiler_install_jit_end (jit_end);
934 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
936 mono_native_tls_alloc (&debugger_tls_id, NULL);
938 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
939 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
941 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
942 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
944 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
945 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
947 pending_assembly_loads = g_ptr_array_new ();
948 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
950 log_level = agent_config.log_level;
952 embedding = agent_config.embedding;
955 if (agent_config.log_file) {
956 log_file = fopen (agent_config.log_file, "w+");
958 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
970 mini_get_debug_options ()->gen_seq_points = TRUE;
972 * This is needed because currently we don't handle liveness info.
974 mini_get_debug_options ()->mdb_optimizations = TRUE;
976 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
977 /* This is needed because we can't set local variables in registers yet */
978 mono_disable_optimizations (MONO_OPT_LINEARS);
982 * The stack walk done from thread_interrupt () needs to be signal safe, but it
983 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
984 * safe (#3411). So load AOT info eagerly when the debugger is running as a
987 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
989 if (!agent_config.onuncaught && !agent_config.onthrow)
990 finish_agent_init (TRUE);
996 * Finish the initialization of the agent. This involves connecting the transport
997 * and starting the agent thread. This is either done at startup, or
998 * in response to some event like an unhandled exception.
1001 finish_agent_init (gboolean on_startup)
1005 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1008 if (agent_config.launch) {
1011 // FIXME: Generated address
1012 // FIXME: Races with transport_connect ()
1014 argv [0] = agent_config.launch;
1015 argv [1] = agent_config.transport;
1016 argv [2] = agent_config.address;
1019 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1021 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1026 transport_connect (agent_config.address);
1029 /* Do some which is usually done after sending the VMStart () event */
1030 vm_start_event_sent = TRUE;
1031 start_debugger_thread ();
1036 mono_debugger_agent_cleanup (void)
1041 stop_debugger_thread ();
1043 breakpoints_cleanup ();
1047 mono_mutex_destroy (&debugger_thread_exited_mutex);
1048 mono_cond_destroy (&debugger_thread_exited_cond);
1055 #ifndef DISABLE_SOCKET_TRANSPORT
1060 * recv() + handle incomplete reads and EINTR
1063 socket_transport_recv (void *buf, int len)
1069 static gint32 last_keepalive;
1074 res = recv (fd, (char *) buf + total, len - total, flags);
1077 if (agent_config.keepalive) {
1078 gboolean need_keepalive = FALSE;
1079 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1080 need_keepalive = TRUE;
1081 } else if (res == -1) {
1082 /* This could happen if recv () is interrupted repeatedly */
1083 msecs = mono_msec_ticks ();
1084 if (msecs - last_keepalive >= agent_config.keepalive) {
1085 need_keepalive = TRUE;
1086 last_keepalive = msecs;
1089 if (need_keepalive) {
1090 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1094 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1099 #define HAVE_GETADDRINFO 1
1103 set_keepalive (void)
1108 if (!agent_config.keepalive || !conn_fd)
1111 tv.tv_sec = agent_config.keepalive / 1000;
1112 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1114 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1115 g_assert (result >= 0);
1119 socket_transport_accept (int socket_fd)
1121 conn_fd = accept (socket_fd, NULL, NULL);
1122 if (conn_fd == -1) {
1123 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1125 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1132 socket_transport_send (void *data, int len)
1137 res = send (conn_fd, data, len, 0);
1138 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1146 * socket_transport_connect:
1148 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1151 socket_transport_connect (const char *address)
1153 #ifdef HAVE_GETADDRINFO
1154 struct addrinfo hints;
1155 struct addrinfo *result, *rp;
1157 struct hostent *result;
1159 int sfd = -1, s, res;
1160 char port_string [128];
1164 if (agent_config.address) {
1165 res = parse_address (agent_config.address, &host, &port);
1166 g_assert (res == 0);
1176 sprintf (port_string, "%d", port);
1178 mono_network_init ();
1180 /* Obtain address(es) matching host/port */
1181 #ifdef HAVE_GETADDRINFO
1182 memset (&hints, 0, sizeof (struct addrinfo));
1183 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1184 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1186 hints.ai_protocol = 0; /* Any protocol */
1188 s = getaddrinfo (host, port_string, &hints, &result);
1190 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1194 /* The PS3 doesn't even have _r or hstrerror () */
1195 result = gethostbyname (host);
1197 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1202 if (agent_config.server) {
1203 #ifdef HAVE_GETADDRINFO
1204 /* Wait for a connection */
1206 struct sockaddr_in addr;
1209 /* No address, generate one */
1210 sfd = socket (AF_INET, SOCK_STREAM, 0);
1213 /* This will bind the socket to a random port */
1214 res = listen (sfd, 16);
1216 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1221 addrlen = sizeof (addr);
1222 memset (&addr, 0, sizeof (addr));
1223 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1224 g_assert (res == 0);
1226 host = (char*)"127.0.0.1";
1227 port = ntohs (addr.sin_port);
1229 /* Emit the address to stdout */
1230 /* FIXME: Should print another interface, not localhost */
1231 printf ("%s:%d\n", host, port);
1233 /* Listen on the provided address */
1234 for (rp = result; rp != NULL; rp = rp->ai_next) {
1237 sfd = socket (rp->ai_family, rp->ai_socktype,
1242 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1245 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1249 res = listen (sfd, 16);
1258 * this function is not present on win2000 which we still support, and the
1259 * workaround described here:
1260 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1261 * only works with MSVC.
1263 #ifdef HAVE_GETADDRINFO
1264 freeaddrinfo (result);
1269 if (agent_config.defer)
1272 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1274 if (agent_config.timeout) {
1279 tv.tv_usec = agent_config.timeout * 1000;
1281 FD_SET (sfd, &readfds);
1282 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1284 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1289 conn_fd = socket_transport_accept (sfd);
1293 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1296 #endif /* HAVE_GETADDRINFO */
1298 /* Connect to the specified address */
1299 #ifdef HAVE_GETADDRINFO
1300 /* FIXME: Respect the timeout */
1301 for (rp = result; rp != NULL; rp = rp->ai_next) {
1302 sfd = socket (rp->ai_family, rp->ai_socktype,
1307 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1308 break; /* Success */
1314 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1318 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1320 g_assert_not_reached ();
1321 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1323 g_assert_not_reached ();
1329 /* See the comment above */
1330 #ifdef HAVE_GETADDRINFO
1331 freeaddrinfo (result);
1336 if (!transport_handshake ())
1341 socket_transport_close1 (void)
1343 /* This will interrupt the agent thread */
1344 /* Close the read part only so it can still send back replies */
1345 /* Also shut down the connection listener so that we can exit normally */
1347 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1348 shutdown (conn_fd, SD_BOTH);
1349 shutdown (listen_fd, SD_BOTH);
1350 closesocket (listen_fd);
1352 shutdown (conn_fd, SHUT_RD);
1353 shutdown (listen_fd, SHUT_RDWR);
1359 socket_transport_close2 (void)
1362 shutdown (conn_fd, SD_BOTH);
1364 shutdown (conn_fd, SHUT_RDWR);
1369 register_socket_transport (void)
1371 DebuggerTransport trans;
1373 trans.name = "dt_socket";
1374 trans.connect = socket_transport_connect;
1375 trans.close1 = socket_transport_close1;
1376 trans.close2 = socket_transport_close2;
1377 trans.send = socket_transport_send;
1378 trans.recv = socket_transport_recv;
1380 register_transport (&trans);
1383 #endif /* DISABLE_SOCKET_TRANSPORT */
1389 #define MAX_TRANSPORTS 16
1391 static DebuggerTransport *transport;
1393 static DebuggerTransport transports [MAX_TRANSPORTS];
1394 static int ntransports;
1397 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1400 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1402 register_transport (trans);
1406 register_transport (DebuggerTransport *trans)
1408 g_assert (ntransports < MAX_TRANSPORTS);
1410 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1415 transport_init (void)
1419 #ifndef DISABLE_SOCKET_TRANSPORT
1420 register_socket_transport ();
1423 for (i = 0; i < ntransports; ++i) {
1424 if (!strcmp (agent_config.transport, transports [i].name))
1427 if (i == ntransports) {
1428 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1429 for (i = 0; i < ntransports; ++i)
1430 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1431 fprintf (stderr, "\n");
1434 transport = &transports [i];
1438 transport_connect (const char *address)
1440 transport->connect (address);
1444 transport_close1 (void)
1446 transport->close1 ();
1450 transport_close2 (void)
1452 transport->close2 ();
1456 transport_send (void *buf, int len)
1458 return transport->send (buf, len);
1462 transport_recv (void *buf, int len)
1464 return transport->recv (buf, len);
1468 mono_debugger_agent_transport_handshake (void)
1470 return transport_handshake ();
1474 transport_handshake (void)
1476 char handshake_msg [128];
1480 disconnected = TRUE;
1482 /* Write handshake message */
1483 sprintf (handshake_msg, "DWP-Handshake");
1485 res = transport_send (handshake_msg, strlen (handshake_msg));
1486 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1487 g_assert (res != -1);
1490 res = transport_recv (buf, strlen (handshake_msg));
1491 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1492 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1497 * To support older clients, the client sends its protocol version after connecting
1498 * using a command. Until that is received, default to our protocol version.
1500 major_version = MAJOR_VERSION;
1501 minor_version = MINOR_VERSION;
1502 protocol_version_set = FALSE;
1504 #ifndef DISABLE_SOCKET_TRANSPORT
1505 // FIXME: Move this somewhere else
1507 * Set TCP_NODELAY on the socket so the client receives events/command
1508 * results immediately.
1512 int result = setsockopt (conn_fd,
1517 g_assert (result >= 0);
1523 disconnected = FALSE;
1528 stop_debugger_thread (void)
1533 transport_close1 ();
1536 * Wait for the thread to exit.
1538 * If we continue with the shutdown without waiting for it, then the client might
1539 * not receive an answer to its last command like a resume.
1540 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1543 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1544 if (GetCurrentThreadId () != debugger_thread_id) {
1546 mono_mutex_lock (&debugger_thread_exited_mutex);
1547 if (!debugger_thread_exited) {
1549 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1550 mono_mutex_unlock (&debugger_thread_exited_mutex);
1552 mono_mutex_lock (&debugger_thread_exited_mutex);
1555 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1558 mono_mutex_unlock (&debugger_thread_exited_mutex);
1559 } while (!debugger_thread_exited);
1562 transport_close2 ();
1566 start_debugger_thread (void)
1570 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1571 g_assert (debugger_thread_handle);
1575 * Functions to decode protocol data
1579 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1582 g_assert (*endbuf <= limit);
1587 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1590 g_assert (*endbuf <= limit);
1592 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1595 static inline gint64
1596 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1598 guint32 high = decode_int (buf, &buf, limit);
1599 guint32 low = decode_int (buf, &buf, limit);
1603 return ((((guint64)high) << 32) | ((guint64)low));
1607 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1609 return decode_int (buf, endbuf, limit);
1613 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1615 int len = decode_int (buf, &buf, limit);
1623 s = g_malloc (len + 1);
1626 memcpy (s, buf, len);
1635 * Functions to encode protocol data
1639 guint8 *buf, *p, *end;
1643 buffer_init (Buffer *buf, int size)
1645 buf->buf = g_malloc (size);
1647 buf->end = buf->buf + size;
1651 buffer_make_room (Buffer *buf, int size)
1653 if (buf->end - buf->p < size) {
1654 int new_size = buf->end - buf->buf + size + 32;
1655 guint8 *p = g_realloc (buf->buf, new_size);
1656 size = buf->p - buf->buf;
1659 buf->end = buf->buf + new_size;
1664 buffer_add_byte (Buffer *buf, guint8 val)
1666 buffer_make_room (buf, 1);
1672 buffer_add_short (Buffer *buf, guint32 val)
1674 buffer_make_room (buf, 2);
1675 buf->p [0] = (val >> 8) & 0xff;
1676 buf->p [1] = (val >> 0) & 0xff;
1681 buffer_add_int (Buffer *buf, guint32 val)
1683 buffer_make_room (buf, 4);
1684 buf->p [0] = (val >> 24) & 0xff;
1685 buf->p [1] = (val >> 16) & 0xff;
1686 buf->p [2] = (val >> 8) & 0xff;
1687 buf->p [3] = (val >> 0) & 0xff;
1692 buffer_add_long (Buffer *buf, guint64 l)
1694 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1695 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1699 buffer_add_id (Buffer *buf, int id)
1701 buffer_add_int (buf, (guint64)id);
1705 buffer_add_data (Buffer *buf, guint8 *data, int len)
1707 buffer_make_room (buf, len);
1708 memcpy (buf->p, data, len);
1713 buffer_add_string (Buffer *buf, const char *str)
1718 buffer_add_int (buf, 0);
1721 buffer_add_int (buf, len);
1722 buffer_add_data (buf, (guint8*)str, len);
1727 buffer_free (Buffer *buf)
1733 send_packet (int command_set, int command, Buffer *data)
1739 id = InterlockedIncrement (&packet_id);
1741 len = data->p - data->buf + 11;
1742 buffer_init (&buf, len);
1743 buffer_add_int (&buf, len);
1744 buffer_add_int (&buf, id);
1745 buffer_add_byte (&buf, 0); /* flags */
1746 buffer_add_byte (&buf, command_set);
1747 buffer_add_byte (&buf, command);
1748 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1750 res = transport_send (buf.buf, len);
1758 send_reply_packet (int id, int error, Buffer *data)
1764 len = data->p - data->buf + 11;
1765 buffer_init (&buf, len);
1766 buffer_add_int (&buf, len);
1767 buffer_add_int (&buf, id);
1768 buffer_add_byte (&buf, 0x80); /* flags */
1769 buffer_add_byte (&buf, (error >> 8) & 0xff);
1770 buffer_add_byte (&buf, error);
1771 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1773 res = transport_send (buf.buf, len);
1785 * Represents an object accessible by the debugger client.
1788 /* Unique id used in the wire protocol to refer to objects */
1791 * A weakref gc handle pointing to the object. The gc handle is used to
1792 * detect if the object was garbage collected.
1797 /* Maps objid -> ObjRef */
1798 static GHashTable *objrefs;
1801 free_objref (gpointer value)
1805 mono_gchandle_free (o->handle);
1813 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1817 objrefs_cleanup (void)
1819 g_hash_table_destroy (objrefs);
1823 static GHashTable *obj_to_objref;
1824 static MonoGHashTable *suspended_objs;
1827 * Return an ObjRef for OBJ.
1830 get_objref (MonoObject *obj)
1833 GSList *reflist = NULL, *l;
1839 mono_loader_lock ();
1841 if (!obj_to_objref) {
1842 obj_to_objref = g_hash_table_new (NULL, NULL);
1843 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1844 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1847 if (suspend_count) {
1849 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1851 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1854 /* FIXME: The tables can grow indefinitely */
1856 if (mono_gc_is_moving ()) {
1858 * Objects can move, so use a hash table mapping hash codes to lists of
1859 * ObjRef structures.
1861 hash = mono_object_hash (obj);
1863 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1864 for (l = reflist; l; l = l->next) {
1866 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1867 mono_loader_unlock ();
1872 /* Use a hash table with masked pointers to internalize object references */
1873 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1874 /* ref might refer to a different object with the same addr which was GCd */
1875 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1876 mono_loader_unlock ();
1881 ref = g_new0 (ObjRef, 1);
1882 ref->id = InterlockedIncrement (&objref_id);
1883 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1885 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1887 if (mono_gc_is_moving ()) {
1888 reflist = g_slist_append (reflist, ref);
1889 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1891 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1894 mono_loader_unlock ();
1900 true_pred (gpointer key, gpointer value, gpointer user_data)
1906 clear_suspended_objs (void)
1908 mono_loader_lock ();
1909 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
1910 mono_loader_unlock ();
1914 get_objid (MonoObject *obj)
1916 return get_objref (obj)->id;
1920 * Set OBJ to the object identified by OBJID.
1921 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1925 get_object_allow_null (int objid, MonoObject **obj)
1935 return ERR_INVALID_OBJECT;
1937 mono_loader_lock ();
1939 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1942 *obj = mono_gchandle_get_target (ref->handle);
1943 mono_loader_unlock ();
1945 return ERR_INVALID_OBJECT;
1948 mono_loader_unlock ();
1949 return ERR_INVALID_OBJECT;
1954 get_object (int objid, MonoObject **obj)
1956 int err = get_object_allow_null (objid, obj);
1961 return ERR_INVALID_OBJECT;
1966 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1968 return decode_id (buf, endbuf, limit);
1972 buffer_add_objid (Buffer *buf, MonoObject *o)
1974 buffer_add_id (buf, get_objid (o));
1993 * Represents a runtime structure accessible to the debugger client
1996 /* Unique id used in the wire protocol */
1998 /* Domain of the runtime structure, NULL if the domain was unloaded */
2005 MonoAssembly *assembly;
2006 MonoClassField *field;
2008 MonoProperty *property;
2013 /* Maps runtime structure -> Id */
2014 GHashTable *val_to_id [ID_NUM];
2015 /* Classes whose class load event has been sent */
2016 GHashTable *loaded_classes;
2017 /* Maps MonoClass->GPtrArray of file names */
2018 GHashTable *source_files;
2019 /* Maps source file basename -> GSList of classes */
2020 GHashTable *source_file_to_class;
2021 /* Same with ignore-case */
2022 GHashTable *source_file_to_class_ignorecase;
2026 static GPtrArray *ids [ID_NUM];
2033 for (i = 0; i < ID_NUM; ++i)
2034 ids [i] = g_ptr_array_new ();
2042 for (i = 0; i < ID_NUM; ++i) {
2044 for (j = 0; j < ids [i]->len; ++j)
2045 g_free (g_ptr_array_index (ids [i], j));
2046 g_ptr_array_free (ids [i], TRUE);
2053 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2055 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2057 GHashTableIter iter;
2058 GPtrArray *file_names;
2063 for (i = 0; i < ID_NUM; ++i)
2064 if (info->val_to_id [i])
2065 g_hash_table_destroy (info->val_to_id [i]);
2066 g_hash_table_destroy (info->loaded_classes);
2068 g_hash_table_iter_init (&iter, info->source_files);
2069 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2070 for (i = 0; i < file_names->len; ++i)
2071 g_free (g_ptr_array_index (file_names, i));
2072 g_ptr_array_free (file_names, TRUE);
2075 g_hash_table_iter_init (&iter, info->source_file_to_class);
2076 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2081 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2082 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2090 domain_jit_info (domain)->agent_info = NULL;
2092 /* Clear ids referencing structures in the domain */
2093 for (i = 0; i < ID_NUM; ++i) {
2095 for (j = 0; j < ids [i]->len; ++j) {
2096 Id *id = g_ptr_array_index (ids [i], j);
2097 if (id->domain == domain)
2103 mono_loader_lock ();
2104 g_hash_table_remove (domains, domain);
2105 mono_loader_unlock ();
2108 static AgentDomainInfo*
2109 get_agent_domain_info (MonoDomain *domain)
2111 AgentDomainInfo *info = NULL;
2113 mono_domain_lock (domain);
2115 info = domain_jit_info (domain)->agent_info;
2117 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2118 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2119 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2120 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2121 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2124 mono_domain_unlock (domain);
2130 get_id (MonoDomain *domain, IdType type, gpointer val)
2133 AgentDomainInfo *info;
2138 mono_loader_lock ();
2140 mono_domain_lock (domain);
2142 info = get_agent_domain_info (domain);
2144 if (info->val_to_id [type] == NULL)
2145 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2147 id = g_hash_table_lookup (info->val_to_id [type], val);
2149 mono_domain_unlock (domain);
2150 mono_loader_unlock ();
2154 id = g_new0 (Id, 1);
2156 id->id = ids [type]->len + 1;
2157 id->domain = domain;
2160 g_hash_table_insert (info->val_to_id [type], val, id);
2162 mono_domain_unlock (domain);
2164 g_ptr_array_add (ids [type], id);
2166 mono_loader_unlock ();
2171 static inline gpointer
2172 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2176 int id = decode_id (buf, endbuf, limit);
2185 // FIXME: error handling
2186 mono_loader_lock ();
2187 g_assert (id > 0 && id <= ids [type]->len);
2189 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2190 mono_loader_unlock ();
2192 if (res->domain == NULL) {
2193 *err = ERR_UNLOADED;
2198 *domain = res->domain;
2200 return res->data.val;
2204 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2206 buffer_add_id (buf, get_id (domain, type, val));
2209 static inline MonoClass*
2210 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2214 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2215 if (G_UNLIKELY (log_level >= 2) && klass) {
2218 s = mono_type_full_name (&klass->byval_arg);
2219 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2225 static inline MonoAssembly*
2226 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2228 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2231 static inline MonoImage*
2232 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2234 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2237 static inline MonoMethod*
2238 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2242 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2243 if (G_UNLIKELY (log_level >= 2) && m) {
2246 s = mono_method_full_name (m, TRUE);
2247 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2253 static inline MonoClassField*
2254 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2256 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2259 static inline MonoDomain*
2260 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2262 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2265 static inline MonoProperty*
2266 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2268 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2272 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2274 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2275 if (G_UNLIKELY (log_level >= 2) && klass) {
2278 s = mono_type_full_name (&klass->byval_arg);
2279 if (GetCurrentThreadId () == debugger_thread_id)
2280 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2282 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2288 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2290 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2291 if (G_UNLIKELY (log_level >= 2) && method) {
2294 s = mono_method_full_name (method, 1);
2295 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2301 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2303 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2307 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2309 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2313 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2315 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2319 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2321 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2325 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2327 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2330 static void invoke_method (void);
2337 * save_thread_context:
2339 * Set CTX as the current threads context which is used for computing stack traces.
2340 * This function is signal-safe.
2343 save_thread_context (MonoContext *ctx)
2345 DebuggerTlsData *tls;
2347 tls = mono_native_tls_get_value (debugger_tls_id);
2351 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2353 mono_thread_state_init_from_current (&tls->context);
2356 /* Number of threads suspended */
2358 * If this is equal to the size of thread_to_tls, the runtime is considered
2361 static gint32 threads_suspend_count;
2363 static mono_mutex_t suspend_mutex;
2365 /* Cond variable used to wait for suspend_count becoming 0 */
2366 static mono_cond_t suspend_cond;
2368 /* Semaphore used to wait for a thread becoming suspended */
2369 static MonoSemType suspend_sem;
2374 mono_mutex_init (&suspend_mutex);
2375 mono_cond_init (&suspend_cond, NULL);
2376 MONO_SEM_INIT (&suspend_sem, 0);
2381 StackFrameInfo last_frame;
2382 gboolean last_frame_set;
2385 } GetLastFrameUserData;
2388 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2390 GetLastFrameUserData *data = user_data;
2392 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2395 if (!data->last_frame_set) {
2396 /* Store the last frame */
2397 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2398 data->last_frame_set = TRUE;
2401 /* Store the context/lmf for the frame above the last frame */
2402 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2403 data->lmf = info->lmf;
2411 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2412 * INFO is set, process the thread described by INFO.
2413 * This should be signal safe.
2416 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2420 MonoNativeThreadId tid;
2423 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2424 * guarantee the signal handler will be called that many times. Instead of tracking
2425 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2426 * has been requested that hasn't been handled yet, otherwise we can have threads
2427 * refuse to die when VM_EXIT is called
2429 #if defined(__APPLE__)
2430 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2434 * We use interrupt_count to determine whenever this interrupt should be processed
2435 * by us or the normal interrupt processing code in the signal handler.
2436 * There is no race here with notify_thread (), since the signal is sent after
2437 * incrementing interrupt_count.
2439 if (tls->interrupt_count == 0)
2442 InterlockedDecrement (&tls->interrupt_count);
2446 ip = mono_arch_ip_from_context (sigctx);
2448 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2453 tid = mono_thread_info_get_tid (info);
2455 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2457 // FIXME: Races when the thread leaves managed code before hitting a single step
2461 /* Running managed code, will be suspended by the single step code */
2462 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2466 * Running native code, will be suspended when it returns to/enters
2467 * managed code. Treat it as already suspended.
2468 * This might interrupt the code in process_single_step_inner (), we use the
2469 * tls->suspending flag to avoid races when that happens.
2471 if (!tls->suspended && !tls->suspending) {
2473 GetLastFrameUserData data;
2475 // FIXME: printf is not signal safe, but this is only used during
2476 // debugger debugging
2478 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2479 //save_thread_context (&ctx);
2482 /* Already terminated */
2486 * We are in a difficult position: we want to be able to provide stack
2487 * traces for this thread, but we can't use the current ctx+lmf, since
2488 * the thread is still running, so it might return to managed code,
2489 * making these invalid.
2490 * So we start a stack walk and save the first frame, along with the
2491 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2492 * suspended when it returns to managed code, so the parent's ctx should
2495 data.last_frame_set = FALSE;
2497 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2499 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2500 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2501 * since we are not in a JITted method.
2503 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2505 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2507 if (data.last_frame_set) {
2508 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2509 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2511 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2514 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2515 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2516 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2518 tls->async_state.valid = FALSE;
2521 mono_memory_barrier ();
2523 tls->suspended = TRUE;
2524 MONO_SEM_POST (&suspend_sem);
2531 * mono_debugger_agent_thread_interrupt:
2533 * Called by the abort signal handler.
2534 * Should be signal safe.
2537 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2539 DebuggerTlsData *tls;
2544 tls = mono_native_tls_get_value (debugger_tls_id);
2546 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2550 return thread_interrupt (tls, NULL, sigctx, ji);
2554 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2557 mono_debugger_agent_thread_interrupt (NULL, NULL);
2559 #endif /* HOST_WIN32 */
2562 * reset_native_thread_suspend_state:
2564 * Reset the suspended flag and state on native threads
2567 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2569 DebuggerTlsData *tls = value;
2571 if (!tls->really_suspended && tls->suspended) {
2572 tls->suspended = FALSE;
2574 * The thread might still be running if it was executing native code, so the state won't be invalided by
2575 * suspend_current ().
2577 tls->context.valid = FALSE;
2578 tls->async_state.valid = FALSE;
2579 invalidate_frames (tls);
2586 * Notify a thread that it needs to suspend.
2589 notify_thread (gpointer key, gpointer value, gpointer user_data)
2591 MonoInternalThread *thread = key;
2592 DebuggerTlsData *tls = value;
2593 gsize tid = thread->tid;
2596 if (GetCurrentThreadId () == tid || tls->terminated)
2599 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2602 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2603 * guarantee the signal handler will be called that many times. Instead of tracking
2604 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2605 * has been requested that hasn't been handled yet, otherwise we can have threads
2606 * refuse to die when VM_EXIT is called
2608 #if defined(__APPLE__)
2609 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2613 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2614 * of things like breaking waits etc. which we don't want.
2616 InterlockedIncrement (&tls->interrupt_count);
2619 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2621 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2623 if (mono_thread_info_new_interrupt_enabled ()) {
2624 MonoThreadInfo *info;
2627 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2629 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2631 * Attached thread which died without detaching.
2633 tls->terminated = TRUE;
2635 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2637 thread_interrupt (tls, info, NULL, ji);
2639 mono_thread_info_resume (mono_thread_info_get_tid (info));
2642 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2644 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2646 * Attached thread which died without detaching.
2648 tls->terminated = TRUE;
2655 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2657 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2661 if (mono_loader_lock_is_owned_by_self ()) {
2663 * Shortcut for the check in suspend_current (). This speeds up processing
2664 * when executing long running code inside the loader lock, i.e. assembly load
2670 if (debugger_thread_id == GetCurrentThreadId ())
2673 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2674 if (suspend_count - tls->resume_count > 0)
2675 tls->suspending = TRUE;
2677 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2679 if (suspend_count - tls->resume_count == 0) {
2681 * We are executing a single threaded invoke but the single step for
2682 * suspending is still active.
2683 * FIXME: This slows down single threaded invokes.
2685 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2689 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2691 /* Can't suspend in these methods */
2692 method = jinfo_get_method (ji);
2693 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2696 save_thread_context (ctx);
2704 * Increase the suspend count of the VM. While the suspend count is greater
2705 * than 0, runtime threads are suspended at certain points during execution.
2710 mono_loader_lock ();
2712 mono_mutex_lock (&suspend_mutex);
2716 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2718 if (suspend_count == 1) {
2719 // FIXME: Is it safe to call this inside the lock ?
2720 start_single_stepping ();
2721 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2724 mono_mutex_unlock (&suspend_mutex);
2726 if (suspend_count == 1)
2728 * Suspend creation of new threadpool threads, since they cannot run
2730 mono_thread_pool_suspend ();
2732 mono_loader_unlock ();
2738 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2746 g_assert (debugger_thread_id == GetCurrentThreadId ());
2748 mono_loader_lock ();
2750 mono_mutex_lock (&suspend_mutex);
2752 g_assert (suspend_count > 0);
2755 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2757 if (suspend_count == 0) {
2758 // FIXME: Is it safe to call this inside the lock ?
2759 stop_single_stepping ();
2760 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2763 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2764 err = mono_cond_broadcast (&suspend_cond);
2765 g_assert (err == 0);
2767 mono_mutex_unlock (&suspend_mutex);
2768 //g_assert (err == 0);
2770 if (suspend_count == 0)
2771 mono_thread_pool_resume ();
2773 mono_loader_unlock ();
2779 * Resume just one thread.
2782 resume_thread (MonoInternalThread *thread)
2785 DebuggerTlsData *tls;
2787 g_assert (debugger_thread_id == GetCurrentThreadId ());
2789 mono_loader_lock ();
2791 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2794 mono_mutex_lock (&suspend_mutex);
2796 g_assert (suspend_count > 0);
2798 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2800 tls->resume_count += suspend_count;
2803 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2804 * but only the one whose resume_count field is > 0 will be resumed.
2806 err = mono_cond_broadcast (&suspend_cond);
2807 g_assert (err == 0);
2809 mono_mutex_unlock (&suspend_mutex);
2810 //g_assert (err == 0);
2812 mono_loader_unlock ();
2816 invalidate_frames (DebuggerTlsData *tls)
2821 tls = mono_native_tls_get_value (debugger_tls_id);
2824 for (i = 0; i < tls->frame_count; ++i) {
2825 if (tls->frames [i]->jit)
2826 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2827 g_free (tls->frames [i]);
2829 g_free (tls->frames);
2830 tls->frame_count = 0;
2837 * Suspend the current thread until the runtime is resumed. If the thread has a
2838 * pending invoke, then the invoke is executed before this function returns.
2841 suspend_current (void)
2844 DebuggerTlsData *tls;
2846 g_assert (debugger_thread_id != GetCurrentThreadId ());
2848 if (mono_loader_lock_is_owned_by_self ()) {
2850 * If we own the loader mutex, can't suspend until we release it, since the
2851 * whole runtime can deadlock otherwise.
2856 tls = mono_native_tls_get_value (debugger_tls_id);
2859 mono_mutex_lock (&suspend_mutex);
2861 tls->suspending = FALSE;
2862 tls->really_suspended = TRUE;
2864 if (!tls->suspended) {
2865 tls->suspended = TRUE;
2866 MONO_SEM_POST (&suspend_sem);
2869 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2871 while (suspend_count - tls->resume_count > 0) {
2873 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2875 mono_mutex_unlock (&suspend_mutex);
2877 mono_mutex_lock (&suspend_mutex);
2883 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2884 g_assert (err == 0);
2888 tls->suspended = FALSE;
2889 tls->really_suspended = FALSE;
2891 threads_suspend_count --;
2893 mono_mutex_unlock (&suspend_mutex);
2895 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2897 if (tls->pending_invoke) {
2898 /* Save the original context */
2899 tls->pending_invoke->has_ctx = TRUE;
2900 tls->pending_invoke->ctx = tls->context.ctx;
2905 /* The frame info becomes invalid after a resume */
2906 tls->context.valid = FALSE;
2907 tls->async_state.valid = FALSE;
2908 invalidate_frames (tls);
2912 count_thread (gpointer key, gpointer value, gpointer user_data)
2914 DebuggerTlsData *tls = value;
2916 if (!tls->suspended && !tls->terminated)
2917 *(int*)user_data = *(int*)user_data + 1;
2921 count_threads_to_wait_for (void)
2925 mono_loader_lock ();
2926 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2927 mono_loader_unlock ();
2935 * Wait until the runtime is completely suspended.
2938 wait_for_suspend (void)
2940 int nthreads, nwait, err;
2941 gboolean waited = FALSE;
2943 // FIXME: Threads starting/stopping ?
2944 mono_loader_lock ();
2945 nthreads = mono_g_hash_table_size (thread_to_tls);
2946 mono_loader_unlock ();
2949 nwait = count_threads_to_wait_for ();
2951 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2952 err = MONO_SEM_WAIT (&suspend_sem);
2953 g_assert (err == 0);
2961 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2967 * Return whenever the runtime is suspended.
2972 return count_threads_to_wait_for () == 0;
2975 static MonoSeqPointInfo*
2976 get_seq_points (MonoDomain *domain, MonoMethod *method)
2978 MonoSeqPointInfo *seq_points;
2980 mono_domain_lock (domain);
2981 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2982 if (!seq_points && method->is_inflated) {
2983 /* generic sharing + aot */
2984 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2986 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2988 mono_domain_unlock (domain);
2994 no_seq_points_found (MonoMethod *method)
2997 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
2999 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3003 * find_next_seq_point_for_native_offset:
3005 * Find the first sequence point after NATIVE_OFFSET.
3008 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3010 MonoSeqPointInfo *seq_points;
3013 seq_points = get_seq_points (domain, method);
3019 g_assert (seq_points);
3023 for (i = 0; i < seq_points->len; ++i) {
3024 if (seq_points->seq_points [i].native_offset >= native_offset)
3025 return &seq_points->seq_points [i];
3032 * find_prev_seq_point_for_native_offset:
3034 * Find the first sequence point before NATIVE_OFFSET.
3037 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3039 MonoSeqPointInfo *seq_points;
3042 seq_points = get_seq_points (domain, method);
3048 for (i = seq_points->len - 1; i >= 0; --i) {
3049 if (seq_points->seq_points [i].native_offset <= native_offset)
3050 return &seq_points->seq_points [i];
3059 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3060 * should be the location of a sequence point.
3062 static G_GNUC_UNUSED SeqPoint*
3063 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3065 MonoSeqPointInfo *seq_points;
3070 seq_points = get_seq_points (domain, method);
3075 for (i = 0; i < seq_points->len; ++i) {
3076 if (seq_points->seq_points [i].il_offset == il_offset)
3077 return &seq_points->seq_points [i];
3084 DebuggerTlsData *tls;
3086 } ComputeFramesUserData;
3089 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3091 ComputeFramesUserData *ud = user_data;
3093 MonoMethod *method, *actual_method, *api_method;
3097 if (info->type != FRAME_TYPE_MANAGED) {
3098 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3099 /* Mark the last frame as an invoke frame */
3101 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3107 method = jinfo_get_method (info->ji);
3109 method = info->method;
3110 actual_method = info->actual_method;
3111 api_method = method;
3116 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3119 if (info->il_offset == -1) {
3120 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3121 if (ud->frames == NULL) {
3122 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3124 info->il_offset = sp->il_offset;
3126 if (info->il_offset == -1)
3127 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3130 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));
3132 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3133 if (!CHECK_PROTOCOL_VERSION (2, 17))
3134 /* Older clients can't handle this flag */
3136 api_method = mono_marshal_method_from_wrapper (method);
3139 actual_method = api_method;
3140 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3143 frame = g_new0 (StackFrame, 1);
3144 frame->method = method;
3145 frame->actual_method = actual_method;
3146 frame->api_method = api_method;
3147 frame->il_offset = info->il_offset;
3148 frame->native_offset = info->native_offset;
3149 frame->flags = flags;
3150 frame->ji = info->ji;
3151 if (info->reg_locations)
3152 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3155 frame->has_ctx = TRUE;
3157 frame->domain = info->domain;
3159 ud->frames = g_slist_append (ud->frames, frame);
3165 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3167 ComputeFramesUserData *ud = user_data;
3170 * 'tls->filter_ctx' is the location of the throw site.
3172 * mono_walk_stack() will never actually hit the throw site, but unwind
3173 * directly from the filter to the call site; we abort stack unwinding here
3174 * once this happens and resume from the throw site.
3177 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3180 return process_frame (info, ctx, user_data);
3184 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3186 ComputeFramesUserData user_data;
3188 int i, findex, new_frame_count;
3189 StackFrame **new_frames, *f;
3190 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3192 // FIXME: Locking on tls
3193 if (tls->frames && tls->frames_up_to_date)
3196 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3198 user_data.tls = tls;
3199 user_data.frames = NULL;
3200 if (tls->terminated) {
3201 tls->frame_count = 0;
3203 } if (!tls->really_suspended && tls->async_state.valid) {
3204 /* Have to use the state saved by the signal handler */
3205 process_frame (&tls->async_last_frame, NULL, &user_data);
3206 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3207 } else if (tls->filter_state.valid) {
3209 * We are inside an exception filter.
3211 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3213 if (tls->context.valid)
3214 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3216 * After that, we resume unwinding from the location where the exception has been thrown.
3218 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3219 } else if (tls->context.valid) {
3220 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3223 tls->frame_count = 0;
3227 new_frame_count = g_slist_length (user_data.frames);
3228 new_frames = g_new0 (StackFrame*, new_frame_count);
3230 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3234 * Reuse the id for already existing stack frames, so invokes don't invalidate
3235 * the still valid stack frames.
3237 for (i = 0; i < tls->frame_count; ++i) {
3238 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3239 f->id = tls->frames [i]->id;
3244 if (i >= tls->frame_count)
3245 f->id = InterlockedIncrement (&frame_id);
3247 new_frames [findex ++] = f;
3250 g_slist_free (user_data.frames);
3252 invalidate_frames (tls);
3254 tls->frames = new_frames;
3255 tls->frame_count = new_frame_count;
3256 tls->frames_up_to_date = TRUE;
3260 * GHFunc to emit an appdomain creation event
3261 * @param key Don't care
3262 * @param value A loaded appdomain
3263 * @param user_data Don't care
3266 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3268 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3269 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3273 * GHFunc to emit a thread start event
3274 * @param key A thread id
3275 * @param value A thread object
3276 * @param user_data Don't care
3279 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3281 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3282 process_profiler_event (EVENT_KIND_THREAD_START, value);
3286 * GFunc to emit an assembly load event
3287 * @param value A loaded assembly
3288 * @param user_data Don't care
3291 emit_assembly_load (gpointer value, gpointer user_data)
3293 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3297 * GFunc to emit a type load event
3298 * @param value A loaded type
3299 * @param user_data Don't care
3302 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3304 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3308 strdup_tolower (char *s)
3313 for (p = s2; *p; ++p)
3323 * create_event_list:
3325 * Return a list of event request ids matching EVENT, starting from REQS, which
3326 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3328 * We return request ids, instead of requests, to simplify threading, since
3329 * requests could be deleted anytime when the loader lock is not held.
3330 * LOCKING: Assumes the loader lock is held.
3333 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3336 GSList *events = NULL;
3338 *suspend_policy = SUSPEND_POLICY_NONE;
3341 reqs = event_requests;
3346 for (i = 0; i < reqs->len; ++i) {
3347 EventRequest *req = g_ptr_array_index (reqs, i);
3348 if (req->event_kind == event) {
3349 gboolean filtered = FALSE;
3352 for (j = 0; j < req->nmodifiers; ++j) {
3353 Modifier *mod = &req->modifiers [j];
3355 if (mod->kind == MOD_KIND_COUNT) {
3357 if (mod->data.count > 0) {
3358 if (mod->data.count > 0) {
3360 if (mod->data.count == 0)
3364 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3365 if (mod->data.thread != mono_thread_internal_current ())
3367 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3368 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3370 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3372 if (ei->caught && !mod->caught)
3374 if (!ei->caught && !mod->uncaught)
3376 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3378 gboolean found = FALSE;
3379 MonoAssembly **assemblies = mod->data.assemblies;
3382 for (k = 0; assemblies [k]; ++k)
3383 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3388 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3389 gpointer iter = NULL;
3391 MonoDebugSourceInfo *sinfo;
3392 char *source_file, *s;
3393 gboolean found = FALSE;
3395 GPtrArray *source_file_list;
3397 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3398 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3401 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3402 for (i = 0; i < source_file_list->len; ++i) {
3403 sinfo = g_ptr_array_index (source_file_list, i);
3405 * Do a case-insesitive match by converting the file name to
3408 s = strdup_tolower (sinfo->source_file);
3409 if (g_hash_table_lookup (mod->data.source_files, s))
3412 char *s2 = g_path_get_basename (sinfo->source_file);
3413 char *s3 = strdup_tolower (s2);
3415 if (g_hash_table_lookup (mod->data.source_files, s3))
3422 g_ptr_array_free (source_file_list, TRUE);
3427 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3430 s = mono_type_full_name (&ei->klass->byval_arg);
3431 if (!g_hash_table_lookup (mod->data.type_names, s))
3434 } else if (mod->kind == MOD_KIND_STEP) {
3435 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3436 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3437 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3439 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3440 MonoCustomAttrInfo *ainfo;
3441 static MonoClass *klass;
3444 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3447 if (!ji->dbg_hidden_inited) {
3448 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3450 if (mono_custom_attrs_has_attr (ainfo, klass))
3451 ji->dbg_hidden = TRUE;
3452 mono_custom_attrs_free (ainfo);
3454 ji->dbg_hidden_inited = TRUE;
3459 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3460 MonoCustomAttrInfo *ainfo;
3461 static MonoClass *klass;
3464 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3467 if (!ji->dbg_step_through_inited) {
3468 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3470 if (mono_custom_attrs_has_attr (ainfo, klass))
3471 ji->dbg_step_through = TRUE;
3472 mono_custom_attrs_free (ainfo);
3474 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3476 if (mono_custom_attrs_has_attr (ainfo, klass))
3477 ji->dbg_step_through = TRUE;
3478 mono_custom_attrs_free (ainfo);
3480 ji->dbg_step_through_inited = TRUE;
3482 if (ji->dbg_step_through)
3489 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3490 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3495 /* Send a VM START/DEATH event by default */
3496 if (event == EVENT_KIND_VM_START)
3497 events = g_slist_append (events, GINT_TO_POINTER (0));
3498 if (event == EVENT_KIND_VM_DEATH)
3499 events = g_slist_append (events, GINT_TO_POINTER (0));
3504 static G_GNUC_UNUSED const char*
3505 event_to_string (EventKind event)
3508 case EVENT_KIND_VM_START: return "VM_START";
3509 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3510 case EVENT_KIND_THREAD_START: return "THREAD_START";
3511 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3512 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3513 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3514 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3515 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3516 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3517 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3518 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3519 case EVENT_KIND_STEP: return "STEP";
3520 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3521 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3522 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3523 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3524 case EVENT_KIND_USER_LOG: return "USER_LOG";
3526 g_assert_not_reached ();
3534 * Send an event to the client, suspending the vm if needed.
3535 * LOCKING: Since this can suspend the calling thread, no locks should be held
3537 * The EVENTS list is freed by this function.
3540 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3544 MonoDomain *domain = mono_domain_get ();
3545 MonoThread *thread = NULL;
3546 MonoObject *keepalive_obj = NULL;
3547 gboolean send_success = FALSE;
3552 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3556 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3557 // FIXME: We miss those events
3558 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3562 if (vm_death_event_sent) {
3563 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3567 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3568 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3573 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3577 if (event == EVENT_KIND_KEEPALIVE)
3578 suspend_policy = SUSPEND_POLICY_NONE;
3583 if (agent_config.defer) {
3584 /* Make sure the thread id is always set when doing deferred debugging */
3585 if (debugger_thread_id == GetCurrentThreadId ()) {
3586 /* Don't suspend on events from the debugger thread */
3587 suspend_policy = SUSPEND_POLICY_NONE;
3588 thread = mono_thread_get_main ();
3590 else thread = mono_thread_current ();
3592 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3593 // FIXME: Send these with a NULL thread, don't suspend the current thread
3598 nevents = g_slist_length (events);
3599 buffer_init (&buf, 128);
3600 buffer_add_byte (&buf, suspend_policy);
3601 buffer_add_int (&buf, nevents);
3603 for (l = events; l; l = l->next) {
3604 buffer_add_byte (&buf, event); // event kind
3605 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3610 thread = mono_thread_current ();
3612 if (event == EVENT_KIND_VM_START && arg != NULL)
3615 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3618 case EVENT_KIND_THREAD_START:
3619 case EVENT_KIND_THREAD_DEATH:
3621 case EVENT_KIND_APPDOMAIN_CREATE:
3622 case EVENT_KIND_APPDOMAIN_UNLOAD:
3623 buffer_add_domainid (&buf, arg);
3625 case EVENT_KIND_METHOD_ENTRY:
3626 case EVENT_KIND_METHOD_EXIT:
3627 buffer_add_methodid (&buf, domain, arg);
3629 case EVENT_KIND_ASSEMBLY_LOAD:
3630 case EVENT_KIND_ASSEMBLY_UNLOAD:
3631 buffer_add_assemblyid (&buf, domain, arg);
3633 case EVENT_KIND_TYPE_LOAD:
3634 buffer_add_typeid (&buf, domain, arg);
3636 case EVENT_KIND_BREAKPOINT:
3637 case EVENT_KIND_STEP:
3638 buffer_add_methodid (&buf, domain, arg);
3639 buffer_add_long (&buf, il_offset);
3641 case EVENT_KIND_VM_START:
3642 buffer_add_domainid (&buf, mono_get_root_domain ());
3644 case EVENT_KIND_VM_DEATH:
3645 if (CHECK_PROTOCOL_VERSION (2, 27))
3646 buffer_add_int (&buf, mono_environment_exitcode_get ());
3648 case EVENT_KIND_EXCEPTION: {
3649 EventInfo *ei = arg;
3650 buffer_add_objid (&buf, ei->exc);
3652 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3653 * later after the suspension. (#12494).
3655 keepalive_obj = ei->exc;
3658 case EVENT_KIND_USER_BREAK:
3660 case EVENT_KIND_USER_LOG: {
3661 EventInfo *ei = arg;
3662 buffer_add_int (&buf, ei->level);
3663 buffer_add_string (&buf, ei->category ? ei->category : "");
3664 buffer_add_string (&buf, ei->message ? ei->message : "");
3667 case EVENT_KIND_KEEPALIVE:
3668 suspend_policy = SUSPEND_POLICY_NONE;
3671 g_assert_not_reached ();
3675 if (event == EVENT_KIND_VM_START) {
3676 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3677 if (!agent_config.defer)
3678 start_debugger_thread ();
3681 if (event == EVENT_KIND_VM_DEATH) {
3682 vm_death_event_sent = TRUE;
3683 suspend_policy = SUSPEND_POLICY_NONE;
3686 if (mono_runtime_is_shutting_down ())
3687 suspend_policy = SUSPEND_POLICY_NONE;
3689 if (suspend_policy != SUSPEND_POLICY_NONE) {
3691 * Save the thread context and start suspending before sending the packet,
3692 * since we could be receiving the resume request before send_packet ()
3695 save_thread_context (ctx);
3699 /* This will keep this object alive */
3700 get_objref (keepalive_obj);
3703 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3707 g_slist_free (events);
3710 if (!send_success) {
3711 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3715 if (event == EVENT_KIND_VM_START) {
3716 vm_start_event_sent = TRUE;
3719 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3721 switch (suspend_policy) {
3722 case SUSPEND_POLICY_NONE:
3724 case SUSPEND_POLICY_ALL:
3727 case SUSPEND_POLICY_EVENT_THREAD:
3731 g_assert_not_reached ();
3736 process_profiler_event (EventKind event, gpointer arg)
3740 EventInfo ei, *ei_arg = NULL;
3742 if (event == EVENT_KIND_TYPE_LOAD) {
3747 mono_loader_lock ();
3748 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3749 mono_loader_unlock ();
3751 process_event (event, arg, 0, NULL, events, suspend_policy);
3755 runtime_initialized (MonoProfiler *prof)
3757 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3758 if (agent_config.defer)
3759 start_debugger_thread ();
3763 runtime_shutdown (MonoProfiler *prof)
3765 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3767 mono_debugger_agent_cleanup ();
3771 thread_startup (MonoProfiler *prof, uintptr_t tid)
3773 MonoInternalThread *thread = mono_thread_internal_current ();
3774 MonoInternalThread *old_thread;
3775 DebuggerTlsData *tls;
3777 if (tid == debugger_thread_id)
3780 g_assert (thread->tid == tid);
3782 mono_loader_lock ();
3783 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3784 mono_loader_unlock ();
3786 if (thread == old_thread) {
3788 * For some reason, thread_startup () might be called for the same thread
3789 * multiple times (attach ?).
3791 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3795 * thread_end () might not be called for some threads, and the tid could
3798 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3799 mono_loader_lock ();
3800 mono_g_hash_table_remove (thread_to_tls, old_thread);
3801 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3802 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3803 mono_loader_unlock ();
3807 tls = mono_native_tls_get_value (debugger_tls_id);
3809 // FIXME: Free this somewhere
3810 tls = g_new0 (DebuggerTlsData, 1);
3811 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3812 tls->thread = thread;
3813 mono_native_tls_set_value (debugger_tls_id, tls);
3815 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3817 mono_loader_lock ();
3818 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3819 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3820 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3821 mono_loader_unlock ();
3823 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3826 * suspend_vm () could have missed this thread, so wait for a resume.
3832 thread_end (MonoProfiler *prof, uintptr_t tid)
3834 MonoInternalThread *thread;
3835 DebuggerTlsData *tls = NULL;
3837 mono_loader_lock ();
3838 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3840 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3841 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3843 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3844 tls->terminated = TRUE;
3845 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3846 MONO_GC_UNREGISTER_ROOT (tls->thread);
3850 mono_loader_unlock ();
3852 /* We might be called for threads started before we registered the start callback */
3854 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3855 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3860 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3862 mono_loader_lock ();
3863 g_hash_table_insert (domains, domain, domain);
3864 mono_loader_unlock ();
3866 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3870 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3872 clear_breakpoints_for_domain (domain);
3874 mono_loader_lock ();
3875 /* Invalidate each thread's frame stack */
3876 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3877 mono_loader_unlock ();
3879 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3883 * invalidate_each_thread:
3885 * A GHFunc to invalidate frames.
3886 * value must be a DebuggerTlsData*
3889 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3891 invalidate_frames (value);
3895 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3897 /* Sent later in jit_end () */
3898 mono_loader_lock ();
3899 g_ptr_array_add (pending_assembly_loads, assembly);
3900 mono_loader_unlock ();
3904 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3906 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3908 clear_event_requests_for_assembly (assembly);
3909 clear_types_for_assembly (assembly);
3913 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3915 #if defined(HOST_WIN32) && !defined(__GNUC__)
3916 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3918 gpointer stackptr = __builtin_frame_address (1);
3920 MonoInternalThread *thread = mono_thread_internal_current ();
3921 DebuggerTlsData *tls;
3923 mono_loader_lock ();
3925 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3926 /* Could be the debugger thread with assembly/type load hooks */
3928 tls->invoke_addr = stackptr;
3930 mono_loader_unlock ();
3934 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3937 #if defined(HOST_WIN32) && !defined(__GNUC__)
3938 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3940 gpointer stackptr = __builtin_frame_address (1);
3943 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3947 * We need to stop single stepping when exiting a runtime invoke, since if it is
3948 * a step out, it may return to native code, and thus never end.
3950 mono_loader_lock ();
3951 ss_invoke_addr = NULL;
3953 for (i = 0; i < event_requests->len; ++i) {
3954 EventRequest *req = g_ptr_array_index (event_requests, i);
3956 if (req->event_kind == EVENT_KIND_STEP) {
3957 ss_destroy (req->info);
3958 g_ptr_array_remove_index_fast (event_requests, i);
3963 mono_loader_unlock ();
3967 send_type_load (MonoClass *klass)
3969 gboolean type_load = FALSE;
3970 MonoDomain *domain = mono_domain_get ();
3971 AgentDomainInfo *info = NULL;
3973 mono_loader_lock ();
3974 mono_domain_lock (domain);
3976 info = get_agent_domain_info (domain);
3978 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3980 g_hash_table_insert (info->loaded_classes, klass, klass);
3983 mono_domain_unlock (domain);
3984 mono_loader_unlock ();
3986 emit_type_load (klass, klass, NULL);
3990 * Emit load events for all types currently loaded in the domain.
3991 * Takes the loader and domain locks.
3992 * user_data is unused.
3995 send_types_for_domain (MonoDomain *domain, void *user_data)
3997 AgentDomainInfo *info = NULL;
3999 mono_loader_lock ();
4000 mono_domain_lock (domain);
4001 info = get_agent_domain_info (domain);
4003 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4004 mono_domain_unlock (domain);
4005 mono_loader_unlock ();
4009 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4012 * We emit type load events when the first method of the type is JITted,
4013 * since the class load profiler callbacks might be called with the
4014 * loader lock held. They could also occur in the debugger thread.
4015 * Same for assembly load events.
4018 MonoAssembly *assembly = NULL;
4020 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4021 mono_loader_lock ();
4022 if (pending_assembly_loads->len > 0) {
4023 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4024 g_ptr_array_remove_index (pending_assembly_loads, 0);
4026 mono_loader_unlock ();
4029 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4035 send_type_load (method->klass);
4038 add_pending_breakpoints (method, jinfo);
4042 * BREAKPOINTS/SINGLE STEPPING
4046 * Contains information about an inserted breakpoint.
4049 long il_offset, native_offset;
4054 } BreakpointInstance;
4057 * Contains generic information about a breakpoint.
4061 * The method where the breakpoint is placed. Can be NULL in which case it
4062 * is inserted into every method. This is used to implement method entry/
4063 * exit events. Can be a generic method definition, in which case the
4064 * breakpoint is inserted into every instance.
4070 * A list of BreakpointInstance structures describing where the breakpoint
4071 * was inserted. There could be more than one because of
4072 * generics/appdomains/method entry/exit.
4074 GPtrArray *children;
4077 /* List of breakpoints */
4078 static GPtrArray *breakpoints;
4079 /* Maps breakpoint locations to the number of breakpoints at that location */
4080 static GHashTable *bp_locs;
4083 breakpoints_init (void)
4085 breakpoints = g_ptr_array_new ();
4086 bp_locs = g_hash_table_new (NULL, NULL);
4090 * insert_breakpoint:
4092 * Insert the breakpoint described by BP into the method described by
4096 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4099 BreakpointInstance *inst;
4100 SeqPoint *sp = NULL;
4103 mono_error_init (error);
4105 for (i = 0; i < seq_points->len; ++i) {
4106 sp = &seq_points->seq_points [i];
4108 if (sp->il_offset == bp->il_offset)
4112 if (i == seq_points->len) {
4114 * The set of IL offsets with seq points doesn't completely match the
4115 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4117 for (i = 0; i < seq_points->len; ++i) {
4118 sp = &seq_points->seq_points [i];
4120 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4125 if (i == seq_points->len) {
4126 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);
4128 for (i = 0; i < seq_points->len; ++i)
4129 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4132 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4133 g_warning ("%s", s);
4137 g_warning ("%s", s);
4143 inst = g_new0 (BreakpointInstance, 1);
4145 inst->native_offset = sp->native_offset;
4146 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4148 inst->domain = domain;
4150 mono_loader_lock ();
4152 g_ptr_array_add (bp->children, inst);
4154 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4155 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4156 mono_loader_unlock ();
4158 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4159 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4160 } else if (count == 0) {
4161 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4162 mono_arch_set_breakpoint (ji, inst->ip);
4168 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));
4172 remove_breakpoint (BreakpointInstance *inst)
4174 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4176 MonoJitInfo *ji = inst->ji;
4177 guint8 *ip = inst->ip;
4179 mono_loader_lock ();
4180 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4181 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4182 mono_loader_unlock ();
4184 g_assert (count > 0);
4186 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4187 mono_arch_clear_breakpoint (ji, ip);
4194 static inline gboolean
4195 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4201 if (method == bp->method)
4203 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4206 if (bp->method->is_inflated && method->is_inflated) {
4207 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4208 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4210 /* Open generic methods should match closed generic methods of the same class */
4211 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4212 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4213 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4215 /* FIXME: Handle !mvar */
4216 if (t1->type != MONO_TYPE_MVAR)
4227 * add_pending_breakpoints:
4229 * Insert pending breakpoints into the newly JITted method METHOD.
4232 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4235 MonoSeqPointInfo *seq_points;
4237 MonoMethod *jmethod;
4242 domain = mono_domain_get ();
4244 mono_loader_lock ();
4246 for (i = 0; i < breakpoints->len; ++i) {
4247 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4248 gboolean found = FALSE;
4250 if (!bp_matches_method (bp, method))
4253 for (j = 0; j < bp->children->len; ++j) {
4254 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4261 jmethod = jinfo_get_method (ji);
4262 mono_domain_lock (domain);
4263 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4264 if (!seq_points && jmethod->is_inflated)
4265 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4266 mono_domain_unlock (domain);
4268 /* Could be AOT code */
4270 g_assert (seq_points);
4272 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4276 mono_loader_unlock ();
4280 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4286 mono_error_init (error);
4288 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4290 /* Might be AOTed code */
4291 code = mono_aot_get_method (domain, method);
4293 ji = mono_jit_info_table_find (domain, code);
4298 insert_breakpoint (seq_points, domain, ji, bp, error);
4302 clear_breakpoint (MonoBreakpoint *bp);
4307 * Set a breakpoint at IL_OFFSET in METHOD.
4308 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4309 * METHOD can also be a generic method definition, in which case a breakpoint
4310 * is placed in all instances of the method.
4311 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4314 static MonoBreakpoint*
4315 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4318 GHashTableIter iter, iter2;
4321 MonoSeqPointInfo *seq_points;
4324 mono_error_init (error);
4327 // - suspend/resume the vm to prevent code patching problems
4328 // - multiple breakpoints on the same location
4329 // - dynamic methods
4332 bp = g_new0 (MonoBreakpoint, 1);
4333 bp->method = method;
4334 bp->il_offset = il_offset;
4336 bp->children = g_ptr_array_new ();
4338 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));
4340 mono_loader_lock ();
4342 g_hash_table_iter_init (&iter, domains);
4343 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4344 mono_domain_lock (domain);
4346 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4347 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4348 if (bp_matches_method (bp, m))
4349 set_bp_in_method (domain, m, seq_points, bp, error);
4352 mono_domain_unlock (domain);
4355 mono_loader_unlock ();
4357 mono_loader_lock ();
4358 g_ptr_array_add (breakpoints, bp);
4359 mono_loader_unlock ();
4361 if (error && !mono_error_ok (error)) {
4362 clear_breakpoint (bp);
4370 clear_breakpoint (MonoBreakpoint *bp)
4374 // FIXME: locking, races
4375 for (i = 0; i < bp->children->len; ++i) {
4376 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4378 remove_breakpoint (inst);
4383 mono_loader_lock ();
4384 g_ptr_array_remove (breakpoints, bp);
4385 mono_loader_unlock ();
4387 g_ptr_array_free (bp->children, TRUE);
4392 breakpoints_cleanup (void)
4396 mono_loader_lock ();
4398 while (i < event_requests->len) {
4399 EventRequest *req = g_ptr_array_index (event_requests, i);
4401 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4402 clear_breakpoint (req->info);
4403 g_ptr_array_remove_index_fast (event_requests, i);
4410 for (i = 0; i < breakpoints->len; ++i)
4411 g_free (g_ptr_array_index (breakpoints, i));
4413 g_ptr_array_free (breakpoints, TRUE);
4414 g_hash_table_destroy (bp_locs);
4419 mono_loader_unlock ();
4423 * clear_breakpoints_for_domain:
4425 * Clear breakpoint instances which reference DOMAIN.
4428 clear_breakpoints_for_domain (MonoDomain *domain)
4432 /* This could be called after shutdown */
4436 mono_loader_lock ();
4437 for (i = 0; i < breakpoints->len; ++i) {
4438 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4441 while (j < bp->children->len) {
4442 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4444 if (inst->domain == domain) {
4445 remove_breakpoint (inst);
4449 g_ptr_array_remove_index_fast (bp->children, j);
4455 mono_loader_unlock ();
4461 * Return FALSE if single stepping needs to continue.
4464 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp)
4466 MonoDebugMethodInfo *minfo;
4467 MonoDebugSourceLocation *loc = NULL;
4468 gboolean hit = TRUE;
4471 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4473 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4475 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4479 if (req->size != STEP_SIZE_LINE)
4482 /* Have to check whenever a different source line was reached */
4483 method = jinfo_get_method (ji);
4484 minfo = mono_debug_lookup_method (method);
4487 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4489 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4490 /* Have to continue single stepping */
4492 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4494 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4499 ss_req->last_method = method;
4500 ss_req->last_line = loc->row;
4501 mono_debug_free_source_location (loc);
4508 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4510 return bp->method && bp->method->klass->image->assembly == assembly;
4514 process_breakpoint_inner (DebuggerTlsData *tls)
4518 int i, j, suspend_policy;
4519 guint32 native_offset;
4521 BreakpointInstance *inst;
4522 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4523 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4524 EventKind kind = EVENT_KIND_BREAKPOINT;
4525 MonoContext *ctx = &tls->restore_ctx;
4527 MonoSeqPointInfo *info;
4530 // FIXME: Speed this up
4532 ip = MONO_CONTEXT_GET_IP (ctx);
4533 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4535 method = jinfo_get_method (ji);
4537 /* Compute the native offset of the breakpoint from the ip */
4538 native_offset = ip - (guint8*)ji->code_start;
4541 * Skip the instruction causing the breakpoint signal.
4543 mono_arch_skip_breakpoint (ctx, ji);
4545 if (method->wrapper_type || tls->disable_breakpoints)
4548 bp_reqs = g_ptr_array_new ();
4549 ss_reqs = g_ptr_array_new ();
4550 ss_reqs_orig = g_ptr_array_new ();
4552 mono_loader_lock ();
4555 * The ip points to the instruction causing the breakpoint event, which is after
4556 * the offset recorded in the seq point map, so find the prev seq point before ip.
4558 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4560 no_seq_points_found (method);
4563 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));
4566 for (i = 0; i < breakpoints->len; ++i) {
4567 bp = g_ptr_array_index (breakpoints, i);
4572 for (j = 0; j < bp->children->len; ++j) {
4573 inst = g_ptr_array_index (bp->children, j);
4574 if (inst->ji == ji && inst->sp == sp) {
4575 if (bp->req->event_kind == EVENT_KIND_STEP) {
4576 g_ptr_array_add (ss_reqs_orig, bp->req);
4578 g_ptr_array_add (bp_reqs, bp->req);
4583 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4584 /* Maybe a method entry/exit event */
4585 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4586 kind = EVENT_KIND_METHOD_ENTRY;
4587 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4588 kind = EVENT_KIND_METHOD_EXIT;
4591 /* Process single step requests */
4592 for (i = 0; i < ss_reqs_orig->len; ++i) {
4593 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4594 SingleStepReq *ss_req = req->info;
4597 if (mono_thread_internal_current () != ss_req->thread)
4600 hit = ss_update (ss_req, ji, sp);
4602 g_ptr_array_add (ss_reqs, req);
4604 /* Start single stepping again from the current sequence point */
4605 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4608 if (ss_reqs->len > 0)
4609 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4610 if (bp_reqs->len > 0)
4611 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4612 if (kind != EVENT_KIND_BREAKPOINT)
4613 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4615 mono_loader_unlock ();
4617 g_ptr_array_free (bp_reqs, TRUE);
4618 g_ptr_array_free (ss_reqs, TRUE);
4621 * FIXME: The first event will suspend, so the second will only be sent after the
4625 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4627 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4628 if (enter_leave_events)
4629 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4632 /* Process a breakpoint/single step event after resuming from a signal handler */
4634 process_signal_event (void (*func) (DebuggerTlsData*))
4636 DebuggerTlsData *tls;
4637 MonoContext orig_restore_ctx, ctx;
4639 tls = mono_native_tls_get_value (debugger_tls_id);
4640 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4641 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4642 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4646 /* This is called when resuming from a signal handler, so it shouldn't return */
4647 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4648 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4649 mono_restore_context (&ctx);
4650 g_assert_not_reached ();
4654 process_breakpoint (void)
4656 process_signal_event (process_breakpoint_inner);
4660 resume_from_signal_handler (void *sigctx, void *func)
4662 DebuggerTlsData *tls;
4665 /* Save the original context in TLS */
4666 // FIXME: This might not work on an altstack ?
4667 tls = mono_native_tls_get_value (debugger_tls_id);
4669 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4672 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4673 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4674 // clob:c could be added to op_seq_point.
4676 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4677 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4678 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4679 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4681 MONO_CONTEXT_SET_IP (&ctx, func);
4683 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4685 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4686 mono_ppc_set_func_into_sigctx (sigctx, func);
4691 mono_debugger_agent_breakpoint_hit (void *sigctx)
4694 * We are called from a signal handler, and running code there causes all kinds of
4695 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4696 * So set up the signal context to return to the real breakpoint handler function.
4698 resume_from_signal_handler (sigctx, process_breakpoint);
4702 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4704 if (frame->managed) {
4705 *(MonoContext*)data = *ctx;
4714 * Called by System.Diagnostics.Debugger:Break ().
4717 mono_debugger_agent_user_break (void)
4719 if (agent_config.enabled) {
4724 /* Obtain a context */
4725 MONO_CONTEXT_SET_IP (&ctx, NULL);
4726 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4727 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4729 mono_loader_lock ();
4730 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4731 mono_loader_unlock ();
4733 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4740 ss_depth_to_string (StepDepth depth)
4743 case STEP_DEPTH_OVER:
4745 case STEP_DEPTH_OUT:
4747 case STEP_DEPTH_INTO:
4750 g_assert_not_reached ();
4756 process_single_step_inner (DebuggerTlsData *tls)
4761 int il_offset, suspend_policy;
4764 MonoContext *ctx = &tls->restore_ctx;
4767 MonoSeqPointInfo *info;
4769 ip = MONO_CONTEXT_GET_IP (ctx);
4771 /* Skip the instruction causing the single step */
4772 mono_arch_skip_single_step (ctx);
4774 if (suspend_count > 0) {
4775 process_suspend (tls, ctx);
4780 // FIXME: A suspend race
4783 if (mono_thread_internal_current () != ss_req->thread)
4786 if (log_level > 0) {
4787 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4789 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));
4792 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4794 method = jinfo_get_method (ji);
4797 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4802 * Stopping in memset makes half-initialized vtypes visible.
4803 * Stopping in memcpy makes half-copied vtypes visible.
4805 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4809 * The ip points to the instruction causing the single step event, which is before
4810 * the offset recorded in the seq point map, so find the next seq point after ip.
4812 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
4815 il_offset = sp->il_offset;
4817 if (!ss_update (ss_req, ji, sp))
4820 /* Start single stepping again from the current sequence point */
4821 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4823 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4824 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4825 !strcmp (method->name, ".cctor"))
4828 // FIXME: Has to lock earlier
4830 reqs = g_ptr_array_new ();
4832 mono_loader_lock ();
4834 g_ptr_array_add (reqs, ss_req->req);
4836 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4838 g_ptr_array_free (reqs, TRUE);
4840 mono_loader_unlock ();
4842 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4846 process_single_step (void)
4848 process_signal_event (process_single_step_inner);
4852 * mono_debugger_agent_single_step_event:
4854 * Called from a signal handler to handle a single step event.
4857 mono_debugger_agent_single_step_event (void *sigctx)
4859 /* Resume to process_single_step through the signal context */
4861 // FIXME: Since step out/over is implemented using step in, the step in case should
4862 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4865 if (GetCurrentThreadId () == debugger_thread_id) {
4867 * This could happen despite our best effors when the runtime calls
4868 * assembly/type resolve hooks.
4869 * FIXME: Breakpoints too.
4873 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4874 mono_arch_skip_single_step (&ctx);
4875 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4879 resume_from_signal_handler (sigctx, process_single_step);
4883 debugger_agent_single_step_from_context (MonoContext *ctx)
4885 DebuggerTlsData *tls;
4886 MonoContext orig_restore_ctx;
4888 tls = mono_native_tls_get_value (debugger_tls_id);
4891 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4892 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4893 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4895 process_single_step_inner (tls);
4897 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4898 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4902 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4904 DebuggerTlsData *tls;
4905 MonoContext orig_restore_ctx;
4907 tls = mono_native_tls_get_value (debugger_tls_id);
4909 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4910 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4912 process_breakpoint_inner (tls);
4914 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4915 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4919 * start_single_stepping:
4921 * Turn on single stepping. Can be called multiple times, for example,
4922 * by a single step event request + a suspend.
4925 start_single_stepping (void)
4927 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4928 int val = InterlockedIncrement (&ss_count);
4931 mono_arch_start_single_stepping ();
4933 if (ss_req != NULL && ss_invoke_addr == NULL) {
4934 DebuggerTlsData *tls;
4936 mono_loader_lock ();
4938 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4939 ss_invoke_addr = tls->invoke_addr;
4941 mono_loader_unlock ();
4944 g_assert_not_reached ();
4949 stop_single_stepping (void)
4951 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4952 int val = InterlockedDecrement (&ss_count);
4955 mono_arch_stop_single_stepping ();
4957 ss_invoke_addr = NULL;
4959 g_assert_not_reached ();
4966 * Stop the single stepping operation given by SS_REQ.
4969 ss_stop (SingleStepReq *ss_req)
4974 for (l = ss_req->bps; l; l = l->next) {
4975 clear_breakpoint (l->data);
4977 g_slist_free (ss_req->bps);
4981 if (ss_req->global) {
4982 stop_single_stepping ();
4983 ss_req->global = FALSE;
4990 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4991 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4992 * belong to the same thread as CTX.
4995 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4997 int i, j, frame_index;
5000 gboolean enable_global = FALSE;
5002 /* Stop the previous operation */
5006 * Implement single stepping using breakpoints if possible.
5008 if (step_to_catch) {
5009 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5010 ss_req->bps = g_slist_append (ss_req->bps, bp);
5014 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5015 /* Need parent frames */
5016 if (!tls->context.valid)
5017 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5018 compute_frame_info (tls->thread, tls);
5022 * Find the first sequence point in the current or in a previous frame which
5023 * is not the last in its method.
5025 if (ss_req->depth == STEP_DEPTH_OUT) {
5026 /* Ignore seq points in current method */
5027 while (frame_index < tls->frame_count) {
5028 StackFrame *frame = tls->frames [frame_index];
5030 method = frame->method;
5031 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5033 if (sp && sp->next_len != 0)
5036 // There could be method calls before the next seq point in the caller when using nested calls
5037 //enable_global = TRUE;
5039 if (sp && sp->next_len == 0) {
5041 while (frame_index < tls->frame_count) {
5042 StackFrame *frame = tls->frames [frame_index];
5044 method = frame->method;
5045 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5046 if (sp && sp->next_len != 0)
5054 if (sp && sp->next_len > 0) {
5055 for (i = 0; i < sp->next_len; ++i) {
5056 next_sp = &info->seq_points [sp->next [i]];
5058 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5059 ss_req->bps = g_slist_append (ss_req->bps, bp);
5063 if (ss_req->depth == STEP_DEPTH_OVER) {
5064 /* Need to stop in catch clauses as well */
5065 for (i = 0; i < tls->frame_count; ++i) {
5066 StackFrame *frame = tls->frames [i];
5069 MonoJitInfo *jinfo = frame->ji;
5070 for (j = 0; j < jinfo->num_clauses; ++j) {
5071 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5073 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5075 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5076 ss_req->bps = g_slist_append (ss_req->bps, bp);
5084 if (ss_req->depth == STEP_DEPTH_INTO) {
5085 /* Enable global stepping so we stop at method entry too */
5086 enable_global = TRUE;
5090 * The ctx/frame info computed above will become invalid when we continue.
5092 tls->context.valid = FALSE;
5093 tls->async_state.valid = FALSE;
5094 invalidate_frames (tls);
5097 if (enable_global) {
5098 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5099 ss_req->global = TRUE;
5100 start_single_stepping ();
5101 } else if (!ss_req->bps) {
5102 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5103 ss_req->global = TRUE;
5104 start_single_stepping ();
5106 ss_req->global = FALSE;
5111 * Start single stepping of thread THREAD
5114 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5116 DebuggerTlsData *tls;
5117 MonoSeqPointInfo *info = NULL;
5118 SeqPoint *sp = NULL;
5119 MonoMethod *method = NULL;
5120 MonoDebugMethodInfo *minfo;
5121 gboolean step_to_catch = FALSE;
5123 if (suspend_count == 0)
5124 return ERR_NOT_SUSPENDED;
5126 wait_for_suspend ();
5128 // FIXME: Multiple requests
5130 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5131 return ERR_NOT_IMPLEMENTED;
5134 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5136 ss_req = g_new0 (SingleStepReq, 1);
5138 ss_req->thread = thread;
5139 ss_req->size = size;
5140 ss_req->depth = depth;
5143 mono_loader_lock ();
5144 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5145 mono_loader_unlock ();
5147 g_assert (tls->context.valid);
5148 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5150 if (tls->catch_state.valid) {
5152 StackFrameInfo frame;
5153 MonoContext new_ctx;
5154 MonoLMF *lmf = NULL;
5157 * We are stopped at a throw site. Stepping should go to the catch site.
5160 /* Find the the jit info for the catch context */
5161 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);
5163 g_assert (frame.type == FRAME_TYPE_MANAGED);
5166 * Find the seq point corresponding to the landing site ip, which is the first seq
5169 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5171 no_seq_points_found (frame.method);
5174 method = frame.method;
5176 step_to_catch = TRUE;
5177 /* This make sure the seq point is not skipped by process_single_step () */
5178 ss_req->last_sp = NULL;
5181 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5184 /* Compute the initial line info */
5185 compute_frame_info (thread, tls);
5187 if (tls->frame_count) {
5188 frame = tls->frames [0];
5190 ss_req->last_method = frame->method;
5191 ss_req->last_line = -1;
5193 minfo = mono_debug_lookup_method (frame->method);
5194 if (minfo && frame->il_offset != -1) {
5195 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5198 ss_req->last_line = loc->row;
5205 if (!step_to_catch) {
5208 compute_frame_info (thread, tls);
5210 if (tls->frame_count) {
5211 frame = tls->frames [0];
5213 if (!method && frame->il_offset != -1) {
5214 /* FIXME: Sort the table and use a binary search */
5215 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5217 no_seq_points_found (frame->method);
5219 method = frame->method;
5224 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5230 ss_destroy (SingleStepReq *req)
5233 g_assert (ss_req == req);
5242 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5245 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5251 if (!agent_config.enabled)
5254 mono_loader_lock ();
5255 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5256 mono_loader_unlock ();
5259 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5260 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5262 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5264 g_free (ei.category);
5265 g_free (ei.message);
5269 mono_debugger_agent_debug_log_is_enabled (void)
5271 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5272 return agent_config.enabled;
5275 #ifdef PLATFORM_ANDROID
5277 mono_debugger_agent_unhandled_exception (MonoException *exc)
5286 memset (&ei, 0, sizeof (EventInfo));
5287 ei.exc = (MonoObject*)exc;
5289 mono_loader_lock ();
5290 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5291 mono_loader_unlock ();
5293 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5298 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5299 MonoContext *catch_ctx)
5301 int i, j, suspend_policy;
5303 MonoJitInfo *ji, *catch_ji;
5305 DebuggerTlsData *tls = NULL;
5307 if (thread_to_tls != NULL) {
5308 MonoInternalThread *thread = mono_thread_internal_current ();
5310 mono_loader_lock ();
5311 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5312 mono_loader_unlock ();
5314 if (tls && tls->abort_requested)
5316 if (tls && tls->disable_breakpoints)
5320 memset (&ei, 0, sizeof (EventInfo));
5322 /* Just-In-Time debugging */
5324 if (agent_config.onuncaught && !inited) {
5325 finish_agent_init (FALSE);
5328 * Send an unsolicited EXCEPTION event with a dummy request id.
5330 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5331 ei.exc = (MonoObject*)exc;
5332 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5335 } else if (agent_config.onthrow && !inited) {
5337 gboolean found = FALSE;
5339 for (l = agent_config.onthrow; l; l = l->next) {
5340 char *ex_type = l->data;
5341 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5343 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5350 finish_agent_init (FALSE);
5353 * Send an unsolicited EXCEPTION event with a dummy request id.
5355 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5356 ei.exc = (MonoObject*)exc;
5357 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5365 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5367 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5371 ei.exc = (MonoObject*)exc;
5372 ei.caught = catch_ctx != NULL;
5374 mono_loader_lock ();
5376 /* Treat exceptions which are caught in non-user code as unhandled */
5377 for (i = 0; i < event_requests->len; ++i) {
5378 EventRequest *req = g_ptr_array_index (event_requests, i);
5379 if (req->event_kind != EVENT_KIND_EXCEPTION)
5382 for (j = 0; j < req->nmodifiers; ++j) {
5383 Modifier *mod = &req->modifiers [j];
5385 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5387 gboolean found = FALSE;
5388 MonoAssembly **assemblies = mod->data.assemblies;
5391 for (k = 0; assemblies [k]; ++k)
5392 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5401 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5402 mono_loader_unlock ();
5404 if (tls && ei.caught && catch_ctx) {
5405 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5406 tls->catch_state.ctx = *catch_ctx;
5407 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5408 tls->catch_state.valid = TRUE;
5411 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5414 tls->catch_state.valid = FALSE;
5418 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5420 DebuggerTlsData *tls;
5425 tls = mono_native_tls_get_value (debugger_tls_id);
5430 * We're about to invoke an exception filter during the first pass of exception handling.
5432 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5433 * 'orig_ctx' is the context where the exception has been thrown.
5436 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5438 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5439 * the call site (line 37) and then continue to Main(), but it would never
5440 * include the throw site (line 32).
5442 * Since exception filters are invoked during the first pass of exception handling,
5443 * the stack frames of the throw site are still intact, so we should include them
5446 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5448 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5449 * but report the location of the 'throw' to the user.
5453 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5457 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5459 DebuggerTlsData *tls;
5464 tls = mono_native_tls_get_value (debugger_tls_id);
5468 tls->filter_state.valid = FALSE;
5472 * buffer_add_value_full:
5474 * Add the encoding of the value at ADDR described by T to the buffer.
5475 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5479 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5485 if (!(*(void**)addr)) {
5486 /* This can happen with compiler generated locals */
5487 //printf ("%s\n", mono_type_full_name (t));
5488 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5491 g_assert (*(void**)addr);
5492 addr = *(void**)addr;
5497 case MONO_TYPE_BOOLEAN:
5500 case MONO_TYPE_CHAR:
5520 case MONO_TYPE_VOID:
5521 buffer_add_byte (buf, t->type);
5523 case MONO_TYPE_BOOLEAN:
5526 buffer_add_byte (buf, t->type);
5527 buffer_add_int (buf, *(gint8*)addr);
5529 case MONO_TYPE_CHAR:
5532 buffer_add_byte (buf, t->type);
5533 buffer_add_int (buf, *(gint16*)addr);
5538 buffer_add_byte (buf, t->type);
5539 buffer_add_int (buf, *(gint32*)addr);
5544 buffer_add_byte (buf, t->type);
5545 buffer_add_long (buf, *(gint64*)addr);
5549 /* Treat it as a vtype */
5551 case MONO_TYPE_PTR: {
5552 gssize val = *(gssize*)addr;
5554 buffer_add_byte (buf, t->type);
5555 buffer_add_long (buf, val);
5559 case MONO_TYPE_STRING:
5560 case MONO_TYPE_SZARRAY:
5561 case MONO_TYPE_OBJECT:
5562 case MONO_TYPE_CLASS:
5563 case MONO_TYPE_ARRAY:
5564 obj = *(MonoObject**)addr;
5567 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5569 if (obj->vtable->klass->valuetype) {
5570 t = &obj->vtable->klass->byval_arg;
5571 addr = mono_object_unbox (obj);
5573 } else if (obj->vtable->klass->rank) {
5574 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5575 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5576 buffer_add_byte (buf, MONO_TYPE_CLASS);
5578 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5580 buffer_add_objid (buf, obj);
5584 case MONO_TYPE_VALUETYPE: {
5588 MonoClass *klass = mono_class_from_mono_type (t);
5590 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5591 buffer_add_byte (buf, klass->enumtype);
5592 buffer_add_typeid (buf, domain, klass);
5596 while ((f = mono_class_get_fields (klass, &iter))) {
5597 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5599 if (mono_field_is_deleted (f))
5603 buffer_add_int (buf, nfields);
5606 while ((f = mono_class_get_fields (klass, &iter))) {
5607 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5609 if (mono_field_is_deleted (f))
5611 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5615 case MONO_TYPE_GENERICINST:
5616 if (mono_type_generic_inst_is_valuetype (t)) {
5628 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5630 buffer_add_value_full (buf, t, addr, domain, FALSE);
5634 obj_is_of_type (MonoObject *obj, MonoType *t)
5636 MonoClass *klass = obj->vtable->klass;
5637 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5638 if (mono_class_is_transparent_proxy (klass)) {
5639 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5640 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5650 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5653 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5659 gpointer iter = NULL;
5663 is_enum = decode_byte (buf, &buf, limit);
5664 /* Enums are sent as a normal vtype */
5666 return ERR_NOT_IMPLEMENTED;
5667 klass = decode_typeid (buf, &buf, limit, &d, &err);
5671 if (t && klass != mono_class_from_mono_type (t)) {
5672 char *name = mono_type_full_name (t);
5673 char *name2 = mono_type_full_name (&klass->byval_arg);
5674 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5677 return ERR_INVALID_ARGUMENT;
5680 nfields = decode_int (buf, &buf, limit);
5681 while ((f = mono_class_get_fields (klass, &iter))) {
5682 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5684 if (mono_field_is_deleted (f))
5686 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5691 g_assert (nfields == 0);
5699 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5703 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5704 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5705 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5706 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5707 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5708 char *name = mono_type_full_name (t);
5709 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5711 return ERR_INVALID_ARGUMENT;
5715 case MONO_TYPE_BOOLEAN:
5716 *(guint8*)addr = decode_int (buf, &buf, limit);
5718 case MONO_TYPE_CHAR:
5719 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5722 *(gint8*)addr = decode_int (buf, &buf, limit);
5725 *(guint8*)addr = decode_int (buf, &buf, limit);
5728 *(gint16*)addr = decode_int (buf, &buf, limit);
5731 *(guint16*)addr = decode_int (buf, &buf, limit);
5734 *(gint32*)addr = decode_int (buf, &buf, limit);
5737 *(guint32*)addr = decode_int (buf, &buf, limit);
5740 *(gint64*)addr = decode_long (buf, &buf, limit);
5743 *(guint64*)addr = decode_long (buf, &buf, limit);
5746 *(guint32*)addr = decode_int (buf, &buf, limit);
5749 *(guint64*)addr = decode_long (buf, &buf, limit);
5752 /* We send these as I8, so we get them back as such */
5753 g_assert (type == MONO_TYPE_I8);
5754 *(gssize*)addr = decode_long (buf, &buf, limit);
5756 case MONO_TYPE_GENERICINST:
5757 if (MONO_TYPE_ISSTRUCT (t)) {
5758 /* The client sends these as a valuetype */
5766 /* We send these as vtypes, so we get them back as such */
5767 g_assert (type == MONO_TYPE_VALUETYPE);
5770 case MONO_TYPE_VALUETYPE:
5771 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5777 if (MONO_TYPE_IS_REFERENCE (t)) {
5778 if (type == MONO_TYPE_OBJECT) {
5779 int objid = decode_objid (buf, &buf, limit);
5783 err = get_object (objid, (MonoObject**)&obj);
5788 if (!obj_is_of_type (obj, t)) {
5789 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5790 return ERR_INVALID_ARGUMENT;
5793 if (obj && obj->vtable->domain != domain)
5794 return ERR_INVALID_ARGUMENT;
5796 mono_gc_wbarrier_generic_store (addr, obj);
5797 } else if (type == VALUE_TYPE_ID_NULL) {
5798 *(MonoObject**)addr = NULL;
5799 } else if (type == MONO_TYPE_VALUETYPE) {
5807 /* This can happen when round-tripping boxed vtypes */
5809 * Obtain vtype class.
5810 * Same as the beginning of the handle_vtype case above.
5813 is_enum = decode_byte (buf, &buf, limit);
5815 return ERR_NOT_IMPLEMENTED;
5816 klass = decode_typeid (buf, &buf, limit, &d, &err);
5820 /* Decode the vtype into a temporary buffer, then box it. */
5821 vtype_buf_size = mono_class_value_size (klass, NULL);
5822 vtype_buf = g_malloc0 (vtype_buf_size);
5823 g_assert (vtype_buf);
5826 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
5831 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
5834 char *name = mono_type_full_name (t);
5835 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5837 return ERR_INVALID_ARGUMENT;
5851 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5854 int type = decode_byte (buf, &buf, limit);
5856 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5857 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5858 guint8 *nullable_buf;
5861 * First try decoding it as a Nullable`1
5863 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5868 * Then try decoding as a primitive value or null.
5870 if (targ->type == type) {
5871 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5872 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5874 g_free (nullable_buf);
5877 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5878 g_free (nullable_buf);
5881 } else if (type == VALUE_TYPE_ID_NULL) {
5882 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5888 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5892 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5896 guint8 *addr, *gaddr;
5899 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5900 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5903 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5904 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5906 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5908 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5909 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5910 addr += (gint32)var->offset;
5912 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5914 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5916 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5919 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5920 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5921 /* Same as regoffset, but with an indirection */
5922 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5923 addr += (gint32)var->offset;
5925 gaddr = *(gpointer*)addr;
5927 buffer_add_value_full (buf, t, gaddr, domain, as_vtype);
5929 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5930 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5931 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5932 MonoGSharedVtMethodRuntimeInfo *info;
5938 g_assert (info_var);
5939 g_assert (locals_var);
5941 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5942 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5943 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5944 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5945 addr += (gint32)info_var->offset;
5946 info = *(gpointer*)addr;
5947 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5948 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5950 g_assert_not_reached ();
5954 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5955 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5956 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5957 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5958 addr += (gint32)locals_var->offset;
5959 locals = *(gpointer*)addr;
5960 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5961 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5963 g_assert_not_reached ();
5967 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5969 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5974 g_assert_not_reached ();
5979 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5983 guint8 *addr, *gaddr;
5985 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5986 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5988 if (MONO_TYPE_IS_REFERENCE (t))
5989 size = sizeof (gpointer);
5991 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5994 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5995 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5997 gboolean is_signed = FALSE;
5999 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6004 v = is_signed ? *(gint8*)val : *(guint8*)val;
6007 v = is_signed ? *(gint16*)val : *(guint16*)val;
6010 v = is_signed ? *(gint32*)val : *(guint32*)val;
6013 v = is_signed ? *(gint64*)val : *(guint64*)val;
6016 g_assert_not_reached ();
6022 /* Set value on the stack or in the return ctx */
6023 if (reg_locations [reg]) {
6024 /* Saved on the stack */
6025 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6026 *(reg_locations [reg]) = v;
6029 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6030 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6033 // FIXME: Move these to mono-context.h/c.
6034 mono_arch_context_set_int_reg (ctx, reg, v);
6036 // FIXME: Can't set registers, so we disable linears
6041 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6042 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6043 addr += (gint32)var->offset;
6045 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6048 addr = *(guint8**)addr;
6054 // FIXME: Write barriers
6055 mono_gc_memmove (addr, val, size);
6057 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6058 /* Same as regoffset, but with an indirection */
6059 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6060 addr += (gint32)var->offset;
6062 gaddr = *(gpointer*)addr;
6064 // FIXME: Write barriers
6065 mono_gc_memmove (gaddr, val, size);
6067 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6071 g_assert_not_reached ();
6076 clear_event_request (int req_id, int etype)
6080 mono_loader_lock ();
6081 for (i = 0; i < event_requests->len; ++i) {
6082 EventRequest *req = g_ptr_array_index (event_requests, i);
6084 if (req->id == req_id && req->event_kind == etype) {
6085 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6086 clear_breakpoint (req->info);
6087 if (req->event_kind == EVENT_KIND_STEP)
6088 ss_destroy (req->info);
6089 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6090 clear_breakpoint (req->info);
6091 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6092 clear_breakpoint (req->info);
6093 g_ptr_array_remove_index_fast (event_requests, i);
6098 mono_loader_unlock ();
6102 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
6104 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6105 return breakpoint_matches_assembly (req->info, assembly);
6109 for (i = 0; i < req->nmodifiers; ++i) {
6110 Modifier *m = &req->modifiers [i];
6112 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6114 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6115 for (j = 0; m->data.assemblies [j]; ++j)
6116 if (m->data.assemblies [j] == assembly)
6126 * clear_event_requests_for_assembly:
6128 * Clear all events requests which reference ASSEMBLY.
6131 clear_event_requests_for_assembly (MonoAssembly *assembly)
6136 mono_loader_lock ();
6140 for (i = 0; i < event_requests->len; ++i) {
6141 EventRequest *req = g_ptr_array_index (event_requests, i);
6143 if (event_req_matches_assembly (req, assembly)) {
6144 clear_event_request (req->id, req->event_kind);
6150 mono_loader_unlock ();
6154 * type_comes_from_assembly:
6156 * GHRFunc that returns TRUE if klass comes from assembly
6159 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6161 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6165 * clear_types_for_assembly:
6167 * Clears types from loaded_classes for a given assembly
6170 clear_types_for_assembly (MonoAssembly *assembly)
6172 MonoDomain *domain = mono_domain_get ();
6173 AgentDomainInfo *info = NULL;
6175 mono_loader_lock ();
6176 info = get_agent_domain_info (domain);
6177 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6178 mono_loader_unlock ();
6182 add_thread (gpointer key, gpointer value, gpointer user_data)
6184 MonoInternalThread *thread = value;
6185 Buffer *buf = user_data;
6187 buffer_add_objid (buf, (MonoObject*)thread);
6191 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6193 guint8 *end = invoke->endp;
6196 MonoMethodSignature *sig;
6199 MonoObject *this, *res, *exc;
6202 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6205 MonoStopwatch watch;
6207 if (invoke->method) {
6209 * Invoke this method directly, currently only Environment.Exit () is supported.
6212 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>"));
6213 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6214 g_assert_not_reached ();
6217 m = decode_methodid (p, &p, end, &domain, &err);
6220 sig = mono_method_signature (m);
6222 if (m->klass->valuetype)
6223 this_buf = g_alloca (mono_class_instance_size (m->klass));
6225 this_buf = g_alloca (sizeof (MonoObject*));
6226 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6227 /* Should be null */
6228 int type = decode_byte (p, &p, end);
6229 if (type != VALUE_TYPE_ID_NULL) {
6230 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6231 return ERR_INVALID_ARGUMENT;
6233 memset (this_buf, 0, mono_class_instance_size (m->klass));
6235 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6240 if (!m->klass->valuetype)
6241 this = *(MonoObject**)this_buf;
6245 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6247 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6248 return ERR_INVALID_ARGUMENT;
6250 m = mono_object_get_virtual_method (this, m);
6253 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>"));
6255 if (this && this->vtable->domain != domain)
6258 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6259 if (!strcmp (m->name, ".ctor")) {
6260 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6261 return ERR_INVALID_ARGUMENT;
6263 this = mono_object_new (domain, m->klass);
6265 return ERR_INVALID_ARGUMENT;
6269 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6270 return ERR_INVALID_ARGUMENT;
6272 nargs = decode_int (p, &p, end);
6273 if (nargs != sig->param_count)
6274 return ERR_INVALID_ARGUMENT;
6275 /* Use alloca to get gc tracking */
6276 arg_buf = g_alloca (nargs * sizeof (gpointer));
6277 memset (arg_buf, 0, nargs * sizeof (gpointer));
6278 args = g_alloca (nargs * sizeof (gpointer));
6279 for (i = 0; i < nargs; ++i) {
6280 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6281 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6285 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6288 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6289 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6292 args [i] = arg_buf [i];
6299 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6300 tls->disable_breakpoints = TRUE;
6302 tls->disable_breakpoints = FALSE;
6305 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6307 /* FIXME: Move this to arch specific code */
6308 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6309 if (invoke->has_ctx) {
6312 lmf_addr = mono_get_lmf_addr ();
6315 memset (&ext, 0, sizeof (ext));
6317 ext.lmf.previous_lmf = *(lmf_addr);
6318 /* Mark that this is a MonoLMFExt */
6319 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6320 ext.lmf.rsp = (gssize)&ext;
6321 #elif defined(TARGET_X86)
6322 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6323 /* Mark that this is a MonoLMFExt */
6324 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6325 ext.lmf.ebp = (gssize)&ext;
6326 #elif defined(TARGET_ARM)
6327 ext.lmf.previous_lmf = *(lmf_addr);
6328 /* Mark that this is a MonoLMFExt */
6329 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6330 ext.lmf.sp = (gssize)&ext;
6331 #elif defined(TARGET_POWERPC)
6332 ext.lmf.previous_lmf = *(lmf_addr);
6333 /* Mark that this is a MonoLMFExt */
6334 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6335 ext.lmf.ebp = (gssize)&ext;
6336 #elif defined(TARGET_S390X)
6337 ext.lmf.previous_lmf = *(lmf_addr);
6338 /* Mark that this is a MonoLMFExt */
6339 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6340 ext.lmf.ebp = (gssize)&ext;
6341 #elif defined(TARGET_MIPS)
6342 ext.lmf.previous_lmf = *(lmf_addr);
6343 /* Mark that this is a MonoLMFExt */
6344 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6345 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6347 g_assert_not_reached ();
6350 ext.debugger_invoke = TRUE;
6351 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6353 mono_set_lmf ((MonoLMF*)&ext);
6357 mono_stopwatch_start (&watch);
6358 if (m->klass->valuetype)
6359 res = mono_runtime_invoke (m, this_buf, args, &exc);
6361 res = mono_runtime_invoke (m, this, args, &exc);
6362 mono_stopwatch_stop (&watch);
6363 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)));
6365 buffer_add_byte (buf, 0);
6366 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6368 buffer_add_byte (buf, 1);
6369 if (sig->ret->type == MONO_TYPE_VOID) {
6370 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6371 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6374 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6375 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6376 buffer_add_value (buf, sig->ret, &res, domain);
6377 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6378 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6379 MonoClass *k = mono_class_from_mono_type (sig->ret);
6380 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6382 g_assert (nullable_buf);
6383 mono_nullable_init (nullable_buf, res, k);
6384 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6387 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6394 tls->disable_breakpoints = FALSE;
6396 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6397 if (invoke->has_ctx)
6398 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6402 // FIXME: byref arguments
6410 * Invoke the method given by tls->pending_invoke in the current thread.
6413 invoke_method (void)
6415 DebuggerTlsData *tls;
6420 MonoContext restore_ctx;
6423 tls = mono_native_tls_get_value (debugger_tls_id);
6427 * Store the `InvokeData *' in `tls->invoke' until we're done with
6428 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6431 mono_loader_lock ();
6433 invoke = tls->pending_invoke;
6435 tls->pending_invoke = NULL;
6437 invoke->last_invoke = tls->invoke;
6438 tls->invoke = invoke;
6440 mono_loader_unlock ();
6442 tls->frames_up_to_date = FALSE;
6448 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6449 buffer_init (&buf, 128);
6452 /* Fail the other invokes as well */
6454 err = do_invoke_method (tls, &buf, invoke, p, &p);
6457 /* Start suspending before sending the reply */
6458 if (mindex == invoke->nmethods - 1) {
6459 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6460 for (i = 0; i < invoke->suspend_count; ++i)
6465 send_reply_packet (id, err, &buf);
6470 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6472 if (invoke->has_ctx)
6473 save_thread_context (&restore_ctx);
6475 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6476 g_assert (tls->resume_count);
6477 tls->resume_count -= invoke->suspend_count;
6480 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6483 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6485 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6486 * after the mono_runtime_invoke() already returned, but it doesn't matter
6487 * because we reset the abort here.
6490 mono_loader_lock ();
6492 if (tls->abort_requested)
6493 mono_thread_internal_reset_abort (tls->thread);
6495 tls->invoke = tls->invoke->last_invoke;
6496 tls->abort_requested = FALSE;
6498 mono_loader_unlock ();
6507 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6509 MonoThread *thread = value;
6510 DebuggerTlsData *tls;
6513 mono_loader_lock ();
6514 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6516 res = tls->really_suspended;
6517 mono_loader_unlock ();
6523 get_source_files_for_type (MonoClass *klass)
6525 gpointer iter = NULL;
6527 MonoDebugSourceInfo *sinfo;
6531 files = g_ptr_array_new ();
6533 while ((method = mono_class_get_methods (klass, &iter))) {
6534 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6535 GPtrArray *source_file_list;
6538 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6539 for (j = 0; j < source_file_list->len; ++j) {
6540 sinfo = g_ptr_array_index (source_file_list, j);
6541 for (i = 0; i < files->len; ++i)
6542 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6544 if (i == files->len)
6545 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6547 g_ptr_array_free (source_file_list, TRUE);
6555 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6558 case CMD_VM_VERSION: {
6559 char *build_info, *version;
6561 build_info = mono_get_runtime_build_info ();
6562 version = g_strdup_printf ("mono %s", build_info);
6564 buffer_add_string (buf, version); /* vm version */
6565 buffer_add_int (buf, MAJOR_VERSION);
6566 buffer_add_int (buf, MINOR_VERSION);
6567 g_free (build_info);
6571 case CMD_VM_SET_PROTOCOL_VERSION: {
6572 major_version = decode_int (p, &p, end);
6573 minor_version = decode_int (p, &p, end);
6574 protocol_version_set = TRUE;
6575 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6578 case CMD_VM_ALL_THREADS: {
6580 mono_loader_lock ();
6581 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6582 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6583 mono_loader_unlock ();
6586 case CMD_VM_SUSPEND:
6588 wait_for_suspend ();
6591 if (suspend_count == 0)
6592 return ERR_NOT_SUSPENDED;
6594 clear_suspended_objs ();
6596 case CMD_VM_DISPOSE:
6597 /* Clear all event requests */
6598 mono_loader_lock ();
6599 while (event_requests->len > 0) {
6600 EventRequest *req = g_ptr_array_index (event_requests, 0);
6602 clear_event_request (req->id, req->event_kind);
6604 mono_loader_unlock ();
6606 while (suspend_count > 0)
6608 disconnected = TRUE;
6609 vm_start_event_sent = FALSE;
6612 MonoInternalThread *thread;
6613 DebuggerTlsData *tls;
6614 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6615 MonoClass *env_class;
6617 MonoMethod *exit_method = NULL;
6621 exit_code = decode_int (p, &p, end);
6623 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6625 /* Have to send a reply before exiting */
6626 send_reply_packet (id, 0, buf);
6628 /* Clear all event requests */
6629 mono_loader_lock ();
6630 while (event_requests->len > 0) {
6631 EventRequest *req = g_ptr_array_index (event_requests, 0);
6633 clear_event_request (req->id, req->event_kind);
6635 mono_loader_unlock ();
6638 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6639 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6640 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6641 * better than doing the shutdown ourselves, since it avoids various races.
6645 wait_for_suspend ();
6647 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6648 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6650 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6653 mono_loader_lock ();
6654 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6655 mono_loader_unlock ();
6657 if (thread && exit_method) {
6658 mono_loader_lock ();
6659 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6660 mono_loader_unlock ();
6662 args = g_new0 (gpointer, 1);
6663 args [0] = g_malloc (sizeof (int));
6664 *(int*)(args [0]) = exit_code;
6666 tls->pending_invoke = g_new0 (InvokeData, 1);
6667 tls->pending_invoke->method = exit_method;
6668 tls->pending_invoke->args = args;
6669 tls->pending_invoke->nmethods = 1;
6671 while (suspend_count > 0)
6675 * No thread found, do it ourselves.
6676 * FIXME: This can race with normal shutdown etc.
6678 while (suspend_count > 0)
6681 if (!mono_runtime_try_shutdown ())
6684 mono_environment_exitcode_set (exit_code);
6686 /* Suspend all managed threads since the runtime is going away */
6687 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6688 mono_thread_suspend_all_other_threads ();
6689 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6690 mono_runtime_quit ();
6691 transport_close2 ();
6692 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6698 case CMD_VM_INVOKE_METHOD:
6699 case CMD_VM_INVOKE_METHODS: {
6700 int objid = decode_objid (p, &p, end);
6702 DebuggerTlsData *tls;
6703 int i, count, err, flags, nmethods;
6705 err = get_object (objid, (MonoObject**)&thread);
6709 flags = decode_int (p, &p, end);
6711 if (command == CMD_VM_INVOKE_METHODS)
6712 nmethods = decode_int (p, &p, end);
6716 // Wait for suspending if it already started
6718 wait_for_suspend ();
6719 if (!is_suspended ())
6720 return ERR_NOT_SUSPENDED;
6722 mono_loader_lock ();
6723 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6724 mono_loader_unlock ();
6727 if (!tls->really_suspended)
6728 /* The thread is still running native code, can't do invokes */
6729 return ERR_NOT_SUSPENDED;
6732 * Store the invoke data into tls, the thread will execute it after it is
6735 if (tls->pending_invoke)
6736 return ERR_NOT_SUSPENDED;
6737 tls->pending_invoke = g_new0 (InvokeData, 1);
6738 tls->pending_invoke->id = id;
6739 tls->pending_invoke->flags = flags;
6740 tls->pending_invoke->p = g_malloc (end - p);
6741 memcpy (tls->pending_invoke->p, p, end - p);
6742 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6743 tls->pending_invoke->suspend_count = suspend_count;
6744 tls->pending_invoke->nmethods = nmethods;
6746 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6747 resume_thread (THREAD_TO_INTERNAL (thread));
6750 count = suspend_count;
6751 for (i = 0; i < count; ++i)
6756 case CMD_VM_ABORT_INVOKE: {
6757 int objid = decode_objid (p, &p, end);
6759 DebuggerTlsData *tls;
6762 err = get_object (objid, (MonoObject**)&thread);
6766 invoke_id = decode_int (p, &p, end);
6768 mono_loader_lock ();
6769 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6772 if (tls->abort_requested) {
6773 mono_loader_unlock ();
6778 * Check whether we're still inside the mono_runtime_invoke() and that it's
6779 * actually the correct invocation.
6781 * Careful, we do not stop the thread that's doing the invocation, so we can't
6782 * inspect its stack. However, invoke_method() also acquires the loader lock
6783 * when it's done, so we're safe here.
6787 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6788 mono_loader_unlock ();
6789 return ERR_NO_INVOCATION;
6792 tls->abort_requested = TRUE;
6794 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6795 mono_loader_unlock ();
6799 case CMD_VM_SET_KEEPALIVE: {
6800 int timeout = decode_int (p, &p, end);
6801 agent_config.keepalive = timeout;
6803 #ifndef DISABLE_SOCKET_TRANSPORT
6810 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6811 GHashTableIter iter, kiter;
6816 char *fname, *basename;
6817 gboolean ignore_case;
6818 GSList *class_list, *l;
6819 GPtrArray *res_classes, *res_domains;
6821 fname = decode_string (p, &p, end);
6822 ignore_case = decode_byte (p, &p, end);
6824 basename = g_path_get_basename (fname);
6826 res_classes = g_ptr_array_new ();
6827 res_domains = g_ptr_array_new ();
6829 mono_loader_lock ();
6830 g_hash_table_iter_init (&iter, domains);
6831 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6832 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6834 /* Update 'source_file_to_class' cache */
6835 g_hash_table_iter_init (&kiter, info->loaded_classes);
6836 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6837 if (!g_hash_table_lookup (info->source_files, klass)) {
6838 files = get_source_files_for_type (klass);
6839 g_hash_table_insert (info->source_files, klass, files);
6841 for (i = 0; i < files->len; ++i) {
6842 char *s = g_ptr_array_index (files, i);
6843 char *s2 = g_path_get_basename (s);
6846 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6848 class_list = g_slist_prepend (class_list, klass);
6849 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6851 class_list = g_slist_prepend (class_list, klass);
6852 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6855 /* The _ignorecase hash contains the lowercase path */
6856 s3 = strdup_tolower (s2);
6857 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6859 class_list = g_slist_prepend (class_list, klass);
6860 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6862 class_list = g_slist_prepend (class_list, klass);
6863 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6875 s = strdup_tolower (basename);
6876 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6879 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6882 for (l = class_list; l; l = l->next) {
6885 g_ptr_array_add (res_classes, klass);
6886 g_ptr_array_add (res_domains, domain);
6889 mono_loader_unlock ();
6894 buffer_add_int (buf, res_classes->len);
6895 for (i = 0; i < res_classes->len; ++i)
6896 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6897 g_ptr_array_free (res_classes, TRUE);
6898 g_ptr_array_free (res_domains, TRUE);
6901 case CMD_VM_GET_TYPES: {
6902 GHashTableIter iter;
6906 gboolean ignore_case;
6907 GPtrArray *res_classes, *res_domains;
6908 MonoTypeNameParse info;
6910 name = decode_string (p, &p, end);
6911 ignore_case = decode_byte (p, &p, end);
6913 if (!mono_reflection_parse_type (name, &info)) {
6915 mono_reflection_free_type_info (&info);
6916 return ERR_INVALID_ARGUMENT;
6919 res_classes = g_ptr_array_new ();
6920 res_domains = g_ptr_array_new ();
6922 mono_loader_lock ();
6923 g_hash_table_iter_init (&iter, domains);
6924 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6926 gboolean type_resolve;
6930 mono_domain_assemblies_lock (domain);
6931 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6935 type_resolve = TRUE;
6936 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6938 g_ptr_array_add (res_classes, mono_type_get_class (t));
6939 g_ptr_array_add (res_domains, domain);
6943 mono_domain_assemblies_unlock (domain);
6945 mono_loader_unlock ();
6948 mono_reflection_free_type_info (&info);
6950 buffer_add_int (buf, res_classes->len);
6951 for (i = 0; i < res_classes->len; ++i)
6952 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6953 g_ptr_array_free (res_classes, TRUE);
6954 g_ptr_array_free (res_domains, TRUE);
6959 return ERR_NOT_IMPLEMENTED;
6966 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6972 case CMD_EVENT_REQUEST_SET: {
6974 int i, event_kind, suspend_policy, nmodifiers, mod;
6977 MonoThread *step_thread;
6978 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6982 event_kind = decode_byte (p, &p, end);
6983 suspend_policy = decode_byte (p, &p, end);
6984 nmodifiers = decode_byte (p, &p, end);
6986 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6987 req->id = InterlockedIncrement (&event_request_id);
6988 req->event_kind = event_kind;
6989 req->suspend_policy = suspend_policy;
6990 req->nmodifiers = nmodifiers;
6993 for (i = 0; i < nmodifiers; ++i) {
6994 mod = decode_byte (p, &p, end);
6996 req->modifiers [i].kind = mod;
6997 if (mod == MOD_KIND_COUNT) {
6998 req->modifiers [i].data.count = decode_int (p, &p, end);
6999 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7000 method = decode_methodid (p, &p, end, &domain, &err);
7003 location = decode_long (p, &p, end);
7004 } else if (mod == MOD_KIND_STEP) {
7005 step_thread_id = decode_id (p, &p, end);
7006 size = decode_int (p, &p, end);
7007 depth = decode_int (p, &p, end);
7008 if (CHECK_PROTOCOL_VERSION (2, 16))
7009 filter = decode_int (p, &p, end);
7010 req->modifiers [i].data.filter = filter;
7011 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7012 /* Treat STEP_THOUGH the same as HIDDEN */
7013 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7014 } else if (mod == MOD_KIND_THREAD_ONLY) {
7015 int id = decode_id (p, &p, end);
7017 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7022 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7023 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7027 req->modifiers [i].caught = decode_byte (p, &p, end);
7028 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7029 if (CHECK_PROTOCOL_VERSION (2, 25))
7030 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7032 req->modifiers [i].subclasses = TRUE;
7033 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" : ""));
7035 req->modifiers [i].data.exc_class = exc_class;
7037 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7039 return ERR_INVALID_ARGUMENT;
7042 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7043 int n = decode_int (p, &p, end);
7046 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7047 for (j = 0; j < n; ++j) {
7048 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7050 g_free (req->modifiers [i].data.assemblies);
7054 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7055 int n = decode_int (p, &p, end);
7058 modifier = &req->modifiers [i];
7059 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7060 for (j = 0; j < n; ++j) {
7061 char *s = decode_string (p, &p, end);
7065 s2 = strdup_tolower (s);
7066 g_hash_table_insert (modifier->data.source_files, s2, s2);
7070 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7071 int n = decode_int (p, &p, end);
7074 modifier = &req->modifiers [i];
7075 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7076 for (j = 0; j < n; ++j) {
7077 char *s = decode_string (p, &p, end);
7080 g_hash_table_insert (modifier->data.type_names, s, s);
7084 return ERR_NOT_IMPLEMENTED;
7088 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7091 req->info = set_breakpoint (method, location, req, &error);
7092 if (!mono_error_ok (&error)) {
7094 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7095 mono_error_cleanup (&error);
7096 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7098 } else if (req->event_kind == EVENT_KIND_STEP) {
7099 g_assert (step_thread_id);
7101 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7107 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7112 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7113 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7114 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7115 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7116 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7117 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7119 if (req->nmodifiers) {
7121 return ERR_NOT_IMPLEMENTED;
7125 mono_loader_lock ();
7126 g_ptr_array_add (event_requests, req);
7128 if (agent_config.defer) {
7129 /* Transmit cached data to the client on receipt of the event request */
7130 switch (req->event_kind) {
7131 case EVENT_KIND_APPDOMAIN_CREATE:
7132 /* Emit load events for currently loaded domains */
7133 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7135 case EVENT_KIND_ASSEMBLY_LOAD:
7136 /* Emit load events for currently loaded assemblies */
7137 mono_assembly_foreach (emit_assembly_load, NULL);
7139 case EVENT_KIND_THREAD_START:
7140 /* Emit start events for currently started threads */
7141 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7143 case EVENT_KIND_TYPE_LOAD:
7144 /* Emit type load events for currently loaded types */
7145 mono_domain_foreach (send_types_for_domain, NULL);
7151 mono_loader_unlock ();
7153 buffer_add_int (buf, req->id);
7156 case CMD_EVENT_REQUEST_CLEAR: {
7157 int etype = decode_byte (p, &p, end);
7158 int req_id = decode_int (p, &p, end);
7160 // FIXME: Make a faster mapping from req_id to request
7161 mono_loader_lock ();
7162 clear_event_request (req_id, etype);
7163 mono_loader_unlock ();
7166 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7169 mono_loader_lock ();
7171 while (i < event_requests->len) {
7172 EventRequest *req = g_ptr_array_index (event_requests, i);
7174 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7175 clear_breakpoint (req->info);
7177 g_ptr_array_remove_index_fast (event_requests, i);
7183 mono_loader_unlock ();
7187 return ERR_NOT_IMPLEMENTED;
7194 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7200 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7201 buffer_add_domainid (buf, mono_get_root_domain ());
7204 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7205 domain = decode_domainid (p, &p, end, NULL, &err);
7208 buffer_add_string (buf, domain->friendly_name);
7211 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7216 domain = decode_domainid (p, &p, end, NULL, &err);
7219 mono_loader_lock ();
7221 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7224 buffer_add_int (buf, count);
7225 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7227 buffer_add_assemblyid (buf, domain, ass);
7229 mono_loader_unlock ();
7232 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7233 domain = decode_domainid (p, &p, end, NULL, &err);
7237 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7240 case CMD_APPDOMAIN_GET_CORLIB: {
7241 domain = decode_domainid (p, &p, end, NULL, &err);
7245 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7248 case CMD_APPDOMAIN_CREATE_STRING: {
7252 domain = decode_domainid (p, &p, end, NULL, &err);
7255 s = decode_string (p, &p, end);
7257 o = mono_string_new (domain, s);
7258 buffer_add_objid (buf, (MonoObject*)o);
7261 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7263 MonoDomain *domain2;
7266 domain = decode_domainid (p, &p, end, NULL, &err);
7269 klass = decode_typeid (p, &p, end, &domain2, &err);
7274 g_assert (domain == domain2);
7276 o = mono_object_new (domain, klass);
7278 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7282 buffer_add_objid (buf, o);
7286 return ERR_NOT_IMPLEMENTED;
7293 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7299 ass = decode_assemblyid (p, &p, end, &domain, &err);
7304 case CMD_ASSEMBLY_GET_LOCATION: {
7305 buffer_add_string (buf, mono_image_get_filename (ass->image));
7308 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7312 if (ass->image->dynamic) {
7313 buffer_add_id (buf, 0);
7315 token = mono_image_get_entry_point (ass->image);
7317 buffer_add_id (buf, 0);
7319 m = mono_get_method (ass->image, token, NULL);
7320 buffer_add_methodid (buf, domain, m);
7325 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7326 buffer_add_moduleid (buf, domain, ass->image);
7329 case CMD_ASSEMBLY_GET_OBJECT: {
7330 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7331 buffer_add_objid (buf, o);
7334 case CMD_ASSEMBLY_GET_TYPE: {
7335 char *s = decode_string (p, &p, end);
7336 gboolean ignorecase = decode_byte (p, &p, end);
7337 MonoTypeNameParse info;
7339 gboolean type_resolve, res;
7340 MonoDomain *d = mono_domain_get ();
7342 /* This is needed to be able to find referenced assemblies */
7343 res = mono_domain_set (domain, FALSE);
7346 if (!mono_reflection_parse_type (s, &info)) {
7349 if (info.assembly.name)
7351 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7353 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7354 mono_reflection_free_type_info (&info);
7357 mono_domain_set (d, TRUE);
7361 case CMD_ASSEMBLY_GET_NAME: {
7363 MonoAssembly *mass = ass;
7365 name = g_strdup_printf (
7366 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7368 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7369 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7370 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7371 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7373 buffer_add_string (buf, name);
7378 return ERR_NOT_IMPLEMENTED;
7385 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7391 case CMD_MODULE_GET_INFO: {
7392 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7395 basename = g_path_get_basename (image->name);
7396 buffer_add_string (buf, basename); // name
7397 buffer_add_string (buf, image->module_name); // scopename
7398 buffer_add_string (buf, image->name); // fqname
7399 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7400 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7405 return ERR_NOT_IMPLEMENTED;
7412 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7414 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7415 /* Special case these so the client doesn't have to handle Type objects */
7417 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7418 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7419 } else if (MONO_TYPE_IS_REFERENCE (t))
7420 buffer_add_value (buf, t, &val, domain);
7422 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7426 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7432 buffer_add_int (buf, 0);
7436 for (i = 0; i < cinfo->num_attrs; ++i) {
7437 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7440 buffer_add_int (buf, nattrs);
7442 for (i = 0; i < cinfo->num_attrs; ++i) {
7443 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7444 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7445 MonoArray *typed_args, *named_args;
7447 CattrNamedArg *arginfo = NULL;
7450 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7451 g_assert (mono_error_ok (&error));
7453 buffer_add_methodid (buf, domain, attr->ctor);
7457 buffer_add_int (buf, mono_array_length (typed_args));
7458 for (j = 0; j < mono_array_length (typed_args); ++j) {
7459 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7461 t = mono_method_signature (attr->ctor)->params [j];
7463 buffer_add_cattr_arg (buf, t, domain, val);
7466 buffer_add_int (buf, 0);
7471 buffer_add_int (buf, mono_array_length (named_args));
7473 for (j = 0; j < mono_array_length (named_args); ++j) {
7474 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7476 if (arginfo [j].prop) {
7477 buffer_add_byte (buf, 0x54);
7478 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7479 } else if (arginfo [j].field) {
7480 buffer_add_byte (buf, 0x53);
7481 buffer_add_fieldid (buf, domain, arginfo [j].field);
7483 g_assert_not_reached ();
7486 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7489 buffer_add_int (buf, 0);
7496 /* FIXME: Code duplication with icall.c */
7498 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7503 mono_class_setup_interfaces (klass, error);
7504 if (!mono_error_ok (error))
7507 for (i = 0; i < klass->interface_count; i++) {
7508 ic = klass->interfaces [i];
7509 g_hash_table_insert (ifaces, ic, ic);
7511 collect_interfaces (ic, ifaces, error);
7512 if (!mono_error_ok (error))
7518 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7528 case CMD_TYPE_GET_INFO: {
7529 buffer_add_string (buf, klass->name_space);
7530 buffer_add_string (buf, klass->name);
7532 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7533 buffer_add_string (buf, name);
7535 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7536 buffer_add_moduleid (buf, domain, klass->image);
7537 buffer_add_typeid (buf, domain, klass->parent);
7538 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7539 buffer_add_typeid (buf, domain, klass->element_class);
7541 buffer_add_id (buf, 0);
7542 buffer_add_int (buf, klass->type_token);
7543 buffer_add_byte (buf, klass->rank);
7544 buffer_add_int (buf, klass->flags);
7546 type = &klass->byval_arg;
7547 // FIXME: Can't decide whenever a class represents a byref type
7550 if (type->type == MONO_TYPE_PTR)
7552 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7554 if (type->type == MONO_TYPE_VALUETYPE)
7556 if (klass->enumtype)
7558 if (klass->generic_container)
7560 if (klass->generic_container || klass->generic_class)
7562 buffer_add_byte (buf, b);
7565 while ((nested = mono_class_get_nested_types (klass, &iter)))
7567 buffer_add_int (buf, nnested);
7569 while ((nested = mono_class_get_nested_types (klass, &iter)))
7570 buffer_add_typeid (buf, domain, nested);
7571 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7572 if (klass->generic_container)
7573 buffer_add_typeid (buf, domain, klass);
7574 else if (klass->generic_class)
7575 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7577 buffer_add_id (buf, 0);
7579 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7582 if (klass->generic_class) {
7583 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7585 count = inst->type_argc;
7586 buffer_add_int (buf, count);
7587 for (i = 0; i < count; i++)
7588 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7589 } else if (klass->generic_container) {
7590 MonoGenericContainer *container = klass->generic_container;
7593 count = container->type_argc;
7594 buffer_add_int (buf, count);
7595 for (i = 0; i < count; i++) {
7596 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7597 buffer_add_typeid (buf, domain, pklass);
7600 buffer_add_int (buf, 0);
7605 case CMD_TYPE_GET_METHODS: {
7608 gpointer iter = NULL;
7611 mono_class_setup_methods (klass);
7613 nmethods = mono_class_num_methods (klass);
7615 buffer_add_int (buf, nmethods);
7617 while ((m = mono_class_get_methods (klass, &iter))) {
7618 buffer_add_methodid (buf, domain, m);
7621 g_assert (i == nmethods);
7624 case CMD_TYPE_GET_FIELDS: {
7627 gpointer iter = NULL;
7630 nfields = mono_class_num_fields (klass);
7632 buffer_add_int (buf, nfields);
7634 while ((f = mono_class_get_fields (klass, &iter))) {
7635 buffer_add_fieldid (buf, domain, f);
7636 buffer_add_string (buf, f->name);
7637 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7638 buffer_add_int (buf, f->type->attrs);
7641 g_assert (i == nfields);
7644 case CMD_TYPE_GET_PROPERTIES: {
7647 gpointer iter = NULL;
7650 nprops = mono_class_num_properties (klass);
7652 buffer_add_int (buf, nprops);
7654 while ((p = mono_class_get_properties (klass, &iter))) {
7655 buffer_add_propertyid (buf, domain, p);
7656 buffer_add_string (buf, p->name);
7657 buffer_add_methodid (buf, domain, p->get);
7658 buffer_add_methodid (buf, domain, p->set);
7659 buffer_add_int (buf, p->attrs);
7662 g_assert (i == nprops);
7665 case CMD_TYPE_GET_CATTRS: {
7666 MonoClass *attr_klass;
7667 MonoCustomAttrInfo *cinfo;
7669 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7670 /* attr_klass can be NULL */
7674 cinfo = mono_custom_attrs_from_class (klass);
7676 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7679 case CMD_TYPE_GET_FIELD_CATTRS: {
7680 MonoClass *attr_klass;
7681 MonoCustomAttrInfo *cinfo;
7682 MonoClassField *field;
7684 field = decode_fieldid (p, &p, end, NULL, &err);
7687 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7691 cinfo = mono_custom_attrs_from_field (klass, field);
7693 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7696 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7697 MonoClass *attr_klass;
7698 MonoCustomAttrInfo *cinfo;
7701 prop = decode_propertyid (p, &p, end, NULL, &err);
7704 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7708 cinfo = mono_custom_attrs_from_property (klass, prop);
7710 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7713 case CMD_TYPE_GET_VALUES:
7714 case CMD_TYPE_GET_VALUES_2: {
7721 MonoThread *thread_obj;
7722 MonoInternalThread *thread = NULL;
7723 guint32 special_static_type;
7725 if (command == CMD_TYPE_GET_VALUES_2) {
7726 int objid = decode_objid (p, &p, end);
7729 err = get_object (objid, (MonoObject**)&thread_obj);
7733 thread = THREAD_TO_INTERNAL (thread_obj);
7736 len = decode_int (p, &p, end);
7737 for (i = 0; i < len; ++i) {
7738 f = decode_fieldid (p, &p, end, NULL, &err);
7742 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7743 return ERR_INVALID_FIELDID;
7744 special_static_type = mono_class_field_get_special_static_type (f);
7745 if (special_static_type != SPECIAL_STATIC_NONE) {
7746 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7747 return ERR_INVALID_FIELDID;
7750 /* Check that the field belongs to the object */
7752 for (k = klass; k; k = k->parent) {
7753 if (k == f->parent) {
7759 return ERR_INVALID_FIELDID;
7761 vtable = mono_class_vtable (domain, f->parent);
7762 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7763 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7764 buffer_add_value (buf, f->type, val, domain);
7769 case CMD_TYPE_SET_VALUES: {
7777 len = decode_int (p, &p, end);
7778 for (i = 0; i < len; ++i) {
7779 f = decode_fieldid (p, &p, end, NULL, &err);
7783 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7784 return ERR_INVALID_FIELDID;
7785 if (mono_class_field_is_special_static (f))
7786 return ERR_INVALID_FIELDID;
7788 /* Check that the field belongs to the object */
7790 for (k = klass; k; k = k->parent) {
7791 if (k == f->parent) {
7797 return ERR_INVALID_FIELDID;
7799 // FIXME: Check for literal/const
7801 vtable = mono_class_vtable (domain, f->parent);
7802 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7803 err = decode_value (f->type, domain, val, p, &p, end);
7808 if (MONO_TYPE_IS_REFERENCE (f->type))
7809 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7811 mono_field_static_set_value (vtable, f, val);
7816 case CMD_TYPE_GET_OBJECT: {
7817 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7818 buffer_add_objid (buf, o);
7821 case CMD_TYPE_GET_SOURCE_FILES:
7822 case CMD_TYPE_GET_SOURCE_FILES_2: {
7823 char *source_file, *base;
7827 files = get_source_files_for_type (klass);
7829 buffer_add_int (buf, files->len);
7830 for (i = 0; i < files->len; ++i) {
7831 source_file = g_ptr_array_index (files, i);
7832 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7833 buffer_add_string (buf, source_file);
7835 base = g_path_get_basename (source_file);
7836 buffer_add_string (buf, base);
7839 g_free (source_file);
7841 g_ptr_array_free (files, TRUE);
7844 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7845 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7849 if (mono_class_is_assignable_from (klass, oklass))
7850 buffer_add_byte (buf, 1);
7852 buffer_add_byte (buf, 0);
7855 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7856 char *name = decode_string (p, &p, end);
7857 int i, flags = decode_int (p, &p, end);
7858 MonoException *ex = NULL;
7859 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7862 return ERR_LOADER_ERROR;
7863 buffer_add_int (buf, array->len);
7864 for (i = 0; i < array->len; ++i) {
7865 MonoMethod *method = g_ptr_array_index (array, i);
7866 buffer_add_methodid (buf, domain, method);
7869 g_ptr_array_free (array, TRUE);
7873 case CMD_TYPE_GET_INTERFACES: {
7875 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7877 MonoClass *tclass, *iface;
7878 GHashTableIter iter;
7882 for (parent = tclass; parent; parent = parent->parent) {
7883 mono_class_setup_interfaces (parent, &error);
7884 if (!mono_error_ok (&error))
7885 return ERR_LOADER_ERROR;
7886 collect_interfaces (parent, iface_hash, &error);
7887 if (!mono_error_ok (&error))
7888 return ERR_LOADER_ERROR;
7891 buffer_add_int (buf, g_hash_table_size (iface_hash));
7893 g_hash_table_iter_init (&iter, iface_hash);
7894 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7895 buffer_add_typeid (buf, domain, iface);
7896 g_hash_table_destroy (iface_hash);
7899 case CMD_TYPE_GET_INTERFACE_MAP: {
7900 int tindex, ioffset;
7901 gboolean variance_used;
7903 int len, nmethods, i;
7907 len = decode_int (p, &p, end);
7908 mono_class_setup_vtable (klass);
7910 for (tindex = 0; tindex < len; ++tindex) {
7911 iclass = decode_typeid (p, &p, end, NULL, &err);
7915 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7917 return ERR_INVALID_ARGUMENT;
7919 nmethods = mono_class_num_methods (iclass);
7920 buffer_add_int (buf, nmethods);
7923 while ((method = mono_class_get_methods (iclass, &iter))) {
7924 buffer_add_methodid (buf, domain, method);
7926 for (i = 0; i < nmethods; ++i)
7927 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7931 case CMD_TYPE_IS_INITIALIZED: {
7932 MonoVTable *vtable = mono_class_vtable (domain, klass);
7935 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7937 buffer_add_int (buf, 0);
7941 return ERR_NOT_IMPLEMENTED;
7948 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7951 MonoDomain *old_domain;
7955 klass = decode_typeid (p, &p, end, &domain, &err);
7959 old_domain = mono_domain_get ();
7961 mono_domain_set (domain, TRUE);
7963 err = type_commands_internal (command, klass, domain, p, end, buf);
7965 mono_domain_set (old_domain, TRUE);
7971 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7973 MonoMethodHeader *header;
7977 case CMD_METHOD_GET_NAME: {
7978 buffer_add_string (buf, method->name);
7981 case CMD_METHOD_GET_DECLARING_TYPE: {
7982 buffer_add_typeid (buf, domain, method->klass);
7985 case CMD_METHOD_GET_DEBUG_INFO: {
7986 MonoDebugMethodInfo *minfo;
7988 int i, j, n_il_offsets;
7991 int *column_numbers;
7993 GPtrArray *source_file_list;
7995 header = mono_method_get_header (method);
7997 buffer_add_int (buf, 0);
7998 buffer_add_string (buf, "");
7999 buffer_add_int (buf, 0);
8003 minfo = mono_debug_lookup_method (method);
8005 buffer_add_int (buf, header->code_size);
8006 buffer_add_string (buf, "");
8007 buffer_add_int (buf, 0);
8008 mono_metadata_free_mh (header);
8012 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
8013 buffer_add_int (buf, header->code_size);
8014 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8015 buffer_add_int (buf, source_file_list->len);
8016 for (i = 0; i < source_file_list->len; ++i) {
8017 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8018 buffer_add_string (buf, sinfo->source_file);
8019 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8020 for (j = 0; j < 16; ++j)
8021 buffer_add_byte (buf, sinfo->hash [j]);
8025 buffer_add_string (buf, source_file);
8027 buffer_add_int (buf, n_il_offsets);
8028 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8029 for (i = 0; i < n_il_offsets; ++i) {
8030 const char *srcfile = "";
8032 if (source_files [i] != -1) {
8033 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8034 srcfile = sinfo->source_file;
8036 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8037 buffer_add_int (buf, il_offsets [i]);
8038 buffer_add_int (buf, line_numbers [i]);
8039 if (CHECK_PROTOCOL_VERSION (2, 13))
8040 buffer_add_int (buf, source_files [i]);
8041 if (CHECK_PROTOCOL_VERSION (2, 19))
8042 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8044 g_free (source_file);
8045 g_free (il_offsets);
8046 g_free (line_numbers);
8047 g_free (source_files);
8048 g_ptr_array_free (source_file_list, TRUE);
8049 mono_metadata_free_mh (header);
8052 case CMD_METHOD_GET_PARAM_INFO: {
8053 MonoMethodSignature *sig = mono_method_signature (method);
8057 /* FIXME: mono_class_from_mono_type () and byrefs */
8059 /* FIXME: Use a smaller encoding */
8060 buffer_add_int (buf, sig->call_convention);
8061 buffer_add_int (buf, sig->param_count);
8062 buffer_add_int (buf, sig->generic_param_count);
8063 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8064 for (i = 0; i < sig->param_count; ++i) {
8066 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8069 /* Emit parameter names */
8070 names = g_new (char *, sig->param_count);
8071 mono_method_get_param_names (method, (const char **) names);
8072 for (i = 0; i < sig->param_count; ++i)
8073 buffer_add_string (buf, names [i]);
8078 case CMD_METHOD_GET_LOCALS_INFO: {
8079 int i, j, num_locals;
8080 MonoDebugLocalsInfo *locals;
8082 header = mono_method_get_header (method);
8084 return ERR_INVALID_ARGUMENT;
8086 buffer_add_int (buf, header->num_locals);
8089 for (i = 0; i < header->num_locals; ++i)
8090 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8093 locals = mono_debug_lookup_locals (method);
8095 num_locals = locals->num_locals;
8098 for (i = 0; i < header->num_locals; ++i) {
8099 for (j = 0; j < num_locals; ++j)
8100 if (locals->locals [j].index == i)
8103 buffer_add_string (buf, locals->locals [j].name);
8105 buffer_add_string (buf, "");
8109 for (i = 0; i < header->num_locals; ++i) {
8110 for (j = 0; j < num_locals; ++j)
8111 if (locals->locals [j].index == i)
8113 if (j < num_locals && locals->locals [j].block) {
8114 buffer_add_int (buf, locals->locals [j].block->start_offset);
8115 buffer_add_int (buf, locals->locals [j].block->end_offset);
8117 buffer_add_int (buf, 0);
8118 buffer_add_int (buf, header->code_size);
8121 mono_metadata_free_mh (header);
8124 mono_debug_symfile_free_locals (locals);
8128 case CMD_METHOD_GET_INFO:
8129 buffer_add_int (buf, method->flags);
8130 buffer_add_int (buf, method->iflags);
8131 buffer_add_int (buf, method->token);
8132 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8134 if (method->is_generic)
8136 if (mono_method_signature (method)->generic_param_count)
8138 buffer_add_byte (buf, attrs);
8139 if (method->is_generic || method->is_inflated) {
8142 if (method->is_generic) {
8145 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8147 result = imethod->declaring;
8148 if (imethod->context.class_inst) {
8149 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8150 /*Generic methods gets the context of the GTD.*/
8151 if (mono_class_get_context (klass))
8152 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8156 buffer_add_methodid (buf, domain, result);
8158 buffer_add_id (buf, 0);
8160 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8161 if (mono_method_signature (method)->generic_param_count) {
8164 if (method->is_inflated) {
8165 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8167 count = inst->type_argc;
8168 buffer_add_int (buf, count);
8170 for (i = 0; i < count; i++)
8171 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8173 buffer_add_int (buf, 0);
8175 } else if (method->is_generic) {
8176 MonoGenericContainer *container = mono_method_get_generic_container (method);
8178 count = mono_method_signature (method)->generic_param_count;
8179 buffer_add_int (buf, count);
8180 for (i = 0; i < count; i++) {
8181 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8182 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8183 buffer_add_typeid (buf, domain, pklass);
8186 buffer_add_int (buf, 0);
8189 buffer_add_int (buf, 0);
8194 case CMD_METHOD_GET_BODY: {
8197 header = mono_method_get_header (method);
8199 buffer_add_int (buf, 0);
8201 if (CHECK_PROTOCOL_VERSION (2, 18))
8202 buffer_add_int (buf, 0);
8204 buffer_add_int (buf, header->code_size);
8205 for (i = 0; i < header->code_size; ++i)
8206 buffer_add_byte (buf, header->code [i]);
8208 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8209 buffer_add_int (buf, header->num_clauses);
8210 for (i = 0; i < header->num_clauses; ++i) {
8211 MonoExceptionClause *clause = &header->clauses [i];
8213 buffer_add_int (buf, clause->flags);
8214 buffer_add_int (buf, clause->try_offset);
8215 buffer_add_int (buf, clause->try_len);
8216 buffer_add_int (buf, clause->handler_offset);
8217 buffer_add_int (buf, clause->handler_len);
8218 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8219 buffer_add_typeid (buf, domain, clause->data.catch_class);
8220 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8221 buffer_add_int (buf, clause->data.filter_offset);
8225 mono_metadata_free_mh (header);
8230 case CMD_METHOD_RESOLVE_TOKEN: {
8231 guint32 token = decode_int (p, &p, end);
8234 switch (mono_metadata_token_code (token)) {
8235 case MONO_TOKEN_STRING: {
8239 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8242 s2 = mono_string_to_utf8 (s);
8244 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8245 buffer_add_string (buf, s2);
8251 MonoClass *handle_class;
8253 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8254 val = mono_method_get_wrapper_data (method, token);
8255 handle_class = mono_method_get_wrapper_data (method, token + 1);
8257 if (handle_class == NULL) {
8258 // Can't figure out the token type
8259 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8263 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8267 if (handle_class == mono_defaults.typehandle_class) {
8268 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8269 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8270 buffer_add_typeid (buf, domain, (MonoClass *) val);
8272 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8273 } else if (handle_class == mono_defaults.fieldhandle_class) {
8274 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8275 buffer_add_fieldid (buf, domain, val);
8276 } else if (handle_class == mono_defaults.methodhandle_class) {
8277 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8278 buffer_add_methodid (buf, domain, val);
8279 } else if (handle_class == mono_defaults.string_class) {
8282 s = mono_string_to_utf8 (val);
8283 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8284 buffer_add_string (buf, s);
8287 g_assert_not_reached ();
8294 case CMD_METHOD_GET_CATTRS: {
8295 MonoClass *attr_klass;
8296 MonoCustomAttrInfo *cinfo;
8298 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8299 /* attr_klass can be NULL */
8303 cinfo = mono_custom_attrs_from_method (method);
8305 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8308 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8309 MonoType **type_argv;
8313 MonoGenericInst *ginst;
8314 MonoGenericContext tmp_context;
8315 MonoMethod *inflated;
8317 type_argc = decode_int (p, &p, end);
8318 type_argv = g_new0 (MonoType*, type_argc);
8319 for (i = 0; i < type_argc; ++i) {
8320 klass = decode_typeid (p, &p, end, &d, &err);
8327 return ERR_INVALID_ARGUMENT;
8329 type_argv [i] = &klass->byval_arg;
8331 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8333 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8334 tmp_context.method_inst = ginst;
8336 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8337 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8338 return ERR_INVALID_ARGUMENT;
8339 buffer_add_methodid (buf, domain, inflated);
8343 return ERR_NOT_IMPLEMENTED;
8350 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8353 MonoDomain *old_domain;
8357 method = decode_methodid (p, &p, end, &domain, &err);
8361 old_domain = mono_domain_get ();
8363 mono_domain_set (domain, TRUE);
8365 err = method_commands_internal (command, method, domain, p, end, buf);
8367 mono_domain_set (old_domain, TRUE);
8373 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8375 int objid = decode_objid (p, &p, end);
8377 MonoThread *thread_obj;
8378 MonoInternalThread *thread;
8380 err = get_object (objid, (MonoObject**)&thread_obj);
8384 thread = THREAD_TO_INTERNAL (thread_obj);
8387 case CMD_THREAD_GET_NAME: {
8389 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8392 buffer_add_int (buf, 0);
8397 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8399 buffer_add_int (buf, len);
8400 buffer_add_data (buf, (guint8*)name, len);
8405 case CMD_THREAD_GET_FRAME_INFO: {
8406 DebuggerTlsData *tls;
8407 int i, start_frame, length;
8409 // Wait for suspending if it already started
8410 // FIXME: Races with suspend_count
8411 while (!is_suspended ()) {
8413 wait_for_suspend ();
8417 wait_for_suspend ();
8418 if (!is_suspended ())
8419 return ERR_NOT_SUSPENDED;
8422 start_frame = decode_int (p, &p, end);
8423 length = decode_int (p, &p, end);
8425 if (start_frame != 0 || length != -1)
8426 return ERR_NOT_IMPLEMENTED;
8428 mono_loader_lock ();
8429 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8430 mono_loader_unlock ();
8433 compute_frame_info (thread, tls);
8435 buffer_add_int (buf, tls->frame_count);
8436 for (i = 0; i < tls->frame_count; ++i) {
8437 buffer_add_int (buf, tls->frames [i]->id);
8438 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8439 buffer_add_int (buf, tls->frames [i]->il_offset);
8441 * Instead of passing the frame type directly to the client, we associate
8442 * it with the previous frame using a set of flags. This avoids lots of
8443 * conditional code in the client, since a frame whose type isn't
8444 * FRAME_TYPE_MANAGED has no method, location, etc.
8446 buffer_add_byte (buf, tls->frames [i]->flags);
8451 case CMD_THREAD_GET_STATE:
8452 buffer_add_int (buf, thread->state);
8454 case CMD_THREAD_GET_INFO:
8455 buffer_add_byte (buf, thread->threadpool_thread);
8457 case CMD_THREAD_GET_ID:
8458 buffer_add_long (buf, (guint64)(gsize)thread);
8460 case CMD_THREAD_GET_TID:
8461 buffer_add_long (buf, (guint64)thread->tid);
8464 return ERR_NOT_IMPLEMENTED;
8471 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8475 MonoThread *thread_obj;
8476 MonoInternalThread *thread;
8477 int pos, i, len, frame_idx;
8478 DebuggerTlsData *tls;
8480 MonoDebugMethodJitInfo *jit;
8481 MonoDebugVarInfo *var;
8482 MonoMethodSignature *sig;
8484 MonoMethodHeader *header;
8486 objid = decode_objid (p, &p, end);
8487 err = get_object (objid, (MonoObject**)&thread_obj);
8491 thread = THREAD_TO_INTERNAL (thread_obj);
8493 id = decode_id (p, &p, end);
8495 mono_loader_lock ();
8496 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8497 mono_loader_unlock ();
8500 for (i = 0; i < tls->frame_count; ++i) {
8501 if (tls->frames [i]->id == id)
8504 if (i == tls->frame_count)
8505 return ERR_INVALID_FRAMEID;
8508 frame = tls->frames [frame_idx];
8510 if (!frame->has_ctx)
8511 return ERR_ABSENT_INFORMATION;
8514 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8515 if (!frame->jit && frame->api_method->is_inflated)
8516 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8520 /* This could happen for aot images with no jit debug info */
8521 s = mono_method_full_name (frame->api_method, TRUE);
8522 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8524 return ERR_ABSENT_INFORMATION;
8529 sig = mono_method_signature (frame->actual_method);
8531 if (!get_seq_points (frame->domain, frame->actual_method))
8533 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8535 return ERR_ABSENT_INFORMATION;
8538 case CMD_STACK_FRAME_GET_VALUES: {
8539 len = decode_int (p, &p, end);
8540 header = mono_method_get_header (frame->actual_method);
8542 for (i = 0; i < len; ++i) {
8543 pos = decode_int (p, &p, end);
8548 g_assert (pos >= 0 && pos < jit->num_params);
8550 var = &jit->params [pos];
8552 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8554 g_assert (pos >= 0 && pos < jit->num_locals);
8556 var = &jit->locals [pos];
8558 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8561 mono_metadata_free_mh (header);
8564 case CMD_STACK_FRAME_GET_THIS: {
8565 if (frame->api_method->klass->valuetype) {
8566 if (!sig->hasthis) {
8567 MonoObject *p = NULL;
8568 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8570 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8573 if (!sig->hasthis) {
8574 MonoObject *p = NULL;
8575 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8577 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8582 case CMD_STACK_FRAME_SET_VALUES: {
8585 MonoDebugVarInfo *var;
8587 len = decode_int (p, &p, end);
8588 header = mono_method_get_header (frame->actual_method);
8590 for (i = 0; i < len; ++i) {
8591 pos = decode_int (p, &p, end);
8596 g_assert (pos >= 0 && pos < jit->num_params);
8598 t = sig->params [pos];
8599 var = &jit->params [pos];
8601 g_assert (pos >= 0 && pos < jit->num_locals);
8603 t = header->locals [pos];
8604 var = &jit->locals [pos];
8607 if (MONO_TYPE_IS_REFERENCE (t))
8608 val_buf = g_alloca (sizeof (MonoObject*));
8610 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8611 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8615 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8617 mono_metadata_free_mh (header);
8621 return ERR_NOT_IMPLEMENTED;
8628 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8631 int objid, err, index, len, i, esize;
8634 objid = decode_objid (p, &p, end);
8635 err = get_object (objid, (MonoObject**)&arr);
8640 case CMD_ARRAY_REF_GET_LENGTH:
8641 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8643 buffer_add_int (buf, arr->max_length);
8644 buffer_add_int (buf, 0);
8646 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8647 buffer_add_int (buf, arr->bounds [i].length);
8648 buffer_add_int (buf, arr->bounds [i].lower_bound);
8652 case CMD_ARRAY_REF_GET_VALUES:
8653 index = decode_int (p, &p, end);
8654 len = decode_int (p, &p, end);
8656 g_assert (index >= 0 && len >= 0);
8657 // Reordered to avoid integer overflow
8658 g_assert (!(index > arr->max_length - len));
8660 esize = mono_array_element_size (arr->obj.vtable->klass);
8661 for (i = index; i < index + len; ++i) {
8662 elem = (gpointer*)((char*)arr->vector + (i * esize));
8663 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8666 case CMD_ARRAY_REF_SET_VALUES:
8667 index = decode_int (p, &p, end);
8668 len = decode_int (p, &p, end);
8670 g_assert (index >= 0 && len >= 0);
8671 // Reordered to avoid integer overflow
8672 g_assert (!(index > arr->max_length - len));
8674 esize = mono_array_element_size (arr->obj.vtable->klass);
8675 for (i = index; i < index + len; ++i) {
8676 elem = (gpointer*)((char*)arr->vector + (i * esize));
8678 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8682 return ERR_NOT_IMPLEMENTED;
8689 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8694 int i, index, length;
8697 objid = decode_objid (p, &p, end);
8698 err = get_object (objid, (MonoObject**)&str);
8703 case CMD_STRING_REF_GET_VALUE:
8704 s = mono_string_to_utf8 (str);
8705 buffer_add_string (buf, s);
8708 case CMD_STRING_REF_GET_LENGTH:
8709 buffer_add_long (buf, mono_string_length (str));
8711 case CMD_STRING_REF_GET_CHARS:
8712 index = decode_long (p, &p, end);
8713 length = decode_long (p, &p, end);
8714 if (index > mono_string_length (str) - length)
8715 return ERR_INVALID_ARGUMENT;
8716 c = mono_string_chars (str) + index;
8717 for (i = 0; i < length; ++i)
8718 buffer_add_short (buf, c [i]);
8721 return ERR_NOT_IMPLEMENTED;
8728 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8737 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8738 objid = decode_objid (p, &p, end);
8739 err = get_object (objid, &obj);
8741 buffer_add_int (buf, 1);
8743 buffer_add_int (buf, 0);
8747 objid = decode_objid (p, &p, end);
8748 err = get_object (objid, &obj);
8753 case CMD_OBJECT_REF_GET_TYPE:
8754 /* This handles transparent proxies too */
8755 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8757 case CMD_OBJECT_REF_GET_VALUES:
8758 len = decode_int (p, &p, end);
8760 for (i = 0; i < len; ++i) {
8761 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8765 /* Check that the field belongs to the object */
8767 for (k = obj->vtable->klass; k; k = k->parent) {
8768 if (k == f->parent) {
8774 return ERR_INVALID_FIELDID;
8776 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8780 if (mono_class_field_is_special_static (f))
8781 return ERR_INVALID_FIELDID;
8783 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8784 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8785 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8786 mono_field_static_get_value (vtable, f, val);
8787 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8790 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8794 case CMD_OBJECT_REF_SET_VALUES:
8795 len = decode_int (p, &p, end);
8797 for (i = 0; i < len; ++i) {
8798 f = decode_fieldid (p, &p, end, NULL, &err);
8802 /* Check that the field belongs to the object */
8804 for (k = obj->vtable->klass; k; k = k->parent) {
8805 if (k == f->parent) {
8811 return ERR_INVALID_FIELDID;
8813 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8817 if (mono_class_field_is_special_static (f))
8818 return ERR_INVALID_FIELDID;
8820 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8821 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8823 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8824 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8829 mono_field_static_set_value (vtable, f, val);
8832 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8838 case CMD_OBJECT_REF_GET_ADDRESS:
8839 buffer_add_long (buf, (gssize)obj);
8841 case CMD_OBJECT_REF_GET_DOMAIN:
8842 buffer_add_domainid (buf, obj->vtable->domain);
8844 case CMD_OBJECT_REF_GET_INFO:
8845 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8846 buffer_add_domainid (buf, obj->vtable->domain);
8849 return ERR_NOT_IMPLEMENTED;
8856 command_set_to_string (CommandSet command_set)
8858 switch (command_set) {
8861 case CMD_SET_OBJECT_REF:
8862 return "OBJECT_REF";
8863 case CMD_SET_STRING_REF:
8864 return "STRING_REF";
8865 case CMD_SET_THREAD:
8867 case CMD_SET_ARRAY_REF:
8869 case CMD_SET_EVENT_REQUEST:
8870 return "EVENT_REQUEST";
8871 case CMD_SET_STACK_FRAME:
8872 return "STACK_FRAME";
8873 case CMD_SET_APPDOMAIN:
8875 case CMD_SET_ASSEMBLY:
8877 case CMD_SET_METHOD:
8881 case CMD_SET_MODULE:
8890 static const char* vm_cmds_str [] = {
8898 "SET_PROTOCOL_VERSION",
8901 "GET_TYPES_FOR_SOURCE_FILE",
8906 static const char* thread_cmds_str[] = {
8915 static const char* event_cmds_str[] = {
8918 "REQUEST_CLEAR_ALL_BREAKPOINTS"
8921 static const char* appdomain_cmds_str[] = {
8923 "GET_FRIENDLY_NAME",
8925 "GET_ENTRY_ASSEMBLY",
8928 "CREATE_BOXED_VALUE"
8931 static const char* assembly_cmds_str[] = {
8934 "GET_MANIFEST_MODULE",
8940 static const char* module_cmds_str[] = {
8944 static const char* method_cmds_str[] = {
8946 "GET_DECLARING_TYPE",
8954 "MAKE_GENERIC_METHOD"
8957 static const char* type_cmds_str[] = {
8965 "IS_ASSIGNABLE_FROM",
8969 "GET_PROPERTY_CATTRS",
8970 "GET_SOURCE_FILES_2",
8972 "GET_METHODS_BY_NAME_FLAGS",
8974 "GET_INTERFACE_MAP",
8978 static const char* stack_frame_cmds_str[] = {
8984 static const char* array_cmds_str[] = {
8990 static const char* string_cmds_str[] = {
8996 static const char* object_cmds_str[] = {
9007 cmd_to_string (CommandSet set, int command)
9015 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9017 case CMD_SET_OBJECT_REF:
9018 cmds = object_cmds_str;
9019 cmds_len = G_N_ELEMENTS (object_cmds_str);
9021 case CMD_SET_STRING_REF:
9022 cmds = string_cmds_str;
9023 cmds_len = G_N_ELEMENTS (string_cmds_str);
9025 case CMD_SET_THREAD:
9026 cmds = thread_cmds_str;
9027 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9029 case CMD_SET_ARRAY_REF:
9030 cmds = array_cmds_str;
9031 cmds_len = G_N_ELEMENTS (array_cmds_str);
9033 case CMD_SET_EVENT_REQUEST:
9034 cmds = event_cmds_str;
9035 cmds_len = G_N_ELEMENTS (event_cmds_str);
9037 case CMD_SET_STACK_FRAME:
9038 cmds = stack_frame_cmds_str;
9039 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9041 case CMD_SET_APPDOMAIN:
9042 cmds = appdomain_cmds_str;
9043 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9045 case CMD_SET_ASSEMBLY:
9046 cmds = assembly_cmds_str;
9047 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9049 case CMD_SET_METHOD:
9050 cmds = method_cmds_str;
9051 cmds_len = G_N_ELEMENTS (method_cmds_str);
9054 cmds = type_cmds_str;
9055 cmds_len = G_N_ELEMENTS (type_cmds_str);
9057 case CMD_SET_MODULE:
9058 cmds = module_cmds_str;
9059 cmds_len = G_N_ELEMENTS (module_cmds_str);
9062 cmds = event_cmds_str;
9063 cmds_len = G_N_ELEMENTS (event_cmds_str);
9068 if (command > 0 && command <= cmds_len)
9069 return cmds [command - 1];
9075 wait_for_attach (void)
9077 #ifndef DISABLE_SOCKET_TRANSPORT
9078 if (listen_fd == -1) {
9079 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9083 /* Block and wait for client connection */
9084 conn_fd = socket_transport_accept (listen_fd);
9085 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9086 if (conn_fd == -1) {
9087 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9091 g_assert_not_reached ();
9095 disconnected = !transport_handshake ();
9097 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9107 * This thread handles communication with the debugger client using a JDWP
9110 static guint32 WINAPI
9111 debugger_thread (void *arg)
9113 int res, len, id, flags, command_set = 0, command = 0;
9114 guint8 header [HEADER_LENGTH];
9115 guint8 *data, *p, *end;
9119 gboolean attach_failed = FALSE;
9121 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9123 debugger_thread_id = GetCurrentThreadId ();
9125 mono_jit_thread_attach (mono_get_root_domain ());
9127 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9129 mono_set_is_debugger_attached (TRUE);
9131 if (agent_config.defer) {
9132 if (!wait_for_attach ()) {
9133 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9134 attach_failed = TRUE; // Don't abort process when we can't listen
9136 /* Send start event to client */
9137 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9141 while (!attach_failed) {
9142 res = transport_recv (header, HEADER_LENGTH);
9144 /* This will break if the socket is closed during shutdown too */
9145 if (res != HEADER_LENGTH) {
9146 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9151 end = header + HEADER_LENGTH;
9153 len = decode_int (p, &p, end);
9154 id = decode_int (p, &p, end);
9155 flags = decode_byte (p, &p, end);
9156 command_set = decode_byte (p, &p, end);
9157 command = decode_byte (p, &p, end);
9159 g_assert (flags == 0);
9162 const char *cmd_str;
9165 cmd_str = cmd_to_string (command_set, command);
9167 sprintf (cmd_num, "%d", command);
9171 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d].\n", command_set_to_string (command_set), cmd_str, id));
9174 data = g_malloc (len - HEADER_LENGTH);
9175 if (len - HEADER_LENGTH > 0)
9177 res = transport_recv (data, len - HEADER_LENGTH);
9178 if (res != len - HEADER_LENGTH) {
9179 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9185 end = data + (len - HEADER_LENGTH);
9187 buffer_init (&buf, 128);
9192 /* Process the request */
9193 switch (command_set) {
9195 err = vm_commands (command, id, p, end, &buf);
9196 if (!err && command == CMD_VM_INVOKE_METHOD)
9197 /* Sent after the invoke is complete */
9200 case CMD_SET_EVENT_REQUEST:
9201 err = event_commands (command, p, end, &buf);
9203 case CMD_SET_APPDOMAIN:
9204 err = domain_commands (command, p, end, &buf);
9206 case CMD_SET_ASSEMBLY:
9207 err = assembly_commands (command, p, end, &buf);
9209 case CMD_SET_MODULE:
9210 err = module_commands (command, p, end, &buf);
9213 err = type_commands (command, p, end, &buf);
9215 case CMD_SET_METHOD:
9216 err = method_commands (command, p, end, &buf);
9218 case CMD_SET_THREAD:
9219 err = thread_commands (command, p, end, &buf);
9221 case CMD_SET_STACK_FRAME:
9222 err = frame_commands (command, p, end, &buf);
9224 case CMD_SET_ARRAY_REF:
9225 err = array_commands (command, p, end, &buf);
9227 case CMD_SET_STRING_REF:
9228 err = string_commands (command, p, end, &buf);
9230 case CMD_SET_OBJECT_REF:
9231 err = object_commands (command, p, end, &buf);
9234 err = ERR_NOT_IMPLEMENTED;
9238 send_reply_packet (id, err, &buf);
9243 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9247 mono_set_is_debugger_attached (FALSE);
9249 mono_mutex_lock (&debugger_thread_exited_mutex);
9250 debugger_thread_exited = TRUE;
9251 mono_cond_signal (&debugger_thread_exited_cond);
9252 mono_mutex_unlock (&debugger_thread_exited_mutex);
9254 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9256 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9257 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9258 start_debugger_thread ();
9264 #else /* DISABLE_DEBUGGER_AGENT */
9267 mono_debugger_agent_parse_options (char *options)
9269 g_error ("This runtime is configured with the debugger agent disabled.");
9273 mono_debugger_agent_init (void)
9278 mono_debugger_agent_breakpoint_hit (void *sigctx)
9283 mono_debugger_agent_single_step_event (void *sigctx)
9288 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9293 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9299 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9300 MonoContext *catch_ctx)
9305 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9310 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9315 mono_debugger_agent_user_break (void)
9321 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9326 mono_debugger_agent_debug_log_is_enabled (void)