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 30
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,
308 EVENT_KIND_VM_START = 0,
309 EVENT_KIND_VM_DEATH = 1,
310 EVENT_KIND_THREAD_START = 2,
311 EVENT_KIND_THREAD_DEATH = 3,
312 EVENT_KIND_APPDOMAIN_CREATE = 4,
313 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
314 EVENT_KIND_METHOD_ENTRY = 6,
315 EVENT_KIND_METHOD_EXIT = 7,
316 EVENT_KIND_ASSEMBLY_LOAD = 8,
317 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
318 EVENT_KIND_BREAKPOINT = 10,
319 EVENT_KIND_STEP = 11,
320 EVENT_KIND_TYPE_LOAD = 12,
321 EVENT_KIND_EXCEPTION = 13,
322 EVENT_KIND_KEEPALIVE = 14,
323 EVENT_KIND_USER_BREAK = 15,
324 EVENT_KIND_USER_LOG = 16
328 SUSPEND_POLICY_NONE = 0,
329 SUSPEND_POLICY_EVENT_THREAD = 1,
330 SUSPEND_POLICY_ALL = 2
335 ERR_INVALID_OBJECT = 20,
336 ERR_INVALID_FIELDID = 25,
337 ERR_INVALID_FRAMEID = 30,
338 ERR_NOT_IMPLEMENTED = 100,
339 ERR_NOT_SUSPENDED = 101,
340 ERR_INVALID_ARGUMENT = 102,
342 ERR_NO_INVOCATION = 104,
343 ERR_ABSENT_INFORMATION = 105,
344 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
345 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
350 MOD_KIND_THREAD_ONLY = 3,
351 MOD_KIND_LOCATION_ONLY = 7,
352 MOD_KIND_EXCEPTION_ONLY = 8,
354 MOD_KIND_ASSEMBLY_ONLY = 11,
355 MOD_KIND_SOURCE_FILE_ONLY = 12,
356 MOD_KIND_TYPE_NAME_ONLY = 13
371 STEP_FILTER_NONE = 0,
372 STEP_FILTER_STATIC_CTOR = 1,
373 STEP_FILTER_DEBUGGER_HIDDEN = 2,
374 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
375 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
379 TOKEN_TYPE_STRING = 0,
381 TOKEN_TYPE_FIELD = 2,
382 TOKEN_TYPE_METHOD = 3,
383 TOKEN_TYPE_UNKNOWN = 4
387 VALUE_TYPE_ID_NULL = 0xf0,
388 VALUE_TYPE_ID_TYPE = 0xf1
392 FRAME_FLAG_DEBUGGER_INVOKE = 1,
393 FRAME_FLAG_NATIVE_TRANSITION = 2
397 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
398 INVOKE_FLAG_SINGLE_THREADED = 2
402 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
403 } BindingFlagsExtensions;
407 CMD_VM_ALL_THREADS = 2,
412 CMD_VM_INVOKE_METHOD = 7,
413 CMD_VM_SET_PROTOCOL_VERSION = 8,
414 CMD_VM_ABORT_INVOKE = 9,
415 CMD_VM_SET_KEEPALIVE = 10,
416 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
417 CMD_VM_GET_TYPES = 12,
418 CMD_VM_INVOKE_METHODS = 13
422 CMD_THREAD_GET_FRAME_INFO = 1,
423 CMD_THREAD_GET_NAME = 2,
424 CMD_THREAD_GET_STATE = 3,
425 CMD_THREAD_GET_INFO = 4,
426 CMD_THREAD_GET_ID = 5,
427 CMD_THREAD_GET_TID = 6,
428 CMD_THREAD_SET_IP = 7
432 CMD_EVENT_REQUEST_SET = 1,
433 CMD_EVENT_REQUEST_CLEAR = 2,
434 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
442 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
443 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
444 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
445 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
446 CMD_APPDOMAIN_CREATE_STRING = 5,
447 CMD_APPDOMAIN_GET_CORLIB = 6,
448 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
452 CMD_ASSEMBLY_GET_LOCATION = 1,
453 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
454 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
455 CMD_ASSEMBLY_GET_OBJECT = 4,
456 CMD_ASSEMBLY_GET_TYPE = 5,
457 CMD_ASSEMBLY_GET_NAME = 6
461 CMD_MODULE_GET_INFO = 1,
465 CMD_FIELD_GET_INFO = 1,
469 CMD_METHOD_GET_NAME = 1,
470 CMD_METHOD_GET_DECLARING_TYPE = 2,
471 CMD_METHOD_GET_DEBUG_INFO = 3,
472 CMD_METHOD_GET_PARAM_INFO = 4,
473 CMD_METHOD_GET_LOCALS_INFO = 5,
474 CMD_METHOD_GET_INFO = 6,
475 CMD_METHOD_GET_BODY = 7,
476 CMD_METHOD_RESOLVE_TOKEN = 8,
477 CMD_METHOD_GET_CATTRS = 9,
478 CMD_METHOD_MAKE_GENERIC_METHOD = 10
482 CMD_TYPE_GET_INFO = 1,
483 CMD_TYPE_GET_METHODS = 2,
484 CMD_TYPE_GET_FIELDS = 3,
485 CMD_TYPE_GET_VALUES = 4,
486 CMD_TYPE_GET_OBJECT = 5,
487 CMD_TYPE_GET_SOURCE_FILES = 6,
488 CMD_TYPE_SET_VALUES = 7,
489 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
490 CMD_TYPE_GET_PROPERTIES = 9,
491 CMD_TYPE_GET_CATTRS = 10,
492 CMD_TYPE_GET_FIELD_CATTRS = 11,
493 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
494 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
495 CMD_TYPE_GET_VALUES_2 = 14,
496 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
497 CMD_TYPE_GET_INTERFACES = 16,
498 CMD_TYPE_GET_INTERFACE_MAP = 17,
499 CMD_TYPE_IS_INITIALIZED = 18
503 CMD_STACK_FRAME_GET_VALUES = 1,
504 CMD_STACK_FRAME_GET_THIS = 2,
505 CMD_STACK_FRAME_SET_VALUES = 3
509 CMD_ARRAY_REF_GET_LENGTH = 1,
510 CMD_ARRAY_REF_GET_VALUES = 2,
511 CMD_ARRAY_REF_SET_VALUES = 3,
515 CMD_STRING_REF_GET_VALUE = 1,
516 CMD_STRING_REF_GET_LENGTH = 2,
517 CMD_STRING_REF_GET_CHARS = 3
521 CMD_OBJECT_REF_GET_TYPE = 1,
522 CMD_OBJECT_REF_GET_VALUES = 2,
523 CMD_OBJECT_REF_IS_COLLECTED = 3,
524 CMD_OBJECT_REF_GET_ADDRESS = 4,
525 CMD_OBJECT_REF_GET_DOMAIN = 5,
526 CMD_OBJECT_REF_SET_VALUES = 6,
527 CMD_OBJECT_REF_GET_INFO = 7,
533 int count; /* For kind == MOD_KIND_COUNT */
534 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
535 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
536 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
537 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
538 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
539 StepFilter filter; /* For kind == MOD_KIND_STEP */
541 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
550 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
554 * Describes a single step request.
558 MonoInternalThread *thread;
564 MonoMethod *last_method;
566 /* Whenever single stepping is performed using start/stop_single_stepping () */
568 /* The list of breakpoints used to implement step-over */
570 /* The number of frames at the start of a step-over */
575 * Contains additional information for an event
578 /* For EVENT_KIND_EXCEPTION */
580 MonoContext catch_ctx;
582 /* For EVENT_KIND_USER_LOG */
584 char *category, *message;
585 /* For EVENT_KIND_TYPE_LOAD */
589 /* Dummy structure used for the profiler callbacks */
594 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
597 #define get_last_sock_error() WSAGetLastError()
598 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
599 #define MONO_EINTR WSAEINTR
601 #define get_last_sock_error() errno
602 #define MONO_EWOULDBLOCK EWOULDBLOCK
603 #define MONO_EINTR EINTR
606 #define CHECK_PROTOCOL_VERSION(major,minor) \
607 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
613 static AgentConfig agent_config;
616 * Whenever the agent is fully initialized.
617 * When using the onuncaught or onthrow options, only some parts of the agent are
618 * initialized on startup, and the full initialization which includes connection
619 * establishment and the startup of the agent thread is only done in response to
622 static gint32 inited;
624 #ifndef DISABLE_SOCKET_TRANSPORT
626 static int listen_fd;
629 static int packet_id = 0;
631 static int objref_id = 0;
633 static int event_request_id = 0;
635 static int frame_id = 0;
637 static GPtrArray *event_requests;
639 static MonoNativeTlsKey debugger_tls_id;
641 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
643 /* Maps MonoInternalThread -> DebuggerTlsData */
644 static MonoGHashTable *thread_to_tls;
646 /* Maps tid -> MonoInternalThread */
647 static MonoGHashTable *tid_to_thread;
649 /* Maps tid -> MonoThread (not MonoInternalThread) */
650 static MonoGHashTable *tid_to_thread_obj;
652 static gsize debugger_thread_id;
654 static HANDLE debugger_thread_handle;
656 static int log_level;
658 static gboolean embedding;
660 static FILE *log_file;
662 /* Assemblies whose assembly load event has no been sent yet */
663 static GPtrArray *pending_assembly_loads;
665 /* Whenever the debugger thread has exited */
666 static gboolean debugger_thread_exited;
668 /* Cond variable used to wait for debugger_thread_exited becoming true */
669 static mono_cond_t debugger_thread_exited_cond;
671 /* Mutex for the cond var above */
672 static mono_mutex_t debugger_thread_exited_mutex;
674 static DebuggerProfiler debugger_profiler;
676 /* The single step request instance */
677 static SingleStepReq *ss_req = NULL;
678 static gpointer ss_invoke_addr = NULL;
680 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
681 /* Number of single stepping operations in progress */
685 /* The protocol version of the client */
686 static int major_version, minor_version;
688 /* Whenever the variables above are set by the client */
689 static gboolean protocol_version_set;
691 /* A hash table containing all active domains */
692 static GHashTable *domains;
694 /* The number of times the runtime is suspended */
695 static gint32 suspend_count;
697 static void transport_init (void);
698 static void transport_connect (const char *address);
699 static gboolean transport_handshake (void);
700 static void register_transport (DebuggerTransport *trans);
702 static guint32 WINAPI debugger_thread (void *arg);
704 static void runtime_initialized (MonoProfiler *prof);
706 static void runtime_shutdown (MonoProfiler *prof);
708 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
710 static void thread_end (MonoProfiler *prof, uintptr_t tid);
712 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
714 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
716 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
718 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
720 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
722 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
724 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
726 static void emit_assembly_load (gpointer assembly, gpointer user_data);
728 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
730 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
732 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
734 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
736 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
738 static void start_single_stepping (void);
740 static void stop_single_stepping (void);
742 static void suspend_current (void);
744 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
746 static void clear_types_for_assembly (MonoAssembly *assembly);
748 static void clear_breakpoints_for_domain (MonoDomain *domain);
750 static void process_profiler_event (EventKind event, gpointer arg);
752 /* Submodule init/cleanup */
753 static void breakpoints_init (void);
754 static void breakpoints_cleanup (void);
756 static void objrefs_init (void);
757 static void objrefs_cleanup (void);
759 static void ids_init (void);
760 static void ids_cleanup (void);
762 static void suspend_init (void);
764 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
765 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
766 static void ss_destroy (SingleStepReq *req);
768 static void start_debugger_thread (void);
769 static void stop_debugger_thread (void);
771 static void finish_agent_init (gboolean on_startup);
773 static void process_profiler_event (EventKind event, gpointer arg);
775 static void invalidate_frames (DebuggerTlsData *tls);
777 #ifndef DISABLE_SOCKET_TRANSPORT
779 register_socket_transport (void);
783 parse_address (char *address, char **host, int *port)
785 char *pos = strchr (address, ':');
787 if (pos == NULL || pos == address)
790 *host = g_malloc (pos - address + 1);
791 strncpy (*host, address, pos - address);
792 (*host) [pos - address] = '\0';
794 *port = atoi (pos + 1);
802 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
803 fprintf (stderr, "Available options:\n");
804 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
805 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
806 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
807 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
808 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
809 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
810 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
811 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
812 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
813 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
817 parse_flag (const char *option, char *flag)
819 if (!strcmp (flag, "y"))
821 else if (!strcmp (flag, "n"))
824 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
831 mono_debugger_agent_parse_options (char *options)
838 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
839 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
843 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
845 options = g_strdup_printf ("%s,%s", options, extra);
847 agent_config.enabled = TRUE;
848 agent_config.suspend = TRUE;
849 agent_config.server = FALSE;
850 agent_config.defer = FALSE;
851 agent_config.address = NULL;
853 args = g_strsplit (options, ",", -1);
854 for (ptr = args; ptr && *ptr; ptr ++) {
857 if (strncmp (arg, "transport=", 10) == 0) {
858 agent_config.transport = g_strdup (arg + 10);
859 } else if (strncmp (arg, "address=", 8) == 0) {
860 agent_config.address = g_strdup (arg + 8);
861 } else if (strncmp (arg, "loglevel=", 9) == 0) {
862 agent_config.log_level = atoi (arg + 9);
863 } else if (strncmp (arg, "logfile=", 8) == 0) {
864 agent_config.log_file = g_strdup (arg + 8);
865 } else if (strncmp (arg, "suspend=", 8) == 0) {
866 agent_config.suspend = parse_flag ("suspend", arg + 8);
867 } else if (strncmp (arg, "server=", 7) == 0) {
868 agent_config.server = parse_flag ("server", arg + 7);
869 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
870 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
871 } else if (strncmp (arg, "onthrow=", 8) == 0) {
872 /* We support multiple onthrow= options */
873 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
874 } else if (strncmp (arg, "onthrow", 7) == 0) {
875 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
876 } else if (strncmp (arg, "help", 4) == 0) {
879 } else if (strncmp (arg, "timeout=", 8) == 0) {
880 agent_config.timeout = atoi (arg + 8);
881 } else if (strncmp (arg, "launch=", 7) == 0) {
882 agent_config.launch = g_strdup (arg + 7);
883 } else if (strncmp (arg, "embedding=", 10) == 0) {
884 agent_config.embedding = atoi (arg + 10) == 1;
885 } else if (strncmp (arg, "keepalive=", 10) == 0) {
886 agent_config.keepalive = atoi (arg + 10);
887 } else if (strncmp (arg, "setpgid=", 8) == 0) {
888 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
895 if (agent_config.server && !agent_config.suspend) {
896 /* Waiting for deferred attachment */
897 agent_config.defer = TRUE;
898 if (agent_config.address == NULL) {
899 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
903 //agent_config.log_level = 0;
905 if (agent_config.transport == NULL) {
906 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
910 if (agent_config.address == NULL && !agent_config.server) {
911 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
916 if (!strcmp (agent_config.transport, "dt_socket")) {
917 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
918 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
925 mono_debugger_agent_init (void)
927 if (!agent_config.enabled)
932 /* Need to know whenever a thread has acquired the loader mutex */
933 mono_loader_lock_track_ownership (TRUE);
935 event_requests = g_ptr_array_new ();
937 mono_mutex_init (&debugger_thread_exited_mutex);
938 mono_cond_init (&debugger_thread_exited_cond, NULL);
940 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
941 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
942 mono_profiler_install_runtime_initialized (runtime_initialized);
943 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
944 mono_profiler_install_thread (thread_startup, thread_end);
945 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
946 mono_profiler_install_jit_end (jit_end);
947 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
949 mono_native_tls_alloc (&debugger_tls_id, NULL);
951 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
952 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
954 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
955 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
957 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
958 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
960 pending_assembly_loads = g_ptr_array_new ();
961 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
963 log_level = agent_config.log_level;
965 embedding = agent_config.embedding;
968 if (agent_config.log_file) {
969 log_file = fopen (agent_config.log_file, "w+");
971 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
983 mini_get_debug_options ()->gen_seq_points = TRUE;
985 * This is needed because currently we don't handle liveness info.
987 mini_get_debug_options ()->mdb_optimizations = TRUE;
989 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
990 /* This is needed because we can't set local variables in registers yet */
991 mono_disable_optimizations (MONO_OPT_LINEARS);
995 * The stack walk done from thread_interrupt () needs to be signal safe, but it
996 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
997 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1000 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1003 if (agent_config.setpgid)
1007 if (!agent_config.onuncaught && !agent_config.onthrow)
1008 finish_agent_init (TRUE);
1012 * finish_agent_init:
1014 * Finish the initialization of the agent. This involves connecting the transport
1015 * and starting the agent thread. This is either done at startup, or
1016 * in response to some event like an unhandled exception.
1019 finish_agent_init (gboolean on_startup)
1023 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1026 if (agent_config.launch) {
1029 // FIXME: Generated address
1030 // FIXME: Races with transport_connect ()
1032 argv [0] = agent_config.launch;
1033 argv [1] = agent_config.transport;
1034 argv [2] = agent_config.address;
1037 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1039 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1044 transport_connect (agent_config.address);
1047 /* Do some which is usually done after sending the VMStart () event */
1048 vm_start_event_sent = TRUE;
1049 start_debugger_thread ();
1054 mono_debugger_agent_cleanup (void)
1059 stop_debugger_thread ();
1061 breakpoints_cleanup ();
1065 mono_mutex_destroy (&debugger_thread_exited_mutex);
1066 mono_cond_destroy (&debugger_thread_exited_cond);
1073 #ifndef DISABLE_SOCKET_TRANSPORT
1078 * recv() + handle incomplete reads and EINTR
1081 socket_transport_recv (void *buf, int len)
1087 static gint32 last_keepalive;
1092 res = recv (fd, (char *) buf + total, len - total, flags);
1095 if (agent_config.keepalive) {
1096 gboolean need_keepalive = FALSE;
1097 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1098 need_keepalive = TRUE;
1099 } else if (res == -1) {
1100 /* This could happen if recv () is interrupted repeatedly */
1101 msecs = mono_msec_ticks ();
1102 if (msecs - last_keepalive >= agent_config.keepalive) {
1103 need_keepalive = TRUE;
1104 last_keepalive = msecs;
1107 if (need_keepalive) {
1108 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1112 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1117 #define HAVE_GETADDRINFO 1
1121 set_keepalive (void)
1126 if (!agent_config.keepalive || !conn_fd)
1129 tv.tv_sec = agent_config.keepalive / 1000;
1130 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1132 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1133 g_assert (result >= 0);
1137 socket_transport_accept (int socket_fd)
1139 conn_fd = accept (socket_fd, NULL, NULL);
1140 if (conn_fd == -1) {
1141 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1143 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1150 socket_transport_send (void *data, int len)
1155 res = send (conn_fd, data, len, 0);
1156 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1164 * socket_transport_connect:
1166 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1169 socket_transport_connect (const char *address)
1171 #ifdef HAVE_GETADDRINFO
1172 struct addrinfo hints;
1173 struct addrinfo *result, *rp;
1175 struct hostent *result;
1177 int sfd = -1, s, res;
1178 char port_string [128];
1182 if (agent_config.address) {
1183 res = parse_address (agent_config.address, &host, &port);
1184 g_assert (res == 0);
1194 sprintf (port_string, "%d", port);
1196 mono_network_init ();
1198 /* Obtain address(es) matching host/port */
1199 #ifdef HAVE_GETADDRINFO
1200 memset (&hints, 0, sizeof (struct addrinfo));
1201 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1202 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1204 hints.ai_protocol = 0; /* Any protocol */
1206 s = getaddrinfo (host, port_string, &hints, &result);
1208 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1212 /* The PS3 doesn't even have _r or hstrerror () */
1213 result = gethostbyname (host);
1215 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1220 if (agent_config.server) {
1221 #ifdef HAVE_GETADDRINFO
1222 /* Wait for a connection */
1224 struct sockaddr_in addr;
1227 /* No address, generate one */
1228 sfd = socket (AF_INET, SOCK_STREAM, 0);
1231 /* This will bind the socket to a random port */
1232 res = listen (sfd, 16);
1234 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1239 addrlen = sizeof (addr);
1240 memset (&addr, 0, sizeof (addr));
1241 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1242 g_assert (res == 0);
1244 host = (char*)"127.0.0.1";
1245 port = ntohs (addr.sin_port);
1247 /* Emit the address to stdout */
1248 /* FIXME: Should print another interface, not localhost */
1249 printf ("%s:%d\n", host, port);
1251 /* Listen on the provided address */
1252 for (rp = result; rp != NULL; rp = rp->ai_next) {
1255 sfd = socket (rp->ai_family, rp->ai_socktype,
1260 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1263 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1267 res = listen (sfd, 16);
1276 * this function is not present on win2000 which we still support, and the
1277 * workaround described here:
1278 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1279 * only works with MSVC.
1281 #ifdef HAVE_GETADDRINFO
1282 freeaddrinfo (result);
1287 if (agent_config.defer)
1290 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1292 if (agent_config.timeout) {
1297 tv.tv_usec = agent_config.timeout * 1000;
1299 FD_SET (sfd, &readfds);
1300 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1302 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1307 conn_fd = socket_transport_accept (sfd);
1311 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1314 #endif /* HAVE_GETADDRINFO */
1316 /* Connect to the specified address */
1317 #ifdef HAVE_GETADDRINFO
1318 /* FIXME: Respect the timeout */
1319 for (rp = result; rp != NULL; rp = rp->ai_next) {
1320 sfd = socket (rp->ai_family, rp->ai_socktype,
1325 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1326 break; /* Success */
1332 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1336 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1338 g_assert_not_reached ();
1339 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1341 g_assert_not_reached ();
1347 /* See the comment above */
1348 #ifdef HAVE_GETADDRINFO
1349 freeaddrinfo (result);
1354 if (!transport_handshake ())
1359 socket_transport_close1 (void)
1361 /* This will interrupt the agent thread */
1362 /* Close the read part only so it can still send back replies */
1363 /* Also shut down the connection listener so that we can exit normally */
1365 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1366 shutdown (conn_fd, SD_BOTH);
1367 shutdown (listen_fd, SD_BOTH);
1368 closesocket (listen_fd);
1370 shutdown (conn_fd, SHUT_RD);
1371 shutdown (listen_fd, SHUT_RDWR);
1377 socket_transport_close2 (void)
1380 shutdown (conn_fd, SD_BOTH);
1382 shutdown (conn_fd, SHUT_RDWR);
1387 register_socket_transport (void)
1389 DebuggerTransport trans;
1391 trans.name = "dt_socket";
1392 trans.connect = socket_transport_connect;
1393 trans.close1 = socket_transport_close1;
1394 trans.close2 = socket_transport_close2;
1395 trans.send = socket_transport_send;
1396 trans.recv = socket_transport_recv;
1398 register_transport (&trans);
1401 #endif /* DISABLE_SOCKET_TRANSPORT */
1407 #define MAX_TRANSPORTS 16
1409 static DebuggerTransport *transport;
1411 static DebuggerTransport transports [MAX_TRANSPORTS];
1412 static int ntransports;
1415 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1418 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1420 register_transport (trans);
1424 register_transport (DebuggerTransport *trans)
1426 g_assert (ntransports < MAX_TRANSPORTS);
1428 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1433 transport_init (void)
1437 #ifndef DISABLE_SOCKET_TRANSPORT
1438 register_socket_transport ();
1441 for (i = 0; i < ntransports; ++i) {
1442 if (!strcmp (agent_config.transport, transports [i].name))
1445 if (i == ntransports) {
1446 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1447 for (i = 0; i < ntransports; ++i)
1448 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1449 fprintf (stderr, "\n");
1452 transport = &transports [i];
1456 transport_connect (const char *address)
1458 transport->connect (address);
1462 transport_close1 (void)
1464 transport->close1 ();
1468 transport_close2 (void)
1470 transport->close2 ();
1474 transport_send (void *buf, int len)
1476 return transport->send (buf, len);
1480 transport_recv (void *buf, int len)
1482 return transport->recv (buf, len);
1486 mono_debugger_agent_transport_handshake (void)
1488 return transport_handshake ();
1492 transport_handshake (void)
1494 char handshake_msg [128];
1498 disconnected = TRUE;
1500 /* Write handshake message */
1501 sprintf (handshake_msg, "DWP-Handshake");
1503 res = transport_send (handshake_msg, strlen (handshake_msg));
1504 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1505 g_assert (res != -1);
1508 res = transport_recv (buf, strlen (handshake_msg));
1509 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1510 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1515 * To support older clients, the client sends its protocol version after connecting
1516 * using a command. Until that is received, default to our protocol version.
1518 major_version = MAJOR_VERSION;
1519 minor_version = MINOR_VERSION;
1520 protocol_version_set = FALSE;
1522 #ifndef DISABLE_SOCKET_TRANSPORT
1523 // FIXME: Move this somewhere else
1525 * Set TCP_NODELAY on the socket so the client receives events/command
1526 * results immediately.
1530 int result = setsockopt (conn_fd,
1535 g_assert (result >= 0);
1541 disconnected = FALSE;
1546 stop_debugger_thread (void)
1551 transport_close1 ();
1554 * Wait for the thread to exit.
1556 * If we continue with the shutdown without waiting for it, then the client might
1557 * not receive an answer to its last command like a resume.
1558 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1561 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1562 if (GetCurrentThreadId () != debugger_thread_id) {
1564 mono_mutex_lock (&debugger_thread_exited_mutex);
1565 if (!debugger_thread_exited) {
1567 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1568 mono_mutex_unlock (&debugger_thread_exited_mutex);
1570 mono_mutex_lock (&debugger_thread_exited_mutex);
1573 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1576 mono_mutex_unlock (&debugger_thread_exited_mutex);
1577 } while (!debugger_thread_exited);
1580 transport_close2 ();
1584 start_debugger_thread (void)
1586 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1587 g_assert (debugger_thread_handle);
1591 * Functions to decode protocol data
1595 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1598 g_assert (*endbuf <= limit);
1603 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1606 g_assert (*endbuf <= limit);
1608 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1611 static inline gint64
1612 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1614 guint32 high = decode_int (buf, &buf, limit);
1615 guint32 low = decode_int (buf, &buf, limit);
1619 return ((((guint64)high) << 32) | ((guint64)low));
1623 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1625 return decode_int (buf, endbuf, limit);
1629 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1631 int len = decode_int (buf, &buf, limit);
1639 s = g_malloc (len + 1);
1642 memcpy (s, buf, len);
1651 * Functions to encode protocol data
1655 guint8 *buf, *p, *end;
1659 buffer_init (Buffer *buf, int size)
1661 buf->buf = g_malloc (size);
1663 buf->end = buf->buf + size;
1667 buffer_make_room (Buffer *buf, int size)
1669 if (buf->end - buf->p < size) {
1670 int new_size = buf->end - buf->buf + size + 32;
1671 guint8 *p = g_realloc (buf->buf, new_size);
1672 size = buf->p - buf->buf;
1675 buf->end = buf->buf + new_size;
1680 buffer_add_byte (Buffer *buf, guint8 val)
1682 buffer_make_room (buf, 1);
1688 buffer_add_short (Buffer *buf, guint32 val)
1690 buffer_make_room (buf, 2);
1691 buf->p [0] = (val >> 8) & 0xff;
1692 buf->p [1] = (val >> 0) & 0xff;
1697 buffer_add_int (Buffer *buf, guint32 val)
1699 buffer_make_room (buf, 4);
1700 buf->p [0] = (val >> 24) & 0xff;
1701 buf->p [1] = (val >> 16) & 0xff;
1702 buf->p [2] = (val >> 8) & 0xff;
1703 buf->p [3] = (val >> 0) & 0xff;
1708 buffer_add_long (Buffer *buf, guint64 l)
1710 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1711 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1715 buffer_add_id (Buffer *buf, int id)
1717 buffer_add_int (buf, (guint64)id);
1721 buffer_add_data (Buffer *buf, guint8 *data, int len)
1723 buffer_make_room (buf, len);
1724 memcpy (buf->p, data, len);
1729 buffer_add_string (Buffer *buf, const char *str)
1734 buffer_add_int (buf, 0);
1737 buffer_add_int (buf, len);
1738 buffer_add_data (buf, (guint8*)str, len);
1743 buffer_free (Buffer *buf)
1749 send_packet (int command_set, int command, Buffer *data)
1755 id = InterlockedIncrement (&packet_id);
1757 len = data->p - data->buf + 11;
1758 buffer_init (&buf, len);
1759 buffer_add_int (&buf, len);
1760 buffer_add_int (&buf, id);
1761 buffer_add_byte (&buf, 0); /* flags */
1762 buffer_add_byte (&buf, command_set);
1763 buffer_add_byte (&buf, command);
1764 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1766 res = transport_send (buf.buf, len);
1774 send_reply_packet (int id, int error, Buffer *data)
1780 len = data->p - data->buf + 11;
1781 buffer_init (&buf, len);
1782 buffer_add_int (&buf, len);
1783 buffer_add_int (&buf, id);
1784 buffer_add_byte (&buf, 0x80); /* flags */
1785 buffer_add_byte (&buf, (error >> 8) & 0xff);
1786 buffer_add_byte (&buf, error);
1787 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1789 res = transport_send (buf.buf, len);
1801 * Represents an object accessible by the debugger client.
1804 /* Unique id used in the wire protocol to refer to objects */
1807 * A weakref gc handle pointing to the object. The gc handle is used to
1808 * detect if the object was garbage collected.
1813 /* Maps objid -> ObjRef */
1814 static GHashTable *objrefs;
1817 free_objref (gpointer value)
1821 mono_gchandle_free (o->handle);
1829 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1833 objrefs_cleanup (void)
1835 g_hash_table_destroy (objrefs);
1839 static GHashTable *obj_to_objref;
1840 static MonoGHashTable *suspended_objs;
1843 * Return an ObjRef for OBJ.
1846 get_objref (MonoObject *obj)
1849 GSList *reflist = NULL, *l;
1855 mono_loader_lock ();
1857 if (!obj_to_objref) {
1858 obj_to_objref = g_hash_table_new (NULL, NULL);
1859 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1860 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1863 if (suspend_count) {
1865 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1867 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1870 /* FIXME: The tables can grow indefinitely */
1872 if (mono_gc_is_moving ()) {
1874 * Objects can move, so use a hash table mapping hash codes to lists of
1875 * ObjRef structures.
1877 hash = mono_object_hash (obj);
1879 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1880 for (l = reflist; l; l = l->next) {
1882 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1883 mono_loader_unlock ();
1888 /* Use a hash table with masked pointers to internalize object references */
1889 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1890 /* ref might refer to a different object with the same addr which was GCd */
1891 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1892 mono_loader_unlock ();
1897 ref = g_new0 (ObjRef, 1);
1898 ref->id = InterlockedIncrement (&objref_id);
1899 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1901 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1903 if (mono_gc_is_moving ()) {
1904 reflist = g_slist_append (reflist, ref);
1905 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1907 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1910 mono_loader_unlock ();
1916 true_pred (gpointer key, gpointer value, gpointer user_data)
1922 clear_suspended_objs (void)
1924 mono_loader_lock ();
1925 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
1926 mono_loader_unlock ();
1930 get_objid (MonoObject *obj)
1932 return get_objref (obj)->id;
1936 * Set OBJ to the object identified by OBJID.
1937 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1941 get_object_allow_null (int objid, MonoObject **obj)
1951 return ERR_INVALID_OBJECT;
1953 mono_loader_lock ();
1955 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1958 *obj = mono_gchandle_get_target (ref->handle);
1959 mono_loader_unlock ();
1961 return ERR_INVALID_OBJECT;
1964 mono_loader_unlock ();
1965 return ERR_INVALID_OBJECT;
1970 get_object (int objid, MonoObject **obj)
1972 int err = get_object_allow_null (objid, obj);
1977 return ERR_INVALID_OBJECT;
1982 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1984 return decode_id (buf, endbuf, limit);
1988 buffer_add_objid (Buffer *buf, MonoObject *o)
1990 buffer_add_id (buf, get_objid (o));
2009 * Represents a runtime structure accessible to the debugger client
2012 /* Unique id used in the wire protocol */
2014 /* Domain of the runtime structure, NULL if the domain was unloaded */
2021 MonoAssembly *assembly;
2022 MonoClassField *field;
2024 MonoProperty *property;
2029 /* Maps runtime structure -> Id */
2030 GHashTable *val_to_id [ID_NUM];
2031 /* Classes whose class load event has been sent */
2032 GHashTable *loaded_classes;
2033 /* Maps MonoClass->GPtrArray of file names */
2034 GHashTable *source_files;
2035 /* Maps source file basename -> GSList of classes */
2036 GHashTable *source_file_to_class;
2037 /* Same with ignore-case */
2038 GHashTable *source_file_to_class_ignorecase;
2042 static GPtrArray *ids [ID_NUM];
2049 for (i = 0; i < ID_NUM; ++i)
2050 ids [i] = g_ptr_array_new ();
2058 for (i = 0; i < ID_NUM; ++i) {
2060 for (j = 0; j < ids [i]->len; ++j)
2061 g_free (g_ptr_array_index (ids [i], j));
2062 g_ptr_array_free (ids [i], TRUE);
2069 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2071 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2073 GHashTableIter iter;
2074 GPtrArray *file_names;
2079 for (i = 0; i < ID_NUM; ++i)
2080 if (info->val_to_id [i])
2081 g_hash_table_destroy (info->val_to_id [i]);
2082 g_hash_table_destroy (info->loaded_classes);
2084 g_hash_table_iter_init (&iter, info->source_files);
2085 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2086 for (i = 0; i < file_names->len; ++i)
2087 g_free (g_ptr_array_index (file_names, i));
2088 g_ptr_array_free (file_names, TRUE);
2091 g_hash_table_iter_init (&iter, info->source_file_to_class);
2092 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2097 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2098 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2106 domain_jit_info (domain)->agent_info = NULL;
2108 /* Clear ids referencing structures in the domain */
2109 for (i = 0; i < ID_NUM; ++i) {
2111 for (j = 0; j < ids [i]->len; ++j) {
2112 Id *id = g_ptr_array_index (ids [i], j);
2113 if (id->domain == domain)
2119 mono_loader_lock ();
2120 g_hash_table_remove (domains, domain);
2121 mono_loader_unlock ();
2124 static AgentDomainInfo*
2125 get_agent_domain_info (MonoDomain *domain)
2127 AgentDomainInfo *info = NULL;
2129 mono_domain_lock (domain);
2131 info = domain_jit_info (domain)->agent_info;
2133 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2134 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2135 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2136 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2137 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2140 mono_domain_unlock (domain);
2146 get_id (MonoDomain *domain, IdType type, gpointer val)
2149 AgentDomainInfo *info;
2154 mono_loader_lock ();
2156 mono_domain_lock (domain);
2158 info = get_agent_domain_info (domain);
2160 if (info->val_to_id [type] == NULL)
2161 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2163 id = g_hash_table_lookup (info->val_to_id [type], val);
2165 mono_domain_unlock (domain);
2166 mono_loader_unlock ();
2170 id = g_new0 (Id, 1);
2172 id->id = ids [type]->len + 1;
2173 id->domain = domain;
2176 g_hash_table_insert (info->val_to_id [type], val, id);
2178 mono_domain_unlock (domain);
2180 g_ptr_array_add (ids [type], id);
2182 mono_loader_unlock ();
2187 static inline gpointer
2188 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2192 int id = decode_id (buf, endbuf, limit);
2201 // FIXME: error handling
2202 mono_loader_lock ();
2203 g_assert (id > 0 && id <= ids [type]->len);
2205 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2206 mono_loader_unlock ();
2208 if (res->domain == NULL) {
2209 DEBUG (0, fprintf (log_file, "ERR_UNLOADED, id=%d, type=%d.\n", id, type));
2210 *err = ERR_UNLOADED;
2215 *domain = res->domain;
2217 return res->data.val;
2221 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2223 buffer_add_id (buf, get_id (domain, type, val));
2226 static inline MonoClass*
2227 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2231 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2232 if (G_UNLIKELY (log_level >= 2) && klass) {
2235 s = mono_type_full_name (&klass->byval_arg);
2236 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2242 static inline MonoAssembly*
2243 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2245 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2248 static inline MonoImage*
2249 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2251 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2254 static inline MonoMethod*
2255 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2259 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2260 if (G_UNLIKELY (log_level >= 2) && m) {
2263 s = mono_method_full_name (m, TRUE);
2264 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2270 static inline MonoClassField*
2271 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2273 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2276 static inline MonoDomain*
2277 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2279 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2282 static inline MonoProperty*
2283 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2285 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2289 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2291 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2292 if (G_UNLIKELY (log_level >= 2) && klass) {
2295 s = mono_type_full_name (&klass->byval_arg);
2296 if (GetCurrentThreadId () == debugger_thread_id)
2297 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2299 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2305 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2307 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2308 if (G_UNLIKELY (log_level >= 2) && method) {
2311 s = mono_method_full_name (method, 1);
2312 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2318 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2320 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2324 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2326 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2330 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2332 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2336 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2338 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2342 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2344 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2347 static void invoke_method (void);
2354 * save_thread_context:
2356 * Set CTX as the current threads context which is used for computing stack traces.
2357 * This function is signal-safe.
2360 save_thread_context (MonoContext *ctx)
2362 DebuggerTlsData *tls;
2364 tls = mono_native_tls_get_value (debugger_tls_id);
2368 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2370 mono_thread_state_init_from_current (&tls->context);
2373 /* Number of threads suspended */
2375 * If this is equal to the size of thread_to_tls, the runtime is considered
2378 static gint32 threads_suspend_count;
2380 static mono_mutex_t suspend_mutex;
2382 /* Cond variable used to wait for suspend_count becoming 0 */
2383 static mono_cond_t suspend_cond;
2385 /* Semaphore used to wait for a thread becoming suspended */
2386 static MonoSemType suspend_sem;
2391 mono_mutex_init (&suspend_mutex);
2392 mono_cond_init (&suspend_cond, NULL);
2393 MONO_SEM_INIT (&suspend_sem, 0);
2398 StackFrameInfo last_frame;
2399 gboolean last_frame_set;
2402 } GetLastFrameUserData;
2405 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2407 GetLastFrameUserData *data = user_data;
2409 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2412 if (!data->last_frame_set) {
2413 /* Store the last frame */
2414 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2415 data->last_frame_set = TRUE;
2418 /* Store the context/lmf for the frame above the last frame */
2419 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2420 data->lmf = info->lmf;
2428 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2429 * INFO is set, process the thread described by INFO.
2430 * This should be signal safe.
2433 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2437 MonoNativeThreadId tid;
2440 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2441 * guarantee the signal handler will be called that many times. Instead of tracking
2442 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2443 * has been requested that hasn't been handled yet, otherwise we can have threads
2444 * refuse to die when VM_EXIT is called
2446 #if defined(__APPLE__)
2447 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2451 * We use interrupt_count to determine whenever this interrupt should be processed
2452 * by us or the normal interrupt processing code in the signal handler.
2453 * There is no race here with notify_thread (), since the signal is sent after
2454 * incrementing interrupt_count.
2456 if (tls->interrupt_count == 0)
2459 InterlockedDecrement (&tls->interrupt_count);
2463 ip = mono_arch_ip_from_context (sigctx);
2465 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2470 tid = mono_thread_info_get_tid (info);
2472 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2474 // FIXME: Races when the thread leaves managed code before hitting a single step
2478 /* Running managed code, will be suspended by the single step code */
2479 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2483 * Running native code, will be suspended when it returns to/enters
2484 * managed code. Treat it as already suspended.
2485 * This might interrupt the code in process_single_step_inner (), we use the
2486 * tls->suspending flag to avoid races when that happens.
2488 if (!tls->suspended && !tls->suspending) {
2490 GetLastFrameUserData data;
2492 // FIXME: printf is not signal safe, but this is only used during
2493 // debugger debugging
2495 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2496 //save_thread_context (&ctx);
2499 /* Already terminated */
2503 * We are in a difficult position: we want to be able to provide stack
2504 * traces for this thread, but we can't use the current ctx+lmf, since
2505 * the thread is still running, so it might return to managed code,
2506 * making these invalid.
2507 * So we start a stack walk and save the first frame, along with the
2508 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2509 * suspended when it returns to managed code, so the parent's ctx should
2512 data.last_frame_set = FALSE;
2514 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2516 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2517 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2518 * since we are not in a JITted method.
2520 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2522 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2524 if (data.last_frame_set) {
2525 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2526 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2528 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2531 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2532 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2533 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2535 tls->async_state.valid = FALSE;
2538 mono_memory_barrier ();
2540 tls->suspended = TRUE;
2541 MONO_SEM_POST (&suspend_sem);
2548 * mono_debugger_agent_thread_interrupt:
2550 * Called by the abort signal handler.
2551 * Should be signal safe.
2554 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2556 DebuggerTlsData *tls;
2561 tls = mono_native_tls_get_value (debugger_tls_id);
2563 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2567 return thread_interrupt (tls, NULL, sigctx, ji);
2571 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2574 mono_debugger_agent_thread_interrupt (NULL, NULL);
2576 #endif /* HOST_WIN32 */
2579 * reset_native_thread_suspend_state:
2581 * Reset the suspended flag and state on native threads
2584 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2586 DebuggerTlsData *tls = value;
2588 if (!tls->really_suspended && tls->suspended) {
2589 tls->suspended = FALSE;
2591 * The thread might still be running if it was executing native code, so the state won't be invalided by
2592 * suspend_current ().
2594 tls->context.valid = FALSE;
2595 tls->async_state.valid = FALSE;
2596 invalidate_frames (tls);
2603 * Notify a thread that it needs to suspend.
2606 notify_thread (gpointer key, gpointer value, gpointer user_data)
2608 MonoInternalThread *thread = key;
2609 DebuggerTlsData *tls = value;
2610 gsize tid = thread->tid;
2613 if (GetCurrentThreadId () == tid || tls->terminated)
2616 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2619 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2620 * guarantee the signal handler will be called that many times. Instead of tracking
2621 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2622 * has been requested that hasn't been handled yet, otherwise we can have threads
2623 * refuse to die when VM_EXIT is called
2625 #if defined(__APPLE__)
2626 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2630 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2631 * of things like breaking waits etc. which we don't want.
2633 InterlockedIncrement (&tls->interrupt_count);
2636 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2638 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2640 if (mono_thread_info_new_interrupt_enabled ()) {
2641 MonoThreadInfo *info;
2644 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2646 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2648 * Attached thread which died without detaching.
2650 tls->terminated = TRUE;
2652 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2654 thread_interrupt (tls, info, NULL, ji);
2656 mono_thread_info_resume (mono_thread_info_get_tid (info));
2659 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2661 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2663 * Attached thread which died without detaching.
2665 tls->terminated = TRUE;
2672 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2674 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2678 if (mono_loader_lock_is_owned_by_self ()) {
2680 * Shortcut for the check in suspend_current (). This speeds up processing
2681 * when executing long running code inside the loader lock, i.e. assembly load
2687 if (debugger_thread_id == GetCurrentThreadId ())
2690 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2691 if (suspend_count - tls->resume_count > 0)
2692 tls->suspending = TRUE;
2694 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2696 if (suspend_count - tls->resume_count == 0) {
2698 * We are executing a single threaded invoke but the single step for
2699 * suspending is still active.
2700 * FIXME: This slows down single threaded invokes.
2702 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2706 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2708 /* Can't suspend in these methods */
2709 method = jinfo_get_method (ji);
2710 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2713 save_thread_context (ctx);
2721 * Increase the suspend count of the VM. While the suspend count is greater
2722 * than 0, runtime threads are suspended at certain points during execution.
2727 mono_loader_lock ();
2729 mono_mutex_lock (&suspend_mutex);
2733 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2735 if (suspend_count == 1) {
2736 // FIXME: Is it safe to call this inside the lock ?
2737 start_single_stepping ();
2738 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2741 mono_mutex_unlock (&suspend_mutex);
2743 if (suspend_count == 1)
2745 * Suspend creation of new threadpool threads, since they cannot run
2747 mono_thread_pool_suspend ();
2749 mono_loader_unlock ();
2755 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2763 g_assert (debugger_thread_id == GetCurrentThreadId ());
2765 mono_loader_lock ();
2767 mono_mutex_lock (&suspend_mutex);
2769 g_assert (suspend_count > 0);
2772 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2774 if (suspend_count == 0) {
2775 // FIXME: Is it safe to call this inside the lock ?
2776 stop_single_stepping ();
2777 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2780 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2781 err = mono_cond_broadcast (&suspend_cond);
2782 g_assert (err == 0);
2784 mono_mutex_unlock (&suspend_mutex);
2785 //g_assert (err == 0);
2787 if (suspend_count == 0)
2788 mono_thread_pool_resume ();
2790 mono_loader_unlock ();
2796 * Resume just one thread.
2799 resume_thread (MonoInternalThread *thread)
2802 DebuggerTlsData *tls;
2804 g_assert (debugger_thread_id == GetCurrentThreadId ());
2806 mono_loader_lock ();
2808 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2811 mono_mutex_lock (&suspend_mutex);
2813 g_assert (suspend_count > 0);
2815 DEBUG(1, fprintf (log_file, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid));
2817 tls->resume_count += suspend_count;
2820 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2821 * but only the one whose resume_count field is > 0 will be resumed.
2823 err = mono_cond_broadcast (&suspend_cond);
2824 g_assert (err == 0);
2826 mono_mutex_unlock (&suspend_mutex);
2827 //g_assert (err == 0);
2829 mono_loader_unlock ();
2833 invalidate_frames (DebuggerTlsData *tls)
2838 tls = mono_native_tls_get_value (debugger_tls_id);
2841 for (i = 0; i < tls->frame_count; ++i) {
2842 if (tls->frames [i]->jit)
2843 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2844 g_free (tls->frames [i]);
2846 g_free (tls->frames);
2847 tls->frame_count = 0;
2854 * Suspend the current thread until the runtime is resumed. If the thread has a
2855 * pending invoke, then the invoke is executed before this function returns.
2858 suspend_current (void)
2861 DebuggerTlsData *tls;
2863 g_assert (debugger_thread_id != GetCurrentThreadId ());
2865 if (mono_loader_lock_is_owned_by_self ()) {
2867 * If we own the loader mutex, can't suspend until we release it, since the
2868 * whole runtime can deadlock otherwise.
2873 tls = mono_native_tls_get_value (debugger_tls_id);
2876 mono_mutex_lock (&suspend_mutex);
2878 tls->suspending = FALSE;
2879 tls->really_suspended = TRUE;
2881 if (!tls->suspended) {
2882 tls->suspended = TRUE;
2883 MONO_SEM_POST (&suspend_sem);
2886 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2888 while (suspend_count - tls->resume_count > 0) {
2890 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2892 mono_mutex_unlock (&suspend_mutex);
2894 mono_mutex_lock (&suspend_mutex);
2900 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2901 g_assert (err == 0);
2905 tls->suspended = FALSE;
2906 tls->really_suspended = FALSE;
2908 threads_suspend_count --;
2910 mono_mutex_unlock (&suspend_mutex);
2912 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2914 if (tls->pending_invoke) {
2915 /* Save the original context */
2916 tls->pending_invoke->has_ctx = TRUE;
2917 tls->pending_invoke->ctx = tls->context.ctx;
2922 /* The frame info becomes invalid after a resume */
2923 tls->context.valid = FALSE;
2924 tls->async_state.valid = FALSE;
2925 invalidate_frames (tls);
2929 count_thread (gpointer key, gpointer value, gpointer user_data)
2931 DebuggerTlsData *tls = value;
2933 if (!tls->suspended && !tls->terminated)
2934 *(int*)user_data = *(int*)user_data + 1;
2938 count_threads_to_wait_for (void)
2942 mono_loader_lock ();
2943 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2944 mono_loader_unlock ();
2952 * Wait until the runtime is completely suspended.
2955 wait_for_suspend (void)
2957 int nthreads, nwait, err;
2958 gboolean waited = FALSE;
2960 // FIXME: Threads starting/stopping ?
2961 mono_loader_lock ();
2962 nthreads = mono_g_hash_table_size (thread_to_tls);
2963 mono_loader_unlock ();
2966 nwait = count_threads_to_wait_for ();
2968 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2969 err = MONO_SEM_WAIT (&suspend_sem);
2970 g_assert (err == 0);
2978 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2984 * Return whenever the runtime is suspended.
2989 return count_threads_to_wait_for () == 0;
2992 static MonoSeqPointInfo*
2993 get_seq_points (MonoDomain *domain, MonoMethod *method)
2995 MonoSeqPointInfo *seq_points;
2997 mono_domain_lock (domain);
2998 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2999 if (!seq_points && method->is_inflated) {
3000 /* generic sharing + aot */
3001 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
3003 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
3005 mono_domain_unlock (domain);
3011 no_seq_points_found (MonoMethod *method)
3014 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3016 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3020 * find_next_seq_point_for_native_offset:
3022 * Find the first sequence point after NATIVE_OFFSET.
3025 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3027 MonoSeqPointInfo *seq_points;
3030 seq_points = get_seq_points (domain, method);
3036 g_assert (seq_points);
3040 for (i = 0; i < seq_points->len; ++i) {
3041 if (seq_points->seq_points [i].native_offset >= native_offset)
3042 return &seq_points->seq_points [i];
3049 * find_prev_seq_point_for_native_offset:
3051 * Find the first sequence point before NATIVE_OFFSET.
3054 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3056 MonoSeqPointInfo *seq_points;
3059 seq_points = get_seq_points (domain, method);
3065 for (i = seq_points->len - 1; i >= 0; --i) {
3066 if (seq_points->seq_points [i].native_offset <= native_offset)
3067 return &seq_points->seq_points [i];
3076 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3077 * should be the location of a sequence point.
3079 static G_GNUC_UNUSED SeqPoint*
3080 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3082 MonoSeqPointInfo *seq_points;
3087 seq_points = get_seq_points (domain, method);
3092 for (i = 0; i < seq_points->len; ++i) {
3093 if (seq_points->seq_points [i].il_offset == il_offset)
3094 return &seq_points->seq_points [i];
3101 DebuggerTlsData *tls;
3103 } ComputeFramesUserData;
3106 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3108 ComputeFramesUserData *ud = user_data;
3110 MonoMethod *method, *actual_method, *api_method;
3114 if (info->type != FRAME_TYPE_MANAGED) {
3115 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3116 /* Mark the last frame as an invoke frame */
3118 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3124 method = jinfo_get_method (info->ji);
3126 method = info->method;
3127 actual_method = info->actual_method;
3128 api_method = method;
3133 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3136 if (info->il_offset == -1) {
3137 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3138 if (ud->frames == NULL) {
3139 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3141 info->il_offset = sp->il_offset;
3143 if (info->il_offset == -1)
3144 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3147 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));
3149 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3150 if (!CHECK_PROTOCOL_VERSION (2, 17))
3151 /* Older clients can't handle this flag */
3153 api_method = mono_marshal_method_from_wrapper (method);
3156 actual_method = api_method;
3157 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3160 frame = g_new0 (StackFrame, 1);
3161 frame->method = method;
3162 frame->actual_method = actual_method;
3163 frame->api_method = api_method;
3164 frame->il_offset = info->il_offset;
3165 frame->native_offset = info->native_offset;
3166 frame->flags = flags;
3167 frame->ji = info->ji;
3168 if (info->reg_locations)
3169 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3172 frame->has_ctx = TRUE;
3174 frame->domain = info->domain;
3176 ud->frames = g_slist_append (ud->frames, frame);
3182 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3184 ComputeFramesUserData *ud = user_data;
3187 * 'tls->filter_ctx' is the location of the throw site.
3189 * mono_walk_stack() will never actually hit the throw site, but unwind
3190 * directly from the filter to the call site; we abort stack unwinding here
3191 * once this happens and resume from the throw site.
3194 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3197 return process_frame (info, ctx, user_data);
3201 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3203 ComputeFramesUserData user_data;
3205 int i, findex, new_frame_count;
3206 StackFrame **new_frames, *f;
3207 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3209 // FIXME: Locking on tls
3210 if (tls->frames && tls->frames_up_to_date)
3213 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3215 user_data.tls = tls;
3216 user_data.frames = NULL;
3217 if (tls->terminated) {
3218 tls->frame_count = 0;
3220 } if (!tls->really_suspended && tls->async_state.valid) {
3221 /* Have to use the state saved by the signal handler */
3222 process_frame (&tls->async_last_frame, NULL, &user_data);
3223 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3224 } else if (tls->filter_state.valid) {
3226 * We are inside an exception filter.
3228 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3230 if (tls->context.valid)
3231 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3233 * After that, we resume unwinding from the location where the exception has been thrown.
3235 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3236 } else if (tls->context.valid) {
3237 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3240 tls->frame_count = 0;
3244 new_frame_count = g_slist_length (user_data.frames);
3245 new_frames = g_new0 (StackFrame*, new_frame_count);
3247 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3251 * Reuse the id for already existing stack frames, so invokes don't invalidate
3252 * the still valid stack frames.
3254 for (i = 0; i < tls->frame_count; ++i) {
3255 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3256 f->id = tls->frames [i]->id;
3261 if (i >= tls->frame_count)
3262 f->id = InterlockedIncrement (&frame_id);
3264 new_frames [findex ++] = f;
3267 g_slist_free (user_data.frames);
3269 invalidate_frames (tls);
3271 tls->frames = new_frames;
3272 tls->frame_count = new_frame_count;
3273 tls->frames_up_to_date = TRUE;
3277 * GHFunc to emit an appdomain creation event
3278 * @param key Don't care
3279 * @param value A loaded appdomain
3280 * @param user_data Don't care
3283 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3285 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3286 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3290 * GHFunc to emit a thread start event
3291 * @param key A thread id
3292 * @param value A thread object
3293 * @param user_data Don't care
3296 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3298 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3299 process_profiler_event (EVENT_KIND_THREAD_START, value);
3303 * GFunc to emit an assembly load event
3304 * @param value A loaded assembly
3305 * @param user_data Don't care
3308 emit_assembly_load (gpointer value, gpointer user_data)
3310 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3314 * GFunc to emit a type load event
3315 * @param value A loaded type
3316 * @param user_data Don't care
3319 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3321 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3325 strdup_tolower (char *s)
3330 for (p = s2; *p; ++p)
3340 * create_event_list:
3342 * Return a list of event request ids matching EVENT, starting from REQS, which
3343 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3345 * We return request ids, instead of requests, to simplify threading, since
3346 * requests could be deleted anytime when the loader lock is not held.
3347 * LOCKING: Assumes the loader lock is held.
3350 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3353 GSList *events = NULL;
3355 *suspend_policy = SUSPEND_POLICY_NONE;
3358 reqs = event_requests;
3363 for (i = 0; i < reqs->len; ++i) {
3364 EventRequest *req = g_ptr_array_index (reqs, i);
3365 if (req->event_kind == event) {
3366 gboolean filtered = FALSE;
3369 for (j = 0; j < req->nmodifiers; ++j) {
3370 Modifier *mod = &req->modifiers [j];
3372 if (mod->kind == MOD_KIND_COUNT) {
3374 if (mod->data.count > 0) {
3375 if (mod->data.count > 0) {
3377 if (mod->data.count == 0)
3381 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3382 if (mod->data.thread != mono_thread_internal_current ())
3384 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3385 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3387 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3389 if (ei->caught && !mod->caught)
3391 if (!ei->caught && !mod->uncaught)
3393 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3395 gboolean found = FALSE;
3396 MonoAssembly **assemblies = mod->data.assemblies;
3399 for (k = 0; assemblies [k]; ++k)
3400 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3405 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3406 gpointer iter = NULL;
3408 MonoDebugSourceInfo *sinfo;
3409 char *source_file, *s;
3410 gboolean found = FALSE;
3412 GPtrArray *source_file_list;
3414 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3415 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3418 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3419 for (i = 0; i < source_file_list->len; ++i) {
3420 sinfo = g_ptr_array_index (source_file_list, i);
3422 * Do a case-insesitive match by converting the file name to
3425 s = strdup_tolower (sinfo->source_file);
3426 if (g_hash_table_lookup (mod->data.source_files, s))
3429 char *s2 = g_path_get_basename (sinfo->source_file);
3430 char *s3 = strdup_tolower (s2);
3432 if (g_hash_table_lookup (mod->data.source_files, s3))
3439 g_ptr_array_free (source_file_list, TRUE);
3444 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3447 s = mono_type_full_name (&ei->klass->byval_arg);
3448 if (!g_hash_table_lookup (mod->data.type_names, s))
3451 } else if (mod->kind == MOD_KIND_STEP) {
3452 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3453 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3454 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3456 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3457 MonoCustomAttrInfo *ainfo;
3458 static MonoClass *klass;
3461 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3464 if (!ji->dbg_hidden_inited) {
3465 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3467 if (mono_custom_attrs_has_attr (ainfo, klass))
3468 ji->dbg_hidden = TRUE;
3469 mono_custom_attrs_free (ainfo);
3471 ji->dbg_hidden_inited = TRUE;
3476 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3477 MonoCustomAttrInfo *ainfo;
3478 static MonoClass *klass;
3481 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3484 if (!ji->dbg_step_through_inited) {
3485 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3487 if (mono_custom_attrs_has_attr (ainfo, klass))
3488 ji->dbg_step_through = TRUE;
3489 mono_custom_attrs_free (ainfo);
3491 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3493 if (mono_custom_attrs_has_attr (ainfo, klass))
3494 ji->dbg_step_through = TRUE;
3495 mono_custom_attrs_free (ainfo);
3497 ji->dbg_step_through_inited = TRUE;
3499 if (ji->dbg_step_through)
3502 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3503 MonoCustomAttrInfo *ainfo;
3504 static MonoClass *klass;
3507 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3510 if (!ji->dbg_non_user_code_inited) {
3511 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3513 if (mono_custom_attrs_has_attr (ainfo, klass))
3514 ji->dbg_non_user_code = TRUE;
3515 mono_custom_attrs_free (ainfo);
3517 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3519 if (mono_custom_attrs_has_attr (ainfo, klass))
3520 ji->dbg_non_user_code = TRUE;
3521 mono_custom_attrs_free (ainfo);
3523 ji->dbg_non_user_code_inited = TRUE;
3525 if (ji->dbg_non_user_code)
3532 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3533 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3538 /* Send a VM START/DEATH event by default */
3539 if (event == EVENT_KIND_VM_START)
3540 events = g_slist_append (events, GINT_TO_POINTER (0));
3541 if (event == EVENT_KIND_VM_DEATH)
3542 events = g_slist_append (events, GINT_TO_POINTER (0));
3547 static G_GNUC_UNUSED const char*
3548 event_to_string (EventKind event)
3551 case EVENT_KIND_VM_START: return "VM_START";
3552 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3553 case EVENT_KIND_THREAD_START: return "THREAD_START";
3554 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3555 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3556 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3557 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3558 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3559 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3560 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3561 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3562 case EVENT_KIND_STEP: return "STEP";
3563 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3564 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3565 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3566 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3567 case EVENT_KIND_USER_LOG: return "USER_LOG";
3569 g_assert_not_reached ();
3577 * Send an event to the client, suspending the vm if needed.
3578 * LOCKING: Since this can suspend the calling thread, no locks should be held
3580 * The EVENTS list is freed by this function.
3583 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3587 MonoDomain *domain = mono_domain_get ();
3588 MonoThread *thread = NULL;
3589 MonoObject *keepalive_obj = NULL;
3590 gboolean send_success = FALSE;
3595 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3599 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3600 // FIXME: We miss those events
3601 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3605 if (vm_death_event_sent) {
3606 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3610 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3611 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3616 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3620 if (event == EVENT_KIND_KEEPALIVE)
3621 suspend_policy = SUSPEND_POLICY_NONE;
3626 if (agent_config.defer) {
3627 /* Make sure the thread id is always set when doing deferred debugging */
3628 if (debugger_thread_id == GetCurrentThreadId ()) {
3629 /* Don't suspend on events from the debugger thread */
3630 suspend_policy = SUSPEND_POLICY_NONE;
3631 thread = mono_thread_get_main ();
3633 else thread = mono_thread_current ();
3635 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3636 // FIXME: Send these with a NULL thread, don't suspend the current thread
3641 nevents = g_slist_length (events);
3642 buffer_init (&buf, 128);
3643 buffer_add_byte (&buf, suspend_policy);
3644 buffer_add_int (&buf, nevents);
3646 for (l = events; l; l = l->next) {
3647 buffer_add_byte (&buf, event); // event kind
3648 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3653 thread = mono_thread_current ();
3655 if (event == EVENT_KIND_VM_START && arg != NULL)
3658 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3661 case EVENT_KIND_THREAD_START:
3662 case EVENT_KIND_THREAD_DEATH:
3664 case EVENT_KIND_APPDOMAIN_CREATE:
3665 case EVENT_KIND_APPDOMAIN_UNLOAD:
3666 buffer_add_domainid (&buf, arg);
3668 case EVENT_KIND_METHOD_ENTRY:
3669 case EVENT_KIND_METHOD_EXIT:
3670 buffer_add_methodid (&buf, domain, arg);
3672 case EVENT_KIND_ASSEMBLY_LOAD:
3673 case EVENT_KIND_ASSEMBLY_UNLOAD:
3674 buffer_add_assemblyid (&buf, domain, arg);
3676 case EVENT_KIND_TYPE_LOAD:
3677 buffer_add_typeid (&buf, domain, arg);
3679 case EVENT_KIND_BREAKPOINT:
3680 case EVENT_KIND_STEP:
3681 buffer_add_methodid (&buf, domain, arg);
3682 buffer_add_long (&buf, il_offset);
3684 case EVENT_KIND_VM_START:
3685 buffer_add_domainid (&buf, mono_get_root_domain ());
3687 case EVENT_KIND_VM_DEATH:
3688 if (CHECK_PROTOCOL_VERSION (2, 27))
3689 buffer_add_int (&buf, mono_environment_exitcode_get ());
3691 case EVENT_KIND_EXCEPTION: {
3692 EventInfo *ei = arg;
3693 buffer_add_objid (&buf, ei->exc);
3695 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3696 * later after the suspension. (#12494).
3698 keepalive_obj = ei->exc;
3701 case EVENT_KIND_USER_BREAK:
3703 case EVENT_KIND_USER_LOG: {
3704 EventInfo *ei = arg;
3705 buffer_add_int (&buf, ei->level);
3706 buffer_add_string (&buf, ei->category ? ei->category : "");
3707 buffer_add_string (&buf, ei->message ? ei->message : "");
3710 case EVENT_KIND_KEEPALIVE:
3711 suspend_policy = SUSPEND_POLICY_NONE;
3714 g_assert_not_reached ();
3718 if (event == EVENT_KIND_VM_START) {
3719 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3720 if (!agent_config.defer)
3721 start_debugger_thread ();
3724 if (event == EVENT_KIND_VM_DEATH) {
3725 vm_death_event_sent = TRUE;
3726 suspend_policy = SUSPEND_POLICY_NONE;
3729 if (mono_runtime_is_shutting_down ())
3730 suspend_policy = SUSPEND_POLICY_NONE;
3732 if (suspend_policy != SUSPEND_POLICY_NONE) {
3734 * Save the thread context and start suspending before sending the packet,
3735 * since we could be receiving the resume request before send_packet ()
3738 save_thread_context (ctx);
3742 /* This will keep this object alive */
3743 get_objref (keepalive_obj);
3746 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3750 g_slist_free (events);
3753 if (!send_success) {
3754 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3758 if (event == EVENT_KIND_VM_START) {
3759 vm_start_event_sent = TRUE;
3762 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3764 switch (suspend_policy) {
3765 case SUSPEND_POLICY_NONE:
3767 case SUSPEND_POLICY_ALL:
3770 case SUSPEND_POLICY_EVENT_THREAD:
3774 g_assert_not_reached ();
3779 process_profiler_event (EventKind event, gpointer arg)
3783 EventInfo ei, *ei_arg = NULL;
3785 if (event == EVENT_KIND_TYPE_LOAD) {
3790 mono_loader_lock ();
3791 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3792 mono_loader_unlock ();
3794 process_event (event, arg, 0, NULL, events, suspend_policy);
3798 runtime_initialized (MonoProfiler *prof)
3800 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3801 if (agent_config.defer)
3802 start_debugger_thread ();
3806 runtime_shutdown (MonoProfiler *prof)
3808 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3810 mono_debugger_agent_cleanup ();
3814 thread_startup (MonoProfiler *prof, uintptr_t tid)
3816 MonoInternalThread *thread = mono_thread_internal_current ();
3817 MonoInternalThread *old_thread;
3818 DebuggerTlsData *tls;
3820 if (tid == debugger_thread_id)
3823 g_assert (thread->tid == tid);
3825 mono_loader_lock ();
3826 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3827 mono_loader_unlock ();
3829 if (thread == old_thread) {
3831 * For some reason, thread_startup () might be called for the same thread
3832 * multiple times (attach ?).
3834 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3838 * thread_end () might not be called for some threads, and the tid could
3841 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3842 mono_loader_lock ();
3843 mono_g_hash_table_remove (thread_to_tls, old_thread);
3844 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3845 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3846 mono_loader_unlock ();
3850 tls = mono_native_tls_get_value (debugger_tls_id);
3852 // FIXME: Free this somewhere
3853 tls = g_new0 (DebuggerTlsData, 1);
3854 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3855 tls->thread = thread;
3856 mono_native_tls_set_value (debugger_tls_id, tls);
3858 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3860 mono_loader_lock ();
3861 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3862 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3863 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3864 mono_loader_unlock ();
3866 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3869 * suspend_vm () could have missed this thread, so wait for a resume.
3875 thread_end (MonoProfiler *prof, uintptr_t tid)
3877 MonoInternalThread *thread;
3878 DebuggerTlsData *tls = NULL;
3880 mono_loader_lock ();
3881 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3883 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3884 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3886 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3887 tls->terminated = TRUE;
3888 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3889 MONO_GC_UNREGISTER_ROOT (tls->thread);
3893 mono_loader_unlock ();
3895 /* We might be called for threads started before we registered the start callback */
3897 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3898 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3903 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3905 mono_loader_lock ();
3906 g_hash_table_insert (domains, domain, domain);
3907 mono_loader_unlock ();
3909 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3913 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3915 clear_breakpoints_for_domain (domain);
3917 mono_loader_lock ();
3918 /* Invalidate each thread's frame stack */
3919 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3920 mono_loader_unlock ();
3922 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3926 * invalidate_each_thread:
3928 * A GHFunc to invalidate frames.
3929 * value must be a DebuggerTlsData*
3932 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3934 invalidate_frames (value);
3938 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3940 /* Sent later in jit_end () */
3941 mono_loader_lock ();
3942 g_ptr_array_add (pending_assembly_loads, assembly);
3943 mono_loader_unlock ();
3947 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3949 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3951 clear_event_requests_for_assembly (assembly);
3952 clear_types_for_assembly (assembly);
3956 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3958 #if defined(HOST_WIN32) && !defined(__GNUC__)
3959 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3961 gpointer stackptr = __builtin_frame_address (1);
3963 MonoInternalThread *thread = mono_thread_internal_current ();
3964 DebuggerTlsData *tls;
3966 mono_loader_lock ();
3968 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3969 /* Could be the debugger thread with assembly/type load hooks */
3971 tls->invoke_addr = stackptr;
3973 mono_loader_unlock ();
3977 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3980 #if defined(HOST_WIN32) && !defined(__GNUC__)
3981 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3983 gpointer stackptr = __builtin_frame_address (1);
3986 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3990 * We need to stop single stepping when exiting a runtime invoke, since if it is
3991 * a step out, it may return to native code, and thus never end.
3993 mono_loader_lock ();
3994 ss_invoke_addr = NULL;
3996 for (i = 0; i < event_requests->len; ++i) {
3997 EventRequest *req = g_ptr_array_index (event_requests, i);
3999 if (req->event_kind == EVENT_KIND_STEP) {
4000 ss_destroy (req->info);
4001 g_ptr_array_remove_index_fast (event_requests, i);
4006 mono_loader_unlock ();
4010 send_type_load (MonoClass *klass)
4012 gboolean type_load = FALSE;
4013 MonoDomain *domain = mono_domain_get ();
4014 AgentDomainInfo *info = NULL;
4016 mono_loader_lock ();
4017 mono_domain_lock (domain);
4019 info = get_agent_domain_info (domain);
4021 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4023 g_hash_table_insert (info->loaded_classes, klass, klass);
4026 mono_domain_unlock (domain);
4027 mono_loader_unlock ();
4029 emit_type_load (klass, klass, NULL);
4033 * Emit load events for all types currently loaded in the domain.
4034 * Takes the loader and domain locks.
4035 * user_data is unused.
4038 send_types_for_domain (MonoDomain *domain, void *user_data)
4040 AgentDomainInfo *info = NULL;
4042 mono_loader_lock ();
4043 mono_domain_lock (domain);
4044 info = get_agent_domain_info (domain);
4046 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4047 mono_domain_unlock (domain);
4048 mono_loader_unlock ();
4052 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4055 * We emit type load events when the first method of the type is JITted,
4056 * since the class load profiler callbacks might be called with the
4057 * loader lock held. They could also occur in the debugger thread.
4058 * Same for assembly load events.
4061 MonoAssembly *assembly = NULL;
4063 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4064 mono_loader_lock ();
4065 if (pending_assembly_loads->len > 0) {
4066 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4067 g_ptr_array_remove_index (pending_assembly_loads, 0);
4069 mono_loader_unlock ();
4072 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4078 send_type_load (method->klass);
4081 add_pending_breakpoints (method, jinfo);
4085 * BREAKPOINTS/SINGLE STEPPING
4089 * Contains information about an inserted breakpoint.
4092 long il_offset, native_offset;
4097 } BreakpointInstance;
4100 * Contains generic information about a breakpoint.
4104 * The method where the breakpoint is placed. Can be NULL in which case it
4105 * is inserted into every method. This is used to implement method entry/
4106 * exit events. Can be a generic method definition, in which case the
4107 * breakpoint is inserted into every instance.
4113 * A list of BreakpointInstance structures describing where the breakpoint
4114 * was inserted. There could be more than one because of
4115 * generics/appdomains/method entry/exit.
4117 GPtrArray *children;
4120 /* List of breakpoints */
4121 static GPtrArray *breakpoints;
4122 /* Maps breakpoint locations to the number of breakpoints at that location */
4123 static GHashTable *bp_locs;
4126 breakpoints_init (void)
4128 breakpoints = g_ptr_array_new ();
4129 bp_locs = g_hash_table_new (NULL, NULL);
4133 * insert_breakpoint:
4135 * Insert the breakpoint described by BP into the method described by
4139 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4142 BreakpointInstance *inst;
4143 SeqPoint *sp = NULL;
4146 mono_error_init (error);
4148 for (i = 0; i < seq_points->len; ++i) {
4149 sp = &seq_points->seq_points [i];
4151 if (sp->il_offset == bp->il_offset)
4155 if (i == seq_points->len) {
4157 * The set of IL offsets with seq points doesn't completely match the
4158 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4160 for (i = 0; i < seq_points->len; ++i) {
4161 sp = &seq_points->seq_points [i];
4163 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4168 if (i == seq_points->len) {
4169 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);
4171 for (i = 0; i < seq_points->len; ++i)
4172 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4175 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4176 g_warning ("%s", s);
4180 g_warning ("%s", s);
4186 inst = g_new0 (BreakpointInstance, 1);
4188 inst->native_offset = sp->native_offset;
4189 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4191 inst->domain = domain;
4193 mono_loader_lock ();
4195 g_ptr_array_add (bp->children, inst);
4197 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4198 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4199 mono_loader_unlock ();
4201 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4202 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4203 } else if (count == 0) {
4204 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4205 mono_arch_set_breakpoint (ji, inst->ip);
4211 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));
4215 remove_breakpoint (BreakpointInstance *inst)
4217 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4219 MonoJitInfo *ji = inst->ji;
4220 guint8 *ip = inst->ip;
4222 mono_loader_lock ();
4223 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4224 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4225 mono_loader_unlock ();
4227 g_assert (count > 0);
4229 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4230 mono_arch_clear_breakpoint (ji, ip);
4237 static inline gboolean
4238 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4244 if (method == bp->method)
4246 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4249 if (bp->method->is_inflated && method->is_inflated) {
4250 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4251 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4253 /* Open generic methods should match closed generic methods of the same class */
4254 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4255 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4256 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4258 /* FIXME: Handle !mvar */
4259 if (t1->type != MONO_TYPE_MVAR)
4270 * add_pending_breakpoints:
4272 * Insert pending breakpoints into the newly JITted method METHOD.
4275 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4278 MonoSeqPointInfo *seq_points;
4280 MonoMethod *jmethod;
4285 domain = mono_domain_get ();
4287 mono_loader_lock ();
4289 for (i = 0; i < breakpoints->len; ++i) {
4290 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4291 gboolean found = FALSE;
4293 if (!bp_matches_method (bp, method))
4296 for (j = 0; j < bp->children->len; ++j) {
4297 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4304 jmethod = jinfo_get_method (ji);
4305 mono_domain_lock (domain);
4306 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4307 if (!seq_points && jmethod->is_inflated)
4308 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4309 mono_domain_unlock (domain);
4311 /* Could be AOT code */
4313 g_assert (seq_points);
4315 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4319 mono_loader_unlock ();
4323 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4329 mono_error_init (error);
4331 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4333 /* Might be AOTed code */
4334 code = mono_aot_get_method (domain, method);
4336 ji = mono_jit_info_table_find (domain, code);
4341 insert_breakpoint (seq_points, domain, ji, bp, error);
4345 clear_breakpoint (MonoBreakpoint *bp);
4350 * Set a breakpoint at IL_OFFSET in METHOD.
4351 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4352 * METHOD can also be a generic method definition, in which case a breakpoint
4353 * is placed in all instances of the method.
4354 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4357 static MonoBreakpoint*
4358 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4361 GHashTableIter iter, iter2;
4364 MonoSeqPointInfo *seq_points;
4367 mono_error_init (error);
4370 // - suspend/resume the vm to prevent code patching problems
4371 // - multiple breakpoints on the same location
4372 // - dynamic methods
4375 bp = g_new0 (MonoBreakpoint, 1);
4376 bp->method = method;
4377 bp->il_offset = il_offset;
4379 bp->children = g_ptr_array_new ();
4381 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));
4383 mono_loader_lock ();
4385 g_hash_table_iter_init (&iter, domains);
4386 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4387 mono_domain_lock (domain);
4389 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4390 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4391 if (bp_matches_method (bp, m))
4392 set_bp_in_method (domain, m, seq_points, bp, error);
4395 mono_domain_unlock (domain);
4398 mono_loader_unlock ();
4400 mono_loader_lock ();
4401 g_ptr_array_add (breakpoints, bp);
4402 mono_loader_unlock ();
4404 if (error && !mono_error_ok (error)) {
4405 clear_breakpoint (bp);
4413 clear_breakpoint (MonoBreakpoint *bp)
4417 // FIXME: locking, races
4418 for (i = 0; i < bp->children->len; ++i) {
4419 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4421 remove_breakpoint (inst);
4426 mono_loader_lock ();
4427 g_ptr_array_remove (breakpoints, bp);
4428 mono_loader_unlock ();
4430 g_ptr_array_free (bp->children, TRUE);
4435 breakpoints_cleanup (void)
4439 mono_loader_lock ();
4441 while (i < event_requests->len) {
4442 EventRequest *req = g_ptr_array_index (event_requests, i);
4444 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4445 clear_breakpoint (req->info);
4446 g_ptr_array_remove_index_fast (event_requests, i);
4453 for (i = 0; i < breakpoints->len; ++i)
4454 g_free (g_ptr_array_index (breakpoints, i));
4456 g_ptr_array_free (breakpoints, TRUE);
4457 g_hash_table_destroy (bp_locs);
4462 mono_loader_unlock ();
4466 * clear_breakpoints_for_domain:
4468 * Clear breakpoint instances which reference DOMAIN.
4471 clear_breakpoints_for_domain (MonoDomain *domain)
4475 /* This could be called after shutdown */
4479 mono_loader_lock ();
4480 for (i = 0; i < breakpoints->len; ++i) {
4481 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4484 while (j < bp->children->len) {
4485 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4487 if (inst->domain == domain) {
4488 remove_breakpoint (inst);
4492 g_ptr_array_remove_index_fast (bp->children, j);
4498 mono_loader_unlock ();
4504 * Return FALSE if single stepping needs to continue.
4507 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4509 MonoDebugMethodInfo *minfo;
4510 MonoDebugSourceLocation *loc = NULL;
4511 gboolean hit = TRUE;
4514 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4516 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4518 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4522 if (req->depth == STEP_DEPTH_OVER && hit) {
4523 if (!tls->context.valid)
4524 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4525 compute_frame_info (tls->thread, tls);
4526 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4527 /* Hit the breakpoint in a recursive call */
4528 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4533 if (req->size != STEP_SIZE_LINE)
4536 /* Have to check whenever a different source line was reached */
4537 method = jinfo_get_method (ji);
4538 minfo = mono_debug_lookup_method (method);
4541 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4543 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4544 /* Have to continue single stepping */
4546 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4548 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4553 ss_req->last_method = method;
4554 ss_req->last_line = loc->row;
4555 mono_debug_free_source_location (loc);
4562 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4564 return bp->method && bp->method->klass->image->assembly == assembly;
4568 process_breakpoint_inner (DebuggerTlsData *tls)
4572 int i, j, suspend_policy;
4573 guint32 native_offset;
4575 BreakpointInstance *inst;
4576 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4577 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4578 EventKind kind = EVENT_KIND_BREAKPOINT;
4579 MonoContext *ctx = &tls->restore_ctx;
4581 MonoSeqPointInfo *info;
4584 // FIXME: Speed this up
4586 ip = MONO_CONTEXT_GET_IP (ctx);
4587 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4589 method = jinfo_get_method (ji);
4591 /* Compute the native offset of the breakpoint from the ip */
4592 native_offset = ip - (guint8*)ji->code_start;
4595 * Skip the instruction causing the breakpoint signal.
4597 mono_arch_skip_breakpoint (ctx, ji);
4599 if (method->wrapper_type || tls->disable_breakpoints)
4602 bp_reqs = g_ptr_array_new ();
4603 ss_reqs = g_ptr_array_new ();
4604 ss_reqs_orig = g_ptr_array_new ();
4606 mono_loader_lock ();
4609 * The ip points to the instruction causing the breakpoint event, which is after
4610 * the offset recorded in the seq point map, so find the prev seq point before ip.
4612 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4614 no_seq_points_found (method);
4617 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));
4620 for (i = 0; i < breakpoints->len; ++i) {
4621 bp = g_ptr_array_index (breakpoints, i);
4626 for (j = 0; j < bp->children->len; ++j) {
4627 inst = g_ptr_array_index (bp->children, j);
4628 if (inst->ji == ji && inst->sp == sp) {
4629 if (bp->req->event_kind == EVENT_KIND_STEP) {
4630 g_ptr_array_add (ss_reqs_orig, bp->req);
4632 g_ptr_array_add (bp_reqs, bp->req);
4637 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4638 /* Maybe a method entry/exit event */
4639 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4640 kind = EVENT_KIND_METHOD_ENTRY;
4641 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4642 kind = EVENT_KIND_METHOD_EXIT;
4645 /* Process single step requests */
4646 for (i = 0; i < ss_reqs_orig->len; ++i) {
4647 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4648 SingleStepReq *ss_req = req->info;
4651 if (mono_thread_internal_current () != ss_req->thread)
4654 hit = ss_update (ss_req, ji, sp, tls, ctx);
4656 g_ptr_array_add (ss_reqs, req);
4658 /* Start single stepping again from the current sequence point */
4659 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4662 if (ss_reqs->len > 0)
4663 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4664 if (bp_reqs->len > 0)
4665 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4666 if (kind != EVENT_KIND_BREAKPOINT)
4667 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4669 mono_loader_unlock ();
4671 g_ptr_array_free (bp_reqs, TRUE);
4672 g_ptr_array_free (ss_reqs, TRUE);
4675 * FIXME: The first event will suspend, so the second will only be sent after the
4679 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4681 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4682 if (enter_leave_events)
4683 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4686 /* Process a breakpoint/single step event after resuming from a signal handler */
4688 process_signal_event (void (*func) (DebuggerTlsData*))
4690 DebuggerTlsData *tls;
4691 MonoContext orig_restore_ctx, ctx;
4693 tls = mono_native_tls_get_value (debugger_tls_id);
4694 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4695 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4696 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4700 /* This is called when resuming from a signal handler, so it shouldn't return */
4701 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4702 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4703 mono_restore_context (&ctx);
4704 g_assert_not_reached ();
4708 process_breakpoint (void)
4710 process_signal_event (process_breakpoint_inner);
4714 resume_from_signal_handler (void *sigctx, void *func)
4716 DebuggerTlsData *tls;
4719 /* Save the original context in TLS */
4720 // FIXME: This might not work on an altstack ?
4721 tls = mono_native_tls_get_value (debugger_tls_id);
4723 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4726 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4727 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4728 // clob:c could be added to op_seq_point.
4730 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4731 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4732 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4733 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4735 MONO_CONTEXT_SET_IP (&ctx, func);
4737 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4739 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4740 mono_ppc_set_func_into_sigctx (sigctx, func);
4745 mono_debugger_agent_breakpoint_hit (void *sigctx)
4748 * We are called from a signal handler, and running code there causes all kinds of
4749 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4750 * So set up the signal context to return to the real breakpoint handler function.
4752 resume_from_signal_handler (sigctx, process_breakpoint);
4756 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4758 if (frame->managed) {
4759 *(MonoContext*)data = *ctx;
4768 * Called by System.Diagnostics.Debugger:Break ().
4771 mono_debugger_agent_user_break (void)
4773 if (agent_config.enabled) {
4778 /* Obtain a context */
4779 MONO_CONTEXT_SET_IP (&ctx, NULL);
4780 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4781 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4783 mono_loader_lock ();
4784 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4785 mono_loader_unlock ();
4787 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4794 ss_depth_to_string (StepDepth depth)
4797 case STEP_DEPTH_OVER:
4799 case STEP_DEPTH_OUT:
4801 case STEP_DEPTH_INTO:
4804 g_assert_not_reached ();
4810 process_single_step_inner (DebuggerTlsData *tls)
4815 int il_offset, suspend_policy;
4818 MonoContext *ctx = &tls->restore_ctx;
4821 MonoSeqPointInfo *info;
4823 ip = MONO_CONTEXT_GET_IP (ctx);
4825 /* Skip the instruction causing the single step */
4826 mono_arch_skip_single_step (ctx);
4828 if (suspend_count > 0) {
4829 process_suspend (tls, ctx);
4834 // FIXME: A suspend race
4837 if (mono_thread_internal_current () != ss_req->thread)
4840 if (log_level > 0) {
4841 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4843 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));
4846 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4848 method = jinfo_get_method (ji);
4851 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4856 * Stopping in memset makes half-initialized vtypes visible.
4857 * Stopping in memcpy makes half-copied vtypes visible.
4859 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4863 * The ip points to the instruction causing the single step event, which is before
4864 * the offset recorded in the seq point map, so find the next seq point after ip.
4866 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
4869 il_offset = sp->il_offset;
4871 if (!ss_update (ss_req, ji, sp, tls, ctx))
4874 /* Start single stepping again from the current sequence point */
4875 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4877 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4878 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4879 !strcmp (method->name, ".cctor"))
4882 // FIXME: Has to lock earlier
4884 reqs = g_ptr_array_new ();
4886 mono_loader_lock ();
4888 g_ptr_array_add (reqs, ss_req->req);
4890 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4892 g_ptr_array_free (reqs, TRUE);
4894 mono_loader_unlock ();
4896 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4900 process_single_step (void)
4902 process_signal_event (process_single_step_inner);
4906 * mono_debugger_agent_single_step_event:
4908 * Called from a signal handler to handle a single step event.
4911 mono_debugger_agent_single_step_event (void *sigctx)
4913 /* Resume to process_single_step through the signal context */
4915 // FIXME: Since step out/over is implemented using step in, the step in case should
4916 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4919 if (GetCurrentThreadId () == debugger_thread_id) {
4921 * This could happen despite our best effors when the runtime calls
4922 * assembly/type resolve hooks.
4923 * FIXME: Breakpoints too.
4927 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4928 mono_arch_skip_single_step (&ctx);
4929 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4933 resume_from_signal_handler (sigctx, process_single_step);
4937 debugger_agent_single_step_from_context (MonoContext *ctx)
4939 DebuggerTlsData *tls;
4940 MonoContext orig_restore_ctx;
4942 tls = mono_native_tls_get_value (debugger_tls_id);
4945 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4946 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4947 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4949 process_single_step_inner (tls);
4951 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4952 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4956 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4958 DebuggerTlsData *tls;
4959 MonoContext orig_restore_ctx;
4961 tls = mono_native_tls_get_value (debugger_tls_id);
4963 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4964 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4966 process_breakpoint_inner (tls);
4968 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4969 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4973 * start_single_stepping:
4975 * Turn on single stepping. Can be called multiple times, for example,
4976 * by a single step event request + a suspend.
4979 start_single_stepping (void)
4981 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4982 int val = InterlockedIncrement (&ss_count);
4985 mono_arch_start_single_stepping ();
4987 if (ss_req != NULL && ss_invoke_addr == NULL) {
4988 DebuggerTlsData *tls;
4990 mono_loader_lock ();
4992 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4993 ss_invoke_addr = tls->invoke_addr;
4995 mono_loader_unlock ();
4998 g_assert_not_reached ();
5003 stop_single_stepping (void)
5005 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5006 int val = InterlockedDecrement (&ss_count);
5009 mono_arch_stop_single_stepping ();
5011 ss_invoke_addr = NULL;
5013 g_assert_not_reached ();
5020 * Stop the single stepping operation given by SS_REQ.
5023 ss_stop (SingleStepReq *ss_req)
5028 for (l = ss_req->bps; l; l = l->next) {
5029 clear_breakpoint (l->data);
5031 g_slist_free (ss_req->bps);
5035 if (ss_req->global) {
5036 stop_single_stepping ();
5037 ss_req->global = FALSE;
5044 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5045 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5046 * belong to the same thread as CTX.
5049 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5051 int i, j, frame_index;
5054 gboolean enable_global = FALSE;
5056 /* Stop the previous operation */
5060 * Implement single stepping using breakpoints if possible.
5062 if (step_to_catch) {
5063 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5064 ss_req->bps = g_slist_append (ss_req->bps, bp);
5068 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5069 /* Need parent frames */
5070 if (!tls->context.valid)
5071 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5072 compute_frame_info (tls->thread, tls);
5076 * Find the first sequence point in the current or in a previous frame which
5077 * is not the last in its method.
5079 if (ss_req->depth == STEP_DEPTH_OUT) {
5080 /* Ignore seq points in current method */
5081 while (frame_index < tls->frame_count) {
5082 StackFrame *frame = tls->frames [frame_index];
5084 method = frame->method;
5085 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5087 if (sp && sp->next_len != 0)
5090 // There could be method calls before the next seq point in the caller when using nested calls
5091 //enable_global = TRUE;
5093 if (sp && sp->next_len == 0) {
5095 while (frame_index < tls->frame_count) {
5096 StackFrame *frame = tls->frames [frame_index];
5098 method = frame->method;
5099 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5100 if (sp && sp->next_len != 0)
5108 if (sp && sp->next_len > 0) {
5109 for (i = 0; i < sp->next_len; ++i) {
5110 next_sp = &info->seq_points [sp->next [i]];
5112 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5113 ss_req->bps = g_slist_append (ss_req->bps, bp);
5117 if (ss_req->depth == STEP_DEPTH_OVER) {
5118 if (ss_req->nframes == 0)
5119 ss_req->nframes = tls->frame_count;
5120 /* Need to stop in catch clauses as well */
5121 for (i = 0; i < tls->frame_count; ++i) {
5122 StackFrame *frame = tls->frames [i];
5125 MonoJitInfo *jinfo = frame->ji;
5126 for (j = 0; j < jinfo->num_clauses; ++j) {
5127 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5129 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5131 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5132 ss_req->bps = g_slist_append (ss_req->bps, bp);
5140 if (ss_req->depth == STEP_DEPTH_INTO) {
5141 /* Enable global stepping so we stop at method entry too */
5142 enable_global = TRUE;
5146 * The ctx/frame info computed above will become invalid when we continue.
5148 tls->context.valid = FALSE;
5149 tls->async_state.valid = FALSE;
5150 invalidate_frames (tls);
5153 if (enable_global) {
5154 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5155 ss_req->global = TRUE;
5156 start_single_stepping ();
5157 } else if (!ss_req->bps) {
5158 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5159 ss_req->global = TRUE;
5160 start_single_stepping ();
5162 ss_req->global = FALSE;
5167 * Start single stepping of thread THREAD
5170 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5172 DebuggerTlsData *tls;
5173 MonoSeqPointInfo *info = NULL;
5174 SeqPoint *sp = NULL;
5175 MonoMethod *method = NULL;
5176 MonoDebugMethodInfo *minfo;
5177 gboolean step_to_catch = FALSE;
5179 if (suspend_count == 0)
5180 return ERR_NOT_SUSPENDED;
5182 wait_for_suspend ();
5184 // FIXME: Multiple requests
5186 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5187 return ERR_NOT_IMPLEMENTED;
5190 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5192 ss_req = g_new0 (SingleStepReq, 1);
5194 ss_req->thread = thread;
5195 ss_req->size = size;
5196 ss_req->depth = depth;
5199 mono_loader_lock ();
5200 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5201 mono_loader_unlock ();
5203 g_assert (tls->context.valid);
5204 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5206 if (tls->catch_state.valid) {
5208 StackFrameInfo frame;
5209 MonoContext new_ctx;
5210 MonoLMF *lmf = NULL;
5213 * We are stopped at a throw site. Stepping should go to the catch site.
5216 /* Find the the jit info for the catch context */
5217 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);
5219 g_assert (frame.type == FRAME_TYPE_MANAGED);
5222 * Find the seq point corresponding to the landing site ip, which is the first seq
5225 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5227 no_seq_points_found (frame.method);
5230 method = frame.method;
5232 step_to_catch = TRUE;
5233 /* This make sure the seq point is not skipped by process_single_step () */
5234 ss_req->last_sp = NULL;
5237 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5240 /* Compute the initial line info */
5241 compute_frame_info (thread, tls);
5243 if (tls->frame_count) {
5244 frame = tls->frames [0];
5246 ss_req->last_method = frame->method;
5247 ss_req->last_line = -1;
5249 minfo = mono_debug_lookup_method (frame->method);
5250 if (minfo && frame->il_offset != -1) {
5251 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5254 ss_req->last_line = loc->row;
5261 if (!step_to_catch) {
5264 compute_frame_info (thread, tls);
5266 if (tls->frame_count) {
5267 frame = tls->frames [0];
5269 if (!method && frame->il_offset != -1) {
5270 /* FIXME: Sort the table and use a binary search */
5271 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5273 no_seq_points_found (frame->method);
5275 method = frame->method;
5280 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5286 ss_destroy (SingleStepReq *req)
5289 g_assert (ss_req == req);
5298 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5301 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5307 if (!agent_config.enabled)
5310 mono_loader_lock ();
5311 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5312 mono_loader_unlock ();
5315 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5316 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5318 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5320 g_free (ei.category);
5321 g_free (ei.message);
5325 mono_debugger_agent_debug_log_is_enabled (void)
5327 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5328 return agent_config.enabled;
5331 #ifdef PLATFORM_ANDROID
5333 mono_debugger_agent_unhandled_exception (MonoException *exc)
5342 memset (&ei, 0, sizeof (EventInfo));
5343 ei.exc = (MonoObject*)exc;
5345 mono_loader_lock ();
5346 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5347 mono_loader_unlock ();
5349 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5354 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5355 MonoContext *catch_ctx)
5357 int i, j, suspend_policy;
5359 MonoJitInfo *ji, *catch_ji;
5361 DebuggerTlsData *tls = NULL;
5363 if (thread_to_tls != NULL) {
5364 MonoInternalThread *thread = mono_thread_internal_current ();
5366 mono_loader_lock ();
5367 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5368 mono_loader_unlock ();
5370 if (tls && tls->abort_requested)
5372 if (tls && tls->disable_breakpoints)
5376 memset (&ei, 0, sizeof (EventInfo));
5378 /* Just-In-Time debugging */
5380 if (agent_config.onuncaught && !inited) {
5381 finish_agent_init (FALSE);
5384 * Send an unsolicited EXCEPTION event with a dummy request id.
5386 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5387 ei.exc = (MonoObject*)exc;
5388 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5391 } else if (agent_config.onthrow && !inited) {
5393 gboolean found = FALSE;
5395 for (l = agent_config.onthrow; l; l = l->next) {
5396 char *ex_type = l->data;
5397 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5399 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5406 finish_agent_init (FALSE);
5409 * Send an unsolicited EXCEPTION event with a dummy request id.
5411 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5412 ei.exc = (MonoObject*)exc;
5413 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5421 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5423 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5427 ei.exc = (MonoObject*)exc;
5428 ei.caught = catch_ctx != NULL;
5430 mono_loader_lock ();
5432 /* Treat exceptions which are caught in non-user code as unhandled */
5433 for (i = 0; i < event_requests->len; ++i) {
5434 EventRequest *req = g_ptr_array_index (event_requests, i);
5435 if (req->event_kind != EVENT_KIND_EXCEPTION)
5438 for (j = 0; j < req->nmodifiers; ++j) {
5439 Modifier *mod = &req->modifiers [j];
5441 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5443 gboolean found = FALSE;
5444 MonoAssembly **assemblies = mod->data.assemblies;
5447 for (k = 0; assemblies [k]; ++k)
5448 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5457 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5458 mono_loader_unlock ();
5460 if (tls && ei.caught && catch_ctx) {
5461 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5462 tls->catch_state.ctx = *catch_ctx;
5463 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5464 tls->catch_state.valid = TRUE;
5467 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5470 tls->catch_state.valid = FALSE;
5474 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5476 DebuggerTlsData *tls;
5481 tls = mono_native_tls_get_value (debugger_tls_id);
5486 * We're about to invoke an exception filter during the first pass of exception handling.
5488 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5489 * 'orig_ctx' is the context where the exception has been thrown.
5492 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5494 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5495 * the call site (line 37) and then continue to Main(), but it would never
5496 * include the throw site (line 32).
5498 * Since exception filters are invoked during the first pass of exception handling,
5499 * the stack frames of the throw site are still intact, so we should include them
5502 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5504 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5505 * but report the location of the 'throw' to the user.
5509 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5513 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5515 DebuggerTlsData *tls;
5520 tls = mono_native_tls_get_value (debugger_tls_id);
5524 tls->filter_state.valid = FALSE;
5528 * buffer_add_value_full:
5530 * Add the encoding of the value at ADDR described by T to the buffer.
5531 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5535 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5541 if (!(*(void**)addr)) {
5542 /* This can happen with compiler generated locals */
5543 //printf ("%s\n", mono_type_full_name (t));
5544 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5547 g_assert (*(void**)addr);
5548 addr = *(void**)addr;
5553 case MONO_TYPE_BOOLEAN:
5556 case MONO_TYPE_CHAR:
5576 case MONO_TYPE_VOID:
5577 buffer_add_byte (buf, t->type);
5579 case MONO_TYPE_BOOLEAN:
5582 buffer_add_byte (buf, t->type);
5583 buffer_add_int (buf, *(gint8*)addr);
5585 case MONO_TYPE_CHAR:
5588 buffer_add_byte (buf, t->type);
5589 buffer_add_int (buf, *(gint16*)addr);
5594 buffer_add_byte (buf, t->type);
5595 buffer_add_int (buf, *(gint32*)addr);
5600 buffer_add_byte (buf, t->type);
5601 buffer_add_long (buf, *(gint64*)addr);
5605 /* Treat it as a vtype */
5607 case MONO_TYPE_PTR: {
5608 gssize val = *(gssize*)addr;
5610 buffer_add_byte (buf, t->type);
5611 buffer_add_long (buf, val);
5615 case MONO_TYPE_STRING:
5616 case MONO_TYPE_SZARRAY:
5617 case MONO_TYPE_OBJECT:
5618 case MONO_TYPE_CLASS:
5619 case MONO_TYPE_ARRAY:
5620 obj = *(MonoObject**)addr;
5623 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5625 if (obj->vtable->klass->valuetype) {
5626 t = &obj->vtable->klass->byval_arg;
5627 addr = mono_object_unbox (obj);
5629 } else if (obj->vtable->klass->rank) {
5630 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5631 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5632 buffer_add_byte (buf, MONO_TYPE_CLASS);
5634 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5636 buffer_add_objid (buf, obj);
5640 case MONO_TYPE_VALUETYPE: {
5644 MonoClass *klass = mono_class_from_mono_type (t);
5646 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5647 buffer_add_byte (buf, klass->enumtype);
5648 buffer_add_typeid (buf, domain, klass);
5652 while ((f = mono_class_get_fields (klass, &iter))) {
5653 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5655 if (mono_field_is_deleted (f))
5659 buffer_add_int (buf, nfields);
5662 while ((f = mono_class_get_fields (klass, &iter))) {
5663 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5665 if (mono_field_is_deleted (f))
5667 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5671 case MONO_TYPE_GENERICINST:
5672 if (mono_type_generic_inst_is_valuetype (t)) {
5684 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5686 buffer_add_value_full (buf, t, addr, domain, FALSE);
5690 obj_is_of_type (MonoObject *obj, MonoType *t)
5692 MonoClass *klass = obj->vtable->klass;
5693 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5694 if (mono_class_is_transparent_proxy (klass)) {
5695 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5696 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5706 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5709 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5715 gpointer iter = NULL;
5719 is_enum = decode_byte (buf, &buf, limit);
5720 /* Enums are sent as a normal vtype */
5722 return ERR_NOT_IMPLEMENTED;
5723 klass = decode_typeid (buf, &buf, limit, &d, &err);
5727 if (t && klass != mono_class_from_mono_type (t)) {
5728 char *name = mono_type_full_name (t);
5729 char *name2 = mono_type_full_name (&klass->byval_arg);
5730 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5733 return ERR_INVALID_ARGUMENT;
5736 nfields = decode_int (buf, &buf, limit);
5737 while ((f = mono_class_get_fields (klass, &iter))) {
5738 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5740 if (mono_field_is_deleted (f))
5742 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5747 g_assert (nfields == 0);
5755 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5759 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5760 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5761 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5762 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5763 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5764 char *name = mono_type_full_name (t);
5765 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5767 return ERR_INVALID_ARGUMENT;
5771 case MONO_TYPE_BOOLEAN:
5772 *(guint8*)addr = decode_int (buf, &buf, limit);
5774 case MONO_TYPE_CHAR:
5775 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5778 *(gint8*)addr = decode_int (buf, &buf, limit);
5781 *(guint8*)addr = decode_int (buf, &buf, limit);
5784 *(gint16*)addr = decode_int (buf, &buf, limit);
5787 *(guint16*)addr = decode_int (buf, &buf, limit);
5790 *(gint32*)addr = decode_int (buf, &buf, limit);
5793 *(guint32*)addr = decode_int (buf, &buf, limit);
5796 *(gint64*)addr = decode_long (buf, &buf, limit);
5799 *(guint64*)addr = decode_long (buf, &buf, limit);
5802 *(guint32*)addr = decode_int (buf, &buf, limit);
5805 *(guint64*)addr = decode_long (buf, &buf, limit);
5808 /* We send these as I8, so we get them back as such */
5809 g_assert (type == MONO_TYPE_I8);
5810 *(gssize*)addr = decode_long (buf, &buf, limit);
5812 case MONO_TYPE_GENERICINST:
5813 if (MONO_TYPE_ISSTRUCT (t)) {
5814 /* The client sends these as a valuetype */
5822 /* We send these as vtypes, so we get them back as such */
5823 g_assert (type == MONO_TYPE_VALUETYPE);
5826 case MONO_TYPE_VALUETYPE:
5827 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5833 if (MONO_TYPE_IS_REFERENCE (t)) {
5834 if (type == MONO_TYPE_OBJECT) {
5835 int objid = decode_objid (buf, &buf, limit);
5839 err = get_object (objid, (MonoObject**)&obj);
5844 if (!obj_is_of_type (obj, t)) {
5845 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5846 return ERR_INVALID_ARGUMENT;
5849 if (obj && obj->vtable->domain != domain)
5850 return ERR_INVALID_ARGUMENT;
5852 mono_gc_wbarrier_generic_store (addr, obj);
5853 } else if (type == VALUE_TYPE_ID_NULL) {
5854 *(MonoObject**)addr = NULL;
5855 } else if (type == MONO_TYPE_VALUETYPE) {
5863 /* This can happen when round-tripping boxed vtypes */
5865 * Obtain vtype class.
5866 * Same as the beginning of the handle_vtype case above.
5869 is_enum = decode_byte (buf, &buf, limit);
5871 return ERR_NOT_IMPLEMENTED;
5872 klass = decode_typeid (buf, &buf, limit, &d, &err);
5876 /* Decode the vtype into a temporary buffer, then box it. */
5877 vtype_buf_size = mono_class_value_size (klass, NULL);
5878 vtype_buf = g_malloc0 (vtype_buf_size);
5879 g_assert (vtype_buf);
5882 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
5887 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
5890 char *name = mono_type_full_name (t);
5891 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5893 return ERR_INVALID_ARGUMENT;
5907 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5910 int type = decode_byte (buf, &buf, limit);
5912 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5913 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5914 guint8 *nullable_buf;
5917 * First try decoding it as a Nullable`1
5919 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5924 * Then try decoding as a primitive value or null.
5926 if (targ->type == type) {
5927 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5928 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5930 g_free (nullable_buf);
5933 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5934 g_free (nullable_buf);
5937 } else if (type == VALUE_TYPE_ID_NULL) {
5938 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5944 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5948 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5952 guint8 *addr, *gaddr;
5955 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5956 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5959 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5960 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5962 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5964 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5965 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5966 addr += (gint32)var->offset;
5968 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5970 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5972 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5975 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5976 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5977 /* Same as regoffset, but with an indirection */
5978 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5979 addr += (gint32)var->offset;
5981 gaddr = *(gpointer*)addr;
5983 buffer_add_value_full (buf, t, gaddr, domain, as_vtype);
5985 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5986 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5987 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5988 MonoGSharedVtMethodRuntimeInfo *info;
5994 g_assert (info_var);
5995 g_assert (locals_var);
5997 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5998 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5999 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6000 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6001 addr += (gint32)info_var->offset;
6002 info = *(gpointer*)addr;
6003 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6004 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6006 g_assert_not_reached ();
6010 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6011 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6012 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6013 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6014 addr += (gint32)locals_var->offset;
6015 locals = *(gpointer*)addr;
6016 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6017 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6019 g_assert_not_reached ();
6023 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6025 buffer_add_value_full (buf, t, addr, domain, as_vtype);
6030 g_assert_not_reached ();
6035 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6039 guint8 *addr, *gaddr;
6041 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6042 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6044 if (MONO_TYPE_IS_REFERENCE (t))
6045 size = sizeof (gpointer);
6047 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6050 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6051 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6053 gboolean is_signed = FALSE;
6056 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6059 // FIXME: Write barriers
6060 mono_gc_memmove_atomic (addr, val, size);
6065 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6070 v = is_signed ? *(gint8*)val : *(guint8*)val;
6073 v = is_signed ? *(gint16*)val : *(guint16*)val;
6076 v = is_signed ? *(gint32*)val : *(guint32*)val;
6079 v = is_signed ? *(gint64*)val : *(guint64*)val;
6082 g_assert_not_reached ();
6085 /* Set value on the stack or in the return ctx */
6086 if (reg_locations [reg]) {
6087 /* Saved on the stack */
6088 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6089 *(reg_locations [reg]) = v;
6092 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6093 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6096 // FIXME: Move these to mono-context.h/c.
6097 mono_arch_context_set_int_reg (ctx, reg, v);
6099 // FIXME: Can't set registers, so we disable linears
6104 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6105 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6106 addr += (gint32)var->offset;
6108 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6111 addr = *(guint8**)addr;
6117 // FIXME: Write barriers
6118 mono_gc_memmove_atomic (addr, val, size);
6120 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6121 /* Same as regoffset, but with an indirection */
6122 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6123 addr += (gint32)var->offset;
6125 gaddr = *(gpointer*)addr;
6127 // FIXME: Write barriers
6128 mono_gc_memmove_atomic (gaddr, val, size);
6130 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6134 g_assert_not_reached ();
6139 clear_event_request (int req_id, int etype)
6143 mono_loader_lock ();
6144 for (i = 0; i < event_requests->len; ++i) {
6145 EventRequest *req = g_ptr_array_index (event_requests, i);
6147 if (req->id == req_id && req->event_kind == etype) {
6148 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6149 clear_breakpoint (req->info);
6150 if (req->event_kind == EVENT_KIND_STEP)
6151 ss_destroy (req->info);
6152 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6153 clear_breakpoint (req->info);
6154 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6155 clear_breakpoint (req->info);
6156 g_ptr_array_remove_index_fast (event_requests, i);
6161 mono_loader_unlock ();
6165 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
6167 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6168 return breakpoint_matches_assembly (req->info, assembly);
6172 for (i = 0; i < req->nmodifiers; ++i) {
6173 Modifier *m = &req->modifiers [i];
6175 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6177 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6178 for (j = 0; m->data.assemblies [j]; ++j)
6179 if (m->data.assemblies [j] == assembly)
6189 * clear_event_requests_for_assembly:
6191 * Clear all events requests which reference ASSEMBLY.
6194 clear_event_requests_for_assembly (MonoAssembly *assembly)
6199 mono_loader_lock ();
6203 for (i = 0; i < event_requests->len; ++i) {
6204 EventRequest *req = g_ptr_array_index (event_requests, i);
6206 if (event_req_matches_assembly (req, assembly)) {
6207 clear_event_request (req->id, req->event_kind);
6213 mono_loader_unlock ();
6217 * type_comes_from_assembly:
6219 * GHRFunc that returns TRUE if klass comes from assembly
6222 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6224 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6228 * clear_types_for_assembly:
6230 * Clears types from loaded_classes for a given assembly
6233 clear_types_for_assembly (MonoAssembly *assembly)
6235 MonoDomain *domain = mono_domain_get ();
6236 AgentDomainInfo *info = NULL;
6238 mono_loader_lock ();
6239 info = get_agent_domain_info (domain);
6240 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6241 mono_loader_unlock ();
6245 add_thread (gpointer key, gpointer value, gpointer user_data)
6247 MonoInternalThread *thread = value;
6248 Buffer *buf = user_data;
6250 buffer_add_objid (buf, (MonoObject*)thread);
6254 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6256 guint8 *end = invoke->endp;
6259 MonoMethodSignature *sig;
6262 MonoObject *this, *res, *exc;
6265 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6268 MonoStopwatch watch;
6270 if (invoke->method) {
6272 * Invoke this method directly, currently only Environment.Exit () is supported.
6275 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>"));
6276 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6277 g_assert_not_reached ();
6280 m = decode_methodid (p, &p, end, &domain, &err);
6283 sig = mono_method_signature (m);
6285 if (m->klass->valuetype)
6286 this_buf = g_alloca (mono_class_instance_size (m->klass));
6288 this_buf = g_alloca (sizeof (MonoObject*));
6289 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6290 /* Should be null */
6291 int type = decode_byte (p, &p, end);
6292 if (type != VALUE_TYPE_ID_NULL) {
6293 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6294 return ERR_INVALID_ARGUMENT;
6296 memset (this_buf, 0, mono_class_instance_size (m->klass));
6298 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6303 if (!m->klass->valuetype)
6304 this = *(MonoObject**)this_buf;
6308 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6310 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6311 return ERR_INVALID_ARGUMENT;
6313 m = mono_object_get_virtual_method (this, m);
6316 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>"));
6318 if (this && this->vtable->domain != domain)
6321 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6322 if (!strcmp (m->name, ".ctor")) {
6323 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6324 return ERR_INVALID_ARGUMENT;
6326 this = mono_object_new (domain, m->klass);
6328 return ERR_INVALID_ARGUMENT;
6332 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6333 return ERR_INVALID_ARGUMENT;
6335 nargs = decode_int (p, &p, end);
6336 if (nargs != sig->param_count)
6337 return ERR_INVALID_ARGUMENT;
6338 /* Use alloca to get gc tracking */
6339 arg_buf = g_alloca (nargs * sizeof (gpointer));
6340 memset (arg_buf, 0, nargs * sizeof (gpointer));
6341 args = g_alloca (nargs * sizeof (gpointer));
6342 for (i = 0; i < nargs; ++i) {
6343 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6344 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6348 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6351 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6352 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6355 args [i] = arg_buf [i];
6362 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6363 tls->disable_breakpoints = TRUE;
6365 tls->disable_breakpoints = FALSE;
6368 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6370 /* FIXME: Move this to arch specific code */
6371 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6372 if (invoke->has_ctx) {
6375 lmf_addr = mono_get_lmf_addr ();
6378 memset (&ext, 0, sizeof (ext));
6379 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6381 ext.debugger_invoke = TRUE;
6382 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6384 mono_set_lmf ((MonoLMF*)&ext);
6388 mono_stopwatch_start (&watch);
6389 if (m->klass->valuetype)
6390 res = mono_runtime_invoke (m, this_buf, args, &exc);
6392 res = mono_runtime_invoke (m, this, args, &exc);
6393 mono_stopwatch_stop (&watch);
6394 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)));
6396 buffer_add_byte (buf, 0);
6397 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6399 buffer_add_byte (buf, 1);
6400 if (sig->ret->type == MONO_TYPE_VOID) {
6401 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6402 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6405 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6406 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6407 buffer_add_value (buf, sig->ret, &res, domain);
6408 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6409 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6410 MonoClass *k = mono_class_from_mono_type (sig->ret);
6411 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6413 g_assert (nullable_buf);
6414 mono_nullable_init (nullable_buf, res, k);
6415 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6418 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6425 tls->disable_breakpoints = FALSE;
6427 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6428 if (invoke->has_ctx)
6429 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6433 // FIXME: byref arguments
6441 * Invoke the method given by tls->pending_invoke in the current thread.
6444 invoke_method (void)
6446 DebuggerTlsData *tls;
6451 MonoContext restore_ctx;
6454 tls = mono_native_tls_get_value (debugger_tls_id);
6458 * Store the `InvokeData *' in `tls->invoke' until we're done with
6459 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6462 mono_loader_lock ();
6464 invoke = tls->pending_invoke;
6466 tls->pending_invoke = NULL;
6468 invoke->last_invoke = tls->invoke;
6469 tls->invoke = invoke;
6471 mono_loader_unlock ();
6473 tls->frames_up_to_date = FALSE;
6479 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6480 buffer_init (&buf, 128);
6483 /* Fail the other invokes as well */
6485 err = do_invoke_method (tls, &buf, invoke, p, &p);
6488 /* Start suspending before sending the reply */
6489 if (mindex == invoke->nmethods - 1) {
6490 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6491 for (i = 0; i < invoke->suspend_count; ++i)
6496 send_reply_packet (id, err, &buf);
6501 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6503 if (invoke->has_ctx)
6504 save_thread_context (&restore_ctx);
6506 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6507 g_assert (tls->resume_count);
6508 tls->resume_count -= invoke->suspend_count;
6511 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6514 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6516 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6517 * after the mono_runtime_invoke() already returned, but it doesn't matter
6518 * because we reset the abort here.
6521 mono_loader_lock ();
6523 if (tls->abort_requested)
6524 mono_thread_internal_reset_abort (tls->thread);
6526 tls->invoke = tls->invoke->last_invoke;
6527 tls->abort_requested = FALSE;
6529 mono_loader_unlock ();
6538 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6540 MonoThread *thread = value;
6541 DebuggerTlsData *tls;
6544 mono_loader_lock ();
6545 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6547 res = tls->really_suspended;
6548 mono_loader_unlock ();
6554 get_source_files_for_type (MonoClass *klass)
6556 gpointer iter = NULL;
6558 MonoDebugSourceInfo *sinfo;
6562 files = g_ptr_array_new ();
6564 while ((method = mono_class_get_methods (klass, &iter))) {
6565 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6566 GPtrArray *source_file_list;
6569 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6570 for (j = 0; j < source_file_list->len; ++j) {
6571 sinfo = g_ptr_array_index (source_file_list, j);
6572 for (i = 0; i < files->len; ++i)
6573 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6575 if (i == files->len)
6576 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6578 g_ptr_array_free (source_file_list, TRUE);
6586 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6589 case CMD_VM_VERSION: {
6590 char *build_info, *version;
6592 build_info = mono_get_runtime_build_info ();
6593 version = g_strdup_printf ("mono %s", build_info);
6595 buffer_add_string (buf, version); /* vm version */
6596 buffer_add_int (buf, MAJOR_VERSION);
6597 buffer_add_int (buf, MINOR_VERSION);
6598 g_free (build_info);
6602 case CMD_VM_SET_PROTOCOL_VERSION: {
6603 major_version = decode_int (p, &p, end);
6604 minor_version = decode_int (p, &p, end);
6605 protocol_version_set = TRUE;
6606 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6609 case CMD_VM_ALL_THREADS: {
6611 mono_loader_lock ();
6612 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6613 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6614 mono_loader_unlock ();
6617 case CMD_VM_SUSPEND:
6619 wait_for_suspend ();
6622 if (suspend_count == 0)
6623 return ERR_NOT_SUSPENDED;
6625 clear_suspended_objs ();
6627 case CMD_VM_DISPOSE:
6628 /* Clear all event requests */
6629 mono_loader_lock ();
6630 while (event_requests->len > 0) {
6631 EventRequest *req = g_ptr_array_index (event_requests, 0);
6633 clear_event_request (req->id, req->event_kind);
6635 mono_loader_unlock ();
6637 while (suspend_count > 0)
6639 disconnected = TRUE;
6640 vm_start_event_sent = FALSE;
6643 MonoInternalThread *thread;
6644 DebuggerTlsData *tls;
6645 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6646 MonoClass *env_class;
6648 MonoMethod *exit_method = NULL;
6652 exit_code = decode_int (p, &p, end);
6654 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6656 /* Have to send a reply before exiting */
6657 send_reply_packet (id, 0, buf);
6659 /* Clear all event requests */
6660 mono_loader_lock ();
6661 while (event_requests->len > 0) {
6662 EventRequest *req = g_ptr_array_index (event_requests, 0);
6664 clear_event_request (req->id, req->event_kind);
6666 mono_loader_unlock ();
6669 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6670 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6671 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6672 * better than doing the shutdown ourselves, since it avoids various races.
6676 wait_for_suspend ();
6678 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6679 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6681 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6684 mono_loader_lock ();
6685 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6686 mono_loader_unlock ();
6688 if (thread && exit_method) {
6689 mono_loader_lock ();
6690 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6691 mono_loader_unlock ();
6693 args = g_new0 (gpointer, 1);
6694 args [0] = g_malloc (sizeof (int));
6695 *(int*)(args [0]) = exit_code;
6697 tls->pending_invoke = g_new0 (InvokeData, 1);
6698 tls->pending_invoke->method = exit_method;
6699 tls->pending_invoke->args = args;
6700 tls->pending_invoke->nmethods = 1;
6702 while (suspend_count > 0)
6706 * No thread found, do it ourselves.
6707 * FIXME: This can race with normal shutdown etc.
6709 while (suspend_count > 0)
6712 if (!mono_runtime_try_shutdown ())
6715 mono_environment_exitcode_set (exit_code);
6717 /* Suspend all managed threads since the runtime is going away */
6718 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6719 mono_thread_suspend_all_other_threads ();
6720 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6721 mono_runtime_quit ();
6722 transport_close2 ();
6723 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6729 case CMD_VM_INVOKE_METHOD:
6730 case CMD_VM_INVOKE_METHODS: {
6731 int objid = decode_objid (p, &p, end);
6733 DebuggerTlsData *tls;
6734 int i, count, err, flags, nmethods;
6736 err = get_object (objid, (MonoObject**)&thread);
6740 flags = decode_int (p, &p, end);
6742 if (command == CMD_VM_INVOKE_METHODS)
6743 nmethods = decode_int (p, &p, end);
6747 // Wait for suspending if it already started
6749 wait_for_suspend ();
6750 if (!is_suspended ())
6751 return ERR_NOT_SUSPENDED;
6753 mono_loader_lock ();
6754 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6755 mono_loader_unlock ();
6758 if (!tls->really_suspended)
6759 /* The thread is still running native code, can't do invokes */
6760 return ERR_NOT_SUSPENDED;
6763 * Store the invoke data into tls, the thread will execute it after it is
6766 if (tls->pending_invoke)
6767 return ERR_NOT_SUSPENDED;
6768 tls->pending_invoke = g_new0 (InvokeData, 1);
6769 tls->pending_invoke->id = id;
6770 tls->pending_invoke->flags = flags;
6771 tls->pending_invoke->p = g_malloc (end - p);
6772 memcpy (tls->pending_invoke->p, p, end - p);
6773 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6774 tls->pending_invoke->suspend_count = suspend_count;
6775 tls->pending_invoke->nmethods = nmethods;
6777 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6778 resume_thread (THREAD_TO_INTERNAL (thread));
6781 count = suspend_count;
6782 for (i = 0; i < count; ++i)
6787 case CMD_VM_ABORT_INVOKE: {
6788 int objid = decode_objid (p, &p, end);
6790 DebuggerTlsData *tls;
6793 err = get_object (objid, (MonoObject**)&thread);
6797 invoke_id = decode_int (p, &p, end);
6799 mono_loader_lock ();
6800 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6803 if (tls->abort_requested) {
6804 mono_loader_unlock ();
6809 * Check whether we're still inside the mono_runtime_invoke() and that it's
6810 * actually the correct invocation.
6812 * Careful, we do not stop the thread that's doing the invocation, so we can't
6813 * inspect its stack. However, invoke_method() also acquires the loader lock
6814 * when it's done, so we're safe here.
6818 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6819 mono_loader_unlock ();
6820 return ERR_NO_INVOCATION;
6823 tls->abort_requested = TRUE;
6825 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6826 mono_loader_unlock ();
6830 case CMD_VM_SET_KEEPALIVE: {
6831 int timeout = decode_int (p, &p, end);
6832 agent_config.keepalive = timeout;
6834 #ifndef DISABLE_SOCKET_TRANSPORT
6841 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6842 GHashTableIter iter, kiter;
6847 char *fname, *basename;
6848 gboolean ignore_case;
6849 GSList *class_list, *l;
6850 GPtrArray *res_classes, *res_domains;
6852 fname = decode_string (p, &p, end);
6853 ignore_case = decode_byte (p, &p, end);
6855 basename = g_path_get_basename (fname);
6857 res_classes = g_ptr_array_new ();
6858 res_domains = g_ptr_array_new ();
6860 mono_loader_lock ();
6861 g_hash_table_iter_init (&iter, domains);
6862 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6863 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6865 /* Update 'source_file_to_class' cache */
6866 g_hash_table_iter_init (&kiter, info->loaded_classes);
6867 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6868 if (!g_hash_table_lookup (info->source_files, klass)) {
6869 files = get_source_files_for_type (klass);
6870 g_hash_table_insert (info->source_files, klass, files);
6872 for (i = 0; i < files->len; ++i) {
6873 char *s = g_ptr_array_index (files, i);
6874 char *s2 = g_path_get_basename (s);
6877 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6879 class_list = g_slist_prepend (class_list, klass);
6880 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6882 class_list = g_slist_prepend (class_list, klass);
6883 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6886 /* The _ignorecase hash contains the lowercase path */
6887 s3 = strdup_tolower (s2);
6888 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6890 class_list = g_slist_prepend (class_list, klass);
6891 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6893 class_list = g_slist_prepend (class_list, klass);
6894 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6906 s = strdup_tolower (basename);
6907 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6910 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6913 for (l = class_list; l; l = l->next) {
6916 g_ptr_array_add (res_classes, klass);
6917 g_ptr_array_add (res_domains, domain);
6920 mono_loader_unlock ();
6925 buffer_add_int (buf, res_classes->len);
6926 for (i = 0; i < res_classes->len; ++i)
6927 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6928 g_ptr_array_free (res_classes, TRUE);
6929 g_ptr_array_free (res_domains, TRUE);
6932 case CMD_VM_GET_TYPES: {
6933 GHashTableIter iter;
6937 gboolean ignore_case;
6938 GPtrArray *res_classes, *res_domains;
6939 MonoTypeNameParse info;
6941 name = decode_string (p, &p, end);
6942 ignore_case = decode_byte (p, &p, end);
6944 if (!mono_reflection_parse_type (name, &info)) {
6946 mono_reflection_free_type_info (&info);
6947 return ERR_INVALID_ARGUMENT;
6950 res_classes = g_ptr_array_new ();
6951 res_domains = g_ptr_array_new ();
6953 mono_loader_lock ();
6954 g_hash_table_iter_init (&iter, domains);
6955 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6957 gboolean type_resolve;
6961 mono_domain_assemblies_lock (domain);
6962 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6966 type_resolve = TRUE;
6967 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6969 g_ptr_array_add (res_classes, mono_type_get_class (t));
6970 g_ptr_array_add (res_domains, domain);
6974 mono_domain_assemblies_unlock (domain);
6976 mono_loader_unlock ();
6979 mono_reflection_free_type_info (&info);
6981 buffer_add_int (buf, res_classes->len);
6982 for (i = 0; i < res_classes->len; ++i)
6983 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6984 g_ptr_array_free (res_classes, TRUE);
6985 g_ptr_array_free (res_domains, TRUE);
6990 return ERR_NOT_IMPLEMENTED;
6997 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7003 case CMD_EVENT_REQUEST_SET: {
7005 int i, event_kind, suspend_policy, nmodifiers, mod;
7008 MonoThread *step_thread;
7009 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7013 event_kind = decode_byte (p, &p, end);
7014 suspend_policy = decode_byte (p, &p, end);
7015 nmodifiers = decode_byte (p, &p, end);
7017 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7018 req->id = InterlockedIncrement (&event_request_id);
7019 req->event_kind = event_kind;
7020 req->suspend_policy = suspend_policy;
7021 req->nmodifiers = nmodifiers;
7024 for (i = 0; i < nmodifiers; ++i) {
7025 mod = decode_byte (p, &p, end);
7027 req->modifiers [i].kind = mod;
7028 if (mod == MOD_KIND_COUNT) {
7029 req->modifiers [i].data.count = decode_int (p, &p, end);
7030 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7031 method = decode_methodid (p, &p, end, &domain, &err);
7034 location = decode_long (p, &p, end);
7035 } else if (mod == MOD_KIND_STEP) {
7036 step_thread_id = decode_id (p, &p, end);
7037 size = decode_int (p, &p, end);
7038 depth = decode_int (p, &p, end);
7039 if (CHECK_PROTOCOL_VERSION (2, 16))
7040 filter = decode_int (p, &p, end);
7041 req->modifiers [i].data.filter = filter;
7042 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7043 /* Treat STEP_THOUGH the same as HIDDEN */
7044 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7045 } else if (mod == MOD_KIND_THREAD_ONLY) {
7046 int id = decode_id (p, &p, end);
7048 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7053 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7054 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7058 req->modifiers [i].caught = decode_byte (p, &p, end);
7059 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7060 if (CHECK_PROTOCOL_VERSION (2, 25))
7061 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7063 req->modifiers [i].subclasses = TRUE;
7064 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" : ""));
7066 req->modifiers [i].data.exc_class = exc_class;
7068 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7070 return ERR_INVALID_ARGUMENT;
7073 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7074 int n = decode_int (p, &p, end);
7077 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7078 for (j = 0; j < n; ++j) {
7079 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7081 g_free (req->modifiers [i].data.assemblies);
7085 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7086 int n = decode_int (p, &p, end);
7089 modifier = &req->modifiers [i];
7090 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7091 for (j = 0; j < n; ++j) {
7092 char *s = decode_string (p, &p, end);
7096 s2 = strdup_tolower (s);
7097 g_hash_table_insert (modifier->data.source_files, s2, s2);
7101 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7102 int n = decode_int (p, &p, end);
7105 modifier = &req->modifiers [i];
7106 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7107 for (j = 0; j < n; ++j) {
7108 char *s = decode_string (p, &p, end);
7111 g_hash_table_insert (modifier->data.type_names, s, s);
7115 return ERR_NOT_IMPLEMENTED;
7119 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7122 req->info = set_breakpoint (method, location, req, &error);
7123 if (!mono_error_ok (&error)) {
7125 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7126 mono_error_cleanup (&error);
7127 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7129 } else if (req->event_kind == EVENT_KIND_STEP) {
7130 g_assert (step_thread_id);
7132 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7138 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7143 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7144 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7145 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7146 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7147 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7148 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7150 if (req->nmodifiers) {
7152 return ERR_NOT_IMPLEMENTED;
7156 mono_loader_lock ();
7157 g_ptr_array_add (event_requests, req);
7159 if (agent_config.defer) {
7160 /* Transmit cached data to the client on receipt of the event request */
7161 switch (req->event_kind) {
7162 case EVENT_KIND_APPDOMAIN_CREATE:
7163 /* Emit load events for currently loaded domains */
7164 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7166 case EVENT_KIND_ASSEMBLY_LOAD:
7167 /* Emit load events for currently loaded assemblies */
7168 mono_assembly_foreach (emit_assembly_load, NULL);
7170 case EVENT_KIND_THREAD_START:
7171 /* Emit start events for currently started threads */
7172 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7174 case EVENT_KIND_TYPE_LOAD:
7175 /* Emit type load events for currently loaded types */
7176 mono_domain_foreach (send_types_for_domain, NULL);
7182 mono_loader_unlock ();
7184 buffer_add_int (buf, req->id);
7187 case CMD_EVENT_REQUEST_CLEAR: {
7188 int etype = decode_byte (p, &p, end);
7189 int req_id = decode_int (p, &p, end);
7191 // FIXME: Make a faster mapping from req_id to request
7192 mono_loader_lock ();
7193 clear_event_request (req_id, etype);
7194 mono_loader_unlock ();
7197 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7200 mono_loader_lock ();
7202 while (i < event_requests->len) {
7203 EventRequest *req = g_ptr_array_index (event_requests, i);
7205 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7206 clear_breakpoint (req->info);
7208 g_ptr_array_remove_index_fast (event_requests, i);
7214 mono_loader_unlock ();
7218 return ERR_NOT_IMPLEMENTED;
7225 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7231 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7232 buffer_add_domainid (buf, mono_get_root_domain ());
7235 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7236 domain = decode_domainid (p, &p, end, NULL, &err);
7239 buffer_add_string (buf, domain->friendly_name);
7242 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7247 domain = decode_domainid (p, &p, end, NULL, &err);
7250 mono_loader_lock ();
7252 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7255 buffer_add_int (buf, count);
7256 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7258 buffer_add_assemblyid (buf, domain, ass);
7260 mono_loader_unlock ();
7263 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7264 domain = decode_domainid (p, &p, end, NULL, &err);
7268 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7271 case CMD_APPDOMAIN_GET_CORLIB: {
7272 domain = decode_domainid (p, &p, end, NULL, &err);
7276 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7279 case CMD_APPDOMAIN_CREATE_STRING: {
7283 domain = decode_domainid (p, &p, end, NULL, &err);
7286 s = decode_string (p, &p, end);
7288 o = mono_string_new (domain, s);
7289 buffer_add_objid (buf, (MonoObject*)o);
7292 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7294 MonoDomain *domain2;
7297 domain = decode_domainid (p, &p, end, NULL, &err);
7300 klass = decode_typeid (p, &p, end, &domain2, &err);
7305 g_assert (domain == domain2);
7307 o = mono_object_new (domain, klass);
7309 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7313 buffer_add_objid (buf, o);
7317 return ERR_NOT_IMPLEMENTED;
7324 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7330 ass = decode_assemblyid (p, &p, end, &domain, &err);
7335 case CMD_ASSEMBLY_GET_LOCATION: {
7336 buffer_add_string (buf, mono_image_get_filename (ass->image));
7339 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7343 if (ass->image->dynamic) {
7344 buffer_add_id (buf, 0);
7346 token = mono_image_get_entry_point (ass->image);
7348 buffer_add_id (buf, 0);
7350 m = mono_get_method (ass->image, token, NULL);
7351 buffer_add_methodid (buf, domain, m);
7356 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7357 buffer_add_moduleid (buf, domain, ass->image);
7360 case CMD_ASSEMBLY_GET_OBJECT: {
7361 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7362 buffer_add_objid (buf, o);
7365 case CMD_ASSEMBLY_GET_TYPE: {
7366 char *s = decode_string (p, &p, end);
7367 gboolean ignorecase = decode_byte (p, &p, end);
7368 MonoTypeNameParse info;
7370 gboolean type_resolve, res;
7371 MonoDomain *d = mono_domain_get ();
7373 /* This is needed to be able to find referenced assemblies */
7374 res = mono_domain_set (domain, FALSE);
7377 if (!mono_reflection_parse_type (s, &info)) {
7380 if (info.assembly.name)
7382 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7384 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7385 mono_reflection_free_type_info (&info);
7388 mono_domain_set (d, TRUE);
7392 case CMD_ASSEMBLY_GET_NAME: {
7394 MonoAssembly *mass = ass;
7396 name = g_strdup_printf (
7397 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7399 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7400 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7401 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7402 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7404 buffer_add_string (buf, name);
7409 return ERR_NOT_IMPLEMENTED;
7416 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7422 case CMD_MODULE_GET_INFO: {
7423 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7426 basename = g_path_get_basename (image->name);
7427 buffer_add_string (buf, basename); // name
7428 buffer_add_string (buf, image->module_name); // scopename
7429 buffer_add_string (buf, image->name); // fqname
7430 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7431 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7436 return ERR_NOT_IMPLEMENTED;
7443 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7449 case CMD_FIELD_GET_INFO: {
7450 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7452 buffer_add_string (buf, f->name);
7453 buffer_add_typeid (buf, domain, f->parent);
7454 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7455 buffer_add_int (buf, f->type->attrs);
7459 return ERR_NOT_IMPLEMENTED;
7466 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7468 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7469 /* Special case these so the client doesn't have to handle Type objects */
7471 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7472 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7473 } else if (MONO_TYPE_IS_REFERENCE (t))
7474 buffer_add_value (buf, t, &val, domain);
7476 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7480 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7486 buffer_add_int (buf, 0);
7490 for (i = 0; i < cinfo->num_attrs; ++i) {
7491 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7494 buffer_add_int (buf, nattrs);
7496 for (i = 0; i < cinfo->num_attrs; ++i) {
7497 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7498 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7499 MonoArray *typed_args, *named_args;
7501 CattrNamedArg *arginfo = NULL;
7504 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7505 g_assert (mono_error_ok (&error));
7507 buffer_add_methodid (buf, domain, attr->ctor);
7511 buffer_add_int (buf, mono_array_length (typed_args));
7512 for (j = 0; j < mono_array_length (typed_args); ++j) {
7513 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7515 t = mono_method_signature (attr->ctor)->params [j];
7517 buffer_add_cattr_arg (buf, t, domain, val);
7520 buffer_add_int (buf, 0);
7525 buffer_add_int (buf, mono_array_length (named_args));
7527 for (j = 0; j < mono_array_length (named_args); ++j) {
7528 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7530 if (arginfo [j].prop) {
7531 buffer_add_byte (buf, 0x54);
7532 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7533 } else if (arginfo [j].field) {
7534 buffer_add_byte (buf, 0x53);
7535 buffer_add_fieldid (buf, domain, arginfo [j].field);
7537 g_assert_not_reached ();
7540 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7543 buffer_add_int (buf, 0);
7550 /* FIXME: Code duplication with icall.c */
7552 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7557 mono_class_setup_interfaces (klass, error);
7558 if (!mono_error_ok (error))
7561 for (i = 0; i < klass->interface_count; i++) {
7562 ic = klass->interfaces [i];
7563 g_hash_table_insert (ifaces, ic, ic);
7565 collect_interfaces (ic, ifaces, error);
7566 if (!mono_error_ok (error))
7572 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7582 case CMD_TYPE_GET_INFO: {
7583 buffer_add_string (buf, klass->name_space);
7584 buffer_add_string (buf, klass->name);
7586 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7587 buffer_add_string (buf, name);
7589 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7590 buffer_add_moduleid (buf, domain, klass->image);
7591 buffer_add_typeid (buf, domain, klass->parent);
7592 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7593 buffer_add_typeid (buf, domain, klass->element_class);
7595 buffer_add_id (buf, 0);
7596 buffer_add_int (buf, klass->type_token);
7597 buffer_add_byte (buf, klass->rank);
7598 buffer_add_int (buf, klass->flags);
7600 type = &klass->byval_arg;
7601 // FIXME: Can't decide whenever a class represents a byref type
7604 if (type->type == MONO_TYPE_PTR)
7606 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7608 if (type->type == MONO_TYPE_VALUETYPE)
7610 if (klass->enumtype)
7612 if (klass->generic_container)
7614 if (klass->generic_container || klass->generic_class)
7616 buffer_add_byte (buf, b);
7619 while ((nested = mono_class_get_nested_types (klass, &iter)))
7621 buffer_add_int (buf, nnested);
7623 while ((nested = mono_class_get_nested_types (klass, &iter)))
7624 buffer_add_typeid (buf, domain, nested);
7625 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7626 if (klass->generic_container)
7627 buffer_add_typeid (buf, domain, klass);
7628 else if (klass->generic_class)
7629 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7631 buffer_add_id (buf, 0);
7633 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7636 if (klass->generic_class) {
7637 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7639 count = inst->type_argc;
7640 buffer_add_int (buf, count);
7641 for (i = 0; i < count; i++)
7642 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7643 } else if (klass->generic_container) {
7644 MonoGenericContainer *container = klass->generic_container;
7647 count = container->type_argc;
7648 buffer_add_int (buf, count);
7649 for (i = 0; i < count; i++) {
7650 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7651 buffer_add_typeid (buf, domain, pklass);
7654 buffer_add_int (buf, 0);
7659 case CMD_TYPE_GET_METHODS: {
7662 gpointer iter = NULL;
7665 mono_class_setup_methods (klass);
7667 nmethods = mono_class_num_methods (klass);
7669 buffer_add_int (buf, nmethods);
7671 while ((m = mono_class_get_methods (klass, &iter))) {
7672 buffer_add_methodid (buf, domain, m);
7675 g_assert (i == nmethods);
7678 case CMD_TYPE_GET_FIELDS: {
7681 gpointer iter = NULL;
7684 nfields = mono_class_num_fields (klass);
7686 buffer_add_int (buf, nfields);
7688 while ((f = mono_class_get_fields (klass, &iter))) {
7689 buffer_add_fieldid (buf, domain, f);
7690 buffer_add_string (buf, f->name);
7691 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7692 buffer_add_int (buf, f->type->attrs);
7695 g_assert (i == nfields);
7698 case CMD_TYPE_GET_PROPERTIES: {
7701 gpointer iter = NULL;
7704 nprops = mono_class_num_properties (klass);
7706 buffer_add_int (buf, nprops);
7708 while ((p = mono_class_get_properties (klass, &iter))) {
7709 buffer_add_propertyid (buf, domain, p);
7710 buffer_add_string (buf, p->name);
7711 buffer_add_methodid (buf, domain, p->get);
7712 buffer_add_methodid (buf, domain, p->set);
7713 buffer_add_int (buf, p->attrs);
7716 g_assert (i == nprops);
7719 case CMD_TYPE_GET_CATTRS: {
7720 MonoClass *attr_klass;
7721 MonoCustomAttrInfo *cinfo;
7723 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7724 /* attr_klass can be NULL */
7728 cinfo = mono_custom_attrs_from_class (klass);
7730 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7733 case CMD_TYPE_GET_FIELD_CATTRS: {
7734 MonoClass *attr_klass;
7735 MonoCustomAttrInfo *cinfo;
7736 MonoClassField *field;
7738 field = decode_fieldid (p, &p, end, NULL, &err);
7741 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7745 cinfo = mono_custom_attrs_from_field (klass, field);
7747 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7750 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7751 MonoClass *attr_klass;
7752 MonoCustomAttrInfo *cinfo;
7755 prop = decode_propertyid (p, &p, end, NULL, &err);
7758 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7762 cinfo = mono_custom_attrs_from_property (klass, prop);
7764 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7767 case CMD_TYPE_GET_VALUES:
7768 case CMD_TYPE_GET_VALUES_2: {
7775 MonoThread *thread_obj;
7776 MonoInternalThread *thread = NULL;
7777 guint32 special_static_type;
7779 if (command == CMD_TYPE_GET_VALUES_2) {
7780 int objid = decode_objid (p, &p, end);
7783 err = get_object (objid, (MonoObject**)&thread_obj);
7787 thread = THREAD_TO_INTERNAL (thread_obj);
7790 len = decode_int (p, &p, end);
7791 for (i = 0; i < len; ++i) {
7792 f = decode_fieldid (p, &p, end, NULL, &err);
7796 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7797 return ERR_INVALID_FIELDID;
7798 special_static_type = mono_class_field_get_special_static_type (f);
7799 if (special_static_type != SPECIAL_STATIC_NONE) {
7800 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7801 return ERR_INVALID_FIELDID;
7804 /* Check that the field belongs to the object */
7806 for (k = klass; k; k = k->parent) {
7807 if (k == f->parent) {
7813 return ERR_INVALID_FIELDID;
7815 vtable = mono_class_vtable (domain, f->parent);
7816 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7817 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7818 buffer_add_value (buf, f->type, val, domain);
7823 case CMD_TYPE_SET_VALUES: {
7831 len = decode_int (p, &p, end);
7832 for (i = 0; i < len; ++i) {
7833 f = decode_fieldid (p, &p, end, NULL, &err);
7837 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7838 return ERR_INVALID_FIELDID;
7839 if (mono_class_field_is_special_static (f))
7840 return ERR_INVALID_FIELDID;
7842 /* Check that the field belongs to the object */
7844 for (k = klass; k; k = k->parent) {
7845 if (k == f->parent) {
7851 return ERR_INVALID_FIELDID;
7853 // FIXME: Check for literal/const
7855 vtable = mono_class_vtable (domain, f->parent);
7856 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7857 err = decode_value (f->type, domain, val, p, &p, end);
7862 if (MONO_TYPE_IS_REFERENCE (f->type))
7863 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7865 mono_field_static_set_value (vtable, f, val);
7870 case CMD_TYPE_GET_OBJECT: {
7871 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7872 buffer_add_objid (buf, o);
7875 case CMD_TYPE_GET_SOURCE_FILES:
7876 case CMD_TYPE_GET_SOURCE_FILES_2: {
7877 char *source_file, *base;
7881 files = get_source_files_for_type (klass);
7883 buffer_add_int (buf, files->len);
7884 for (i = 0; i < files->len; ++i) {
7885 source_file = g_ptr_array_index (files, i);
7886 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7887 buffer_add_string (buf, source_file);
7889 base = g_path_get_basename (source_file);
7890 buffer_add_string (buf, base);
7893 g_free (source_file);
7895 g_ptr_array_free (files, TRUE);
7898 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7899 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7903 if (mono_class_is_assignable_from (klass, oklass))
7904 buffer_add_byte (buf, 1);
7906 buffer_add_byte (buf, 0);
7909 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7910 char *name = decode_string (p, &p, end);
7911 int i, flags = decode_int (p, &p, end);
7912 MonoException *ex = NULL;
7913 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7916 return ERR_LOADER_ERROR;
7917 buffer_add_int (buf, array->len);
7918 for (i = 0; i < array->len; ++i) {
7919 MonoMethod *method = g_ptr_array_index (array, i);
7920 buffer_add_methodid (buf, domain, method);
7923 g_ptr_array_free (array, TRUE);
7927 case CMD_TYPE_GET_INTERFACES: {
7929 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7931 MonoClass *tclass, *iface;
7932 GHashTableIter iter;
7936 for (parent = tclass; parent; parent = parent->parent) {
7937 mono_class_setup_interfaces (parent, &error);
7938 if (!mono_error_ok (&error))
7939 return ERR_LOADER_ERROR;
7940 collect_interfaces (parent, iface_hash, &error);
7941 if (!mono_error_ok (&error))
7942 return ERR_LOADER_ERROR;
7945 buffer_add_int (buf, g_hash_table_size (iface_hash));
7947 g_hash_table_iter_init (&iter, iface_hash);
7948 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7949 buffer_add_typeid (buf, domain, iface);
7950 g_hash_table_destroy (iface_hash);
7953 case CMD_TYPE_GET_INTERFACE_MAP: {
7954 int tindex, ioffset;
7955 gboolean variance_used;
7957 int len, nmethods, i;
7961 len = decode_int (p, &p, end);
7962 mono_class_setup_vtable (klass);
7964 for (tindex = 0; tindex < len; ++tindex) {
7965 iclass = decode_typeid (p, &p, end, NULL, &err);
7969 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7971 return ERR_INVALID_ARGUMENT;
7973 nmethods = mono_class_num_methods (iclass);
7974 buffer_add_int (buf, nmethods);
7977 while ((method = mono_class_get_methods (iclass, &iter))) {
7978 buffer_add_methodid (buf, domain, method);
7980 for (i = 0; i < nmethods; ++i)
7981 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7985 case CMD_TYPE_IS_INITIALIZED: {
7986 MonoVTable *vtable = mono_class_vtable (domain, klass);
7989 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7991 buffer_add_int (buf, 0);
7995 return ERR_NOT_IMPLEMENTED;
8002 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8005 MonoDomain *old_domain;
8009 klass = decode_typeid (p, &p, end, &domain, &err);
8013 old_domain = mono_domain_get ();
8015 mono_domain_set (domain, TRUE);
8017 err = type_commands_internal (command, klass, domain, p, end, buf);
8019 mono_domain_set (old_domain, TRUE);
8025 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8027 MonoMethodHeader *header;
8031 case CMD_METHOD_GET_NAME: {
8032 buffer_add_string (buf, method->name);
8035 case CMD_METHOD_GET_DECLARING_TYPE: {
8036 buffer_add_typeid (buf, domain, method->klass);
8039 case CMD_METHOD_GET_DEBUG_INFO: {
8040 MonoDebugMethodInfo *minfo;
8042 int i, j, n_il_offsets;
8045 int *column_numbers;
8047 GPtrArray *source_file_list;
8049 header = mono_method_get_header (method);
8051 buffer_add_int (buf, 0);
8052 buffer_add_string (buf, "");
8053 buffer_add_int (buf, 0);
8057 minfo = mono_debug_lookup_method (method);
8059 buffer_add_int (buf, header->code_size);
8060 buffer_add_string (buf, "");
8061 buffer_add_int (buf, 0);
8062 mono_metadata_free_mh (header);
8066 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
8067 buffer_add_int (buf, header->code_size);
8068 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8069 buffer_add_int (buf, source_file_list->len);
8070 for (i = 0; i < source_file_list->len; ++i) {
8071 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8072 buffer_add_string (buf, sinfo->source_file);
8073 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8074 for (j = 0; j < 16; ++j)
8075 buffer_add_byte (buf, sinfo->hash [j]);
8079 buffer_add_string (buf, source_file);
8081 buffer_add_int (buf, n_il_offsets);
8082 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8083 for (i = 0; i < n_il_offsets; ++i) {
8084 const char *srcfile = "";
8086 if (source_files [i] != -1) {
8087 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8088 srcfile = sinfo->source_file;
8090 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8091 buffer_add_int (buf, il_offsets [i]);
8092 buffer_add_int (buf, line_numbers [i]);
8093 if (CHECK_PROTOCOL_VERSION (2, 13))
8094 buffer_add_int (buf, source_files [i]);
8095 if (CHECK_PROTOCOL_VERSION (2, 19))
8096 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8098 g_free (source_file);
8099 g_free (il_offsets);
8100 g_free (line_numbers);
8101 g_free (source_files);
8102 g_ptr_array_free (source_file_list, TRUE);
8103 mono_metadata_free_mh (header);
8106 case CMD_METHOD_GET_PARAM_INFO: {
8107 MonoMethodSignature *sig = mono_method_signature (method);
8111 /* FIXME: mono_class_from_mono_type () and byrefs */
8113 /* FIXME: Use a smaller encoding */
8114 buffer_add_int (buf, sig->call_convention);
8115 buffer_add_int (buf, sig->param_count);
8116 buffer_add_int (buf, sig->generic_param_count);
8117 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8118 for (i = 0; i < sig->param_count; ++i) {
8120 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8123 /* Emit parameter names */
8124 names = g_new (char *, sig->param_count);
8125 mono_method_get_param_names (method, (const char **) names);
8126 for (i = 0; i < sig->param_count; ++i)
8127 buffer_add_string (buf, names [i]);
8132 case CMD_METHOD_GET_LOCALS_INFO: {
8133 int i, j, num_locals;
8134 MonoDebugLocalsInfo *locals;
8136 header = mono_method_get_header (method);
8138 return ERR_INVALID_ARGUMENT;
8140 buffer_add_int (buf, header->num_locals);
8143 for (i = 0; i < header->num_locals; ++i)
8144 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8147 locals = mono_debug_lookup_locals (method);
8149 num_locals = locals->num_locals;
8152 for (i = 0; i < header->num_locals; ++i) {
8153 for (j = 0; j < num_locals; ++j)
8154 if (locals->locals [j].index == i)
8157 buffer_add_string (buf, locals->locals [j].name);
8159 buffer_add_string (buf, "");
8163 for (i = 0; i < header->num_locals; ++i) {
8164 for (j = 0; j < num_locals; ++j)
8165 if (locals->locals [j].index == i)
8167 if (j < num_locals && locals->locals [j].block) {
8168 buffer_add_int (buf, locals->locals [j].block->start_offset);
8169 buffer_add_int (buf, locals->locals [j].block->end_offset);
8171 buffer_add_int (buf, 0);
8172 buffer_add_int (buf, header->code_size);
8175 mono_metadata_free_mh (header);
8178 mono_debug_symfile_free_locals (locals);
8182 case CMD_METHOD_GET_INFO:
8183 buffer_add_int (buf, method->flags);
8184 buffer_add_int (buf, method->iflags);
8185 buffer_add_int (buf, method->token);
8186 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8188 if (method->is_generic)
8190 if (mono_method_signature (method)->generic_param_count)
8192 buffer_add_byte (buf, attrs);
8193 if (method->is_generic || method->is_inflated) {
8196 if (method->is_generic) {
8199 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8201 result = imethod->declaring;
8202 if (imethod->context.class_inst) {
8203 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8204 /*Generic methods gets the context of the GTD.*/
8205 if (mono_class_get_context (klass))
8206 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8210 buffer_add_methodid (buf, domain, result);
8212 buffer_add_id (buf, 0);
8214 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8215 if (mono_method_signature (method)->generic_param_count) {
8218 if (method->is_inflated) {
8219 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8221 count = inst->type_argc;
8222 buffer_add_int (buf, count);
8224 for (i = 0; i < count; i++)
8225 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8227 buffer_add_int (buf, 0);
8229 } else if (method->is_generic) {
8230 MonoGenericContainer *container = mono_method_get_generic_container (method);
8232 count = mono_method_signature (method)->generic_param_count;
8233 buffer_add_int (buf, count);
8234 for (i = 0; i < count; i++) {
8235 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8236 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8237 buffer_add_typeid (buf, domain, pklass);
8240 buffer_add_int (buf, 0);
8243 buffer_add_int (buf, 0);
8248 case CMD_METHOD_GET_BODY: {
8251 header = mono_method_get_header (method);
8253 buffer_add_int (buf, 0);
8255 if (CHECK_PROTOCOL_VERSION (2, 18))
8256 buffer_add_int (buf, 0);
8258 buffer_add_int (buf, header->code_size);
8259 for (i = 0; i < header->code_size; ++i)
8260 buffer_add_byte (buf, header->code [i]);
8262 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8263 buffer_add_int (buf, header->num_clauses);
8264 for (i = 0; i < header->num_clauses; ++i) {
8265 MonoExceptionClause *clause = &header->clauses [i];
8267 buffer_add_int (buf, clause->flags);
8268 buffer_add_int (buf, clause->try_offset);
8269 buffer_add_int (buf, clause->try_len);
8270 buffer_add_int (buf, clause->handler_offset);
8271 buffer_add_int (buf, clause->handler_len);
8272 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8273 buffer_add_typeid (buf, domain, clause->data.catch_class);
8274 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8275 buffer_add_int (buf, clause->data.filter_offset);
8279 mono_metadata_free_mh (header);
8284 case CMD_METHOD_RESOLVE_TOKEN: {
8285 guint32 token = decode_int (p, &p, end);
8288 switch (mono_metadata_token_code (token)) {
8289 case MONO_TOKEN_STRING: {
8293 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8296 s2 = mono_string_to_utf8 (s);
8298 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8299 buffer_add_string (buf, s2);
8305 MonoClass *handle_class;
8307 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8308 val = mono_method_get_wrapper_data (method, token);
8309 handle_class = mono_method_get_wrapper_data (method, token + 1);
8311 if (handle_class == NULL) {
8312 // Can't figure out the token type
8313 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8317 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8321 if (handle_class == mono_defaults.typehandle_class) {
8322 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8323 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8324 buffer_add_typeid (buf, domain, (MonoClass *) val);
8326 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8327 } else if (handle_class == mono_defaults.fieldhandle_class) {
8328 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8329 buffer_add_fieldid (buf, domain, val);
8330 } else if (handle_class == mono_defaults.methodhandle_class) {
8331 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8332 buffer_add_methodid (buf, domain, val);
8333 } else if (handle_class == mono_defaults.string_class) {
8336 s = mono_string_to_utf8 (val);
8337 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8338 buffer_add_string (buf, s);
8341 g_assert_not_reached ();
8348 case CMD_METHOD_GET_CATTRS: {
8349 MonoClass *attr_klass;
8350 MonoCustomAttrInfo *cinfo;
8352 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8353 /* attr_klass can be NULL */
8357 cinfo = mono_custom_attrs_from_method (method);
8359 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8362 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8363 MonoType **type_argv;
8367 MonoGenericInst *ginst;
8368 MonoGenericContext tmp_context;
8369 MonoMethod *inflated;
8371 type_argc = decode_int (p, &p, end);
8372 type_argv = g_new0 (MonoType*, type_argc);
8373 for (i = 0; i < type_argc; ++i) {
8374 klass = decode_typeid (p, &p, end, &d, &err);
8381 return ERR_INVALID_ARGUMENT;
8383 type_argv [i] = &klass->byval_arg;
8385 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8387 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8388 tmp_context.method_inst = ginst;
8390 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8391 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8392 return ERR_INVALID_ARGUMENT;
8393 buffer_add_methodid (buf, domain, inflated);
8397 return ERR_NOT_IMPLEMENTED;
8404 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8407 MonoDomain *old_domain;
8411 method = decode_methodid (p, &p, end, &domain, &err);
8415 old_domain = mono_domain_get ();
8417 mono_domain_set (domain, TRUE);
8419 err = method_commands_internal (command, method, domain, p, end, buf);
8421 mono_domain_set (old_domain, TRUE);
8427 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8429 int objid = decode_objid (p, &p, end);
8431 MonoThread *thread_obj;
8432 MonoInternalThread *thread;
8434 err = get_object (objid, (MonoObject**)&thread_obj);
8438 thread = THREAD_TO_INTERNAL (thread_obj);
8441 case CMD_THREAD_GET_NAME: {
8443 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8446 buffer_add_int (buf, 0);
8451 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8453 buffer_add_int (buf, len);
8454 buffer_add_data (buf, (guint8*)name, len);
8459 case CMD_THREAD_GET_FRAME_INFO: {
8460 DebuggerTlsData *tls;
8461 int i, start_frame, length;
8463 // Wait for suspending if it already started
8464 // FIXME: Races with suspend_count
8465 while (!is_suspended ()) {
8467 wait_for_suspend ();
8471 wait_for_suspend ();
8472 if (!is_suspended ())
8473 return ERR_NOT_SUSPENDED;
8476 start_frame = decode_int (p, &p, end);
8477 length = decode_int (p, &p, end);
8479 if (start_frame != 0 || length != -1)
8480 return ERR_NOT_IMPLEMENTED;
8482 mono_loader_lock ();
8483 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8484 mono_loader_unlock ();
8487 compute_frame_info (thread, tls);
8489 buffer_add_int (buf, tls->frame_count);
8490 for (i = 0; i < tls->frame_count; ++i) {
8491 buffer_add_int (buf, tls->frames [i]->id);
8492 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8493 buffer_add_int (buf, tls->frames [i]->il_offset);
8495 * Instead of passing the frame type directly to the client, we associate
8496 * it with the previous frame using a set of flags. This avoids lots of
8497 * conditional code in the client, since a frame whose type isn't
8498 * FRAME_TYPE_MANAGED has no method, location, etc.
8500 buffer_add_byte (buf, tls->frames [i]->flags);
8505 case CMD_THREAD_GET_STATE:
8506 buffer_add_int (buf, thread->state);
8508 case CMD_THREAD_GET_INFO:
8509 buffer_add_byte (buf, thread->threadpool_thread);
8511 case CMD_THREAD_GET_ID:
8512 buffer_add_long (buf, (guint64)(gsize)thread);
8514 case CMD_THREAD_GET_TID:
8515 buffer_add_long (buf, (guint64)thread->tid);
8517 case CMD_THREAD_SET_IP: {
8518 DebuggerTlsData *tls;
8521 MonoSeqPointInfo *seq_points;
8522 SeqPoint *sp = NULL;
8526 method = decode_methodid (p, &p, end, &domain, &err);
8529 il_offset = decode_long (p, &p, end);
8531 while (!is_suspended ()) {
8533 wait_for_suspend ();
8536 mono_loader_lock ();
8537 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8538 mono_loader_unlock ();
8541 compute_frame_info (thread, tls);
8542 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8543 return ERR_INVALID_ARGUMENT;
8545 seq_points = get_seq_points (domain, method);
8546 g_assert (seq_points);
8548 for (i = 0; i < seq_points->len; ++i) {
8549 sp = &seq_points->seq_points [i];
8551 if (sp->il_offset == il_offset)
8554 if (i == seq_points->len)
8555 return ERR_INVALID_ARGUMENT;
8557 // FIXME: Check that the ip change is safe
8559 DEBUG (1, fprintf (log_file, "[dbg] Setting IP to %s:0x%0x(0x%0x)\n", tls->frames [0]->actual_method->name, (int)sp->il_offset, (int)sp->native_offset));
8560 MONO_CONTEXT_SET_IP (&tls->restore_ctx, (guint8*)tls->frames [0]->ji->code_start + sp->native_offset);
8564 return ERR_NOT_IMPLEMENTED;
8571 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8575 MonoThread *thread_obj;
8576 MonoInternalThread *thread;
8577 int pos, i, len, frame_idx;
8578 DebuggerTlsData *tls;
8580 MonoDebugMethodJitInfo *jit;
8581 MonoDebugVarInfo *var;
8582 MonoMethodSignature *sig;
8584 MonoMethodHeader *header;
8586 objid = decode_objid (p, &p, end);
8587 err = get_object (objid, (MonoObject**)&thread_obj);
8591 thread = THREAD_TO_INTERNAL (thread_obj);
8593 id = decode_id (p, &p, end);
8595 mono_loader_lock ();
8596 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8597 mono_loader_unlock ();
8600 for (i = 0; i < tls->frame_count; ++i) {
8601 if (tls->frames [i]->id == id)
8604 if (i == tls->frame_count)
8605 return ERR_INVALID_FRAMEID;
8608 frame = tls->frames [frame_idx];
8610 if (!frame->has_ctx)
8611 return ERR_ABSENT_INFORMATION;
8614 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8615 if (!frame->jit && frame->api_method->is_inflated)
8616 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8620 /* This could happen for aot images with no jit debug info */
8621 s = mono_method_full_name (frame->api_method, TRUE);
8622 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8624 return ERR_ABSENT_INFORMATION;
8629 sig = mono_method_signature (frame->actual_method);
8631 if (!get_seq_points (frame->domain, frame->actual_method))
8633 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8635 return ERR_ABSENT_INFORMATION;
8638 case CMD_STACK_FRAME_GET_VALUES: {
8639 len = decode_int (p, &p, end);
8640 header = mono_method_get_header (frame->actual_method);
8642 for (i = 0; i < len; ++i) {
8643 pos = decode_int (p, &p, end);
8648 g_assert (pos >= 0 && pos < jit->num_params);
8650 var = &jit->params [pos];
8652 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8654 g_assert (pos >= 0 && pos < jit->num_locals);
8656 var = &jit->locals [pos];
8658 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8661 mono_metadata_free_mh (header);
8664 case CMD_STACK_FRAME_GET_THIS: {
8665 if (frame->api_method->klass->valuetype) {
8666 if (!sig->hasthis) {
8667 MonoObject *p = NULL;
8668 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8670 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8673 if (!sig->hasthis) {
8674 MonoObject *p = NULL;
8675 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8677 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8682 case CMD_STACK_FRAME_SET_VALUES: {
8685 MonoDebugVarInfo *var;
8687 len = decode_int (p, &p, end);
8688 header = mono_method_get_header (frame->actual_method);
8690 for (i = 0; i < len; ++i) {
8691 pos = decode_int (p, &p, end);
8696 g_assert (pos >= 0 && pos < jit->num_params);
8698 t = sig->params [pos];
8699 var = &jit->params [pos];
8701 g_assert (pos >= 0 && pos < jit->num_locals);
8703 t = header->locals [pos];
8704 var = &jit->locals [pos];
8707 if (MONO_TYPE_IS_REFERENCE (t))
8708 val_buf = g_alloca (sizeof (MonoObject*));
8710 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8711 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8715 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8717 mono_metadata_free_mh (header);
8721 return ERR_NOT_IMPLEMENTED;
8728 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8731 int objid, err, index, len, i, esize;
8734 objid = decode_objid (p, &p, end);
8735 err = get_object (objid, (MonoObject**)&arr);
8740 case CMD_ARRAY_REF_GET_LENGTH:
8741 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8743 buffer_add_int (buf, arr->max_length);
8744 buffer_add_int (buf, 0);
8746 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8747 buffer_add_int (buf, arr->bounds [i].length);
8748 buffer_add_int (buf, arr->bounds [i].lower_bound);
8752 case CMD_ARRAY_REF_GET_VALUES:
8753 index = decode_int (p, &p, end);
8754 len = decode_int (p, &p, end);
8756 g_assert (index >= 0 && len >= 0);
8757 // Reordered to avoid integer overflow
8758 g_assert (!(index > arr->max_length - len));
8760 esize = mono_array_element_size (arr->obj.vtable->klass);
8761 for (i = index; i < index + len; ++i) {
8762 elem = (gpointer*)((char*)arr->vector + (i * esize));
8763 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8766 case CMD_ARRAY_REF_SET_VALUES:
8767 index = decode_int (p, &p, end);
8768 len = decode_int (p, &p, end);
8770 g_assert (index >= 0 && len >= 0);
8771 // Reordered to avoid integer overflow
8772 g_assert (!(index > arr->max_length - len));
8774 esize = mono_array_element_size (arr->obj.vtable->klass);
8775 for (i = index; i < index + len; ++i) {
8776 elem = (gpointer*)((char*)arr->vector + (i * esize));
8778 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8782 return ERR_NOT_IMPLEMENTED;
8789 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8794 int i, index, length;
8797 objid = decode_objid (p, &p, end);
8798 err = get_object (objid, (MonoObject**)&str);
8803 case CMD_STRING_REF_GET_VALUE:
8804 s = mono_string_to_utf8 (str);
8805 buffer_add_string (buf, s);
8808 case CMD_STRING_REF_GET_LENGTH:
8809 buffer_add_long (buf, mono_string_length (str));
8811 case CMD_STRING_REF_GET_CHARS:
8812 index = decode_long (p, &p, end);
8813 length = decode_long (p, &p, end);
8814 if (index > mono_string_length (str) - length)
8815 return ERR_INVALID_ARGUMENT;
8816 c = mono_string_chars (str) + index;
8817 for (i = 0; i < length; ++i)
8818 buffer_add_short (buf, c [i]);
8821 return ERR_NOT_IMPLEMENTED;
8828 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8837 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8838 objid = decode_objid (p, &p, end);
8839 err = get_object (objid, &obj);
8841 buffer_add_int (buf, 1);
8843 buffer_add_int (buf, 0);
8847 objid = decode_objid (p, &p, end);
8848 err = get_object (objid, &obj);
8853 case CMD_OBJECT_REF_GET_TYPE:
8854 /* This handles transparent proxies too */
8855 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8857 case CMD_OBJECT_REF_GET_VALUES:
8858 len = decode_int (p, &p, end);
8860 for (i = 0; i < len; ++i) {
8861 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8865 /* Check that the field belongs to the object */
8867 for (k = obj->vtable->klass; k; k = k->parent) {
8868 if (k == f->parent) {
8874 return ERR_INVALID_FIELDID;
8876 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8880 if (mono_class_field_is_special_static (f))
8881 return ERR_INVALID_FIELDID;
8883 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8884 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8885 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8886 mono_field_static_get_value (vtable, f, val);
8887 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8890 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8894 case CMD_OBJECT_REF_SET_VALUES:
8895 len = decode_int (p, &p, end);
8897 for (i = 0; i < len; ++i) {
8898 f = decode_fieldid (p, &p, end, NULL, &err);
8902 /* Check that the field belongs to the object */
8904 for (k = obj->vtable->klass; k; k = k->parent) {
8905 if (k == f->parent) {
8911 return ERR_INVALID_FIELDID;
8913 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8917 if (mono_class_field_is_special_static (f))
8918 return ERR_INVALID_FIELDID;
8920 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8921 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8923 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8924 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8929 mono_field_static_set_value (vtable, f, val);
8932 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8938 case CMD_OBJECT_REF_GET_ADDRESS:
8939 buffer_add_long (buf, (gssize)obj);
8941 case CMD_OBJECT_REF_GET_DOMAIN:
8942 buffer_add_domainid (buf, obj->vtable->domain);
8944 case CMD_OBJECT_REF_GET_INFO:
8945 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8946 buffer_add_domainid (buf, obj->vtable->domain);
8949 return ERR_NOT_IMPLEMENTED;
8956 command_set_to_string (CommandSet command_set)
8958 switch (command_set) {
8961 case CMD_SET_OBJECT_REF:
8962 return "OBJECT_REF";
8963 case CMD_SET_STRING_REF:
8964 return "STRING_REF";
8965 case CMD_SET_THREAD:
8967 case CMD_SET_ARRAY_REF:
8969 case CMD_SET_EVENT_REQUEST:
8970 return "EVENT_REQUEST";
8971 case CMD_SET_STACK_FRAME:
8972 return "STACK_FRAME";
8973 case CMD_SET_APPDOMAIN:
8975 case CMD_SET_ASSEMBLY:
8977 case CMD_SET_METHOD:
8981 case CMD_SET_MODULE:
8992 static const char* vm_cmds_str [] = {
9000 "SET_PROTOCOL_VERSION",
9003 "GET_TYPES_FOR_SOURCE_FILE",
9008 static const char* thread_cmds_str[] = {
9018 static const char* event_cmds_str[] = {
9021 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9024 static const char* appdomain_cmds_str[] = {
9026 "GET_FRIENDLY_NAME",
9028 "GET_ENTRY_ASSEMBLY",
9031 "CREATE_BOXED_VALUE"
9034 static const char* assembly_cmds_str[] = {
9037 "GET_MANIFEST_MODULE",
9043 static const char* module_cmds_str[] = {
9047 static const char* field_cmds_str[] = {
9051 static const char* method_cmds_str[] = {
9053 "GET_DECLARING_TYPE",
9061 "MAKE_GENERIC_METHOD"
9064 static const char* type_cmds_str[] = {
9072 "IS_ASSIGNABLE_FROM",
9076 "GET_PROPERTY_CATTRS",
9077 "GET_SOURCE_FILES_2",
9079 "GET_METHODS_BY_NAME_FLAGS",
9081 "GET_INTERFACE_MAP",
9085 static const char* stack_frame_cmds_str[] = {
9091 static const char* array_cmds_str[] = {
9097 static const char* string_cmds_str[] = {
9103 static const char* object_cmds_str[] = {
9114 cmd_to_string (CommandSet set, int command)
9122 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9124 case CMD_SET_OBJECT_REF:
9125 cmds = object_cmds_str;
9126 cmds_len = G_N_ELEMENTS (object_cmds_str);
9128 case CMD_SET_STRING_REF:
9129 cmds = string_cmds_str;
9130 cmds_len = G_N_ELEMENTS (string_cmds_str);
9132 case CMD_SET_THREAD:
9133 cmds = thread_cmds_str;
9134 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9136 case CMD_SET_ARRAY_REF:
9137 cmds = array_cmds_str;
9138 cmds_len = G_N_ELEMENTS (array_cmds_str);
9140 case CMD_SET_EVENT_REQUEST:
9141 cmds = event_cmds_str;
9142 cmds_len = G_N_ELEMENTS (event_cmds_str);
9144 case CMD_SET_STACK_FRAME:
9145 cmds = stack_frame_cmds_str;
9146 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9148 case CMD_SET_APPDOMAIN:
9149 cmds = appdomain_cmds_str;
9150 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9152 case CMD_SET_ASSEMBLY:
9153 cmds = assembly_cmds_str;
9154 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9156 case CMD_SET_METHOD:
9157 cmds = method_cmds_str;
9158 cmds_len = G_N_ELEMENTS (method_cmds_str);
9161 cmds = type_cmds_str;
9162 cmds_len = G_N_ELEMENTS (type_cmds_str);
9164 case CMD_SET_MODULE:
9165 cmds = module_cmds_str;
9166 cmds_len = G_N_ELEMENTS (module_cmds_str);
9169 cmds = field_cmds_str;
9170 cmds_len = G_N_ELEMENTS (field_cmds_str);
9173 cmds = event_cmds_str;
9174 cmds_len = G_N_ELEMENTS (event_cmds_str);
9179 if (command > 0 && command <= cmds_len)
9180 return cmds [command - 1];
9186 wait_for_attach (void)
9188 #ifndef DISABLE_SOCKET_TRANSPORT
9189 if (listen_fd == -1) {
9190 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9194 /* Block and wait for client connection */
9195 conn_fd = socket_transport_accept (listen_fd);
9196 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9197 if (conn_fd == -1) {
9198 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9202 g_assert_not_reached ();
9206 disconnected = !transport_handshake ();
9208 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9218 * This thread handles communication with the debugger client using a JDWP
9221 static guint32 WINAPI
9222 debugger_thread (void *arg)
9224 int res, len, id, flags, command_set = 0, command = 0;
9225 guint8 header [HEADER_LENGTH];
9226 guint8 *data, *p, *end;
9230 gboolean attach_failed = FALSE;
9232 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9234 debugger_thread_id = GetCurrentThreadId ();
9236 mono_jit_thread_attach (mono_get_root_domain ());
9238 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9240 mono_set_is_debugger_attached (TRUE);
9242 if (agent_config.defer) {
9243 if (!wait_for_attach ()) {
9244 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9245 attach_failed = TRUE; // Don't abort process when we can't listen
9247 /* Send start event to client */
9248 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9252 while (!attach_failed) {
9253 res = transport_recv (header, HEADER_LENGTH);
9255 /* This will break if the socket is closed during shutdown too */
9256 if (res != HEADER_LENGTH) {
9257 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9262 end = header + HEADER_LENGTH;
9264 len = decode_int (p, &p, end);
9265 id = decode_int (p, &p, end);
9266 flags = decode_byte (p, &p, end);
9267 command_set = decode_byte (p, &p, end);
9268 command = decode_byte (p, &p, end);
9270 g_assert (flags == 0);
9273 const char *cmd_str;
9276 cmd_str = cmd_to_string (command_set, command);
9278 sprintf (cmd_num, "%d", command);
9282 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d].\n", command_set_to_string (command_set), cmd_str, id));
9285 data = g_malloc (len - HEADER_LENGTH);
9286 if (len - HEADER_LENGTH > 0)
9288 res = transport_recv (data, len - HEADER_LENGTH);
9289 if (res != len - HEADER_LENGTH) {
9290 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9296 end = data + (len - HEADER_LENGTH);
9298 buffer_init (&buf, 128);
9303 /* Process the request */
9304 switch (command_set) {
9306 err = vm_commands (command, id, p, end, &buf);
9307 if (!err && command == CMD_VM_INVOKE_METHOD)
9308 /* Sent after the invoke is complete */
9311 case CMD_SET_EVENT_REQUEST:
9312 err = event_commands (command, p, end, &buf);
9314 case CMD_SET_APPDOMAIN:
9315 err = domain_commands (command, p, end, &buf);
9317 case CMD_SET_ASSEMBLY:
9318 err = assembly_commands (command, p, end, &buf);
9320 case CMD_SET_MODULE:
9321 err = module_commands (command, p, end, &buf);
9324 err = field_commands (command, p, end, &buf);
9327 err = type_commands (command, p, end, &buf);
9329 case CMD_SET_METHOD:
9330 err = method_commands (command, p, end, &buf);
9332 case CMD_SET_THREAD:
9333 err = thread_commands (command, p, end, &buf);
9335 case CMD_SET_STACK_FRAME:
9336 err = frame_commands (command, p, end, &buf);
9338 case CMD_SET_ARRAY_REF:
9339 err = array_commands (command, p, end, &buf);
9341 case CMD_SET_STRING_REF:
9342 err = string_commands (command, p, end, &buf);
9344 case CMD_SET_OBJECT_REF:
9345 err = object_commands (command, p, end, &buf);
9348 err = ERR_NOT_IMPLEMENTED;
9352 send_reply_packet (id, err, &buf);
9357 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9361 mono_set_is_debugger_attached (FALSE);
9363 mono_mutex_lock (&debugger_thread_exited_mutex);
9364 debugger_thread_exited = TRUE;
9365 mono_cond_signal (&debugger_thread_exited_cond);
9366 mono_mutex_unlock (&debugger_thread_exited_mutex);
9368 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9370 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9371 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9372 start_debugger_thread ();
9378 #else /* DISABLE_DEBUGGER_AGENT */
9381 mono_debugger_agent_parse_options (char *options)
9383 g_error ("This runtime is configured with the debugger agent disabled.");
9387 mono_debugger_agent_init (void)
9392 mono_debugger_agent_breakpoint_hit (void *sigctx)
9397 mono_debugger_agent_single_step_event (void *sigctx)
9402 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9407 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9413 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9414 MonoContext *catch_ctx)
9419 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9424 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9429 mono_debugger_agent_user_break (void)
9435 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9440 mono_debugger_agent_debug_log_is_enabled (void)