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
134 guint32 il_offset, native_offset;
138 * If method is gshared, this is the actual instance, otherwise this is equal to
141 MonoMethod *actual_method;
143 * This is the method which is visible to debugger clients. Same as method,
144 * except for native-to-managed wrappers.
146 MonoMethod *api_method;
148 MonoDebugMethodJitInfo *jit;
151 mgreg_t *reg_locations [MONO_MAX_IREGS];
153 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
154 * the frame can become invalid.
159 typedef struct _InvokeData InvokeData;
167 /* This is the context which needs to be restored after the invoke */
171 * If this is set, invoke this method with the arguments given by ARGS.
175 guint32 suspend_count;
178 InvokeData *last_invoke;
182 MonoThreadUnwindState context;
184 /* This is computed on demand when it is requested using the wire protocol */
185 /* It is freed up when the thread is resumed */
189 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
192 gboolean frames_up_to_date;
194 * Points to data about a pending invoke which needs to be executed after the thread
197 InvokeData *pending_invoke;
199 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
204 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
205 * within a finite amount of time.
209 * Set to TRUE if this thread is suspended in suspend_current ().
211 gboolean really_suspended;
212 /* Used to pass the context to the breakpoint/single step handler */
213 MonoContext handler_ctx;
214 /* Whenever thread_stop () was called for this thread */
217 /* Number of thread interruptions not yet processed */
218 gint32 interrupt_count;
220 /* Whenever to disable breakpoints (used during invokes) */
221 gboolean disable_breakpoints;
224 * Number of times this thread has been resumed using resume_thread ().
226 guint32 resume_count;
228 MonoInternalThread *thread;
231 * Information about the frame which transitioned to native code for running
234 StackFrameInfo async_last_frame;
237 * The context where the stack walk can be started for running threads.
239 MonoThreadUnwindState async_state;
242 * The context used for filter clauses
244 MonoThreadUnwindState filter_state;
247 * The callee address of the last mono_runtime_invoke call
249 gpointer invoke_addr;
251 gboolean abort_requested;
254 * The current mono_runtime_invoke invocation.
259 * The context where single stepping should resume while the thread is suspended because
260 * of an EXCEPTION event.
262 MonoThreadUnwindState catch_state;
265 * The context which needs to be restored after handling a single step/breakpoint
266 * event. This is the same as the ctx at step/breakpoint site, but includes changes
267 * to caller saved registers done by set_var ().
269 MonoContext restore_ctx;
274 void (*connect) (const char *address);
275 void (*close1) (void);
276 void (*close2) (void);
277 gboolean (*send) (void *buf, int len);
278 int (*recv) (void *buf, int len);
282 * Wire Protocol definitions
285 #define HEADER_LENGTH 11
287 #define MAJOR_VERSION 2
288 #define MINOR_VERSION 27
292 CMD_SET_OBJECT_REF = 9,
293 CMD_SET_STRING_REF = 10,
295 CMD_SET_ARRAY_REF = 13,
296 CMD_SET_EVENT_REQUEST = 15,
297 CMD_SET_STACK_FRAME = 16,
298 CMD_SET_APPDOMAIN = 20,
299 CMD_SET_ASSEMBLY = 21,
307 EVENT_KIND_VM_START = 0,
308 EVENT_KIND_VM_DEATH = 1,
309 EVENT_KIND_THREAD_START = 2,
310 EVENT_KIND_THREAD_DEATH = 3,
311 EVENT_KIND_APPDOMAIN_CREATE = 4,
312 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
313 EVENT_KIND_METHOD_ENTRY = 6,
314 EVENT_KIND_METHOD_EXIT = 7,
315 EVENT_KIND_ASSEMBLY_LOAD = 8,
316 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
317 EVENT_KIND_BREAKPOINT = 10,
318 EVENT_KIND_STEP = 11,
319 EVENT_KIND_TYPE_LOAD = 12,
320 EVENT_KIND_EXCEPTION = 13,
321 EVENT_KIND_KEEPALIVE = 14,
322 EVENT_KIND_USER_BREAK = 15,
323 EVENT_KIND_USER_LOG = 16
327 SUSPEND_POLICY_NONE = 0,
328 SUSPEND_POLICY_EVENT_THREAD = 1,
329 SUSPEND_POLICY_ALL = 2
334 ERR_INVALID_OBJECT = 20,
335 ERR_INVALID_FIELDID = 25,
336 ERR_INVALID_FRAMEID = 30,
337 ERR_NOT_IMPLEMENTED = 100,
338 ERR_NOT_SUSPENDED = 101,
339 ERR_INVALID_ARGUMENT = 102,
341 ERR_NO_INVOCATION = 104,
342 ERR_ABSENT_INFORMATION = 105,
343 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
344 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
349 MOD_KIND_THREAD_ONLY = 3,
350 MOD_KIND_LOCATION_ONLY = 7,
351 MOD_KIND_EXCEPTION_ONLY = 8,
353 MOD_KIND_ASSEMBLY_ONLY = 11,
354 MOD_KIND_SOURCE_FILE_ONLY = 12,
355 MOD_KIND_TYPE_NAME_ONLY = 13
370 STEP_FILTER_NONE = 0,
371 STEP_FILTER_STATIC_CTOR = 1,
372 STEP_FILTER_DEBUGGER_HIDDEN = 2,
373 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4
377 TOKEN_TYPE_STRING = 0,
379 TOKEN_TYPE_FIELD = 2,
380 TOKEN_TYPE_METHOD = 3,
381 TOKEN_TYPE_UNKNOWN = 4
385 VALUE_TYPE_ID_NULL = 0xf0,
386 VALUE_TYPE_ID_TYPE = 0xf1
390 FRAME_FLAG_DEBUGGER_INVOKE = 1,
391 FRAME_FLAG_NATIVE_TRANSITION = 2
395 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
396 INVOKE_FLAG_SINGLE_THREADED = 2
400 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
401 } BindingFlagsExtensions;
405 CMD_VM_ALL_THREADS = 2,
410 CMD_VM_INVOKE_METHOD = 7,
411 CMD_VM_SET_PROTOCOL_VERSION = 8,
412 CMD_VM_ABORT_INVOKE = 9,
413 CMD_VM_SET_KEEPALIVE = 10,
414 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
415 CMD_VM_GET_TYPES = 12,
416 CMD_VM_INVOKE_METHODS = 13
420 CMD_THREAD_GET_FRAME_INFO = 1,
421 CMD_THREAD_GET_NAME = 2,
422 CMD_THREAD_GET_STATE = 3,
423 CMD_THREAD_GET_INFO = 4,
424 CMD_THREAD_GET_ID = 5,
425 CMD_THREAD_GET_TID = 6
429 CMD_EVENT_REQUEST_SET = 1,
430 CMD_EVENT_REQUEST_CLEAR = 2,
431 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
439 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
440 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
441 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
442 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
443 CMD_APPDOMAIN_CREATE_STRING = 5,
444 CMD_APPDOMAIN_GET_CORLIB = 6,
445 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
449 CMD_ASSEMBLY_GET_LOCATION = 1,
450 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
451 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
452 CMD_ASSEMBLY_GET_OBJECT = 4,
453 CMD_ASSEMBLY_GET_TYPE = 5,
454 CMD_ASSEMBLY_GET_NAME = 6
458 CMD_MODULE_GET_INFO = 1,
462 CMD_METHOD_GET_NAME = 1,
463 CMD_METHOD_GET_DECLARING_TYPE = 2,
464 CMD_METHOD_GET_DEBUG_INFO = 3,
465 CMD_METHOD_GET_PARAM_INFO = 4,
466 CMD_METHOD_GET_LOCALS_INFO = 5,
467 CMD_METHOD_GET_INFO = 6,
468 CMD_METHOD_GET_BODY = 7,
469 CMD_METHOD_RESOLVE_TOKEN = 8,
470 CMD_METHOD_GET_CATTRS = 9,
471 CMD_METHOD_MAKE_GENERIC_METHOD = 10
475 CMD_TYPE_GET_INFO = 1,
476 CMD_TYPE_GET_METHODS = 2,
477 CMD_TYPE_GET_FIELDS = 3,
478 CMD_TYPE_GET_VALUES = 4,
479 CMD_TYPE_GET_OBJECT = 5,
480 CMD_TYPE_GET_SOURCE_FILES = 6,
481 CMD_TYPE_SET_VALUES = 7,
482 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
483 CMD_TYPE_GET_PROPERTIES = 9,
484 CMD_TYPE_GET_CATTRS = 10,
485 CMD_TYPE_GET_FIELD_CATTRS = 11,
486 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
487 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
488 CMD_TYPE_GET_VALUES_2 = 14,
489 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
490 CMD_TYPE_GET_INTERFACES = 16,
491 CMD_TYPE_GET_INTERFACE_MAP = 17,
492 CMD_TYPE_IS_INITIALIZED = 18
496 CMD_STACK_FRAME_GET_VALUES = 1,
497 CMD_STACK_FRAME_GET_THIS = 2,
498 CMD_STACK_FRAME_SET_VALUES = 3
502 CMD_ARRAY_REF_GET_LENGTH = 1,
503 CMD_ARRAY_REF_GET_VALUES = 2,
504 CMD_ARRAY_REF_SET_VALUES = 3,
508 CMD_STRING_REF_GET_VALUE = 1,
509 CMD_STRING_REF_GET_LENGTH = 2,
510 CMD_STRING_REF_GET_CHARS = 3
514 CMD_OBJECT_REF_GET_TYPE = 1,
515 CMD_OBJECT_REF_GET_VALUES = 2,
516 CMD_OBJECT_REF_IS_COLLECTED = 3,
517 CMD_OBJECT_REF_GET_ADDRESS = 4,
518 CMD_OBJECT_REF_GET_DOMAIN = 5,
519 CMD_OBJECT_REF_SET_VALUES = 6,
520 CMD_OBJECT_REF_GET_INFO = 7,
526 int count; /* For kind == MOD_KIND_COUNT */
527 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
528 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
529 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
530 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
531 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
532 StepFilter filter; /* For kind == MOD_KIND_STEP */
534 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
543 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
547 * Describes a single step request.
551 MonoInternalThread *thread;
557 MonoMethod *last_method;
559 /* Whenever single stepping is performed using start/stop_single_stepping () */
561 /* The list of breakpoints used to implement step-over */
563 /* The number of frames at the start of a step-over */
568 * Contains additional information for an event
571 /* For EVENT_KIND_EXCEPTION */
573 MonoContext catch_ctx;
575 /* For EVENT_KIND_USER_LOG */
577 char *category, *message;
578 /* For EVENT_KIND_TYPE_LOAD */
582 /* Dummy structure used for the profiler callbacks */
587 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
590 #define get_last_sock_error() WSAGetLastError()
591 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
592 #define MONO_EINTR WSAEINTR
594 #define get_last_sock_error() errno
595 #define MONO_EWOULDBLOCK EWOULDBLOCK
596 #define MONO_EINTR EINTR
599 #define CHECK_PROTOCOL_VERSION(major,minor) \
600 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
606 static AgentConfig agent_config;
609 * Whenever the agent is fully initialized.
610 * When using the onuncaught or onthrow options, only some parts of the agent are
611 * initialized on startup, and the full initialization which includes connection
612 * establishment and the startup of the agent thread is only done in response to
615 static gint32 inited;
617 #ifndef DISABLE_SOCKET_TRANSPORT
619 static int listen_fd;
622 static int packet_id = 0;
624 static int objref_id = 0;
626 static int event_request_id = 0;
628 static int frame_id = 0;
630 static GPtrArray *event_requests;
632 static MonoNativeTlsKey debugger_tls_id;
634 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
636 /* Maps MonoInternalThread -> DebuggerTlsData */
637 static MonoGHashTable *thread_to_tls;
639 /* Maps tid -> MonoInternalThread */
640 static MonoGHashTable *tid_to_thread;
642 /* Maps tid -> MonoThread (not MonoInternalThread) */
643 static MonoGHashTable *tid_to_thread_obj;
645 static gsize debugger_thread_id;
647 static HANDLE debugger_thread_handle;
649 static int log_level;
651 static gboolean embedding;
653 static FILE *log_file;
655 /* Assemblies whose assembly load event has no been sent yet */
656 static GPtrArray *pending_assembly_loads;
658 /* Whenever the debugger thread has exited */
659 static gboolean debugger_thread_exited;
661 /* Cond variable used to wait for debugger_thread_exited becoming true */
662 static mono_cond_t debugger_thread_exited_cond;
664 /* Mutex for the cond var above */
665 static mono_mutex_t debugger_thread_exited_mutex;
667 static DebuggerProfiler debugger_profiler;
669 /* The single step request instance */
670 static SingleStepReq *ss_req = NULL;
671 static gpointer ss_invoke_addr = NULL;
673 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
674 /* Number of single stepping operations in progress */
678 /* The protocol version of the client */
679 static int major_version, minor_version;
681 /* Whenever the variables above are set by the client */
682 static gboolean protocol_version_set;
684 /* A hash table containing all active domains */
685 static GHashTable *domains;
687 /* The number of times the runtime is suspended */
688 static gint32 suspend_count;
690 static void transport_init (void);
691 static void transport_connect (const char *address);
692 static gboolean transport_handshake (void);
693 static void register_transport (DebuggerTransport *trans);
695 static guint32 WINAPI debugger_thread (void *arg);
697 static void runtime_initialized (MonoProfiler *prof);
699 static void runtime_shutdown (MonoProfiler *prof);
701 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
703 static void thread_end (MonoProfiler *prof, uintptr_t tid);
705 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
707 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
709 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
711 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
713 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
715 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
717 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
719 static void emit_assembly_load (gpointer assembly, gpointer user_data);
721 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
723 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
725 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
727 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
729 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
731 static void start_single_stepping (void);
733 static void stop_single_stepping (void);
735 static void suspend_current (void);
737 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
739 static void clear_types_for_assembly (MonoAssembly *assembly);
741 static void clear_breakpoints_for_domain (MonoDomain *domain);
743 static void process_profiler_event (EventKind event, gpointer arg);
745 /* Submodule init/cleanup */
746 static void breakpoints_init (void);
747 static void breakpoints_cleanup (void);
749 static void objrefs_init (void);
750 static void objrefs_cleanup (void);
752 static void ids_init (void);
753 static void ids_cleanup (void);
755 static void suspend_init (void);
757 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
758 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
759 static void ss_destroy (SingleStepReq *req);
761 static void start_debugger_thread (void);
762 static void stop_debugger_thread (void);
764 static void finish_agent_init (gboolean on_startup);
766 static void process_profiler_event (EventKind event, gpointer arg);
768 static void invalidate_frames (DebuggerTlsData *tls);
770 #ifndef DISABLE_SOCKET_TRANSPORT
772 register_socket_transport (void);
776 parse_address (char *address, char **host, int *port)
778 char *pos = strchr (address, ':');
780 if (pos == NULL || pos == address)
783 *host = g_malloc (pos - address + 1);
784 strncpy (*host, address, pos - address);
785 (*host) [pos - address] = '\0';
787 *port = atoi (pos + 1);
795 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
796 fprintf (stderr, "Available options:\n");
797 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
798 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
799 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
800 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
801 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
802 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
803 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
804 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
805 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
806 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
810 parse_flag (const char *option, char *flag)
812 if (!strcmp (flag, "y"))
814 else if (!strcmp (flag, "n"))
817 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
824 mono_debugger_agent_parse_options (char *options)
831 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
832 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
836 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
838 options = g_strdup_printf ("%s,%s", options, extra);
840 agent_config.enabled = TRUE;
841 agent_config.suspend = TRUE;
842 agent_config.server = FALSE;
843 agent_config.defer = FALSE;
844 agent_config.address = NULL;
846 args = g_strsplit (options, ",", -1);
847 for (ptr = args; ptr && *ptr; ptr ++) {
850 if (strncmp (arg, "transport=", 10) == 0) {
851 agent_config.transport = g_strdup (arg + 10);
852 } else if (strncmp (arg, "address=", 8) == 0) {
853 agent_config.address = g_strdup (arg + 8);
854 } else if (strncmp (arg, "loglevel=", 9) == 0) {
855 agent_config.log_level = atoi (arg + 9);
856 } else if (strncmp (arg, "logfile=", 8) == 0) {
857 agent_config.log_file = g_strdup (arg + 8);
858 } else if (strncmp (arg, "suspend=", 8) == 0) {
859 agent_config.suspend = parse_flag ("suspend", arg + 8);
860 } else if (strncmp (arg, "server=", 7) == 0) {
861 agent_config.server = parse_flag ("server", arg + 7);
862 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
863 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
864 } else if (strncmp (arg, "onthrow=", 8) == 0) {
865 /* We support multiple onthrow= options */
866 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
867 } else if (strncmp (arg, "onthrow", 7) == 0) {
868 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
869 } else if (strncmp (arg, "help", 4) == 0) {
872 } else if (strncmp (arg, "timeout=", 8) == 0) {
873 agent_config.timeout = atoi (arg + 8);
874 } else if (strncmp (arg, "launch=", 7) == 0) {
875 agent_config.launch = g_strdup (arg + 7);
876 } else if (strncmp (arg, "embedding=", 10) == 0) {
877 agent_config.embedding = atoi (arg + 10) == 1;
878 } else if (strncmp (arg, "keepalive=", 10) == 0) {
879 agent_config.keepalive = atoi (arg + 10);
880 } else if (strncmp (arg, "setpgid=", 8) == 0) {
881 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
888 if (agent_config.server && !agent_config.suspend) {
889 /* Waiting for deferred attachment */
890 agent_config.defer = TRUE;
891 if (agent_config.address == NULL) {
892 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
896 //agent_config.log_level = 0;
898 if (agent_config.transport == NULL) {
899 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
903 if (agent_config.address == NULL && !agent_config.server) {
904 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
909 if (!strcmp (agent_config.transport, "dt_socket")) {
910 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
911 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
918 mono_debugger_agent_init (void)
920 if (!agent_config.enabled)
925 /* Need to know whenever a thread has acquired the loader mutex */
926 mono_loader_lock_track_ownership (TRUE);
928 event_requests = g_ptr_array_new ();
930 mono_mutex_init (&debugger_thread_exited_mutex);
931 mono_cond_init (&debugger_thread_exited_cond, NULL);
933 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
934 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
935 mono_profiler_install_runtime_initialized (runtime_initialized);
936 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
937 mono_profiler_install_thread (thread_startup, thread_end);
938 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
939 mono_profiler_install_jit_end (jit_end);
940 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
942 mono_native_tls_alloc (&debugger_tls_id, NULL);
944 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
945 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
947 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
948 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
950 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
951 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
953 pending_assembly_loads = g_ptr_array_new ();
954 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
956 log_level = agent_config.log_level;
958 embedding = agent_config.embedding;
961 if (agent_config.log_file) {
962 log_file = fopen (agent_config.log_file, "w+");
964 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
976 mini_get_debug_options ()->gen_seq_points = TRUE;
978 * This is needed because currently we don't handle liveness info.
980 mini_get_debug_options ()->mdb_optimizations = TRUE;
982 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
983 /* This is needed because we can't set local variables in registers yet */
984 mono_disable_optimizations (MONO_OPT_LINEARS);
988 * The stack walk done from thread_interrupt () needs to be signal safe, but it
989 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
990 * safe (#3411). So load AOT info eagerly when the debugger is running as a
993 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
996 if (agent_config.setpgid)
1000 if (!agent_config.onuncaught && !agent_config.onthrow)
1001 finish_agent_init (TRUE);
1005 * finish_agent_init:
1007 * Finish the initialization of the agent. This involves connecting the transport
1008 * and starting the agent thread. This is either done at startup, or
1009 * in response to some event like an unhandled exception.
1012 finish_agent_init (gboolean on_startup)
1016 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1019 if (agent_config.launch) {
1022 // FIXME: Generated address
1023 // FIXME: Races with transport_connect ()
1025 argv [0] = agent_config.launch;
1026 argv [1] = agent_config.transport;
1027 argv [2] = agent_config.address;
1030 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1032 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1037 transport_connect (agent_config.address);
1040 /* Do some which is usually done after sending the VMStart () event */
1041 vm_start_event_sent = TRUE;
1042 start_debugger_thread ();
1047 mono_debugger_agent_cleanup (void)
1052 stop_debugger_thread ();
1054 breakpoints_cleanup ();
1058 mono_mutex_destroy (&debugger_thread_exited_mutex);
1059 mono_cond_destroy (&debugger_thread_exited_cond);
1066 #ifndef DISABLE_SOCKET_TRANSPORT
1071 * recv() + handle incomplete reads and EINTR
1074 socket_transport_recv (void *buf, int len)
1080 static gint32 last_keepalive;
1085 res = recv (fd, (char *) buf + total, len - total, flags);
1088 if (agent_config.keepalive) {
1089 gboolean need_keepalive = FALSE;
1090 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1091 need_keepalive = TRUE;
1092 } else if (res == -1) {
1093 /* This could happen if recv () is interrupted repeatedly */
1094 msecs = mono_msec_ticks ();
1095 if (msecs - last_keepalive >= agent_config.keepalive) {
1096 need_keepalive = TRUE;
1097 last_keepalive = msecs;
1100 if (need_keepalive) {
1101 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1105 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1110 #define HAVE_GETADDRINFO 1
1114 set_keepalive (void)
1119 if (!agent_config.keepalive || !conn_fd)
1122 tv.tv_sec = agent_config.keepalive / 1000;
1123 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1125 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1126 g_assert (result >= 0);
1130 socket_transport_accept (int socket_fd)
1132 conn_fd = accept (socket_fd, NULL, NULL);
1133 if (conn_fd == -1) {
1134 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1136 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1143 socket_transport_send (void *data, int len)
1148 res = send (conn_fd, data, len, 0);
1149 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1157 * socket_transport_connect:
1159 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1162 socket_transport_connect (const char *address)
1164 #ifdef HAVE_GETADDRINFO
1165 struct addrinfo hints;
1166 struct addrinfo *result, *rp;
1168 struct hostent *result;
1170 int sfd = -1, s, res;
1171 char port_string [128];
1175 if (agent_config.address) {
1176 res = parse_address (agent_config.address, &host, &port);
1177 g_assert (res == 0);
1187 sprintf (port_string, "%d", port);
1189 mono_network_init ();
1191 /* Obtain address(es) matching host/port */
1192 #ifdef HAVE_GETADDRINFO
1193 memset (&hints, 0, sizeof (struct addrinfo));
1194 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1195 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1197 hints.ai_protocol = 0; /* Any protocol */
1199 s = getaddrinfo (host, port_string, &hints, &result);
1201 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1205 /* The PS3 doesn't even have _r or hstrerror () */
1206 result = gethostbyname (host);
1208 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1213 if (agent_config.server) {
1214 #ifdef HAVE_GETADDRINFO
1215 /* Wait for a connection */
1217 struct sockaddr_in addr;
1220 /* No address, generate one */
1221 sfd = socket (AF_INET, SOCK_STREAM, 0);
1224 /* This will bind the socket to a random port */
1225 res = listen (sfd, 16);
1227 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1232 addrlen = sizeof (addr);
1233 memset (&addr, 0, sizeof (addr));
1234 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1235 g_assert (res == 0);
1237 host = (char*)"127.0.0.1";
1238 port = ntohs (addr.sin_port);
1240 /* Emit the address to stdout */
1241 /* FIXME: Should print another interface, not localhost */
1242 printf ("%s:%d\n", host, port);
1244 /* Listen on the provided address */
1245 for (rp = result; rp != NULL; rp = rp->ai_next) {
1248 sfd = socket (rp->ai_family, rp->ai_socktype,
1253 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1256 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1260 res = listen (sfd, 16);
1269 * this function is not present on win2000 which we still support, and the
1270 * workaround described here:
1271 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1272 * only works with MSVC.
1274 #ifdef HAVE_GETADDRINFO
1275 freeaddrinfo (result);
1280 if (agent_config.defer)
1283 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1285 if (agent_config.timeout) {
1290 tv.tv_usec = agent_config.timeout * 1000;
1292 FD_SET (sfd, &readfds);
1293 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1295 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1300 conn_fd = socket_transport_accept (sfd);
1304 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1307 #endif /* HAVE_GETADDRINFO */
1309 /* Connect to the specified address */
1310 #ifdef HAVE_GETADDRINFO
1311 /* FIXME: Respect the timeout */
1312 for (rp = result; rp != NULL; rp = rp->ai_next) {
1313 sfd = socket (rp->ai_family, rp->ai_socktype,
1318 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1319 break; /* Success */
1325 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1329 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1331 g_assert_not_reached ();
1332 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1334 g_assert_not_reached ();
1340 /* See the comment above */
1341 #ifdef HAVE_GETADDRINFO
1342 freeaddrinfo (result);
1347 if (!transport_handshake ())
1352 socket_transport_close1 (void)
1354 /* This will interrupt the agent thread */
1355 /* Close the read part only so it can still send back replies */
1356 /* Also shut down the connection listener so that we can exit normally */
1358 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1359 shutdown (conn_fd, SD_BOTH);
1360 shutdown (listen_fd, SD_BOTH);
1361 closesocket (listen_fd);
1363 shutdown (conn_fd, SHUT_RD);
1364 shutdown (listen_fd, SHUT_RDWR);
1370 socket_transport_close2 (void)
1373 shutdown (conn_fd, SD_BOTH);
1375 shutdown (conn_fd, SHUT_RDWR);
1380 register_socket_transport (void)
1382 DebuggerTransport trans;
1384 trans.name = "dt_socket";
1385 trans.connect = socket_transport_connect;
1386 trans.close1 = socket_transport_close1;
1387 trans.close2 = socket_transport_close2;
1388 trans.send = socket_transport_send;
1389 trans.recv = socket_transport_recv;
1391 register_transport (&trans);
1394 #endif /* DISABLE_SOCKET_TRANSPORT */
1400 #define MAX_TRANSPORTS 16
1402 static DebuggerTransport *transport;
1404 static DebuggerTransport transports [MAX_TRANSPORTS];
1405 static int ntransports;
1408 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1411 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1413 register_transport (trans);
1417 register_transport (DebuggerTransport *trans)
1419 g_assert (ntransports < MAX_TRANSPORTS);
1421 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1426 transport_init (void)
1430 #ifndef DISABLE_SOCKET_TRANSPORT
1431 register_socket_transport ();
1434 for (i = 0; i < ntransports; ++i) {
1435 if (!strcmp (agent_config.transport, transports [i].name))
1438 if (i == ntransports) {
1439 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1440 for (i = 0; i < ntransports; ++i)
1441 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1442 fprintf (stderr, "\n");
1445 transport = &transports [i];
1449 transport_connect (const char *address)
1451 transport->connect (address);
1455 transport_close1 (void)
1457 transport->close1 ();
1461 transport_close2 (void)
1463 transport->close2 ();
1467 transport_send (void *buf, int len)
1469 return transport->send (buf, len);
1473 transport_recv (void *buf, int len)
1475 return transport->recv (buf, len);
1479 mono_debugger_agent_transport_handshake (void)
1481 return transport_handshake ();
1485 transport_handshake (void)
1487 char handshake_msg [128];
1491 disconnected = TRUE;
1493 /* Write handshake message */
1494 sprintf (handshake_msg, "DWP-Handshake");
1496 res = transport_send (handshake_msg, strlen (handshake_msg));
1497 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1498 g_assert (res != -1);
1501 res = transport_recv (buf, strlen (handshake_msg));
1502 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1503 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1508 * To support older clients, the client sends its protocol version after connecting
1509 * using a command. Until that is received, default to our protocol version.
1511 major_version = MAJOR_VERSION;
1512 minor_version = MINOR_VERSION;
1513 protocol_version_set = FALSE;
1515 #ifndef DISABLE_SOCKET_TRANSPORT
1516 // FIXME: Move this somewhere else
1518 * Set TCP_NODELAY on the socket so the client receives events/command
1519 * results immediately.
1523 int result = setsockopt (conn_fd,
1528 g_assert (result >= 0);
1534 disconnected = FALSE;
1539 stop_debugger_thread (void)
1544 transport_close1 ();
1547 * Wait for the thread to exit.
1549 * If we continue with the shutdown without waiting for it, then the client might
1550 * not receive an answer to its last command like a resume.
1551 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1554 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1555 if (GetCurrentThreadId () != debugger_thread_id) {
1557 mono_mutex_lock (&debugger_thread_exited_mutex);
1558 if (!debugger_thread_exited) {
1560 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1561 mono_mutex_unlock (&debugger_thread_exited_mutex);
1563 mono_mutex_lock (&debugger_thread_exited_mutex);
1566 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1569 mono_mutex_unlock (&debugger_thread_exited_mutex);
1570 } while (!debugger_thread_exited);
1573 transport_close2 ();
1577 start_debugger_thread (void)
1581 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1582 g_assert (debugger_thread_handle);
1586 * Functions to decode protocol data
1590 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1593 g_assert (*endbuf <= limit);
1598 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1601 g_assert (*endbuf <= limit);
1603 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1606 static inline gint64
1607 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1609 guint32 high = decode_int (buf, &buf, limit);
1610 guint32 low = decode_int (buf, &buf, limit);
1614 return ((((guint64)high) << 32) | ((guint64)low));
1618 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1620 return decode_int (buf, endbuf, limit);
1624 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1626 int len = decode_int (buf, &buf, limit);
1634 s = g_malloc (len + 1);
1637 memcpy (s, buf, len);
1646 * Functions to encode protocol data
1650 guint8 *buf, *p, *end;
1654 buffer_init (Buffer *buf, int size)
1656 buf->buf = g_malloc (size);
1658 buf->end = buf->buf + size;
1662 buffer_make_room (Buffer *buf, int size)
1664 if (buf->end - buf->p < size) {
1665 int new_size = buf->end - buf->buf + size + 32;
1666 guint8 *p = g_realloc (buf->buf, new_size);
1667 size = buf->p - buf->buf;
1670 buf->end = buf->buf + new_size;
1675 buffer_add_byte (Buffer *buf, guint8 val)
1677 buffer_make_room (buf, 1);
1683 buffer_add_short (Buffer *buf, guint32 val)
1685 buffer_make_room (buf, 2);
1686 buf->p [0] = (val >> 8) & 0xff;
1687 buf->p [1] = (val >> 0) & 0xff;
1692 buffer_add_int (Buffer *buf, guint32 val)
1694 buffer_make_room (buf, 4);
1695 buf->p [0] = (val >> 24) & 0xff;
1696 buf->p [1] = (val >> 16) & 0xff;
1697 buf->p [2] = (val >> 8) & 0xff;
1698 buf->p [3] = (val >> 0) & 0xff;
1703 buffer_add_long (Buffer *buf, guint64 l)
1705 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1706 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1710 buffer_add_id (Buffer *buf, int id)
1712 buffer_add_int (buf, (guint64)id);
1716 buffer_add_data (Buffer *buf, guint8 *data, int len)
1718 buffer_make_room (buf, len);
1719 memcpy (buf->p, data, len);
1724 buffer_add_string (Buffer *buf, const char *str)
1729 buffer_add_int (buf, 0);
1732 buffer_add_int (buf, len);
1733 buffer_add_data (buf, (guint8*)str, len);
1738 buffer_free (Buffer *buf)
1744 send_packet (int command_set, int command, Buffer *data)
1750 id = InterlockedIncrement (&packet_id);
1752 len = data->p - data->buf + 11;
1753 buffer_init (&buf, len);
1754 buffer_add_int (&buf, len);
1755 buffer_add_int (&buf, id);
1756 buffer_add_byte (&buf, 0); /* flags */
1757 buffer_add_byte (&buf, command_set);
1758 buffer_add_byte (&buf, command);
1759 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1761 res = transport_send (buf.buf, len);
1769 send_reply_packet (int id, int error, Buffer *data)
1775 len = data->p - data->buf + 11;
1776 buffer_init (&buf, len);
1777 buffer_add_int (&buf, len);
1778 buffer_add_int (&buf, id);
1779 buffer_add_byte (&buf, 0x80); /* flags */
1780 buffer_add_byte (&buf, (error >> 8) & 0xff);
1781 buffer_add_byte (&buf, error);
1782 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1784 res = transport_send (buf.buf, len);
1796 * Represents an object accessible by the debugger client.
1799 /* Unique id used in the wire protocol to refer to objects */
1802 * A weakref gc handle pointing to the object. The gc handle is used to
1803 * detect if the object was garbage collected.
1808 /* Maps objid -> ObjRef */
1809 static GHashTable *objrefs;
1812 free_objref (gpointer value)
1816 mono_gchandle_free (o->handle);
1824 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1828 objrefs_cleanup (void)
1830 g_hash_table_destroy (objrefs);
1834 static GHashTable *obj_to_objref;
1835 static MonoGHashTable *suspended_objs;
1838 * Return an ObjRef for OBJ.
1841 get_objref (MonoObject *obj)
1844 GSList *reflist = NULL, *l;
1850 mono_loader_lock ();
1852 if (!obj_to_objref) {
1853 obj_to_objref = g_hash_table_new (NULL, NULL);
1854 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1855 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1858 if (suspend_count) {
1860 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1862 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1865 /* FIXME: The tables can grow indefinitely */
1867 if (mono_gc_is_moving ()) {
1869 * Objects can move, so use a hash table mapping hash codes to lists of
1870 * ObjRef structures.
1872 hash = mono_object_hash (obj);
1874 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1875 for (l = reflist; l; l = l->next) {
1877 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1878 mono_loader_unlock ();
1883 /* Use a hash table with masked pointers to internalize object references */
1884 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1885 /* ref might refer to a different object with the same addr which was GCd */
1886 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1887 mono_loader_unlock ();
1892 ref = g_new0 (ObjRef, 1);
1893 ref->id = InterlockedIncrement (&objref_id);
1894 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1896 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1898 if (mono_gc_is_moving ()) {
1899 reflist = g_slist_append (reflist, ref);
1900 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1902 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1905 mono_loader_unlock ();
1911 true_pred (gpointer key, gpointer value, gpointer user_data)
1917 clear_suspended_objs (void)
1919 mono_loader_lock ();
1920 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
1921 mono_loader_unlock ();
1925 get_objid (MonoObject *obj)
1927 return get_objref (obj)->id;
1931 * Set OBJ to the object identified by OBJID.
1932 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1936 get_object_allow_null (int objid, MonoObject **obj)
1946 return ERR_INVALID_OBJECT;
1948 mono_loader_lock ();
1950 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1953 *obj = mono_gchandle_get_target (ref->handle);
1954 mono_loader_unlock ();
1956 return ERR_INVALID_OBJECT;
1959 mono_loader_unlock ();
1960 return ERR_INVALID_OBJECT;
1965 get_object (int objid, MonoObject **obj)
1967 int err = get_object_allow_null (objid, obj);
1972 return ERR_INVALID_OBJECT;
1977 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1979 return decode_id (buf, endbuf, limit);
1983 buffer_add_objid (Buffer *buf, MonoObject *o)
1985 buffer_add_id (buf, get_objid (o));
2004 * Represents a runtime structure accessible to the debugger client
2007 /* Unique id used in the wire protocol */
2009 /* Domain of the runtime structure, NULL if the domain was unloaded */
2016 MonoAssembly *assembly;
2017 MonoClassField *field;
2019 MonoProperty *property;
2024 /* Maps runtime structure -> Id */
2025 GHashTable *val_to_id [ID_NUM];
2026 /* Classes whose class load event has been sent */
2027 GHashTable *loaded_classes;
2028 /* Maps MonoClass->GPtrArray of file names */
2029 GHashTable *source_files;
2030 /* Maps source file basename -> GSList of classes */
2031 GHashTable *source_file_to_class;
2032 /* Same with ignore-case */
2033 GHashTable *source_file_to_class_ignorecase;
2037 static GPtrArray *ids [ID_NUM];
2044 for (i = 0; i < ID_NUM; ++i)
2045 ids [i] = g_ptr_array_new ();
2053 for (i = 0; i < ID_NUM; ++i) {
2055 for (j = 0; j < ids [i]->len; ++j)
2056 g_free (g_ptr_array_index (ids [i], j));
2057 g_ptr_array_free (ids [i], TRUE);
2064 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2066 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2068 GHashTableIter iter;
2069 GPtrArray *file_names;
2074 for (i = 0; i < ID_NUM; ++i)
2075 if (info->val_to_id [i])
2076 g_hash_table_destroy (info->val_to_id [i]);
2077 g_hash_table_destroy (info->loaded_classes);
2079 g_hash_table_iter_init (&iter, info->source_files);
2080 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2081 for (i = 0; i < file_names->len; ++i)
2082 g_free (g_ptr_array_index (file_names, i));
2083 g_ptr_array_free (file_names, TRUE);
2086 g_hash_table_iter_init (&iter, info->source_file_to_class);
2087 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2092 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2093 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2101 domain_jit_info (domain)->agent_info = NULL;
2103 /* Clear ids referencing structures in the domain */
2104 for (i = 0; i < ID_NUM; ++i) {
2106 for (j = 0; j < ids [i]->len; ++j) {
2107 Id *id = g_ptr_array_index (ids [i], j);
2108 if (id->domain == domain)
2114 mono_loader_lock ();
2115 g_hash_table_remove (domains, domain);
2116 mono_loader_unlock ();
2119 static AgentDomainInfo*
2120 get_agent_domain_info (MonoDomain *domain)
2122 AgentDomainInfo *info = NULL;
2124 mono_domain_lock (domain);
2126 info = domain_jit_info (domain)->agent_info;
2128 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2129 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2130 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2131 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2132 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2135 mono_domain_unlock (domain);
2141 get_id (MonoDomain *domain, IdType type, gpointer val)
2144 AgentDomainInfo *info;
2149 mono_loader_lock ();
2151 mono_domain_lock (domain);
2153 info = get_agent_domain_info (domain);
2155 if (info->val_to_id [type] == NULL)
2156 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2158 id = g_hash_table_lookup (info->val_to_id [type], val);
2160 mono_domain_unlock (domain);
2161 mono_loader_unlock ();
2165 id = g_new0 (Id, 1);
2167 id->id = ids [type]->len + 1;
2168 id->domain = domain;
2171 g_hash_table_insert (info->val_to_id [type], val, id);
2173 mono_domain_unlock (domain);
2175 g_ptr_array_add (ids [type], id);
2177 mono_loader_unlock ();
2182 static inline gpointer
2183 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2187 int id = decode_id (buf, endbuf, limit);
2196 // FIXME: error handling
2197 mono_loader_lock ();
2198 g_assert (id > 0 && id <= ids [type]->len);
2200 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2201 mono_loader_unlock ();
2203 if (res->domain == NULL) {
2204 *err = ERR_UNLOADED;
2209 *domain = res->domain;
2211 return res->data.val;
2215 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2217 buffer_add_id (buf, get_id (domain, type, val));
2220 static inline MonoClass*
2221 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2225 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2226 if (G_UNLIKELY (log_level >= 2) && klass) {
2229 s = mono_type_full_name (&klass->byval_arg);
2230 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2236 static inline MonoAssembly*
2237 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2239 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2242 static inline MonoImage*
2243 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2245 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2248 static inline MonoMethod*
2249 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2253 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2254 if (G_UNLIKELY (log_level >= 2) && m) {
2257 s = mono_method_full_name (m, TRUE);
2258 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2264 static inline MonoClassField*
2265 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2267 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2270 static inline MonoDomain*
2271 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2273 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2276 static inline MonoProperty*
2277 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2279 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2283 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2285 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2286 if (G_UNLIKELY (log_level >= 2) && klass) {
2289 s = mono_type_full_name (&klass->byval_arg);
2290 if (GetCurrentThreadId () == debugger_thread_id)
2291 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2293 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2299 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2301 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2302 if (G_UNLIKELY (log_level >= 2) && method) {
2305 s = mono_method_full_name (method, 1);
2306 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2312 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2314 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2318 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2320 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2324 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2326 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2330 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2332 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2336 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2338 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2341 static void invoke_method (void);
2348 * save_thread_context:
2350 * Set CTX as the current threads context which is used for computing stack traces.
2351 * This function is signal-safe.
2354 save_thread_context (MonoContext *ctx)
2356 DebuggerTlsData *tls;
2358 tls = mono_native_tls_get_value (debugger_tls_id);
2362 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2364 mono_thread_state_init_from_current (&tls->context);
2367 /* Number of threads suspended */
2369 * If this is equal to the size of thread_to_tls, the runtime is considered
2372 static gint32 threads_suspend_count;
2374 static mono_mutex_t suspend_mutex;
2376 /* Cond variable used to wait for suspend_count becoming 0 */
2377 static mono_cond_t suspend_cond;
2379 /* Semaphore used to wait for a thread becoming suspended */
2380 static MonoSemType suspend_sem;
2385 mono_mutex_init (&suspend_mutex);
2386 mono_cond_init (&suspend_cond, NULL);
2387 MONO_SEM_INIT (&suspend_sem, 0);
2392 StackFrameInfo last_frame;
2393 gboolean last_frame_set;
2396 } GetLastFrameUserData;
2399 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2401 GetLastFrameUserData *data = user_data;
2403 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2406 if (!data->last_frame_set) {
2407 /* Store the last frame */
2408 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2409 data->last_frame_set = TRUE;
2412 /* Store the context/lmf for the frame above the last frame */
2413 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2414 data->lmf = info->lmf;
2422 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2423 * INFO is set, process the thread described by INFO.
2424 * This should be signal safe.
2427 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2431 MonoNativeThreadId tid;
2434 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2435 * guarantee the signal handler will be called that many times. Instead of tracking
2436 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2437 * has been requested that hasn't been handled yet, otherwise we can have threads
2438 * refuse to die when VM_EXIT is called
2440 #if defined(__APPLE__)
2441 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2445 * We use interrupt_count to determine whenever this interrupt should be processed
2446 * by us or the normal interrupt processing code in the signal handler.
2447 * There is no race here with notify_thread (), since the signal is sent after
2448 * incrementing interrupt_count.
2450 if (tls->interrupt_count == 0)
2453 InterlockedDecrement (&tls->interrupt_count);
2457 ip = mono_arch_ip_from_context (sigctx);
2459 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2464 tid = mono_thread_info_get_tid (info);
2466 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2468 // FIXME: Races when the thread leaves managed code before hitting a single step
2472 /* Running managed code, will be suspended by the single step code */
2473 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2477 * Running native code, will be suspended when it returns to/enters
2478 * managed code. Treat it as already suspended.
2479 * This might interrupt the code in process_single_step_inner (), we use the
2480 * tls->suspending flag to avoid races when that happens.
2482 if (!tls->suspended && !tls->suspending) {
2484 GetLastFrameUserData data;
2486 // FIXME: printf is not signal safe, but this is only used during
2487 // debugger debugging
2489 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2490 //save_thread_context (&ctx);
2493 /* Already terminated */
2497 * We are in a difficult position: we want to be able to provide stack
2498 * traces for this thread, but we can't use the current ctx+lmf, since
2499 * the thread is still running, so it might return to managed code,
2500 * making these invalid.
2501 * So we start a stack walk and save the first frame, along with the
2502 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2503 * suspended when it returns to managed code, so the parent's ctx should
2506 data.last_frame_set = FALSE;
2508 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2510 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2511 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2512 * since we are not in a JITted method.
2514 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2516 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2518 if (data.last_frame_set) {
2519 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2520 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2522 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2525 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2526 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2527 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2529 tls->async_state.valid = FALSE;
2532 mono_memory_barrier ();
2534 tls->suspended = TRUE;
2535 MONO_SEM_POST (&suspend_sem);
2542 * mono_debugger_agent_thread_interrupt:
2544 * Called by the abort signal handler.
2545 * Should be signal safe.
2548 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2550 DebuggerTlsData *tls;
2555 tls = mono_native_tls_get_value (debugger_tls_id);
2557 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2561 return thread_interrupt (tls, NULL, sigctx, ji);
2565 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2568 mono_debugger_agent_thread_interrupt (NULL, NULL);
2570 #endif /* HOST_WIN32 */
2573 * reset_native_thread_suspend_state:
2575 * Reset the suspended flag and state on native threads
2578 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2580 DebuggerTlsData *tls = value;
2582 if (!tls->really_suspended && tls->suspended) {
2583 tls->suspended = FALSE;
2585 * The thread might still be running if it was executing native code, so the state won't be invalided by
2586 * suspend_current ().
2588 tls->context.valid = FALSE;
2589 tls->async_state.valid = FALSE;
2590 invalidate_frames (tls);
2597 * Notify a thread that it needs to suspend.
2600 notify_thread (gpointer key, gpointer value, gpointer user_data)
2602 MonoInternalThread *thread = key;
2603 DebuggerTlsData *tls = value;
2604 gsize tid = thread->tid;
2607 if (GetCurrentThreadId () == tid || tls->terminated)
2610 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2613 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2614 * guarantee the signal handler will be called that many times. Instead of tracking
2615 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2616 * has been requested that hasn't been handled yet, otherwise we can have threads
2617 * refuse to die when VM_EXIT is called
2619 #if defined(__APPLE__)
2620 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2624 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2625 * of things like breaking waits etc. which we don't want.
2627 InterlockedIncrement (&tls->interrupt_count);
2630 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2632 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2634 if (mono_thread_info_new_interrupt_enabled ()) {
2635 MonoThreadInfo *info;
2638 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2640 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2642 * Attached thread which died without detaching.
2644 tls->terminated = TRUE;
2646 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2648 thread_interrupt (tls, info, NULL, ji);
2650 mono_thread_info_resume (mono_thread_info_get_tid (info));
2653 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2655 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2657 * Attached thread which died without detaching.
2659 tls->terminated = TRUE;
2666 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2668 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2672 if (mono_loader_lock_is_owned_by_self ()) {
2674 * Shortcut for the check in suspend_current (). This speeds up processing
2675 * when executing long running code inside the loader lock, i.e. assembly load
2681 if (debugger_thread_id == GetCurrentThreadId ())
2684 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2685 if (suspend_count - tls->resume_count > 0)
2686 tls->suspending = TRUE;
2688 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2690 if (suspend_count - tls->resume_count == 0) {
2692 * We are executing a single threaded invoke but the single step for
2693 * suspending is still active.
2694 * FIXME: This slows down single threaded invokes.
2696 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2700 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2702 /* Can't suspend in these methods */
2703 method = jinfo_get_method (ji);
2704 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2707 save_thread_context (ctx);
2715 * Increase the suspend count of the VM. While the suspend count is greater
2716 * than 0, runtime threads are suspended at certain points during execution.
2721 mono_loader_lock ();
2723 mono_mutex_lock (&suspend_mutex);
2727 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2729 if (suspend_count == 1) {
2730 // FIXME: Is it safe to call this inside the lock ?
2731 start_single_stepping ();
2732 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2735 mono_mutex_unlock (&suspend_mutex);
2737 if (suspend_count == 1)
2739 * Suspend creation of new threadpool threads, since they cannot run
2741 mono_thread_pool_suspend ();
2743 mono_loader_unlock ();
2749 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2757 g_assert (debugger_thread_id == GetCurrentThreadId ());
2759 mono_loader_lock ();
2761 mono_mutex_lock (&suspend_mutex);
2763 g_assert (suspend_count > 0);
2766 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2768 if (suspend_count == 0) {
2769 // FIXME: Is it safe to call this inside the lock ?
2770 stop_single_stepping ();
2771 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2774 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2775 err = mono_cond_broadcast (&suspend_cond);
2776 g_assert (err == 0);
2778 mono_mutex_unlock (&suspend_mutex);
2779 //g_assert (err == 0);
2781 if (suspend_count == 0)
2782 mono_thread_pool_resume ();
2784 mono_loader_unlock ();
2790 * Resume just one thread.
2793 resume_thread (MonoInternalThread *thread)
2796 DebuggerTlsData *tls;
2798 g_assert (debugger_thread_id == GetCurrentThreadId ());
2800 mono_loader_lock ();
2802 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2805 mono_mutex_lock (&suspend_mutex);
2807 g_assert (suspend_count > 0);
2809 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2811 tls->resume_count += suspend_count;
2814 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2815 * but only the one whose resume_count field is > 0 will be resumed.
2817 err = mono_cond_broadcast (&suspend_cond);
2818 g_assert (err == 0);
2820 mono_mutex_unlock (&suspend_mutex);
2821 //g_assert (err == 0);
2823 mono_loader_unlock ();
2827 invalidate_frames (DebuggerTlsData *tls)
2832 tls = mono_native_tls_get_value (debugger_tls_id);
2835 for (i = 0; i < tls->frame_count; ++i) {
2836 if (tls->frames [i]->jit)
2837 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2838 g_free (tls->frames [i]);
2840 g_free (tls->frames);
2841 tls->frame_count = 0;
2848 * Suspend the current thread until the runtime is resumed. If the thread has a
2849 * pending invoke, then the invoke is executed before this function returns.
2852 suspend_current (void)
2855 DebuggerTlsData *tls;
2857 g_assert (debugger_thread_id != GetCurrentThreadId ());
2859 if (mono_loader_lock_is_owned_by_self ()) {
2861 * If we own the loader mutex, can't suspend until we release it, since the
2862 * whole runtime can deadlock otherwise.
2867 tls = mono_native_tls_get_value (debugger_tls_id);
2870 mono_mutex_lock (&suspend_mutex);
2872 tls->suspending = FALSE;
2873 tls->really_suspended = TRUE;
2875 if (!tls->suspended) {
2876 tls->suspended = TRUE;
2877 MONO_SEM_POST (&suspend_sem);
2880 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2882 while (suspend_count - tls->resume_count > 0) {
2884 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2886 mono_mutex_unlock (&suspend_mutex);
2888 mono_mutex_lock (&suspend_mutex);
2894 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2895 g_assert (err == 0);
2899 tls->suspended = FALSE;
2900 tls->really_suspended = FALSE;
2902 threads_suspend_count --;
2904 mono_mutex_unlock (&suspend_mutex);
2906 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2908 if (tls->pending_invoke) {
2909 /* Save the original context */
2910 tls->pending_invoke->has_ctx = TRUE;
2911 tls->pending_invoke->ctx = tls->context.ctx;
2916 /* The frame info becomes invalid after a resume */
2917 tls->context.valid = FALSE;
2918 tls->async_state.valid = FALSE;
2919 invalidate_frames (tls);
2923 count_thread (gpointer key, gpointer value, gpointer user_data)
2925 DebuggerTlsData *tls = value;
2927 if (!tls->suspended && !tls->terminated)
2928 *(int*)user_data = *(int*)user_data + 1;
2932 count_threads_to_wait_for (void)
2936 mono_loader_lock ();
2937 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2938 mono_loader_unlock ();
2946 * Wait until the runtime is completely suspended.
2949 wait_for_suspend (void)
2951 int nthreads, nwait, err;
2952 gboolean waited = FALSE;
2954 // FIXME: Threads starting/stopping ?
2955 mono_loader_lock ();
2956 nthreads = mono_g_hash_table_size (thread_to_tls);
2957 mono_loader_unlock ();
2960 nwait = count_threads_to_wait_for ();
2962 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2963 err = MONO_SEM_WAIT (&suspend_sem);
2964 g_assert (err == 0);
2972 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2978 * Return whenever the runtime is suspended.
2983 return count_threads_to_wait_for () == 0;
2986 static MonoSeqPointInfo*
2987 get_seq_points (MonoDomain *domain, MonoMethod *method)
2989 MonoSeqPointInfo *seq_points;
2991 mono_domain_lock (domain);
2992 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2993 if (!seq_points && method->is_inflated) {
2994 /* generic sharing + aot */
2995 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2997 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2999 mono_domain_unlock (domain);
3005 no_seq_points_found (MonoMethod *method)
3008 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3010 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3014 * find_next_seq_point_for_native_offset:
3016 * Find the first sequence point after NATIVE_OFFSET.
3019 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3021 MonoSeqPointInfo *seq_points;
3024 seq_points = get_seq_points (domain, method);
3030 g_assert (seq_points);
3034 for (i = 0; i < seq_points->len; ++i) {
3035 if (seq_points->seq_points [i].native_offset >= native_offset)
3036 return &seq_points->seq_points [i];
3043 * find_prev_seq_point_for_native_offset:
3045 * Find the first sequence point before NATIVE_OFFSET.
3048 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3050 MonoSeqPointInfo *seq_points;
3053 seq_points = get_seq_points (domain, method);
3059 for (i = seq_points->len - 1; i >= 0; --i) {
3060 if (seq_points->seq_points [i].native_offset <= native_offset)
3061 return &seq_points->seq_points [i];
3070 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3071 * should be the location of a sequence point.
3073 static G_GNUC_UNUSED SeqPoint*
3074 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3076 MonoSeqPointInfo *seq_points;
3081 seq_points = get_seq_points (domain, method);
3086 for (i = 0; i < seq_points->len; ++i) {
3087 if (seq_points->seq_points [i].il_offset == il_offset)
3088 return &seq_points->seq_points [i];
3095 DebuggerTlsData *tls;
3097 } ComputeFramesUserData;
3100 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3102 ComputeFramesUserData *ud = user_data;
3104 MonoMethod *method, *actual_method, *api_method;
3108 if (info->type != FRAME_TYPE_MANAGED) {
3109 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3110 /* Mark the last frame as an invoke frame */
3112 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3118 method = jinfo_get_method (info->ji);
3120 method = info->method;
3121 actual_method = info->actual_method;
3122 api_method = method;
3127 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3130 if (info->il_offset == -1) {
3131 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3132 if (ud->frames == NULL) {
3133 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3135 info->il_offset = sp->il_offset;
3137 if (info->il_offset == -1)
3138 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3141 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));
3143 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3144 if (!CHECK_PROTOCOL_VERSION (2, 17))
3145 /* Older clients can't handle this flag */
3147 api_method = mono_marshal_method_from_wrapper (method);
3150 actual_method = api_method;
3151 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3154 frame = g_new0 (StackFrame, 1);
3155 frame->method = method;
3156 frame->actual_method = actual_method;
3157 frame->api_method = api_method;
3158 frame->il_offset = info->il_offset;
3159 frame->native_offset = info->native_offset;
3160 frame->flags = flags;
3161 frame->ji = info->ji;
3162 if (info->reg_locations)
3163 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3166 frame->has_ctx = TRUE;
3168 frame->domain = info->domain;
3170 ud->frames = g_slist_append (ud->frames, frame);
3176 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3178 ComputeFramesUserData *ud = user_data;
3181 * 'tls->filter_ctx' is the location of the throw site.
3183 * mono_walk_stack() will never actually hit the throw site, but unwind
3184 * directly from the filter to the call site; we abort stack unwinding here
3185 * once this happens and resume from the throw site.
3188 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3191 return process_frame (info, ctx, user_data);
3195 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3197 ComputeFramesUserData user_data;
3199 int i, findex, new_frame_count;
3200 StackFrame **new_frames, *f;
3201 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3203 // FIXME: Locking on tls
3204 if (tls->frames && tls->frames_up_to_date)
3207 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3209 user_data.tls = tls;
3210 user_data.frames = NULL;
3211 if (tls->terminated) {
3212 tls->frame_count = 0;
3214 } if (!tls->really_suspended && tls->async_state.valid) {
3215 /* Have to use the state saved by the signal handler */
3216 process_frame (&tls->async_last_frame, NULL, &user_data);
3217 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3218 } else if (tls->filter_state.valid) {
3220 * We are inside an exception filter.
3222 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3224 if (tls->context.valid)
3225 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3227 * After that, we resume unwinding from the location where the exception has been thrown.
3229 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3230 } else if (tls->context.valid) {
3231 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3234 tls->frame_count = 0;
3238 new_frame_count = g_slist_length (user_data.frames);
3239 new_frames = g_new0 (StackFrame*, new_frame_count);
3241 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3245 * Reuse the id for already existing stack frames, so invokes don't invalidate
3246 * the still valid stack frames.
3248 for (i = 0; i < tls->frame_count; ++i) {
3249 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3250 f->id = tls->frames [i]->id;
3255 if (i >= tls->frame_count)
3256 f->id = InterlockedIncrement (&frame_id);
3258 new_frames [findex ++] = f;
3261 g_slist_free (user_data.frames);
3263 invalidate_frames (tls);
3265 tls->frames = new_frames;
3266 tls->frame_count = new_frame_count;
3267 tls->frames_up_to_date = TRUE;
3271 * GHFunc to emit an appdomain creation event
3272 * @param key Don't care
3273 * @param value A loaded appdomain
3274 * @param user_data Don't care
3277 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3279 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3280 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3284 * GHFunc to emit a thread start event
3285 * @param key A thread id
3286 * @param value A thread object
3287 * @param user_data Don't care
3290 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3292 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3293 process_profiler_event (EVENT_KIND_THREAD_START, value);
3297 * GFunc to emit an assembly load event
3298 * @param value A loaded assembly
3299 * @param user_data Don't care
3302 emit_assembly_load (gpointer value, gpointer user_data)
3304 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3308 * GFunc to emit a type load event
3309 * @param value A loaded type
3310 * @param user_data Don't care
3313 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3315 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3319 strdup_tolower (char *s)
3324 for (p = s2; *p; ++p)
3334 * create_event_list:
3336 * Return a list of event request ids matching EVENT, starting from REQS, which
3337 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3339 * We return request ids, instead of requests, to simplify threading, since
3340 * requests could be deleted anytime when the loader lock is not held.
3341 * LOCKING: Assumes the loader lock is held.
3344 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3347 GSList *events = NULL;
3349 *suspend_policy = SUSPEND_POLICY_NONE;
3352 reqs = event_requests;
3357 for (i = 0; i < reqs->len; ++i) {
3358 EventRequest *req = g_ptr_array_index (reqs, i);
3359 if (req->event_kind == event) {
3360 gboolean filtered = FALSE;
3363 for (j = 0; j < req->nmodifiers; ++j) {
3364 Modifier *mod = &req->modifiers [j];
3366 if (mod->kind == MOD_KIND_COUNT) {
3368 if (mod->data.count > 0) {
3369 if (mod->data.count > 0) {
3371 if (mod->data.count == 0)
3375 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3376 if (mod->data.thread != mono_thread_internal_current ())
3378 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3379 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3381 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3383 if (ei->caught && !mod->caught)
3385 if (!ei->caught && !mod->uncaught)
3387 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3389 gboolean found = FALSE;
3390 MonoAssembly **assemblies = mod->data.assemblies;
3393 for (k = 0; assemblies [k]; ++k)
3394 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3399 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3400 gpointer iter = NULL;
3402 MonoDebugSourceInfo *sinfo;
3403 char *source_file, *s;
3404 gboolean found = FALSE;
3406 GPtrArray *source_file_list;
3408 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3409 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3412 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3413 for (i = 0; i < source_file_list->len; ++i) {
3414 sinfo = g_ptr_array_index (source_file_list, i);
3416 * Do a case-insesitive match by converting the file name to
3419 s = strdup_tolower (sinfo->source_file);
3420 if (g_hash_table_lookup (mod->data.source_files, s))
3423 char *s2 = g_path_get_basename (sinfo->source_file);
3424 char *s3 = strdup_tolower (s2);
3426 if (g_hash_table_lookup (mod->data.source_files, s3))
3433 g_ptr_array_free (source_file_list, TRUE);
3438 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3441 s = mono_type_full_name (&ei->klass->byval_arg);
3442 if (!g_hash_table_lookup (mod->data.type_names, s))
3445 } else if (mod->kind == MOD_KIND_STEP) {
3446 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3447 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3448 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3450 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3451 MonoCustomAttrInfo *ainfo;
3452 static MonoClass *klass;
3455 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3458 if (!ji->dbg_hidden_inited) {
3459 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3461 if (mono_custom_attrs_has_attr (ainfo, klass))
3462 ji->dbg_hidden = TRUE;
3463 mono_custom_attrs_free (ainfo);
3465 ji->dbg_hidden_inited = TRUE;
3470 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3471 MonoCustomAttrInfo *ainfo;
3472 static MonoClass *klass;
3475 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3478 if (!ji->dbg_step_through_inited) {
3479 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3481 if (mono_custom_attrs_has_attr (ainfo, klass))
3482 ji->dbg_step_through = TRUE;
3483 mono_custom_attrs_free (ainfo);
3485 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3487 if (mono_custom_attrs_has_attr (ainfo, klass))
3488 ji->dbg_step_through = TRUE;
3489 mono_custom_attrs_free (ainfo);
3491 ji->dbg_step_through_inited = TRUE;
3493 if (ji->dbg_step_through)
3500 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3501 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3506 /* Send a VM START/DEATH event by default */
3507 if (event == EVENT_KIND_VM_START)
3508 events = g_slist_append (events, GINT_TO_POINTER (0));
3509 if (event == EVENT_KIND_VM_DEATH)
3510 events = g_slist_append (events, GINT_TO_POINTER (0));
3515 static G_GNUC_UNUSED const char*
3516 event_to_string (EventKind event)
3519 case EVENT_KIND_VM_START: return "VM_START";
3520 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3521 case EVENT_KIND_THREAD_START: return "THREAD_START";
3522 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3523 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3524 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3525 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3526 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3527 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3528 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3529 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3530 case EVENT_KIND_STEP: return "STEP";
3531 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3532 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3533 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3534 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3535 case EVENT_KIND_USER_LOG: return "USER_LOG";
3537 g_assert_not_reached ();
3545 * Send an event to the client, suspending the vm if needed.
3546 * LOCKING: Since this can suspend the calling thread, no locks should be held
3548 * The EVENTS list is freed by this function.
3551 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3555 MonoDomain *domain = mono_domain_get ();
3556 MonoThread *thread = NULL;
3557 MonoObject *keepalive_obj = NULL;
3558 gboolean send_success = FALSE;
3563 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3567 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3568 // FIXME: We miss those events
3569 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3573 if (vm_death_event_sent) {
3574 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3578 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3579 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3584 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3588 if (event == EVENT_KIND_KEEPALIVE)
3589 suspend_policy = SUSPEND_POLICY_NONE;
3594 if (agent_config.defer) {
3595 /* Make sure the thread id is always set when doing deferred debugging */
3596 if (debugger_thread_id == GetCurrentThreadId ()) {
3597 /* Don't suspend on events from the debugger thread */
3598 suspend_policy = SUSPEND_POLICY_NONE;
3599 thread = mono_thread_get_main ();
3601 else thread = mono_thread_current ();
3603 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3604 // FIXME: Send these with a NULL thread, don't suspend the current thread
3609 nevents = g_slist_length (events);
3610 buffer_init (&buf, 128);
3611 buffer_add_byte (&buf, suspend_policy);
3612 buffer_add_int (&buf, nevents);
3614 for (l = events; l; l = l->next) {
3615 buffer_add_byte (&buf, event); // event kind
3616 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3621 thread = mono_thread_current ();
3623 if (event == EVENT_KIND_VM_START && arg != NULL)
3626 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3629 case EVENT_KIND_THREAD_START:
3630 case EVENT_KIND_THREAD_DEATH:
3632 case EVENT_KIND_APPDOMAIN_CREATE:
3633 case EVENT_KIND_APPDOMAIN_UNLOAD:
3634 buffer_add_domainid (&buf, arg);
3636 case EVENT_KIND_METHOD_ENTRY:
3637 case EVENT_KIND_METHOD_EXIT:
3638 buffer_add_methodid (&buf, domain, arg);
3640 case EVENT_KIND_ASSEMBLY_LOAD:
3641 case EVENT_KIND_ASSEMBLY_UNLOAD:
3642 buffer_add_assemblyid (&buf, domain, arg);
3644 case EVENT_KIND_TYPE_LOAD:
3645 buffer_add_typeid (&buf, domain, arg);
3647 case EVENT_KIND_BREAKPOINT:
3648 case EVENT_KIND_STEP:
3649 buffer_add_methodid (&buf, domain, arg);
3650 buffer_add_long (&buf, il_offset);
3652 case EVENT_KIND_VM_START:
3653 buffer_add_domainid (&buf, mono_get_root_domain ());
3655 case EVENT_KIND_VM_DEATH:
3656 if (CHECK_PROTOCOL_VERSION (2, 27))
3657 buffer_add_int (&buf, mono_environment_exitcode_get ());
3659 case EVENT_KIND_EXCEPTION: {
3660 EventInfo *ei = arg;
3661 buffer_add_objid (&buf, ei->exc);
3663 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3664 * later after the suspension. (#12494).
3666 keepalive_obj = ei->exc;
3669 case EVENT_KIND_USER_BREAK:
3671 case EVENT_KIND_USER_LOG: {
3672 EventInfo *ei = arg;
3673 buffer_add_int (&buf, ei->level);
3674 buffer_add_string (&buf, ei->category ? ei->category : "");
3675 buffer_add_string (&buf, ei->message ? ei->message : "");
3678 case EVENT_KIND_KEEPALIVE:
3679 suspend_policy = SUSPEND_POLICY_NONE;
3682 g_assert_not_reached ();
3686 if (event == EVENT_KIND_VM_START) {
3687 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3688 if (!agent_config.defer)
3689 start_debugger_thread ();
3692 if (event == EVENT_KIND_VM_DEATH) {
3693 vm_death_event_sent = TRUE;
3694 suspend_policy = SUSPEND_POLICY_NONE;
3697 if (mono_runtime_is_shutting_down ())
3698 suspend_policy = SUSPEND_POLICY_NONE;
3700 if (suspend_policy != SUSPEND_POLICY_NONE) {
3702 * Save the thread context and start suspending before sending the packet,
3703 * since we could be receiving the resume request before send_packet ()
3706 save_thread_context (ctx);
3710 /* This will keep this object alive */
3711 get_objref (keepalive_obj);
3714 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3718 g_slist_free (events);
3721 if (!send_success) {
3722 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3726 if (event == EVENT_KIND_VM_START) {
3727 vm_start_event_sent = TRUE;
3730 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3732 switch (suspend_policy) {
3733 case SUSPEND_POLICY_NONE:
3735 case SUSPEND_POLICY_ALL:
3738 case SUSPEND_POLICY_EVENT_THREAD:
3742 g_assert_not_reached ();
3747 process_profiler_event (EventKind event, gpointer arg)
3751 EventInfo ei, *ei_arg = NULL;
3753 if (event == EVENT_KIND_TYPE_LOAD) {
3758 mono_loader_lock ();
3759 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3760 mono_loader_unlock ();
3762 process_event (event, arg, 0, NULL, events, suspend_policy);
3766 runtime_initialized (MonoProfiler *prof)
3768 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3769 if (agent_config.defer)
3770 start_debugger_thread ();
3774 runtime_shutdown (MonoProfiler *prof)
3776 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3778 mono_debugger_agent_cleanup ();
3782 thread_startup (MonoProfiler *prof, uintptr_t tid)
3784 MonoInternalThread *thread = mono_thread_internal_current ();
3785 MonoInternalThread *old_thread;
3786 DebuggerTlsData *tls;
3788 if (tid == debugger_thread_id)
3791 g_assert (thread->tid == tid);
3793 mono_loader_lock ();
3794 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3795 mono_loader_unlock ();
3797 if (thread == old_thread) {
3799 * For some reason, thread_startup () might be called for the same thread
3800 * multiple times (attach ?).
3802 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3806 * thread_end () might not be called for some threads, and the tid could
3809 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3810 mono_loader_lock ();
3811 mono_g_hash_table_remove (thread_to_tls, old_thread);
3812 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3813 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3814 mono_loader_unlock ();
3818 tls = mono_native_tls_get_value (debugger_tls_id);
3820 // FIXME: Free this somewhere
3821 tls = g_new0 (DebuggerTlsData, 1);
3822 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3823 tls->thread = thread;
3824 mono_native_tls_set_value (debugger_tls_id, tls);
3826 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3828 mono_loader_lock ();
3829 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3830 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3831 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3832 mono_loader_unlock ();
3834 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3837 * suspend_vm () could have missed this thread, so wait for a resume.
3843 thread_end (MonoProfiler *prof, uintptr_t tid)
3845 MonoInternalThread *thread;
3846 DebuggerTlsData *tls = NULL;
3848 mono_loader_lock ();
3849 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3851 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3852 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3854 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3855 tls->terminated = TRUE;
3856 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3857 MONO_GC_UNREGISTER_ROOT (tls->thread);
3861 mono_loader_unlock ();
3863 /* We might be called for threads started before we registered the start callback */
3865 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3866 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3871 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3873 mono_loader_lock ();
3874 g_hash_table_insert (domains, domain, domain);
3875 mono_loader_unlock ();
3877 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3881 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3883 clear_breakpoints_for_domain (domain);
3885 mono_loader_lock ();
3886 /* Invalidate each thread's frame stack */
3887 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3888 mono_loader_unlock ();
3890 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3894 * invalidate_each_thread:
3896 * A GHFunc to invalidate frames.
3897 * value must be a DebuggerTlsData*
3900 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3902 invalidate_frames (value);
3906 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3908 /* Sent later in jit_end () */
3909 mono_loader_lock ();
3910 g_ptr_array_add (pending_assembly_loads, assembly);
3911 mono_loader_unlock ();
3915 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3917 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3919 clear_event_requests_for_assembly (assembly);
3920 clear_types_for_assembly (assembly);
3924 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3926 #if defined(HOST_WIN32) && !defined(__GNUC__)
3927 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3929 gpointer stackptr = __builtin_frame_address (1);
3931 MonoInternalThread *thread = mono_thread_internal_current ();
3932 DebuggerTlsData *tls;
3934 mono_loader_lock ();
3936 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3937 /* Could be the debugger thread with assembly/type load hooks */
3939 tls->invoke_addr = stackptr;
3941 mono_loader_unlock ();
3945 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3948 #if defined(HOST_WIN32) && !defined(__GNUC__)
3949 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3951 gpointer stackptr = __builtin_frame_address (1);
3954 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3958 * We need to stop single stepping when exiting a runtime invoke, since if it is
3959 * a step out, it may return to native code, and thus never end.
3961 mono_loader_lock ();
3962 ss_invoke_addr = NULL;
3964 for (i = 0; i < event_requests->len; ++i) {
3965 EventRequest *req = g_ptr_array_index (event_requests, i);
3967 if (req->event_kind == EVENT_KIND_STEP) {
3968 ss_destroy (req->info);
3969 g_ptr_array_remove_index_fast (event_requests, i);
3974 mono_loader_unlock ();
3978 send_type_load (MonoClass *klass)
3980 gboolean type_load = FALSE;
3981 MonoDomain *domain = mono_domain_get ();
3982 AgentDomainInfo *info = NULL;
3984 mono_loader_lock ();
3985 mono_domain_lock (domain);
3987 info = get_agent_domain_info (domain);
3989 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3991 g_hash_table_insert (info->loaded_classes, klass, klass);
3994 mono_domain_unlock (domain);
3995 mono_loader_unlock ();
3997 emit_type_load (klass, klass, NULL);
4001 * Emit load events for all types currently loaded in the domain.
4002 * Takes the loader and domain locks.
4003 * user_data is unused.
4006 send_types_for_domain (MonoDomain *domain, void *user_data)
4008 AgentDomainInfo *info = NULL;
4010 mono_loader_lock ();
4011 mono_domain_lock (domain);
4012 info = get_agent_domain_info (domain);
4014 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4015 mono_domain_unlock (domain);
4016 mono_loader_unlock ();
4020 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4023 * We emit type load events when the first method of the type is JITted,
4024 * since the class load profiler callbacks might be called with the
4025 * loader lock held. They could also occur in the debugger thread.
4026 * Same for assembly load events.
4029 MonoAssembly *assembly = NULL;
4031 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4032 mono_loader_lock ();
4033 if (pending_assembly_loads->len > 0) {
4034 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4035 g_ptr_array_remove_index (pending_assembly_loads, 0);
4037 mono_loader_unlock ();
4040 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4046 send_type_load (method->klass);
4049 add_pending_breakpoints (method, jinfo);
4053 * BREAKPOINTS/SINGLE STEPPING
4057 * Contains information about an inserted breakpoint.
4060 long il_offset, native_offset;
4065 } BreakpointInstance;
4068 * Contains generic information about a breakpoint.
4072 * The method where the breakpoint is placed. Can be NULL in which case it
4073 * is inserted into every method. This is used to implement method entry/
4074 * exit events. Can be a generic method definition, in which case the
4075 * breakpoint is inserted into every instance.
4081 * A list of BreakpointInstance structures describing where the breakpoint
4082 * was inserted. There could be more than one because of
4083 * generics/appdomains/method entry/exit.
4085 GPtrArray *children;
4088 /* List of breakpoints */
4089 static GPtrArray *breakpoints;
4090 /* Maps breakpoint locations to the number of breakpoints at that location */
4091 static GHashTable *bp_locs;
4094 breakpoints_init (void)
4096 breakpoints = g_ptr_array_new ();
4097 bp_locs = g_hash_table_new (NULL, NULL);
4101 * insert_breakpoint:
4103 * Insert the breakpoint described by BP into the method described by
4107 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4110 BreakpointInstance *inst;
4111 SeqPoint *sp = NULL;
4114 mono_error_init (error);
4116 for (i = 0; i < seq_points->len; ++i) {
4117 sp = &seq_points->seq_points [i];
4119 if (sp->il_offset == bp->il_offset)
4123 if (i == seq_points->len) {
4125 * The set of IL offsets with seq points doesn't completely match the
4126 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4128 for (i = 0; i < seq_points->len; ++i) {
4129 sp = &seq_points->seq_points [i];
4131 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4136 if (i == seq_points->len) {
4137 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);
4139 for (i = 0; i < seq_points->len; ++i)
4140 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4143 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4144 g_warning ("%s", s);
4148 g_warning ("%s", s);
4154 inst = g_new0 (BreakpointInstance, 1);
4156 inst->native_offset = sp->native_offset;
4157 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4159 inst->domain = domain;
4161 mono_loader_lock ();
4163 g_ptr_array_add (bp->children, inst);
4165 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4166 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4167 mono_loader_unlock ();
4169 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4170 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4171 } else if (count == 0) {
4172 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4173 mono_arch_set_breakpoint (ji, inst->ip);
4179 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));
4183 remove_breakpoint (BreakpointInstance *inst)
4185 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4187 MonoJitInfo *ji = inst->ji;
4188 guint8 *ip = inst->ip;
4190 mono_loader_lock ();
4191 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4192 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4193 mono_loader_unlock ();
4195 g_assert (count > 0);
4197 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4198 mono_arch_clear_breakpoint (ji, ip);
4205 static inline gboolean
4206 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4212 if (method == bp->method)
4214 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4217 if (bp->method->is_inflated && method->is_inflated) {
4218 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4219 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4221 /* Open generic methods should match closed generic methods of the same class */
4222 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4223 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4224 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4226 /* FIXME: Handle !mvar */
4227 if (t1->type != MONO_TYPE_MVAR)
4238 * add_pending_breakpoints:
4240 * Insert pending breakpoints into the newly JITted method METHOD.
4243 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4246 MonoSeqPointInfo *seq_points;
4248 MonoMethod *jmethod;
4253 domain = mono_domain_get ();
4255 mono_loader_lock ();
4257 for (i = 0; i < breakpoints->len; ++i) {
4258 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4259 gboolean found = FALSE;
4261 if (!bp_matches_method (bp, method))
4264 for (j = 0; j < bp->children->len; ++j) {
4265 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4272 jmethod = jinfo_get_method (ji);
4273 mono_domain_lock (domain);
4274 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4275 if (!seq_points && jmethod->is_inflated)
4276 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4277 mono_domain_unlock (domain);
4279 /* Could be AOT code */
4281 g_assert (seq_points);
4283 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4287 mono_loader_unlock ();
4291 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4297 mono_error_init (error);
4299 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4301 /* Might be AOTed code */
4302 code = mono_aot_get_method (domain, method);
4304 ji = mono_jit_info_table_find (domain, code);
4309 insert_breakpoint (seq_points, domain, ji, bp, error);
4313 clear_breakpoint (MonoBreakpoint *bp);
4318 * Set a breakpoint at IL_OFFSET in METHOD.
4319 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4320 * METHOD can also be a generic method definition, in which case a breakpoint
4321 * is placed in all instances of the method.
4322 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4325 static MonoBreakpoint*
4326 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4329 GHashTableIter iter, iter2;
4332 MonoSeqPointInfo *seq_points;
4335 mono_error_init (error);
4338 // - suspend/resume the vm to prevent code patching problems
4339 // - multiple breakpoints on the same location
4340 // - dynamic methods
4343 bp = g_new0 (MonoBreakpoint, 1);
4344 bp->method = method;
4345 bp->il_offset = il_offset;
4347 bp->children = g_ptr_array_new ();
4349 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));
4351 mono_loader_lock ();
4353 g_hash_table_iter_init (&iter, domains);
4354 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4355 mono_domain_lock (domain);
4357 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4358 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4359 if (bp_matches_method (bp, m))
4360 set_bp_in_method (domain, m, seq_points, bp, error);
4363 mono_domain_unlock (domain);
4366 mono_loader_unlock ();
4368 mono_loader_lock ();
4369 g_ptr_array_add (breakpoints, bp);
4370 mono_loader_unlock ();
4372 if (error && !mono_error_ok (error)) {
4373 clear_breakpoint (bp);
4381 clear_breakpoint (MonoBreakpoint *bp)
4385 // FIXME: locking, races
4386 for (i = 0; i < bp->children->len; ++i) {
4387 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4389 remove_breakpoint (inst);
4394 mono_loader_lock ();
4395 g_ptr_array_remove (breakpoints, bp);
4396 mono_loader_unlock ();
4398 g_ptr_array_free (bp->children, TRUE);
4403 breakpoints_cleanup (void)
4407 mono_loader_lock ();
4409 while (i < event_requests->len) {
4410 EventRequest *req = g_ptr_array_index (event_requests, i);
4412 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4413 clear_breakpoint (req->info);
4414 g_ptr_array_remove_index_fast (event_requests, i);
4421 for (i = 0; i < breakpoints->len; ++i)
4422 g_free (g_ptr_array_index (breakpoints, i));
4424 g_ptr_array_free (breakpoints, TRUE);
4425 g_hash_table_destroy (bp_locs);
4430 mono_loader_unlock ();
4434 * clear_breakpoints_for_domain:
4436 * Clear breakpoint instances which reference DOMAIN.
4439 clear_breakpoints_for_domain (MonoDomain *domain)
4443 /* This could be called after shutdown */
4447 mono_loader_lock ();
4448 for (i = 0; i < breakpoints->len; ++i) {
4449 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4452 while (j < bp->children->len) {
4453 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4455 if (inst->domain == domain) {
4456 remove_breakpoint (inst);
4460 g_ptr_array_remove_index_fast (bp->children, j);
4466 mono_loader_unlock ();
4472 * Return FALSE if single stepping needs to continue.
4475 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4477 MonoDebugMethodInfo *minfo;
4478 MonoDebugSourceLocation *loc = NULL;
4479 gboolean hit = TRUE;
4482 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4484 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4486 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4490 if (req->depth == STEP_DEPTH_OVER && hit) {
4491 if (!tls->context.valid)
4492 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4493 compute_frame_info (tls->thread, tls);
4494 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4495 /* Hit the breakpoint in a recursive call */
4496 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4501 if (req->size != STEP_SIZE_LINE)
4504 /* Have to check whenever a different source line was reached */
4505 method = jinfo_get_method (ji);
4506 minfo = mono_debug_lookup_method (method);
4509 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4511 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4512 /* Have to continue single stepping */
4514 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4516 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4521 ss_req->last_method = method;
4522 ss_req->last_line = loc->row;
4523 mono_debug_free_source_location (loc);
4530 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4532 return bp->method && bp->method->klass->image->assembly == assembly;
4536 process_breakpoint_inner (DebuggerTlsData *tls)
4540 int i, j, suspend_policy;
4541 guint32 native_offset;
4543 BreakpointInstance *inst;
4544 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4545 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4546 EventKind kind = EVENT_KIND_BREAKPOINT;
4547 MonoContext *ctx = &tls->restore_ctx;
4549 MonoSeqPointInfo *info;
4552 // FIXME: Speed this up
4554 ip = MONO_CONTEXT_GET_IP (ctx);
4555 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4557 method = jinfo_get_method (ji);
4559 /* Compute the native offset of the breakpoint from the ip */
4560 native_offset = ip - (guint8*)ji->code_start;
4563 * Skip the instruction causing the breakpoint signal.
4565 mono_arch_skip_breakpoint (ctx, ji);
4567 if (method->wrapper_type || tls->disable_breakpoints)
4570 bp_reqs = g_ptr_array_new ();
4571 ss_reqs = g_ptr_array_new ();
4572 ss_reqs_orig = g_ptr_array_new ();
4574 mono_loader_lock ();
4577 * The ip points to the instruction causing the breakpoint event, which is after
4578 * the offset recorded in the seq point map, so find the prev seq point before ip.
4580 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4582 no_seq_points_found (method);
4585 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));
4588 for (i = 0; i < breakpoints->len; ++i) {
4589 bp = g_ptr_array_index (breakpoints, i);
4594 for (j = 0; j < bp->children->len; ++j) {
4595 inst = g_ptr_array_index (bp->children, j);
4596 if (inst->ji == ji && inst->sp == sp) {
4597 if (bp->req->event_kind == EVENT_KIND_STEP) {
4598 g_ptr_array_add (ss_reqs_orig, bp->req);
4600 g_ptr_array_add (bp_reqs, bp->req);
4605 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4606 /* Maybe a method entry/exit event */
4607 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4608 kind = EVENT_KIND_METHOD_ENTRY;
4609 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4610 kind = EVENT_KIND_METHOD_EXIT;
4613 /* Process single step requests */
4614 for (i = 0; i < ss_reqs_orig->len; ++i) {
4615 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4616 SingleStepReq *ss_req = req->info;
4619 if (mono_thread_internal_current () != ss_req->thread)
4622 hit = ss_update (ss_req, ji, sp, tls, ctx);
4624 g_ptr_array_add (ss_reqs, req);
4626 /* Start single stepping again from the current sequence point */
4627 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4630 if (ss_reqs->len > 0)
4631 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4632 if (bp_reqs->len > 0)
4633 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4634 if (kind != EVENT_KIND_BREAKPOINT)
4635 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4637 mono_loader_unlock ();
4639 g_ptr_array_free (bp_reqs, TRUE);
4640 g_ptr_array_free (ss_reqs, TRUE);
4643 * FIXME: The first event will suspend, so the second will only be sent after the
4647 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4649 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4650 if (enter_leave_events)
4651 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4654 /* Process a breakpoint/single step event after resuming from a signal handler */
4656 process_signal_event (void (*func) (DebuggerTlsData*))
4658 DebuggerTlsData *tls;
4659 MonoContext orig_restore_ctx, ctx;
4661 tls = mono_native_tls_get_value (debugger_tls_id);
4662 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4663 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4664 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4668 /* This is called when resuming from a signal handler, so it shouldn't return */
4669 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4670 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4671 mono_restore_context (&ctx);
4672 g_assert_not_reached ();
4676 process_breakpoint (void)
4678 process_signal_event (process_breakpoint_inner);
4682 resume_from_signal_handler (void *sigctx, void *func)
4684 DebuggerTlsData *tls;
4687 /* Save the original context in TLS */
4688 // FIXME: This might not work on an altstack ?
4689 tls = mono_native_tls_get_value (debugger_tls_id);
4691 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4694 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4695 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4696 // clob:c could be added to op_seq_point.
4698 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4699 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4700 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4701 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4703 MONO_CONTEXT_SET_IP (&ctx, func);
4705 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4707 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4708 mono_ppc_set_func_into_sigctx (sigctx, func);
4713 mono_debugger_agent_breakpoint_hit (void *sigctx)
4716 * We are called from a signal handler, and running code there causes all kinds of
4717 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4718 * So set up the signal context to return to the real breakpoint handler function.
4720 resume_from_signal_handler (sigctx, process_breakpoint);
4724 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4726 if (frame->managed) {
4727 *(MonoContext*)data = *ctx;
4736 * Called by System.Diagnostics.Debugger:Break ().
4739 mono_debugger_agent_user_break (void)
4741 if (agent_config.enabled) {
4746 /* Obtain a context */
4747 MONO_CONTEXT_SET_IP (&ctx, NULL);
4748 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4749 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4751 mono_loader_lock ();
4752 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4753 mono_loader_unlock ();
4755 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4762 ss_depth_to_string (StepDepth depth)
4765 case STEP_DEPTH_OVER:
4767 case STEP_DEPTH_OUT:
4769 case STEP_DEPTH_INTO:
4772 g_assert_not_reached ();
4778 process_single_step_inner (DebuggerTlsData *tls)
4783 int il_offset, suspend_policy;
4786 MonoContext *ctx = &tls->restore_ctx;
4789 MonoSeqPointInfo *info;
4791 ip = MONO_CONTEXT_GET_IP (ctx);
4793 /* Skip the instruction causing the single step */
4794 mono_arch_skip_single_step (ctx);
4796 if (suspend_count > 0) {
4797 process_suspend (tls, ctx);
4802 // FIXME: A suspend race
4805 if (mono_thread_internal_current () != ss_req->thread)
4808 if (log_level > 0) {
4809 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4811 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));
4814 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4816 method = jinfo_get_method (ji);
4819 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4824 * Stopping in memset makes half-initialized vtypes visible.
4825 * Stopping in memcpy makes half-copied vtypes visible.
4827 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4831 * The ip points to the instruction causing the single step event, which is before
4832 * the offset recorded in the seq point map, so find the next seq point after ip.
4834 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
4837 il_offset = sp->il_offset;
4839 if (!ss_update (ss_req, ji, sp, tls, ctx))
4842 /* Start single stepping again from the current sequence point */
4843 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4845 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4846 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4847 !strcmp (method->name, ".cctor"))
4850 // FIXME: Has to lock earlier
4852 reqs = g_ptr_array_new ();
4854 mono_loader_lock ();
4856 g_ptr_array_add (reqs, ss_req->req);
4858 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4860 g_ptr_array_free (reqs, TRUE);
4862 mono_loader_unlock ();
4864 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4868 process_single_step (void)
4870 process_signal_event (process_single_step_inner);
4874 * mono_debugger_agent_single_step_event:
4876 * Called from a signal handler to handle a single step event.
4879 mono_debugger_agent_single_step_event (void *sigctx)
4881 /* Resume to process_single_step through the signal context */
4883 // FIXME: Since step out/over is implemented using step in, the step in case should
4884 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4887 if (GetCurrentThreadId () == debugger_thread_id) {
4889 * This could happen despite our best effors when the runtime calls
4890 * assembly/type resolve hooks.
4891 * FIXME: Breakpoints too.
4895 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4896 mono_arch_skip_single_step (&ctx);
4897 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4901 resume_from_signal_handler (sigctx, process_single_step);
4905 debugger_agent_single_step_from_context (MonoContext *ctx)
4907 DebuggerTlsData *tls;
4908 MonoContext orig_restore_ctx;
4910 tls = mono_native_tls_get_value (debugger_tls_id);
4913 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4914 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4915 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4917 process_single_step_inner (tls);
4919 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4920 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4924 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4926 DebuggerTlsData *tls;
4927 MonoContext orig_restore_ctx;
4929 tls = mono_native_tls_get_value (debugger_tls_id);
4931 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4932 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4934 process_breakpoint_inner (tls);
4936 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4937 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4941 * start_single_stepping:
4943 * Turn on single stepping. Can be called multiple times, for example,
4944 * by a single step event request + a suspend.
4947 start_single_stepping (void)
4949 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4950 int val = InterlockedIncrement (&ss_count);
4953 mono_arch_start_single_stepping ();
4955 if (ss_req != NULL && ss_invoke_addr == NULL) {
4956 DebuggerTlsData *tls;
4958 mono_loader_lock ();
4960 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4961 ss_invoke_addr = tls->invoke_addr;
4963 mono_loader_unlock ();
4966 g_assert_not_reached ();
4971 stop_single_stepping (void)
4973 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4974 int val = InterlockedDecrement (&ss_count);
4977 mono_arch_stop_single_stepping ();
4979 ss_invoke_addr = NULL;
4981 g_assert_not_reached ();
4988 * Stop the single stepping operation given by SS_REQ.
4991 ss_stop (SingleStepReq *ss_req)
4996 for (l = ss_req->bps; l; l = l->next) {
4997 clear_breakpoint (l->data);
4999 g_slist_free (ss_req->bps);
5003 if (ss_req->global) {
5004 stop_single_stepping ();
5005 ss_req->global = FALSE;
5012 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5013 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5014 * belong to the same thread as CTX.
5017 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5019 int i, j, frame_index;
5022 gboolean enable_global = FALSE;
5024 /* Stop the previous operation */
5028 * Implement single stepping using breakpoints if possible.
5030 if (step_to_catch) {
5031 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5032 ss_req->bps = g_slist_append (ss_req->bps, bp);
5036 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5037 /* Need parent frames */
5038 if (!tls->context.valid)
5039 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5040 compute_frame_info (tls->thread, tls);
5044 * Find the first sequence point in the current or in a previous frame which
5045 * is not the last in its method.
5047 if (ss_req->depth == STEP_DEPTH_OUT) {
5048 /* Ignore seq points in current method */
5049 while (frame_index < tls->frame_count) {
5050 StackFrame *frame = tls->frames [frame_index];
5052 method = frame->method;
5053 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5055 if (sp && sp->next_len != 0)
5058 // There could be method calls before the next seq point in the caller when using nested calls
5059 //enable_global = TRUE;
5061 if (sp && sp->next_len == 0) {
5063 while (frame_index < tls->frame_count) {
5064 StackFrame *frame = tls->frames [frame_index];
5066 method = frame->method;
5067 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5068 if (sp && sp->next_len != 0)
5076 if (sp && sp->next_len > 0) {
5077 for (i = 0; i < sp->next_len; ++i) {
5078 next_sp = &info->seq_points [sp->next [i]];
5080 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5081 ss_req->bps = g_slist_append (ss_req->bps, bp);
5085 if (ss_req->depth == STEP_DEPTH_OVER) {
5086 if (ss_req->nframes == 0)
5087 ss_req->nframes = tls->frame_count;
5088 /* Need to stop in catch clauses as well */
5089 for (i = 0; i < tls->frame_count; ++i) {
5090 StackFrame *frame = tls->frames [i];
5093 MonoJitInfo *jinfo = frame->ji;
5094 for (j = 0; j < jinfo->num_clauses; ++j) {
5095 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5097 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5099 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5100 ss_req->bps = g_slist_append (ss_req->bps, bp);
5108 if (ss_req->depth == STEP_DEPTH_INTO) {
5109 /* Enable global stepping so we stop at method entry too */
5110 enable_global = TRUE;
5114 * The ctx/frame info computed above will become invalid when we continue.
5116 tls->context.valid = FALSE;
5117 tls->async_state.valid = FALSE;
5118 invalidate_frames (tls);
5121 if (enable_global) {
5122 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5123 ss_req->global = TRUE;
5124 start_single_stepping ();
5125 } else if (!ss_req->bps) {
5126 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5127 ss_req->global = TRUE;
5128 start_single_stepping ();
5130 ss_req->global = FALSE;
5135 * Start single stepping of thread THREAD
5138 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5140 DebuggerTlsData *tls;
5141 MonoSeqPointInfo *info = NULL;
5142 SeqPoint *sp = NULL;
5143 MonoMethod *method = NULL;
5144 MonoDebugMethodInfo *minfo;
5145 gboolean step_to_catch = FALSE;
5147 if (suspend_count == 0)
5148 return ERR_NOT_SUSPENDED;
5150 wait_for_suspend ();
5152 // FIXME: Multiple requests
5154 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5155 return ERR_NOT_IMPLEMENTED;
5158 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5160 ss_req = g_new0 (SingleStepReq, 1);
5162 ss_req->thread = thread;
5163 ss_req->size = size;
5164 ss_req->depth = depth;
5167 mono_loader_lock ();
5168 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5169 mono_loader_unlock ();
5171 g_assert (tls->context.valid);
5172 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5174 if (tls->catch_state.valid) {
5176 StackFrameInfo frame;
5177 MonoContext new_ctx;
5178 MonoLMF *lmf = NULL;
5181 * We are stopped at a throw site. Stepping should go to the catch site.
5184 /* Find the the jit info for the catch context */
5185 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);
5187 g_assert (frame.type == FRAME_TYPE_MANAGED);
5190 * Find the seq point corresponding to the landing site ip, which is the first seq
5193 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5195 no_seq_points_found (frame.method);
5198 method = frame.method;
5200 step_to_catch = TRUE;
5201 /* This make sure the seq point is not skipped by process_single_step () */
5202 ss_req->last_sp = NULL;
5205 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5208 /* Compute the initial line info */
5209 compute_frame_info (thread, tls);
5211 if (tls->frame_count) {
5212 frame = tls->frames [0];
5214 ss_req->last_method = frame->method;
5215 ss_req->last_line = -1;
5217 minfo = mono_debug_lookup_method (frame->method);
5218 if (minfo && frame->il_offset != -1) {
5219 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5222 ss_req->last_line = loc->row;
5229 if (!step_to_catch) {
5232 compute_frame_info (thread, tls);
5234 if (tls->frame_count) {
5235 frame = tls->frames [0];
5237 if (!method && frame->il_offset != -1) {
5238 /* FIXME: Sort the table and use a binary search */
5239 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5241 no_seq_points_found (frame->method);
5243 method = frame->method;
5248 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5254 ss_destroy (SingleStepReq *req)
5257 g_assert (ss_req == req);
5266 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5269 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5275 if (!agent_config.enabled)
5278 mono_loader_lock ();
5279 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5280 mono_loader_unlock ();
5283 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5284 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5286 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5288 g_free (ei.category);
5289 g_free (ei.message);
5293 mono_debugger_agent_debug_log_is_enabled (void)
5295 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5296 return agent_config.enabled;
5299 #ifdef PLATFORM_ANDROID
5301 mono_debugger_agent_unhandled_exception (MonoException *exc)
5310 memset (&ei, 0, sizeof (EventInfo));
5311 ei.exc = (MonoObject*)exc;
5313 mono_loader_lock ();
5314 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5315 mono_loader_unlock ();
5317 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5322 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5323 MonoContext *catch_ctx)
5325 int i, j, suspend_policy;
5327 MonoJitInfo *ji, *catch_ji;
5329 DebuggerTlsData *tls = NULL;
5331 if (thread_to_tls != NULL) {
5332 MonoInternalThread *thread = mono_thread_internal_current ();
5334 mono_loader_lock ();
5335 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5336 mono_loader_unlock ();
5338 if (tls && tls->abort_requested)
5340 if (tls && tls->disable_breakpoints)
5344 memset (&ei, 0, sizeof (EventInfo));
5346 /* Just-In-Time debugging */
5348 if (agent_config.onuncaught && !inited) {
5349 finish_agent_init (FALSE);
5352 * Send an unsolicited EXCEPTION event with a dummy request id.
5354 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5355 ei.exc = (MonoObject*)exc;
5356 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5359 } else if (agent_config.onthrow && !inited) {
5361 gboolean found = FALSE;
5363 for (l = agent_config.onthrow; l; l = l->next) {
5364 char *ex_type = l->data;
5365 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5367 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5374 finish_agent_init (FALSE);
5377 * Send an unsolicited EXCEPTION event with a dummy request id.
5379 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5380 ei.exc = (MonoObject*)exc;
5381 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5389 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5391 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5395 ei.exc = (MonoObject*)exc;
5396 ei.caught = catch_ctx != NULL;
5398 mono_loader_lock ();
5400 /* Treat exceptions which are caught in non-user code as unhandled */
5401 for (i = 0; i < event_requests->len; ++i) {
5402 EventRequest *req = g_ptr_array_index (event_requests, i);
5403 if (req->event_kind != EVENT_KIND_EXCEPTION)
5406 for (j = 0; j < req->nmodifiers; ++j) {
5407 Modifier *mod = &req->modifiers [j];
5409 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5411 gboolean found = FALSE;
5412 MonoAssembly **assemblies = mod->data.assemblies;
5415 for (k = 0; assemblies [k]; ++k)
5416 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5425 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5426 mono_loader_unlock ();
5428 if (tls && ei.caught && catch_ctx) {
5429 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5430 tls->catch_state.ctx = *catch_ctx;
5431 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5432 tls->catch_state.valid = TRUE;
5435 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5438 tls->catch_state.valid = FALSE;
5442 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5444 DebuggerTlsData *tls;
5449 tls = mono_native_tls_get_value (debugger_tls_id);
5454 * We're about to invoke an exception filter during the first pass of exception handling.
5456 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5457 * 'orig_ctx' is the context where the exception has been thrown.
5460 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5462 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5463 * the call site (line 37) and then continue to Main(), but it would never
5464 * include the throw site (line 32).
5466 * Since exception filters are invoked during the first pass of exception handling,
5467 * the stack frames of the throw site are still intact, so we should include them
5470 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5472 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5473 * but report the location of the 'throw' to the user.
5477 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5481 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5483 DebuggerTlsData *tls;
5488 tls = mono_native_tls_get_value (debugger_tls_id);
5492 tls->filter_state.valid = FALSE;
5496 * buffer_add_value_full:
5498 * Add the encoding of the value at ADDR described by T to the buffer.
5499 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5503 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5509 if (!(*(void**)addr)) {
5510 /* This can happen with compiler generated locals */
5511 //printf ("%s\n", mono_type_full_name (t));
5512 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5515 g_assert (*(void**)addr);
5516 addr = *(void**)addr;
5521 case MONO_TYPE_BOOLEAN:
5524 case MONO_TYPE_CHAR:
5544 case MONO_TYPE_VOID:
5545 buffer_add_byte (buf, t->type);
5547 case MONO_TYPE_BOOLEAN:
5550 buffer_add_byte (buf, t->type);
5551 buffer_add_int (buf, *(gint8*)addr);
5553 case MONO_TYPE_CHAR:
5556 buffer_add_byte (buf, t->type);
5557 buffer_add_int (buf, *(gint16*)addr);
5562 buffer_add_byte (buf, t->type);
5563 buffer_add_int (buf, *(gint32*)addr);
5568 buffer_add_byte (buf, t->type);
5569 buffer_add_long (buf, *(gint64*)addr);
5573 /* Treat it as a vtype */
5575 case MONO_TYPE_PTR: {
5576 gssize val = *(gssize*)addr;
5578 buffer_add_byte (buf, t->type);
5579 buffer_add_long (buf, val);
5583 case MONO_TYPE_STRING:
5584 case MONO_TYPE_SZARRAY:
5585 case MONO_TYPE_OBJECT:
5586 case MONO_TYPE_CLASS:
5587 case MONO_TYPE_ARRAY:
5588 obj = *(MonoObject**)addr;
5591 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5593 if (obj->vtable->klass->valuetype) {
5594 t = &obj->vtable->klass->byval_arg;
5595 addr = mono_object_unbox (obj);
5597 } else if (obj->vtable->klass->rank) {
5598 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5599 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5600 buffer_add_byte (buf, MONO_TYPE_CLASS);
5602 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5604 buffer_add_objid (buf, obj);
5608 case MONO_TYPE_VALUETYPE: {
5612 MonoClass *klass = mono_class_from_mono_type (t);
5614 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5615 buffer_add_byte (buf, klass->enumtype);
5616 buffer_add_typeid (buf, domain, klass);
5620 while ((f = mono_class_get_fields (klass, &iter))) {
5621 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5623 if (mono_field_is_deleted (f))
5627 buffer_add_int (buf, nfields);
5630 while ((f = mono_class_get_fields (klass, &iter))) {
5631 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5633 if (mono_field_is_deleted (f))
5635 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5639 case MONO_TYPE_GENERICINST:
5640 if (mono_type_generic_inst_is_valuetype (t)) {
5652 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5654 buffer_add_value_full (buf, t, addr, domain, FALSE);
5658 obj_is_of_type (MonoObject *obj, MonoType *t)
5660 MonoClass *klass = obj->vtable->klass;
5661 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5662 if (mono_class_is_transparent_proxy (klass)) {
5663 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5664 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5674 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5677 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5683 gpointer iter = NULL;
5687 is_enum = decode_byte (buf, &buf, limit);
5688 /* Enums are sent as a normal vtype */
5690 return ERR_NOT_IMPLEMENTED;
5691 klass = decode_typeid (buf, &buf, limit, &d, &err);
5695 if (t && klass != mono_class_from_mono_type (t)) {
5696 char *name = mono_type_full_name (t);
5697 char *name2 = mono_type_full_name (&klass->byval_arg);
5698 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5701 return ERR_INVALID_ARGUMENT;
5704 nfields = decode_int (buf, &buf, limit);
5705 while ((f = mono_class_get_fields (klass, &iter))) {
5706 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5708 if (mono_field_is_deleted (f))
5710 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5715 g_assert (nfields == 0);
5723 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5727 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5728 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5729 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5730 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5731 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5732 char *name = mono_type_full_name (t);
5733 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5735 return ERR_INVALID_ARGUMENT;
5739 case MONO_TYPE_BOOLEAN:
5740 *(guint8*)addr = decode_int (buf, &buf, limit);
5742 case MONO_TYPE_CHAR:
5743 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5746 *(gint8*)addr = decode_int (buf, &buf, limit);
5749 *(guint8*)addr = decode_int (buf, &buf, limit);
5752 *(gint16*)addr = decode_int (buf, &buf, limit);
5755 *(guint16*)addr = decode_int (buf, &buf, limit);
5758 *(gint32*)addr = decode_int (buf, &buf, limit);
5761 *(guint32*)addr = decode_int (buf, &buf, limit);
5764 *(gint64*)addr = decode_long (buf, &buf, limit);
5767 *(guint64*)addr = decode_long (buf, &buf, limit);
5770 *(guint32*)addr = decode_int (buf, &buf, limit);
5773 *(guint64*)addr = decode_long (buf, &buf, limit);
5776 /* We send these as I8, so we get them back as such */
5777 g_assert (type == MONO_TYPE_I8);
5778 *(gssize*)addr = decode_long (buf, &buf, limit);
5780 case MONO_TYPE_GENERICINST:
5781 if (MONO_TYPE_ISSTRUCT (t)) {
5782 /* The client sends these as a valuetype */
5790 /* We send these as vtypes, so we get them back as such */
5791 g_assert (type == MONO_TYPE_VALUETYPE);
5794 case MONO_TYPE_VALUETYPE:
5795 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5801 if (MONO_TYPE_IS_REFERENCE (t)) {
5802 if (type == MONO_TYPE_OBJECT) {
5803 int objid = decode_objid (buf, &buf, limit);
5807 err = get_object (objid, (MonoObject**)&obj);
5812 if (!obj_is_of_type (obj, t)) {
5813 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5814 return ERR_INVALID_ARGUMENT;
5817 if (obj && obj->vtable->domain != domain)
5818 return ERR_INVALID_ARGUMENT;
5820 mono_gc_wbarrier_generic_store (addr, obj);
5821 } else if (type == VALUE_TYPE_ID_NULL) {
5822 *(MonoObject**)addr = NULL;
5823 } else if (type == MONO_TYPE_VALUETYPE) {
5831 /* This can happen when round-tripping boxed vtypes */
5833 * Obtain vtype class.
5834 * Same as the beginning of the handle_vtype case above.
5837 is_enum = decode_byte (buf, &buf, limit);
5839 return ERR_NOT_IMPLEMENTED;
5840 klass = decode_typeid (buf, &buf, limit, &d, &err);
5844 /* Decode the vtype into a temporary buffer, then box it. */
5845 vtype_buf_size = mono_class_value_size (klass, NULL);
5846 vtype_buf = g_malloc0 (vtype_buf_size);
5847 g_assert (vtype_buf);
5850 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
5855 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
5858 char *name = mono_type_full_name (t);
5859 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5861 return ERR_INVALID_ARGUMENT;
5875 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5878 int type = decode_byte (buf, &buf, limit);
5880 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5881 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5882 guint8 *nullable_buf;
5885 * First try decoding it as a Nullable`1
5887 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5892 * Then try decoding as a primitive value or null.
5894 if (targ->type == type) {
5895 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5896 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5898 g_free (nullable_buf);
5901 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5902 g_free (nullable_buf);
5905 } else if (type == VALUE_TYPE_ID_NULL) {
5906 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5912 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5916 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5920 guint8 *addr, *gaddr;
5923 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5924 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5927 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5928 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5930 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5932 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5933 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5934 addr += (gint32)var->offset;
5936 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5938 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5940 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5943 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5944 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5945 /* Same as regoffset, but with an indirection */
5946 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5947 addr += (gint32)var->offset;
5949 gaddr = *(gpointer*)addr;
5951 buffer_add_value_full (buf, t, gaddr, domain, as_vtype);
5953 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5954 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5955 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5956 MonoGSharedVtMethodRuntimeInfo *info;
5962 g_assert (info_var);
5963 g_assert (locals_var);
5965 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5966 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5967 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5968 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5969 addr += (gint32)info_var->offset;
5970 info = *(gpointer*)addr;
5971 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5972 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5974 g_assert_not_reached ();
5978 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5979 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5980 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5981 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5982 addr += (gint32)locals_var->offset;
5983 locals = *(gpointer*)addr;
5984 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5985 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5987 g_assert_not_reached ();
5991 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5993 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5998 g_assert_not_reached ();
6003 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6007 guint8 *addr, *gaddr;
6009 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6010 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6012 if (MONO_TYPE_IS_REFERENCE (t))
6013 size = sizeof (gpointer);
6015 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6018 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6019 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6021 gboolean is_signed = FALSE;
6023 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6028 v = is_signed ? *(gint8*)val : *(guint8*)val;
6031 v = is_signed ? *(gint16*)val : *(guint16*)val;
6034 v = is_signed ? *(gint32*)val : *(guint32*)val;
6037 v = is_signed ? *(gint64*)val : *(guint64*)val;
6040 g_assert_not_reached ();
6046 /* Set value on the stack or in the return ctx */
6047 if (reg_locations [reg]) {
6048 /* Saved on the stack */
6049 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6050 *(reg_locations [reg]) = v;
6053 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6054 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6057 // FIXME: Move these to mono-context.h/c.
6058 mono_arch_context_set_int_reg (ctx, reg, v);
6060 // FIXME: Can't set registers, so we disable linears
6065 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6066 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6067 addr += (gint32)var->offset;
6069 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6072 addr = *(guint8**)addr;
6078 // FIXME: Write barriers
6079 mono_gc_memmove (addr, val, size);
6081 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6082 /* Same as regoffset, but with an indirection */
6083 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6084 addr += (gint32)var->offset;
6086 gaddr = *(gpointer*)addr;
6088 // FIXME: Write barriers
6089 mono_gc_memmove (gaddr, val, size);
6091 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6095 g_assert_not_reached ();
6100 clear_event_request (int req_id, int etype)
6104 mono_loader_lock ();
6105 for (i = 0; i < event_requests->len; ++i) {
6106 EventRequest *req = g_ptr_array_index (event_requests, i);
6108 if (req->id == req_id && req->event_kind == etype) {
6109 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6110 clear_breakpoint (req->info);
6111 if (req->event_kind == EVENT_KIND_STEP)
6112 ss_destroy (req->info);
6113 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6114 clear_breakpoint (req->info);
6115 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6116 clear_breakpoint (req->info);
6117 g_ptr_array_remove_index_fast (event_requests, i);
6122 mono_loader_unlock ();
6126 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
6128 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6129 return breakpoint_matches_assembly (req->info, assembly);
6133 for (i = 0; i < req->nmodifiers; ++i) {
6134 Modifier *m = &req->modifiers [i];
6136 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6138 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6139 for (j = 0; m->data.assemblies [j]; ++j)
6140 if (m->data.assemblies [j] == assembly)
6150 * clear_event_requests_for_assembly:
6152 * Clear all events requests which reference ASSEMBLY.
6155 clear_event_requests_for_assembly (MonoAssembly *assembly)
6160 mono_loader_lock ();
6164 for (i = 0; i < event_requests->len; ++i) {
6165 EventRequest *req = g_ptr_array_index (event_requests, i);
6167 if (event_req_matches_assembly (req, assembly)) {
6168 clear_event_request (req->id, req->event_kind);
6174 mono_loader_unlock ();
6178 * type_comes_from_assembly:
6180 * GHRFunc that returns TRUE if klass comes from assembly
6183 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6185 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6189 * clear_types_for_assembly:
6191 * Clears types from loaded_classes for a given assembly
6194 clear_types_for_assembly (MonoAssembly *assembly)
6196 MonoDomain *domain = mono_domain_get ();
6197 AgentDomainInfo *info = NULL;
6199 mono_loader_lock ();
6200 info = get_agent_domain_info (domain);
6201 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6202 mono_loader_unlock ();
6206 add_thread (gpointer key, gpointer value, gpointer user_data)
6208 MonoInternalThread *thread = value;
6209 Buffer *buf = user_data;
6211 buffer_add_objid (buf, (MonoObject*)thread);
6215 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6217 guint8 *end = invoke->endp;
6220 MonoMethodSignature *sig;
6223 MonoObject *this, *res, *exc;
6226 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6229 MonoStopwatch watch;
6231 if (invoke->method) {
6233 * Invoke this method directly, currently only Environment.Exit () is supported.
6236 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>"));
6237 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6238 g_assert_not_reached ();
6241 m = decode_methodid (p, &p, end, &domain, &err);
6244 sig = mono_method_signature (m);
6246 if (m->klass->valuetype)
6247 this_buf = g_alloca (mono_class_instance_size (m->klass));
6249 this_buf = g_alloca (sizeof (MonoObject*));
6250 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6251 /* Should be null */
6252 int type = decode_byte (p, &p, end);
6253 if (type != VALUE_TYPE_ID_NULL) {
6254 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6255 return ERR_INVALID_ARGUMENT;
6257 memset (this_buf, 0, mono_class_instance_size (m->klass));
6259 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6264 if (!m->klass->valuetype)
6265 this = *(MonoObject**)this_buf;
6269 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6271 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6272 return ERR_INVALID_ARGUMENT;
6274 m = mono_object_get_virtual_method (this, m);
6277 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>"));
6279 if (this && this->vtable->domain != domain)
6282 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6283 if (!strcmp (m->name, ".ctor")) {
6284 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6285 return ERR_INVALID_ARGUMENT;
6287 this = mono_object_new (domain, m->klass);
6289 return ERR_INVALID_ARGUMENT;
6293 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6294 return ERR_INVALID_ARGUMENT;
6296 nargs = decode_int (p, &p, end);
6297 if (nargs != sig->param_count)
6298 return ERR_INVALID_ARGUMENT;
6299 /* Use alloca to get gc tracking */
6300 arg_buf = g_alloca (nargs * sizeof (gpointer));
6301 memset (arg_buf, 0, nargs * sizeof (gpointer));
6302 args = g_alloca (nargs * sizeof (gpointer));
6303 for (i = 0; i < nargs; ++i) {
6304 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6305 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6309 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6312 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6313 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6316 args [i] = arg_buf [i];
6323 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6324 tls->disable_breakpoints = TRUE;
6326 tls->disable_breakpoints = FALSE;
6329 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6331 /* FIXME: Move this to arch specific code */
6332 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6333 if (invoke->has_ctx) {
6336 lmf_addr = mono_get_lmf_addr ();
6339 memset (&ext, 0, sizeof (ext));
6340 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6342 ext.debugger_invoke = TRUE;
6343 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6345 mono_set_lmf ((MonoLMF*)&ext);
6349 mono_stopwatch_start (&watch);
6350 if (m->klass->valuetype)
6351 res = mono_runtime_invoke (m, this_buf, args, &exc);
6353 res = mono_runtime_invoke (m, this, args, &exc);
6354 mono_stopwatch_stop (&watch);
6355 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)));
6357 buffer_add_byte (buf, 0);
6358 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6360 buffer_add_byte (buf, 1);
6361 if (sig->ret->type == MONO_TYPE_VOID) {
6362 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6363 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6366 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6367 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6368 buffer_add_value (buf, sig->ret, &res, domain);
6369 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6370 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6371 MonoClass *k = mono_class_from_mono_type (sig->ret);
6372 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6374 g_assert (nullable_buf);
6375 mono_nullable_init (nullable_buf, res, k);
6376 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6379 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6386 tls->disable_breakpoints = FALSE;
6388 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6389 if (invoke->has_ctx)
6390 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6394 // FIXME: byref arguments
6402 * Invoke the method given by tls->pending_invoke in the current thread.
6405 invoke_method (void)
6407 DebuggerTlsData *tls;
6412 MonoContext restore_ctx;
6415 tls = mono_native_tls_get_value (debugger_tls_id);
6419 * Store the `InvokeData *' in `tls->invoke' until we're done with
6420 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6423 mono_loader_lock ();
6425 invoke = tls->pending_invoke;
6427 tls->pending_invoke = NULL;
6429 invoke->last_invoke = tls->invoke;
6430 tls->invoke = invoke;
6432 mono_loader_unlock ();
6434 tls->frames_up_to_date = FALSE;
6440 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6441 buffer_init (&buf, 128);
6444 /* Fail the other invokes as well */
6446 err = do_invoke_method (tls, &buf, invoke, p, &p);
6449 /* Start suspending before sending the reply */
6450 if (mindex == invoke->nmethods - 1) {
6451 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6452 for (i = 0; i < invoke->suspend_count; ++i)
6457 send_reply_packet (id, err, &buf);
6462 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6464 if (invoke->has_ctx)
6465 save_thread_context (&restore_ctx);
6467 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6468 g_assert (tls->resume_count);
6469 tls->resume_count -= invoke->suspend_count;
6472 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6475 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6477 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6478 * after the mono_runtime_invoke() already returned, but it doesn't matter
6479 * because we reset the abort here.
6482 mono_loader_lock ();
6484 if (tls->abort_requested)
6485 mono_thread_internal_reset_abort (tls->thread);
6487 tls->invoke = tls->invoke->last_invoke;
6488 tls->abort_requested = FALSE;
6490 mono_loader_unlock ();
6499 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6501 MonoThread *thread = value;
6502 DebuggerTlsData *tls;
6505 mono_loader_lock ();
6506 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6508 res = tls->really_suspended;
6509 mono_loader_unlock ();
6515 get_source_files_for_type (MonoClass *klass)
6517 gpointer iter = NULL;
6519 MonoDebugSourceInfo *sinfo;
6523 files = g_ptr_array_new ();
6525 while ((method = mono_class_get_methods (klass, &iter))) {
6526 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6527 GPtrArray *source_file_list;
6530 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6531 for (j = 0; j < source_file_list->len; ++j) {
6532 sinfo = g_ptr_array_index (source_file_list, j);
6533 for (i = 0; i < files->len; ++i)
6534 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6536 if (i == files->len)
6537 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6539 g_ptr_array_free (source_file_list, TRUE);
6547 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6550 case CMD_VM_VERSION: {
6551 char *build_info, *version;
6553 build_info = mono_get_runtime_build_info ();
6554 version = g_strdup_printf ("mono %s", build_info);
6556 buffer_add_string (buf, version); /* vm version */
6557 buffer_add_int (buf, MAJOR_VERSION);
6558 buffer_add_int (buf, MINOR_VERSION);
6559 g_free (build_info);
6563 case CMD_VM_SET_PROTOCOL_VERSION: {
6564 major_version = decode_int (p, &p, end);
6565 minor_version = decode_int (p, &p, end);
6566 protocol_version_set = TRUE;
6567 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6570 case CMD_VM_ALL_THREADS: {
6572 mono_loader_lock ();
6573 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6574 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6575 mono_loader_unlock ();
6578 case CMD_VM_SUSPEND:
6580 wait_for_suspend ();
6583 if (suspend_count == 0)
6584 return ERR_NOT_SUSPENDED;
6586 clear_suspended_objs ();
6588 case CMD_VM_DISPOSE:
6589 /* Clear all event requests */
6590 mono_loader_lock ();
6591 while (event_requests->len > 0) {
6592 EventRequest *req = g_ptr_array_index (event_requests, 0);
6594 clear_event_request (req->id, req->event_kind);
6596 mono_loader_unlock ();
6598 while (suspend_count > 0)
6600 disconnected = TRUE;
6601 vm_start_event_sent = FALSE;
6604 MonoInternalThread *thread;
6605 DebuggerTlsData *tls;
6606 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6607 MonoClass *env_class;
6609 MonoMethod *exit_method = NULL;
6613 exit_code = decode_int (p, &p, end);
6615 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6617 /* Have to send a reply before exiting */
6618 send_reply_packet (id, 0, buf);
6620 /* Clear all event requests */
6621 mono_loader_lock ();
6622 while (event_requests->len > 0) {
6623 EventRequest *req = g_ptr_array_index (event_requests, 0);
6625 clear_event_request (req->id, req->event_kind);
6627 mono_loader_unlock ();
6630 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6631 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6632 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6633 * better than doing the shutdown ourselves, since it avoids various races.
6637 wait_for_suspend ();
6639 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6640 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6642 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6645 mono_loader_lock ();
6646 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6647 mono_loader_unlock ();
6649 if (thread && exit_method) {
6650 mono_loader_lock ();
6651 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6652 mono_loader_unlock ();
6654 args = g_new0 (gpointer, 1);
6655 args [0] = g_malloc (sizeof (int));
6656 *(int*)(args [0]) = exit_code;
6658 tls->pending_invoke = g_new0 (InvokeData, 1);
6659 tls->pending_invoke->method = exit_method;
6660 tls->pending_invoke->args = args;
6661 tls->pending_invoke->nmethods = 1;
6663 while (suspend_count > 0)
6667 * No thread found, do it ourselves.
6668 * FIXME: This can race with normal shutdown etc.
6670 while (suspend_count > 0)
6673 if (!mono_runtime_try_shutdown ())
6676 mono_environment_exitcode_set (exit_code);
6678 /* Suspend all managed threads since the runtime is going away */
6679 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6680 mono_thread_suspend_all_other_threads ();
6681 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6682 mono_runtime_quit ();
6683 transport_close2 ();
6684 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6690 case CMD_VM_INVOKE_METHOD:
6691 case CMD_VM_INVOKE_METHODS: {
6692 int objid = decode_objid (p, &p, end);
6694 DebuggerTlsData *tls;
6695 int i, count, err, flags, nmethods;
6697 err = get_object (objid, (MonoObject**)&thread);
6701 flags = decode_int (p, &p, end);
6703 if (command == CMD_VM_INVOKE_METHODS)
6704 nmethods = decode_int (p, &p, end);
6708 // Wait for suspending if it already started
6710 wait_for_suspend ();
6711 if (!is_suspended ())
6712 return ERR_NOT_SUSPENDED;
6714 mono_loader_lock ();
6715 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6716 mono_loader_unlock ();
6719 if (!tls->really_suspended)
6720 /* The thread is still running native code, can't do invokes */
6721 return ERR_NOT_SUSPENDED;
6724 * Store the invoke data into tls, the thread will execute it after it is
6727 if (tls->pending_invoke)
6728 return ERR_NOT_SUSPENDED;
6729 tls->pending_invoke = g_new0 (InvokeData, 1);
6730 tls->pending_invoke->id = id;
6731 tls->pending_invoke->flags = flags;
6732 tls->pending_invoke->p = g_malloc (end - p);
6733 memcpy (tls->pending_invoke->p, p, end - p);
6734 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6735 tls->pending_invoke->suspend_count = suspend_count;
6736 tls->pending_invoke->nmethods = nmethods;
6738 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6739 resume_thread (THREAD_TO_INTERNAL (thread));
6742 count = suspend_count;
6743 for (i = 0; i < count; ++i)
6748 case CMD_VM_ABORT_INVOKE: {
6749 int objid = decode_objid (p, &p, end);
6751 DebuggerTlsData *tls;
6754 err = get_object (objid, (MonoObject**)&thread);
6758 invoke_id = decode_int (p, &p, end);
6760 mono_loader_lock ();
6761 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6764 if (tls->abort_requested) {
6765 mono_loader_unlock ();
6770 * Check whether we're still inside the mono_runtime_invoke() and that it's
6771 * actually the correct invocation.
6773 * Careful, we do not stop the thread that's doing the invocation, so we can't
6774 * inspect its stack. However, invoke_method() also acquires the loader lock
6775 * when it's done, so we're safe here.
6779 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6780 mono_loader_unlock ();
6781 return ERR_NO_INVOCATION;
6784 tls->abort_requested = TRUE;
6786 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6787 mono_loader_unlock ();
6791 case CMD_VM_SET_KEEPALIVE: {
6792 int timeout = decode_int (p, &p, end);
6793 agent_config.keepalive = timeout;
6795 #ifndef DISABLE_SOCKET_TRANSPORT
6802 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6803 GHashTableIter iter, kiter;
6808 char *fname, *basename;
6809 gboolean ignore_case;
6810 GSList *class_list, *l;
6811 GPtrArray *res_classes, *res_domains;
6813 fname = decode_string (p, &p, end);
6814 ignore_case = decode_byte (p, &p, end);
6816 basename = g_path_get_basename (fname);
6818 res_classes = g_ptr_array_new ();
6819 res_domains = g_ptr_array_new ();
6821 mono_loader_lock ();
6822 g_hash_table_iter_init (&iter, domains);
6823 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6824 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6826 /* Update 'source_file_to_class' cache */
6827 g_hash_table_iter_init (&kiter, info->loaded_classes);
6828 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6829 if (!g_hash_table_lookup (info->source_files, klass)) {
6830 files = get_source_files_for_type (klass);
6831 g_hash_table_insert (info->source_files, klass, files);
6833 for (i = 0; i < files->len; ++i) {
6834 char *s = g_ptr_array_index (files, i);
6835 char *s2 = g_path_get_basename (s);
6838 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6840 class_list = g_slist_prepend (class_list, klass);
6841 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6843 class_list = g_slist_prepend (class_list, klass);
6844 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6847 /* The _ignorecase hash contains the lowercase path */
6848 s3 = strdup_tolower (s2);
6849 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6851 class_list = g_slist_prepend (class_list, klass);
6852 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6854 class_list = g_slist_prepend (class_list, klass);
6855 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6867 s = strdup_tolower (basename);
6868 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6871 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6874 for (l = class_list; l; l = l->next) {
6877 g_ptr_array_add (res_classes, klass);
6878 g_ptr_array_add (res_domains, domain);
6881 mono_loader_unlock ();
6886 buffer_add_int (buf, res_classes->len);
6887 for (i = 0; i < res_classes->len; ++i)
6888 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6889 g_ptr_array_free (res_classes, TRUE);
6890 g_ptr_array_free (res_domains, TRUE);
6893 case CMD_VM_GET_TYPES: {
6894 GHashTableIter iter;
6898 gboolean ignore_case;
6899 GPtrArray *res_classes, *res_domains;
6900 MonoTypeNameParse info;
6902 name = decode_string (p, &p, end);
6903 ignore_case = decode_byte (p, &p, end);
6905 if (!mono_reflection_parse_type (name, &info)) {
6907 mono_reflection_free_type_info (&info);
6908 return ERR_INVALID_ARGUMENT;
6911 res_classes = g_ptr_array_new ();
6912 res_domains = g_ptr_array_new ();
6914 mono_loader_lock ();
6915 g_hash_table_iter_init (&iter, domains);
6916 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6918 gboolean type_resolve;
6922 mono_domain_assemblies_lock (domain);
6923 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6927 type_resolve = TRUE;
6928 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6930 g_ptr_array_add (res_classes, mono_type_get_class (t));
6931 g_ptr_array_add (res_domains, domain);
6935 mono_domain_assemblies_unlock (domain);
6937 mono_loader_unlock ();
6940 mono_reflection_free_type_info (&info);
6942 buffer_add_int (buf, res_classes->len);
6943 for (i = 0; i < res_classes->len; ++i)
6944 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6945 g_ptr_array_free (res_classes, TRUE);
6946 g_ptr_array_free (res_domains, TRUE);
6951 return ERR_NOT_IMPLEMENTED;
6958 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6964 case CMD_EVENT_REQUEST_SET: {
6966 int i, event_kind, suspend_policy, nmodifiers, mod;
6969 MonoThread *step_thread;
6970 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6974 event_kind = decode_byte (p, &p, end);
6975 suspend_policy = decode_byte (p, &p, end);
6976 nmodifiers = decode_byte (p, &p, end);
6978 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6979 req->id = InterlockedIncrement (&event_request_id);
6980 req->event_kind = event_kind;
6981 req->suspend_policy = suspend_policy;
6982 req->nmodifiers = nmodifiers;
6985 for (i = 0; i < nmodifiers; ++i) {
6986 mod = decode_byte (p, &p, end);
6988 req->modifiers [i].kind = mod;
6989 if (mod == MOD_KIND_COUNT) {
6990 req->modifiers [i].data.count = decode_int (p, &p, end);
6991 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6992 method = decode_methodid (p, &p, end, &domain, &err);
6995 location = decode_long (p, &p, end);
6996 } else if (mod == MOD_KIND_STEP) {
6997 step_thread_id = decode_id (p, &p, end);
6998 size = decode_int (p, &p, end);
6999 depth = decode_int (p, &p, end);
7000 if (CHECK_PROTOCOL_VERSION (2, 16))
7001 filter = decode_int (p, &p, end);
7002 req->modifiers [i].data.filter = filter;
7003 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7004 /* Treat STEP_THOUGH the same as HIDDEN */
7005 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7006 } else if (mod == MOD_KIND_THREAD_ONLY) {
7007 int id = decode_id (p, &p, end);
7009 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7014 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7015 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7019 req->modifiers [i].caught = decode_byte (p, &p, end);
7020 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7021 if (CHECK_PROTOCOL_VERSION (2, 25))
7022 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7024 req->modifiers [i].subclasses = TRUE;
7025 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" : ""));
7027 req->modifiers [i].data.exc_class = exc_class;
7029 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7031 return ERR_INVALID_ARGUMENT;
7034 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7035 int n = decode_int (p, &p, end);
7038 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7039 for (j = 0; j < n; ++j) {
7040 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7042 g_free (req->modifiers [i].data.assemblies);
7046 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7047 int n = decode_int (p, &p, end);
7050 modifier = &req->modifiers [i];
7051 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7052 for (j = 0; j < n; ++j) {
7053 char *s = decode_string (p, &p, end);
7057 s2 = strdup_tolower (s);
7058 g_hash_table_insert (modifier->data.source_files, s2, s2);
7062 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7063 int n = decode_int (p, &p, end);
7066 modifier = &req->modifiers [i];
7067 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7068 for (j = 0; j < n; ++j) {
7069 char *s = decode_string (p, &p, end);
7072 g_hash_table_insert (modifier->data.type_names, s, s);
7076 return ERR_NOT_IMPLEMENTED;
7080 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7083 req->info = set_breakpoint (method, location, req, &error);
7084 if (!mono_error_ok (&error)) {
7086 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7087 mono_error_cleanup (&error);
7088 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7090 } else if (req->event_kind == EVENT_KIND_STEP) {
7091 g_assert (step_thread_id);
7093 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7099 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7104 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7105 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7106 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7107 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7108 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7109 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7111 if (req->nmodifiers) {
7113 return ERR_NOT_IMPLEMENTED;
7117 mono_loader_lock ();
7118 g_ptr_array_add (event_requests, req);
7120 if (agent_config.defer) {
7121 /* Transmit cached data to the client on receipt of the event request */
7122 switch (req->event_kind) {
7123 case EVENT_KIND_APPDOMAIN_CREATE:
7124 /* Emit load events for currently loaded domains */
7125 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7127 case EVENT_KIND_ASSEMBLY_LOAD:
7128 /* Emit load events for currently loaded assemblies */
7129 mono_assembly_foreach (emit_assembly_load, NULL);
7131 case EVENT_KIND_THREAD_START:
7132 /* Emit start events for currently started threads */
7133 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7135 case EVENT_KIND_TYPE_LOAD:
7136 /* Emit type load events for currently loaded types */
7137 mono_domain_foreach (send_types_for_domain, NULL);
7143 mono_loader_unlock ();
7145 buffer_add_int (buf, req->id);
7148 case CMD_EVENT_REQUEST_CLEAR: {
7149 int etype = decode_byte (p, &p, end);
7150 int req_id = decode_int (p, &p, end);
7152 // FIXME: Make a faster mapping from req_id to request
7153 mono_loader_lock ();
7154 clear_event_request (req_id, etype);
7155 mono_loader_unlock ();
7158 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7161 mono_loader_lock ();
7163 while (i < event_requests->len) {
7164 EventRequest *req = g_ptr_array_index (event_requests, i);
7166 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7167 clear_breakpoint (req->info);
7169 g_ptr_array_remove_index_fast (event_requests, i);
7175 mono_loader_unlock ();
7179 return ERR_NOT_IMPLEMENTED;
7186 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7192 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7193 buffer_add_domainid (buf, mono_get_root_domain ());
7196 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7197 domain = decode_domainid (p, &p, end, NULL, &err);
7200 buffer_add_string (buf, domain->friendly_name);
7203 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7208 domain = decode_domainid (p, &p, end, NULL, &err);
7211 mono_loader_lock ();
7213 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7216 buffer_add_int (buf, count);
7217 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7219 buffer_add_assemblyid (buf, domain, ass);
7221 mono_loader_unlock ();
7224 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7225 domain = decode_domainid (p, &p, end, NULL, &err);
7229 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7232 case CMD_APPDOMAIN_GET_CORLIB: {
7233 domain = decode_domainid (p, &p, end, NULL, &err);
7237 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7240 case CMD_APPDOMAIN_CREATE_STRING: {
7244 domain = decode_domainid (p, &p, end, NULL, &err);
7247 s = decode_string (p, &p, end);
7249 o = mono_string_new (domain, s);
7250 buffer_add_objid (buf, (MonoObject*)o);
7253 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7255 MonoDomain *domain2;
7258 domain = decode_domainid (p, &p, end, NULL, &err);
7261 klass = decode_typeid (p, &p, end, &domain2, &err);
7266 g_assert (domain == domain2);
7268 o = mono_object_new (domain, klass);
7270 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7274 buffer_add_objid (buf, o);
7278 return ERR_NOT_IMPLEMENTED;
7285 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7291 ass = decode_assemblyid (p, &p, end, &domain, &err);
7296 case CMD_ASSEMBLY_GET_LOCATION: {
7297 buffer_add_string (buf, mono_image_get_filename (ass->image));
7300 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7304 if (ass->image->dynamic) {
7305 buffer_add_id (buf, 0);
7307 token = mono_image_get_entry_point (ass->image);
7309 buffer_add_id (buf, 0);
7311 m = mono_get_method (ass->image, token, NULL);
7312 buffer_add_methodid (buf, domain, m);
7317 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7318 buffer_add_moduleid (buf, domain, ass->image);
7321 case CMD_ASSEMBLY_GET_OBJECT: {
7322 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7323 buffer_add_objid (buf, o);
7326 case CMD_ASSEMBLY_GET_TYPE: {
7327 char *s = decode_string (p, &p, end);
7328 gboolean ignorecase = decode_byte (p, &p, end);
7329 MonoTypeNameParse info;
7331 gboolean type_resolve, res;
7332 MonoDomain *d = mono_domain_get ();
7334 /* This is needed to be able to find referenced assemblies */
7335 res = mono_domain_set (domain, FALSE);
7338 if (!mono_reflection_parse_type (s, &info)) {
7341 if (info.assembly.name)
7343 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7345 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7346 mono_reflection_free_type_info (&info);
7349 mono_domain_set (d, TRUE);
7353 case CMD_ASSEMBLY_GET_NAME: {
7355 MonoAssembly *mass = ass;
7357 name = g_strdup_printf (
7358 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7360 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7361 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7362 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7363 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7365 buffer_add_string (buf, name);
7370 return ERR_NOT_IMPLEMENTED;
7377 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7383 case CMD_MODULE_GET_INFO: {
7384 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7387 basename = g_path_get_basename (image->name);
7388 buffer_add_string (buf, basename); // name
7389 buffer_add_string (buf, image->module_name); // scopename
7390 buffer_add_string (buf, image->name); // fqname
7391 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7392 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7397 return ERR_NOT_IMPLEMENTED;
7404 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7406 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7407 /* Special case these so the client doesn't have to handle Type objects */
7409 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7410 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7411 } else if (MONO_TYPE_IS_REFERENCE (t))
7412 buffer_add_value (buf, t, &val, domain);
7414 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7418 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7424 buffer_add_int (buf, 0);
7428 for (i = 0; i < cinfo->num_attrs; ++i) {
7429 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7432 buffer_add_int (buf, nattrs);
7434 for (i = 0; i < cinfo->num_attrs; ++i) {
7435 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7436 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7437 MonoArray *typed_args, *named_args;
7439 CattrNamedArg *arginfo = NULL;
7442 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7443 g_assert (mono_error_ok (&error));
7445 buffer_add_methodid (buf, domain, attr->ctor);
7449 buffer_add_int (buf, mono_array_length (typed_args));
7450 for (j = 0; j < mono_array_length (typed_args); ++j) {
7451 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7453 t = mono_method_signature (attr->ctor)->params [j];
7455 buffer_add_cattr_arg (buf, t, domain, val);
7458 buffer_add_int (buf, 0);
7463 buffer_add_int (buf, mono_array_length (named_args));
7465 for (j = 0; j < mono_array_length (named_args); ++j) {
7466 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7468 if (arginfo [j].prop) {
7469 buffer_add_byte (buf, 0x54);
7470 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7471 } else if (arginfo [j].field) {
7472 buffer_add_byte (buf, 0x53);
7473 buffer_add_fieldid (buf, domain, arginfo [j].field);
7475 g_assert_not_reached ();
7478 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7481 buffer_add_int (buf, 0);
7488 /* FIXME: Code duplication with icall.c */
7490 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7495 mono_class_setup_interfaces (klass, error);
7496 if (!mono_error_ok (error))
7499 for (i = 0; i < klass->interface_count; i++) {
7500 ic = klass->interfaces [i];
7501 g_hash_table_insert (ifaces, ic, ic);
7503 collect_interfaces (ic, ifaces, error);
7504 if (!mono_error_ok (error))
7510 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7520 case CMD_TYPE_GET_INFO: {
7521 buffer_add_string (buf, klass->name_space);
7522 buffer_add_string (buf, klass->name);
7524 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7525 buffer_add_string (buf, name);
7527 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7528 buffer_add_moduleid (buf, domain, klass->image);
7529 buffer_add_typeid (buf, domain, klass->parent);
7530 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7531 buffer_add_typeid (buf, domain, klass->element_class);
7533 buffer_add_id (buf, 0);
7534 buffer_add_int (buf, klass->type_token);
7535 buffer_add_byte (buf, klass->rank);
7536 buffer_add_int (buf, klass->flags);
7538 type = &klass->byval_arg;
7539 // FIXME: Can't decide whenever a class represents a byref type
7542 if (type->type == MONO_TYPE_PTR)
7544 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7546 if (type->type == MONO_TYPE_VALUETYPE)
7548 if (klass->enumtype)
7550 if (klass->generic_container)
7552 if (klass->generic_container || klass->generic_class)
7554 buffer_add_byte (buf, b);
7557 while ((nested = mono_class_get_nested_types (klass, &iter)))
7559 buffer_add_int (buf, nnested);
7561 while ((nested = mono_class_get_nested_types (klass, &iter)))
7562 buffer_add_typeid (buf, domain, nested);
7563 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7564 if (klass->generic_container)
7565 buffer_add_typeid (buf, domain, klass);
7566 else if (klass->generic_class)
7567 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7569 buffer_add_id (buf, 0);
7571 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7574 if (klass->generic_class) {
7575 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7577 count = inst->type_argc;
7578 buffer_add_int (buf, count);
7579 for (i = 0; i < count; i++)
7580 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7581 } else if (klass->generic_container) {
7582 MonoGenericContainer *container = klass->generic_container;
7585 count = container->type_argc;
7586 buffer_add_int (buf, count);
7587 for (i = 0; i < count; i++) {
7588 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7589 buffer_add_typeid (buf, domain, pklass);
7592 buffer_add_int (buf, 0);
7597 case CMD_TYPE_GET_METHODS: {
7600 gpointer iter = NULL;
7603 mono_class_setup_methods (klass);
7605 nmethods = mono_class_num_methods (klass);
7607 buffer_add_int (buf, nmethods);
7609 while ((m = mono_class_get_methods (klass, &iter))) {
7610 buffer_add_methodid (buf, domain, m);
7613 g_assert (i == nmethods);
7616 case CMD_TYPE_GET_FIELDS: {
7619 gpointer iter = NULL;
7622 nfields = mono_class_num_fields (klass);
7624 buffer_add_int (buf, nfields);
7626 while ((f = mono_class_get_fields (klass, &iter))) {
7627 buffer_add_fieldid (buf, domain, f);
7628 buffer_add_string (buf, f->name);
7629 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7630 buffer_add_int (buf, f->type->attrs);
7633 g_assert (i == nfields);
7636 case CMD_TYPE_GET_PROPERTIES: {
7639 gpointer iter = NULL;
7642 nprops = mono_class_num_properties (klass);
7644 buffer_add_int (buf, nprops);
7646 while ((p = mono_class_get_properties (klass, &iter))) {
7647 buffer_add_propertyid (buf, domain, p);
7648 buffer_add_string (buf, p->name);
7649 buffer_add_methodid (buf, domain, p->get);
7650 buffer_add_methodid (buf, domain, p->set);
7651 buffer_add_int (buf, p->attrs);
7654 g_assert (i == nprops);
7657 case CMD_TYPE_GET_CATTRS: {
7658 MonoClass *attr_klass;
7659 MonoCustomAttrInfo *cinfo;
7661 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7662 /* attr_klass can be NULL */
7666 cinfo = mono_custom_attrs_from_class (klass);
7668 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7671 case CMD_TYPE_GET_FIELD_CATTRS: {
7672 MonoClass *attr_klass;
7673 MonoCustomAttrInfo *cinfo;
7674 MonoClassField *field;
7676 field = decode_fieldid (p, &p, end, NULL, &err);
7679 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7683 cinfo = mono_custom_attrs_from_field (klass, field);
7685 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7688 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7689 MonoClass *attr_klass;
7690 MonoCustomAttrInfo *cinfo;
7693 prop = decode_propertyid (p, &p, end, NULL, &err);
7696 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7700 cinfo = mono_custom_attrs_from_property (klass, prop);
7702 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7705 case CMD_TYPE_GET_VALUES:
7706 case CMD_TYPE_GET_VALUES_2: {
7713 MonoThread *thread_obj;
7714 MonoInternalThread *thread = NULL;
7715 guint32 special_static_type;
7717 if (command == CMD_TYPE_GET_VALUES_2) {
7718 int objid = decode_objid (p, &p, end);
7721 err = get_object (objid, (MonoObject**)&thread_obj);
7725 thread = THREAD_TO_INTERNAL (thread_obj);
7728 len = decode_int (p, &p, end);
7729 for (i = 0; i < len; ++i) {
7730 f = decode_fieldid (p, &p, end, NULL, &err);
7734 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7735 return ERR_INVALID_FIELDID;
7736 special_static_type = mono_class_field_get_special_static_type (f);
7737 if (special_static_type != SPECIAL_STATIC_NONE) {
7738 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7739 return ERR_INVALID_FIELDID;
7742 /* Check that the field belongs to the object */
7744 for (k = klass; k; k = k->parent) {
7745 if (k == f->parent) {
7751 return ERR_INVALID_FIELDID;
7753 vtable = mono_class_vtable (domain, f->parent);
7754 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7755 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7756 buffer_add_value (buf, f->type, val, domain);
7761 case CMD_TYPE_SET_VALUES: {
7769 len = decode_int (p, &p, end);
7770 for (i = 0; i < len; ++i) {
7771 f = decode_fieldid (p, &p, end, NULL, &err);
7775 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7776 return ERR_INVALID_FIELDID;
7777 if (mono_class_field_is_special_static (f))
7778 return ERR_INVALID_FIELDID;
7780 /* Check that the field belongs to the object */
7782 for (k = klass; k; k = k->parent) {
7783 if (k == f->parent) {
7789 return ERR_INVALID_FIELDID;
7791 // FIXME: Check for literal/const
7793 vtable = mono_class_vtable (domain, f->parent);
7794 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7795 err = decode_value (f->type, domain, val, p, &p, end);
7800 if (MONO_TYPE_IS_REFERENCE (f->type))
7801 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7803 mono_field_static_set_value (vtable, f, val);
7808 case CMD_TYPE_GET_OBJECT: {
7809 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7810 buffer_add_objid (buf, o);
7813 case CMD_TYPE_GET_SOURCE_FILES:
7814 case CMD_TYPE_GET_SOURCE_FILES_2: {
7815 char *source_file, *base;
7819 files = get_source_files_for_type (klass);
7821 buffer_add_int (buf, files->len);
7822 for (i = 0; i < files->len; ++i) {
7823 source_file = g_ptr_array_index (files, i);
7824 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7825 buffer_add_string (buf, source_file);
7827 base = g_path_get_basename (source_file);
7828 buffer_add_string (buf, base);
7831 g_free (source_file);
7833 g_ptr_array_free (files, TRUE);
7836 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7837 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7841 if (mono_class_is_assignable_from (klass, oklass))
7842 buffer_add_byte (buf, 1);
7844 buffer_add_byte (buf, 0);
7847 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7848 char *name = decode_string (p, &p, end);
7849 int i, flags = decode_int (p, &p, end);
7850 MonoException *ex = NULL;
7851 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7854 return ERR_LOADER_ERROR;
7855 buffer_add_int (buf, array->len);
7856 for (i = 0; i < array->len; ++i) {
7857 MonoMethod *method = g_ptr_array_index (array, i);
7858 buffer_add_methodid (buf, domain, method);
7861 g_ptr_array_free (array, TRUE);
7865 case CMD_TYPE_GET_INTERFACES: {
7867 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7869 MonoClass *tclass, *iface;
7870 GHashTableIter iter;
7874 for (parent = tclass; parent; parent = parent->parent) {
7875 mono_class_setup_interfaces (parent, &error);
7876 if (!mono_error_ok (&error))
7877 return ERR_LOADER_ERROR;
7878 collect_interfaces (parent, iface_hash, &error);
7879 if (!mono_error_ok (&error))
7880 return ERR_LOADER_ERROR;
7883 buffer_add_int (buf, g_hash_table_size (iface_hash));
7885 g_hash_table_iter_init (&iter, iface_hash);
7886 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7887 buffer_add_typeid (buf, domain, iface);
7888 g_hash_table_destroy (iface_hash);
7891 case CMD_TYPE_GET_INTERFACE_MAP: {
7892 int tindex, ioffset;
7893 gboolean variance_used;
7895 int len, nmethods, i;
7899 len = decode_int (p, &p, end);
7900 mono_class_setup_vtable (klass);
7902 for (tindex = 0; tindex < len; ++tindex) {
7903 iclass = decode_typeid (p, &p, end, NULL, &err);
7907 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7909 return ERR_INVALID_ARGUMENT;
7911 nmethods = mono_class_num_methods (iclass);
7912 buffer_add_int (buf, nmethods);
7915 while ((method = mono_class_get_methods (iclass, &iter))) {
7916 buffer_add_methodid (buf, domain, method);
7918 for (i = 0; i < nmethods; ++i)
7919 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7923 case CMD_TYPE_IS_INITIALIZED: {
7924 MonoVTable *vtable = mono_class_vtable (domain, klass);
7927 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7929 buffer_add_int (buf, 0);
7933 return ERR_NOT_IMPLEMENTED;
7940 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7943 MonoDomain *old_domain;
7947 klass = decode_typeid (p, &p, end, &domain, &err);
7951 old_domain = mono_domain_get ();
7953 mono_domain_set (domain, TRUE);
7955 err = type_commands_internal (command, klass, domain, p, end, buf);
7957 mono_domain_set (old_domain, TRUE);
7963 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7965 MonoMethodHeader *header;
7969 case CMD_METHOD_GET_NAME: {
7970 buffer_add_string (buf, method->name);
7973 case CMD_METHOD_GET_DECLARING_TYPE: {
7974 buffer_add_typeid (buf, domain, method->klass);
7977 case CMD_METHOD_GET_DEBUG_INFO: {
7978 MonoDebugMethodInfo *minfo;
7980 int i, j, n_il_offsets;
7983 int *column_numbers;
7985 GPtrArray *source_file_list;
7987 header = mono_method_get_header (method);
7989 buffer_add_int (buf, 0);
7990 buffer_add_string (buf, "");
7991 buffer_add_int (buf, 0);
7995 minfo = mono_debug_lookup_method (method);
7997 buffer_add_int (buf, header->code_size);
7998 buffer_add_string (buf, "");
7999 buffer_add_int (buf, 0);
8000 mono_metadata_free_mh (header);
8004 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
8005 buffer_add_int (buf, header->code_size);
8006 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8007 buffer_add_int (buf, source_file_list->len);
8008 for (i = 0; i < source_file_list->len; ++i) {
8009 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8010 buffer_add_string (buf, sinfo->source_file);
8011 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8012 for (j = 0; j < 16; ++j)
8013 buffer_add_byte (buf, sinfo->hash [j]);
8017 buffer_add_string (buf, source_file);
8019 buffer_add_int (buf, n_il_offsets);
8020 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8021 for (i = 0; i < n_il_offsets; ++i) {
8022 const char *srcfile = "";
8024 if (source_files [i] != -1) {
8025 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8026 srcfile = sinfo->source_file;
8028 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8029 buffer_add_int (buf, il_offsets [i]);
8030 buffer_add_int (buf, line_numbers [i]);
8031 if (CHECK_PROTOCOL_VERSION (2, 13))
8032 buffer_add_int (buf, source_files [i]);
8033 if (CHECK_PROTOCOL_VERSION (2, 19))
8034 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8036 g_free (source_file);
8037 g_free (il_offsets);
8038 g_free (line_numbers);
8039 g_free (source_files);
8040 g_ptr_array_free (source_file_list, TRUE);
8041 mono_metadata_free_mh (header);
8044 case CMD_METHOD_GET_PARAM_INFO: {
8045 MonoMethodSignature *sig = mono_method_signature (method);
8049 /* FIXME: mono_class_from_mono_type () and byrefs */
8051 /* FIXME: Use a smaller encoding */
8052 buffer_add_int (buf, sig->call_convention);
8053 buffer_add_int (buf, sig->param_count);
8054 buffer_add_int (buf, sig->generic_param_count);
8055 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8056 for (i = 0; i < sig->param_count; ++i) {
8058 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8061 /* Emit parameter names */
8062 names = g_new (char *, sig->param_count);
8063 mono_method_get_param_names (method, (const char **) names);
8064 for (i = 0; i < sig->param_count; ++i)
8065 buffer_add_string (buf, names [i]);
8070 case CMD_METHOD_GET_LOCALS_INFO: {
8071 int i, j, num_locals;
8072 MonoDebugLocalsInfo *locals;
8074 header = mono_method_get_header (method);
8076 return ERR_INVALID_ARGUMENT;
8078 buffer_add_int (buf, header->num_locals);
8081 for (i = 0; i < header->num_locals; ++i)
8082 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8085 locals = mono_debug_lookup_locals (method);
8087 num_locals = locals->num_locals;
8090 for (i = 0; i < header->num_locals; ++i) {
8091 for (j = 0; j < num_locals; ++j)
8092 if (locals->locals [j].index == i)
8095 buffer_add_string (buf, locals->locals [j].name);
8097 buffer_add_string (buf, "");
8101 for (i = 0; i < header->num_locals; ++i) {
8102 for (j = 0; j < num_locals; ++j)
8103 if (locals->locals [j].index == i)
8105 if (j < num_locals && locals->locals [j].block) {
8106 buffer_add_int (buf, locals->locals [j].block->start_offset);
8107 buffer_add_int (buf, locals->locals [j].block->end_offset);
8109 buffer_add_int (buf, 0);
8110 buffer_add_int (buf, header->code_size);
8113 mono_metadata_free_mh (header);
8116 mono_debug_symfile_free_locals (locals);
8120 case CMD_METHOD_GET_INFO:
8121 buffer_add_int (buf, method->flags);
8122 buffer_add_int (buf, method->iflags);
8123 buffer_add_int (buf, method->token);
8124 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8126 if (method->is_generic)
8128 if (mono_method_signature (method)->generic_param_count)
8130 buffer_add_byte (buf, attrs);
8131 if (method->is_generic || method->is_inflated) {
8134 if (method->is_generic) {
8137 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8139 result = imethod->declaring;
8140 if (imethod->context.class_inst) {
8141 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8142 /*Generic methods gets the context of the GTD.*/
8143 if (mono_class_get_context (klass))
8144 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8148 buffer_add_methodid (buf, domain, result);
8150 buffer_add_id (buf, 0);
8152 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8153 if (mono_method_signature (method)->generic_param_count) {
8156 if (method->is_inflated) {
8157 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8159 count = inst->type_argc;
8160 buffer_add_int (buf, count);
8162 for (i = 0; i < count; i++)
8163 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8165 buffer_add_int (buf, 0);
8167 } else if (method->is_generic) {
8168 MonoGenericContainer *container = mono_method_get_generic_container (method);
8170 count = mono_method_signature (method)->generic_param_count;
8171 buffer_add_int (buf, count);
8172 for (i = 0; i < count; i++) {
8173 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8174 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8175 buffer_add_typeid (buf, domain, pklass);
8178 buffer_add_int (buf, 0);
8181 buffer_add_int (buf, 0);
8186 case CMD_METHOD_GET_BODY: {
8189 header = mono_method_get_header (method);
8191 buffer_add_int (buf, 0);
8193 if (CHECK_PROTOCOL_VERSION (2, 18))
8194 buffer_add_int (buf, 0);
8196 buffer_add_int (buf, header->code_size);
8197 for (i = 0; i < header->code_size; ++i)
8198 buffer_add_byte (buf, header->code [i]);
8200 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8201 buffer_add_int (buf, header->num_clauses);
8202 for (i = 0; i < header->num_clauses; ++i) {
8203 MonoExceptionClause *clause = &header->clauses [i];
8205 buffer_add_int (buf, clause->flags);
8206 buffer_add_int (buf, clause->try_offset);
8207 buffer_add_int (buf, clause->try_len);
8208 buffer_add_int (buf, clause->handler_offset);
8209 buffer_add_int (buf, clause->handler_len);
8210 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8211 buffer_add_typeid (buf, domain, clause->data.catch_class);
8212 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8213 buffer_add_int (buf, clause->data.filter_offset);
8217 mono_metadata_free_mh (header);
8222 case CMD_METHOD_RESOLVE_TOKEN: {
8223 guint32 token = decode_int (p, &p, end);
8226 switch (mono_metadata_token_code (token)) {
8227 case MONO_TOKEN_STRING: {
8231 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8234 s2 = mono_string_to_utf8 (s);
8236 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8237 buffer_add_string (buf, s2);
8243 MonoClass *handle_class;
8245 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8246 val = mono_method_get_wrapper_data (method, token);
8247 handle_class = mono_method_get_wrapper_data (method, token + 1);
8249 if (handle_class == NULL) {
8250 // Can't figure out the token type
8251 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8255 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8259 if (handle_class == mono_defaults.typehandle_class) {
8260 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8261 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8262 buffer_add_typeid (buf, domain, (MonoClass *) val);
8264 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8265 } else if (handle_class == mono_defaults.fieldhandle_class) {
8266 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8267 buffer_add_fieldid (buf, domain, val);
8268 } else if (handle_class == mono_defaults.methodhandle_class) {
8269 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8270 buffer_add_methodid (buf, domain, val);
8271 } else if (handle_class == mono_defaults.string_class) {
8274 s = mono_string_to_utf8 (val);
8275 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8276 buffer_add_string (buf, s);
8279 g_assert_not_reached ();
8286 case CMD_METHOD_GET_CATTRS: {
8287 MonoClass *attr_klass;
8288 MonoCustomAttrInfo *cinfo;
8290 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8291 /* attr_klass can be NULL */
8295 cinfo = mono_custom_attrs_from_method (method);
8297 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8300 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8301 MonoType **type_argv;
8305 MonoGenericInst *ginst;
8306 MonoGenericContext tmp_context;
8307 MonoMethod *inflated;
8309 type_argc = decode_int (p, &p, end);
8310 type_argv = g_new0 (MonoType*, type_argc);
8311 for (i = 0; i < type_argc; ++i) {
8312 klass = decode_typeid (p, &p, end, &d, &err);
8319 return ERR_INVALID_ARGUMENT;
8321 type_argv [i] = &klass->byval_arg;
8323 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8325 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8326 tmp_context.method_inst = ginst;
8328 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8329 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8330 return ERR_INVALID_ARGUMENT;
8331 buffer_add_methodid (buf, domain, inflated);
8335 return ERR_NOT_IMPLEMENTED;
8342 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8345 MonoDomain *old_domain;
8349 method = decode_methodid (p, &p, end, &domain, &err);
8353 old_domain = mono_domain_get ();
8355 mono_domain_set (domain, TRUE);
8357 err = method_commands_internal (command, method, domain, p, end, buf);
8359 mono_domain_set (old_domain, TRUE);
8365 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8367 int objid = decode_objid (p, &p, end);
8369 MonoThread *thread_obj;
8370 MonoInternalThread *thread;
8372 err = get_object (objid, (MonoObject**)&thread_obj);
8376 thread = THREAD_TO_INTERNAL (thread_obj);
8379 case CMD_THREAD_GET_NAME: {
8381 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8384 buffer_add_int (buf, 0);
8389 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8391 buffer_add_int (buf, len);
8392 buffer_add_data (buf, (guint8*)name, len);
8397 case CMD_THREAD_GET_FRAME_INFO: {
8398 DebuggerTlsData *tls;
8399 int i, start_frame, length;
8401 // Wait for suspending if it already started
8402 // FIXME: Races with suspend_count
8403 while (!is_suspended ()) {
8405 wait_for_suspend ();
8409 wait_for_suspend ();
8410 if (!is_suspended ())
8411 return ERR_NOT_SUSPENDED;
8414 start_frame = decode_int (p, &p, end);
8415 length = decode_int (p, &p, end);
8417 if (start_frame != 0 || length != -1)
8418 return ERR_NOT_IMPLEMENTED;
8420 mono_loader_lock ();
8421 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8422 mono_loader_unlock ();
8425 compute_frame_info (thread, tls);
8427 buffer_add_int (buf, tls->frame_count);
8428 for (i = 0; i < tls->frame_count; ++i) {
8429 buffer_add_int (buf, tls->frames [i]->id);
8430 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8431 buffer_add_int (buf, tls->frames [i]->il_offset);
8433 * Instead of passing the frame type directly to the client, we associate
8434 * it with the previous frame using a set of flags. This avoids lots of
8435 * conditional code in the client, since a frame whose type isn't
8436 * FRAME_TYPE_MANAGED has no method, location, etc.
8438 buffer_add_byte (buf, tls->frames [i]->flags);
8443 case CMD_THREAD_GET_STATE:
8444 buffer_add_int (buf, thread->state);
8446 case CMD_THREAD_GET_INFO:
8447 buffer_add_byte (buf, thread->threadpool_thread);
8449 case CMD_THREAD_GET_ID:
8450 buffer_add_long (buf, (guint64)(gsize)thread);
8452 case CMD_THREAD_GET_TID:
8453 buffer_add_long (buf, (guint64)thread->tid);
8456 return ERR_NOT_IMPLEMENTED;
8463 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8467 MonoThread *thread_obj;
8468 MonoInternalThread *thread;
8469 int pos, i, len, frame_idx;
8470 DebuggerTlsData *tls;
8472 MonoDebugMethodJitInfo *jit;
8473 MonoDebugVarInfo *var;
8474 MonoMethodSignature *sig;
8476 MonoMethodHeader *header;
8478 objid = decode_objid (p, &p, end);
8479 err = get_object (objid, (MonoObject**)&thread_obj);
8483 thread = THREAD_TO_INTERNAL (thread_obj);
8485 id = decode_id (p, &p, end);
8487 mono_loader_lock ();
8488 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8489 mono_loader_unlock ();
8492 for (i = 0; i < tls->frame_count; ++i) {
8493 if (tls->frames [i]->id == id)
8496 if (i == tls->frame_count)
8497 return ERR_INVALID_FRAMEID;
8500 frame = tls->frames [frame_idx];
8502 if (!frame->has_ctx)
8503 return ERR_ABSENT_INFORMATION;
8506 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8507 if (!frame->jit && frame->api_method->is_inflated)
8508 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8512 /* This could happen for aot images with no jit debug info */
8513 s = mono_method_full_name (frame->api_method, TRUE);
8514 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8516 return ERR_ABSENT_INFORMATION;
8521 sig = mono_method_signature (frame->actual_method);
8523 if (!get_seq_points (frame->domain, frame->actual_method))
8525 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8527 return ERR_ABSENT_INFORMATION;
8530 case CMD_STACK_FRAME_GET_VALUES: {
8531 len = decode_int (p, &p, end);
8532 header = mono_method_get_header (frame->actual_method);
8534 for (i = 0; i < len; ++i) {
8535 pos = decode_int (p, &p, end);
8540 g_assert (pos >= 0 && pos < jit->num_params);
8542 var = &jit->params [pos];
8544 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8546 g_assert (pos >= 0 && pos < jit->num_locals);
8548 var = &jit->locals [pos];
8550 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8553 mono_metadata_free_mh (header);
8556 case CMD_STACK_FRAME_GET_THIS: {
8557 if (frame->api_method->klass->valuetype) {
8558 if (!sig->hasthis) {
8559 MonoObject *p = NULL;
8560 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8562 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8565 if (!sig->hasthis) {
8566 MonoObject *p = NULL;
8567 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8569 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8574 case CMD_STACK_FRAME_SET_VALUES: {
8577 MonoDebugVarInfo *var;
8579 len = decode_int (p, &p, end);
8580 header = mono_method_get_header (frame->actual_method);
8582 for (i = 0; i < len; ++i) {
8583 pos = decode_int (p, &p, end);
8588 g_assert (pos >= 0 && pos < jit->num_params);
8590 t = sig->params [pos];
8591 var = &jit->params [pos];
8593 g_assert (pos >= 0 && pos < jit->num_locals);
8595 t = header->locals [pos];
8596 var = &jit->locals [pos];
8599 if (MONO_TYPE_IS_REFERENCE (t))
8600 val_buf = g_alloca (sizeof (MonoObject*));
8602 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8603 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8607 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8609 mono_metadata_free_mh (header);
8613 return ERR_NOT_IMPLEMENTED;
8620 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8623 int objid, err, index, len, i, esize;
8626 objid = decode_objid (p, &p, end);
8627 err = get_object (objid, (MonoObject**)&arr);
8632 case CMD_ARRAY_REF_GET_LENGTH:
8633 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8635 buffer_add_int (buf, arr->max_length);
8636 buffer_add_int (buf, 0);
8638 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8639 buffer_add_int (buf, arr->bounds [i].length);
8640 buffer_add_int (buf, arr->bounds [i].lower_bound);
8644 case CMD_ARRAY_REF_GET_VALUES:
8645 index = decode_int (p, &p, end);
8646 len = decode_int (p, &p, end);
8648 g_assert (index >= 0 && len >= 0);
8649 // Reordered to avoid integer overflow
8650 g_assert (!(index > arr->max_length - len));
8652 esize = mono_array_element_size (arr->obj.vtable->klass);
8653 for (i = index; i < index + len; ++i) {
8654 elem = (gpointer*)((char*)arr->vector + (i * esize));
8655 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8658 case CMD_ARRAY_REF_SET_VALUES:
8659 index = decode_int (p, &p, end);
8660 len = decode_int (p, &p, end);
8662 g_assert (index >= 0 && len >= 0);
8663 // Reordered to avoid integer overflow
8664 g_assert (!(index > arr->max_length - len));
8666 esize = mono_array_element_size (arr->obj.vtable->klass);
8667 for (i = index; i < index + len; ++i) {
8668 elem = (gpointer*)((char*)arr->vector + (i * esize));
8670 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8674 return ERR_NOT_IMPLEMENTED;
8681 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8686 int i, index, length;
8689 objid = decode_objid (p, &p, end);
8690 err = get_object (objid, (MonoObject**)&str);
8695 case CMD_STRING_REF_GET_VALUE:
8696 s = mono_string_to_utf8 (str);
8697 buffer_add_string (buf, s);
8700 case CMD_STRING_REF_GET_LENGTH:
8701 buffer_add_long (buf, mono_string_length (str));
8703 case CMD_STRING_REF_GET_CHARS:
8704 index = decode_long (p, &p, end);
8705 length = decode_long (p, &p, end);
8706 if (index > mono_string_length (str) - length)
8707 return ERR_INVALID_ARGUMENT;
8708 c = mono_string_chars (str) + index;
8709 for (i = 0; i < length; ++i)
8710 buffer_add_short (buf, c [i]);
8713 return ERR_NOT_IMPLEMENTED;
8720 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8729 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8730 objid = decode_objid (p, &p, end);
8731 err = get_object (objid, &obj);
8733 buffer_add_int (buf, 1);
8735 buffer_add_int (buf, 0);
8739 objid = decode_objid (p, &p, end);
8740 err = get_object (objid, &obj);
8745 case CMD_OBJECT_REF_GET_TYPE:
8746 /* This handles transparent proxies too */
8747 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8749 case CMD_OBJECT_REF_GET_VALUES:
8750 len = decode_int (p, &p, end);
8752 for (i = 0; i < len; ++i) {
8753 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8757 /* Check that the field belongs to the object */
8759 for (k = obj->vtable->klass; k; k = k->parent) {
8760 if (k == f->parent) {
8766 return ERR_INVALID_FIELDID;
8768 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8772 if (mono_class_field_is_special_static (f))
8773 return ERR_INVALID_FIELDID;
8775 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8776 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8777 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8778 mono_field_static_get_value (vtable, f, val);
8779 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8782 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8786 case CMD_OBJECT_REF_SET_VALUES:
8787 len = decode_int (p, &p, end);
8789 for (i = 0; i < len; ++i) {
8790 f = decode_fieldid (p, &p, end, NULL, &err);
8794 /* Check that the field belongs to the object */
8796 for (k = obj->vtable->klass; k; k = k->parent) {
8797 if (k == f->parent) {
8803 return ERR_INVALID_FIELDID;
8805 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8809 if (mono_class_field_is_special_static (f))
8810 return ERR_INVALID_FIELDID;
8812 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8813 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8815 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8816 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8821 mono_field_static_set_value (vtable, f, val);
8824 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8830 case CMD_OBJECT_REF_GET_ADDRESS:
8831 buffer_add_long (buf, (gssize)obj);
8833 case CMD_OBJECT_REF_GET_DOMAIN:
8834 buffer_add_domainid (buf, obj->vtable->domain);
8836 case CMD_OBJECT_REF_GET_INFO:
8837 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8838 buffer_add_domainid (buf, obj->vtable->domain);
8841 return ERR_NOT_IMPLEMENTED;
8848 command_set_to_string (CommandSet command_set)
8850 switch (command_set) {
8853 case CMD_SET_OBJECT_REF:
8854 return "OBJECT_REF";
8855 case CMD_SET_STRING_REF:
8856 return "STRING_REF";
8857 case CMD_SET_THREAD:
8859 case CMD_SET_ARRAY_REF:
8861 case CMD_SET_EVENT_REQUEST:
8862 return "EVENT_REQUEST";
8863 case CMD_SET_STACK_FRAME:
8864 return "STACK_FRAME";
8865 case CMD_SET_APPDOMAIN:
8867 case CMD_SET_ASSEMBLY:
8869 case CMD_SET_METHOD:
8873 case CMD_SET_MODULE:
8882 static const char* vm_cmds_str [] = {
8890 "SET_PROTOCOL_VERSION",
8893 "GET_TYPES_FOR_SOURCE_FILE",
8898 static const char* thread_cmds_str[] = {
8907 static const char* event_cmds_str[] = {
8910 "REQUEST_CLEAR_ALL_BREAKPOINTS"
8913 static const char* appdomain_cmds_str[] = {
8915 "GET_FRIENDLY_NAME",
8917 "GET_ENTRY_ASSEMBLY",
8920 "CREATE_BOXED_VALUE"
8923 static const char* assembly_cmds_str[] = {
8926 "GET_MANIFEST_MODULE",
8932 static const char* module_cmds_str[] = {
8936 static const char* method_cmds_str[] = {
8938 "GET_DECLARING_TYPE",
8946 "MAKE_GENERIC_METHOD"
8949 static const char* type_cmds_str[] = {
8957 "IS_ASSIGNABLE_FROM",
8961 "GET_PROPERTY_CATTRS",
8962 "GET_SOURCE_FILES_2",
8964 "GET_METHODS_BY_NAME_FLAGS",
8966 "GET_INTERFACE_MAP",
8970 static const char* stack_frame_cmds_str[] = {
8976 static const char* array_cmds_str[] = {
8982 static const char* string_cmds_str[] = {
8988 static const char* object_cmds_str[] = {
8999 cmd_to_string (CommandSet set, int command)
9007 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9009 case CMD_SET_OBJECT_REF:
9010 cmds = object_cmds_str;
9011 cmds_len = G_N_ELEMENTS (object_cmds_str);
9013 case CMD_SET_STRING_REF:
9014 cmds = string_cmds_str;
9015 cmds_len = G_N_ELEMENTS (string_cmds_str);
9017 case CMD_SET_THREAD:
9018 cmds = thread_cmds_str;
9019 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9021 case CMD_SET_ARRAY_REF:
9022 cmds = array_cmds_str;
9023 cmds_len = G_N_ELEMENTS (array_cmds_str);
9025 case CMD_SET_EVENT_REQUEST:
9026 cmds = event_cmds_str;
9027 cmds_len = G_N_ELEMENTS (event_cmds_str);
9029 case CMD_SET_STACK_FRAME:
9030 cmds = stack_frame_cmds_str;
9031 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9033 case CMD_SET_APPDOMAIN:
9034 cmds = appdomain_cmds_str;
9035 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9037 case CMD_SET_ASSEMBLY:
9038 cmds = assembly_cmds_str;
9039 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9041 case CMD_SET_METHOD:
9042 cmds = method_cmds_str;
9043 cmds_len = G_N_ELEMENTS (method_cmds_str);
9046 cmds = type_cmds_str;
9047 cmds_len = G_N_ELEMENTS (type_cmds_str);
9049 case CMD_SET_MODULE:
9050 cmds = module_cmds_str;
9051 cmds_len = G_N_ELEMENTS (module_cmds_str);
9054 cmds = event_cmds_str;
9055 cmds_len = G_N_ELEMENTS (event_cmds_str);
9060 if (command > 0 && command <= cmds_len)
9061 return cmds [command - 1];
9067 wait_for_attach (void)
9069 #ifndef DISABLE_SOCKET_TRANSPORT
9070 if (listen_fd == -1) {
9071 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9075 /* Block and wait for client connection */
9076 conn_fd = socket_transport_accept (listen_fd);
9077 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9078 if (conn_fd == -1) {
9079 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9083 g_assert_not_reached ();
9087 disconnected = !transport_handshake ();
9089 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9099 * This thread handles communication with the debugger client using a JDWP
9102 static guint32 WINAPI
9103 debugger_thread (void *arg)
9105 int res, len, id, flags, command_set = 0, command = 0;
9106 guint8 header [HEADER_LENGTH];
9107 guint8 *data, *p, *end;
9111 gboolean attach_failed = FALSE;
9113 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9115 debugger_thread_id = GetCurrentThreadId ();
9117 mono_jit_thread_attach (mono_get_root_domain ());
9119 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9121 mono_set_is_debugger_attached (TRUE);
9123 if (agent_config.defer) {
9124 if (!wait_for_attach ()) {
9125 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9126 attach_failed = TRUE; // Don't abort process when we can't listen
9128 /* Send start event to client */
9129 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9133 while (!attach_failed) {
9134 res = transport_recv (header, HEADER_LENGTH);
9136 /* This will break if the socket is closed during shutdown too */
9137 if (res != HEADER_LENGTH) {
9138 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9143 end = header + HEADER_LENGTH;
9145 len = decode_int (p, &p, end);
9146 id = decode_int (p, &p, end);
9147 flags = decode_byte (p, &p, end);
9148 command_set = decode_byte (p, &p, end);
9149 command = decode_byte (p, &p, end);
9151 g_assert (flags == 0);
9154 const char *cmd_str;
9157 cmd_str = cmd_to_string (command_set, command);
9159 sprintf (cmd_num, "%d", command);
9163 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d].\n", command_set_to_string (command_set), cmd_str, id));
9166 data = g_malloc (len - HEADER_LENGTH);
9167 if (len - HEADER_LENGTH > 0)
9169 res = transport_recv (data, len - HEADER_LENGTH);
9170 if (res != len - HEADER_LENGTH) {
9171 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9177 end = data + (len - HEADER_LENGTH);
9179 buffer_init (&buf, 128);
9184 /* Process the request */
9185 switch (command_set) {
9187 err = vm_commands (command, id, p, end, &buf);
9188 if (!err && command == CMD_VM_INVOKE_METHOD)
9189 /* Sent after the invoke is complete */
9192 case CMD_SET_EVENT_REQUEST:
9193 err = event_commands (command, p, end, &buf);
9195 case CMD_SET_APPDOMAIN:
9196 err = domain_commands (command, p, end, &buf);
9198 case CMD_SET_ASSEMBLY:
9199 err = assembly_commands (command, p, end, &buf);
9201 case CMD_SET_MODULE:
9202 err = module_commands (command, p, end, &buf);
9205 err = type_commands (command, p, end, &buf);
9207 case CMD_SET_METHOD:
9208 err = method_commands (command, p, end, &buf);
9210 case CMD_SET_THREAD:
9211 err = thread_commands (command, p, end, &buf);
9213 case CMD_SET_STACK_FRAME:
9214 err = frame_commands (command, p, end, &buf);
9216 case CMD_SET_ARRAY_REF:
9217 err = array_commands (command, p, end, &buf);
9219 case CMD_SET_STRING_REF:
9220 err = string_commands (command, p, end, &buf);
9222 case CMD_SET_OBJECT_REF:
9223 err = object_commands (command, p, end, &buf);
9226 err = ERR_NOT_IMPLEMENTED;
9230 send_reply_packet (id, err, &buf);
9235 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9239 mono_set_is_debugger_attached (FALSE);
9241 mono_mutex_lock (&debugger_thread_exited_mutex);
9242 debugger_thread_exited = TRUE;
9243 mono_cond_signal (&debugger_thread_exited_cond);
9244 mono_mutex_unlock (&debugger_thread_exited_mutex);
9246 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9248 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9249 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9250 start_debugger_thread ();
9256 #else /* DISABLE_DEBUGGER_AGENT */
9259 mono_debugger_agent_parse_options (char *options)
9261 g_error ("This runtime is configured with the debugger agent disabled.");
9265 mono_debugger_agent_init (void)
9270 mono_debugger_agent_breakpoint_hit (void *sigctx)
9275 mono_debugger_agent_single_step_event (void *sigctx)
9280 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9285 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9291 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9292 MonoContext *catch_ctx)
9297 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9302 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9307 mono_debugger_agent_user_break (void)
9313 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9318 mono_debugger_agent_debug_log_is_enabled (void)