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/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/utils/mono-semaphore.h>
76 #include <mono/utils/mono-error-internals.h>
77 #include <mono/utils/mono-stack-unwinding.h>
78 #include <mono/utils/mono-time.h>
79 #include "debugger-agent.h"
82 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
83 #define DISABLE_DEBUGGER_AGENT 1
86 #ifdef DISABLE_SOFT_DEBUG
87 #define DISABLE_DEBUGGER_AGENT 1
91 #include <mono/utils/mono-threads.h>
94 #ifndef DISABLE_DEBUGGER_AGENT
96 #include <mono/io-layer/mono-mutex.h>
98 /* Definitions to make backporting to 2.6 easier */
99 //#define MonoInternalThread MonoThread
100 //#define mono_thread_internal_current mono_thread_current
101 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
123 guint32 il_offset, native_offset;
127 * If method is gshared, this is the actual instance, otherwise this is equal to
130 MonoMethod *actual_method;
132 MonoDebugMethodJitInfo *jit;
134 mgreg_t *reg_locations [MONO_MAX_IREGS];
136 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
137 * the frame can become invalid.
142 typedef struct _InvokeData InvokeData;
150 /* This is the context which needs to be restored after the invoke */
154 * If this is set, invoke this method with the arguments given by ARGS.
158 guint32 suspend_count;
160 InvokeData *last_invoke;
164 MonoThreadUnwindState context;
166 gpointer resume_event;
167 /* This is computed on demand when it is requested using the wire protocol */
168 /* It is freed up when the thread is resumed */
172 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
175 gboolean frames_up_to_date;
177 * Points to data about a pending invoke which needs to be executed after the thread
180 InvokeData *pending_invoke;
182 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
187 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
188 * within a finite amount of time.
192 * Set to TRUE if this thread is suspended in suspend_current ().
194 gboolean really_suspended;
195 /* Used to pass the context to the breakpoint/single step handler */
196 MonoContext handler_ctx;
197 /* Whenever thread_stop () was called for this thread */
200 /* Number of thread interruptions not yet processed */
201 gint32 interrupt_count;
203 /* Whenever to disable breakpoints (used during invokes) */
204 gboolean disable_breakpoints;
207 * Number of times this thread has been resumed using resume_thread ().
209 guint32 resume_count;
211 MonoInternalThread *thread;
214 * Information about the frame which transitioned to native code for running
217 StackFrameInfo async_last_frame;
220 * The context where the stack walk can be started for running threads.
222 MonoThreadUnwindState async_state;
225 * The context used for filter clauses
227 MonoThreadUnwindState filter_state;
230 * The callee address of the last mono_runtime_invoke call
232 gpointer invoke_addr;
234 gboolean abort_requested;
237 * The current mono_runtime_invoke invocation.
242 * The context where single stepping should resume while the thread is suspended because
243 * of an EXCEPTION event.
245 MonoContext catch_ctx;
247 gboolean has_catch_ctx;
250 * The context which needs to be restored after handling a single step/breakpoint
251 * event. This is the same as the ctx at step/breakpoint site, but includes changes
252 * to caller saved registers done by set_var ().
254 MonoContext restore_ctx;
259 void (*connect) (const char *address);
260 void (*close1) (void);
261 void (*close2) (void);
262 gboolean (*send) (void *buf, int len);
263 int (*recv) (void *buf, int len);
267 * Wire Protocol definitions
270 #define HEADER_LENGTH 11
272 #define MAJOR_VERSION 2
273 #define MINOR_VERSION 14
277 CMD_SET_OBJECT_REF = 9,
278 CMD_SET_STRING_REF = 10,
280 CMD_SET_ARRAY_REF = 13,
281 CMD_SET_EVENT_REQUEST = 15,
282 CMD_SET_STACK_FRAME = 16,
283 CMD_SET_APPDOMAIN = 20,
284 CMD_SET_ASSEMBLY = 21,
292 EVENT_KIND_VM_START = 0,
293 EVENT_KIND_VM_DEATH = 1,
294 EVENT_KIND_THREAD_START = 2,
295 EVENT_KIND_THREAD_DEATH = 3,
296 EVENT_KIND_APPDOMAIN_CREATE = 4,
297 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
298 EVENT_KIND_METHOD_ENTRY = 6,
299 EVENT_KIND_METHOD_EXIT = 7,
300 EVENT_KIND_ASSEMBLY_LOAD = 8,
301 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
302 EVENT_KIND_BREAKPOINT = 10,
303 EVENT_KIND_STEP = 11,
304 EVENT_KIND_TYPE_LOAD = 12,
305 EVENT_KIND_EXCEPTION = 13,
306 EVENT_KIND_KEEPALIVE = 14,
307 EVENT_KIND_USER_BREAK = 15,
308 EVENT_KIND_USER_LOG = 16
312 SUSPEND_POLICY_NONE = 0,
313 SUSPEND_POLICY_EVENT_THREAD = 1,
314 SUSPEND_POLICY_ALL = 2
319 ERR_INVALID_OBJECT = 20,
320 ERR_INVALID_FIELDID = 25,
321 ERR_INVALID_FRAMEID = 30,
322 ERR_NOT_IMPLEMENTED = 100,
323 ERR_NOT_SUSPENDED = 101,
324 ERR_INVALID_ARGUMENT = 102,
326 ERR_NO_INVOCATION = 104,
327 ERR_ABSENT_INFORMATION = 105,
328 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
329 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
334 MOD_KIND_THREAD_ONLY = 3,
335 MOD_KIND_LOCATION_ONLY = 7,
336 MOD_KIND_EXCEPTION_ONLY = 8,
338 MOD_KIND_ASSEMBLY_ONLY = 11,
339 MOD_KIND_SOURCE_FILE_ONLY = 12,
340 MOD_KIND_TYPE_NAME_ONLY = 13
355 TOKEN_TYPE_STRING = 0,
357 TOKEN_TYPE_FIELD = 2,
358 TOKEN_TYPE_METHOD = 3,
359 TOKEN_TYPE_UNKNOWN = 4
363 VALUE_TYPE_ID_NULL = 0xf0,
364 VALUE_TYPE_ID_TYPE = 0xf1
368 FRAME_FLAG_DEBUGGER_INVOKE = 1
372 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
373 INVOKE_FLAG_SINGLE_THREADED = 2
377 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
378 } BindingFlagsExtensions;
382 CMD_VM_ALL_THREADS = 2,
387 CMD_VM_INVOKE_METHOD = 7,
388 CMD_VM_SET_PROTOCOL_VERSION = 8,
389 CMD_VM_ABORT_INVOKE = 9,
390 CMD_VM_SET_KEEPALIVE = 10,
391 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
392 CMD_VM_GET_TYPES = 12
396 CMD_THREAD_GET_FRAME_INFO = 1,
397 CMD_THREAD_GET_NAME = 2,
398 CMD_THREAD_GET_STATE = 3,
399 CMD_THREAD_GET_INFO = 4,
400 CMD_THREAD_GET_ID = 5,
401 CMD_THREAD_GET_TID = 6
405 CMD_EVENT_REQUEST_SET = 1,
406 CMD_EVENT_REQUEST_CLEAR = 2,
407 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
415 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
416 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
417 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
418 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
419 CMD_APPDOMAIN_CREATE_STRING = 5,
420 CMD_APPDOMAIN_GET_CORLIB = 6,
421 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
425 CMD_ASSEMBLY_GET_LOCATION = 1,
426 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
427 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
428 CMD_ASSEMBLY_GET_OBJECT = 4,
429 CMD_ASSEMBLY_GET_TYPE = 5,
430 CMD_ASSEMBLY_GET_NAME = 6
434 CMD_MODULE_GET_INFO = 1,
438 CMD_METHOD_GET_NAME = 1,
439 CMD_METHOD_GET_DECLARING_TYPE = 2,
440 CMD_METHOD_GET_DEBUG_INFO = 3,
441 CMD_METHOD_GET_PARAM_INFO = 4,
442 CMD_METHOD_GET_LOCALS_INFO = 5,
443 CMD_METHOD_GET_INFO = 6,
444 CMD_METHOD_GET_BODY = 7,
445 CMD_METHOD_RESOLVE_TOKEN = 8,
449 CMD_TYPE_GET_INFO = 1,
450 CMD_TYPE_GET_METHODS = 2,
451 CMD_TYPE_GET_FIELDS = 3,
452 CMD_TYPE_GET_VALUES = 4,
453 CMD_TYPE_GET_OBJECT = 5,
454 CMD_TYPE_GET_SOURCE_FILES = 6,
455 CMD_TYPE_SET_VALUES = 7,
456 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
457 CMD_TYPE_GET_PROPERTIES = 9,
458 CMD_TYPE_GET_CATTRS = 10,
459 CMD_TYPE_GET_FIELD_CATTRS = 11,
460 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
461 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
462 CMD_TYPE_GET_VALUES_2 = 14,
463 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
464 CMD_TYPE_GET_INTERFACES = 16,
465 CMD_TYPE_GET_INTERFACE_MAP = 17,
469 CMD_STACK_FRAME_GET_VALUES = 1,
470 CMD_STACK_FRAME_GET_THIS = 2,
471 CMD_STACK_FRAME_SET_VALUES = 3
475 CMD_ARRAY_REF_GET_LENGTH = 1,
476 CMD_ARRAY_REF_GET_VALUES = 2,
477 CMD_ARRAY_REF_SET_VALUES = 3,
481 CMD_STRING_REF_GET_VALUE = 1,
482 CMD_STRING_REF_GET_LENGTH = 2,
483 CMD_STRING_REF_GET_CHARS = 3
487 CMD_OBJECT_REF_GET_TYPE = 1,
488 CMD_OBJECT_REF_GET_VALUES = 2,
489 CMD_OBJECT_REF_IS_COLLECTED = 3,
490 CMD_OBJECT_REF_GET_ADDRESS = 4,
491 CMD_OBJECT_REF_GET_DOMAIN = 5,
492 CMD_OBJECT_REF_SET_VALUES = 6,
493 CMD_OBJECT_REF_GET_INFO = 7,
499 int count; /* For kind == MOD_KIND_COUNT */
500 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
501 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
502 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
503 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
504 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
506 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
515 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
519 * Describes a single step request.
523 MonoInternalThread *thread;
528 MonoMethod *last_method;
530 /* Whenever single stepping is performed using start/stop_single_stepping () */
532 /* The list of breakpoints used to implement step-over */
537 * Contains additional information for an event
540 /* For EVENT_KIND_EXCEPTION */
542 MonoContext catch_ctx;
544 /* For EVENT_KIND_USER_LOG */
546 char *category, *message;
547 /* For EVENT_KIND_TYPE_LOAD */
551 /* Dummy structure used for the profiler callbacks */
556 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
559 #define get_last_sock_error() WSAGetLastError()
560 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
561 #define MONO_EINTR WSAEINTR
563 #define get_last_sock_error() errno
564 #define MONO_EWOULDBLOCK EWOULDBLOCK
565 #define MONO_EINTR EINTR
568 #define CHECK_PROTOCOL_VERSION(major,minor) \
569 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
575 static AgentConfig agent_config;
578 * Whenever the agent is fully initialized.
579 * When using the onuncaught or onthrow options, only some parts of the agent are
580 * initialized on startup, and the full initialization which includes connection
581 * establishment and the startup of the agent thread is only done in response to
584 static gint32 inited;
586 #ifndef DISABLE_SOCKET_TRANSPORT
588 static int listen_fd;
591 static int packet_id = 0;
593 static int objref_id = 0;
595 static int event_request_id = 0;
597 static int frame_id = 0;
599 static GPtrArray *event_requests;
601 static MonoNativeTlsKey debugger_tls_id;
603 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
605 /* Maps MonoInternalThread -> DebuggerTlsData */
606 static MonoGHashTable *thread_to_tls;
608 /* Maps tid -> MonoInternalThread */
609 static MonoGHashTable *tid_to_thread;
611 /* Maps tid -> MonoThread (not MonoInternalThread) */
612 static MonoGHashTable *tid_to_thread_obj;
614 static gsize debugger_thread_id;
616 static HANDLE debugger_thread_handle;
618 static int log_level;
620 static gboolean embedding;
622 static FILE *log_file;
624 /* Assemblies whose assembly load event has no been sent yet */
625 static GPtrArray *pending_assembly_loads;
627 /* Whenever the debugger thread has exited */
628 static gboolean debugger_thread_exited;
630 /* Cond variable used to wait for debugger_thread_exited becoming true */
631 static mono_cond_t debugger_thread_exited_cond;
633 /* Mutex for the cond var above */
634 static mono_mutex_t debugger_thread_exited_mutex;
636 static DebuggerProfiler debugger_profiler;
638 /* The single step request instance */
639 static SingleStepReq *ss_req = NULL;
640 static gpointer ss_invoke_addr = NULL;
642 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
643 /* Number of single stepping operations in progress */
647 /* The protocol version of the client */
648 static int major_version, minor_version;
650 /* Whenever the variables above are set by the client */
651 static gboolean protocol_version_set;
653 /* A hash table containing all active domains */
654 static GHashTable *domains;
656 static void transport_init (void);
657 static void transport_connect (const char *address);
658 static gboolean transport_handshake (void);
659 static void register_transport (DebuggerTransport *trans);
661 static guint32 WINAPI debugger_thread (void *arg);
663 static void runtime_initialized (MonoProfiler *prof);
665 static void runtime_shutdown (MonoProfiler *prof);
667 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
669 static void thread_end (MonoProfiler *prof, uintptr_t tid);
671 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
673 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
675 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
677 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
679 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
681 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
683 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
685 static void emit_assembly_load (gpointer assembly, gpointer user_data);
687 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
689 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
691 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
693 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
695 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
697 static void start_single_stepping (void);
699 static void stop_single_stepping (void);
701 static void suspend_current (void);
703 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
705 static void clear_types_for_assembly (MonoAssembly *assembly);
707 static void clear_breakpoints_for_domain (MonoDomain *domain);
709 static void process_profiler_event (EventKind event, gpointer arg);
711 /* Submodule init/cleanup */
712 static void breakpoints_init (void);
713 static void breakpoints_cleanup (void);
715 static void objrefs_init (void);
716 static void objrefs_cleanup (void);
718 static void ids_init (void);
719 static void ids_cleanup (void);
721 static void suspend_init (void);
723 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
724 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
725 static void ss_destroy (SingleStepReq *req);
727 static void start_debugger_thread (void);
728 static void stop_debugger_thread (void);
730 static void finish_agent_init (gboolean on_startup);
732 static void process_profiler_event (EventKind event, gpointer arg);
734 #ifndef DISABLE_SOCKET_TRANSPORT
736 register_socket_transport (void);
740 parse_address (char *address, char **host, int *port)
742 char *pos = strchr (address, ':');
744 if (pos == NULL || pos == address)
747 *host = g_malloc (pos - address + 1);
748 strncpy (*host, address, pos - address);
749 (*host) [pos - address] = '\0';
751 *port = atoi (pos + 1);
759 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
760 fprintf (stderr, "Available options:\n");
761 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
762 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
763 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
764 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
765 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
766 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
767 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
768 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
769 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
773 parse_flag (const char *option, char *flag)
775 if (!strcmp (flag, "y"))
777 else if (!strcmp (flag, "n"))
780 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
787 mono_debugger_agent_parse_options (char *options)
794 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
795 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
799 extra = getenv ("MONO_SDB_ENV_OPTIONS");
801 options = g_strdup_printf ("%s,%s", options, extra);
803 agent_config.enabled = TRUE;
804 agent_config.suspend = TRUE;
805 agent_config.server = FALSE;
806 agent_config.defer = FALSE;
807 agent_config.address = NULL;
809 args = g_strsplit (options, ",", -1);
810 for (ptr = args; ptr && *ptr; ptr ++) {
813 if (strncmp (arg, "transport=", 10) == 0) {
814 agent_config.transport = g_strdup (arg + 10);
815 } else if (strncmp (arg, "address=", 8) == 0) {
816 agent_config.address = g_strdup (arg + 8);
817 } else if (strncmp (arg, "loglevel=", 9) == 0) {
818 agent_config.log_level = atoi (arg + 9);
819 } else if (strncmp (arg, "logfile=", 8) == 0) {
820 agent_config.log_file = g_strdup (arg + 8);
821 } else if (strncmp (arg, "suspend=", 8) == 0) {
822 agent_config.suspend = parse_flag ("suspend", arg + 8);
823 } else if (strncmp (arg, "server=", 7) == 0) {
824 agent_config.server = parse_flag ("server", arg + 7);
825 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
826 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
827 } else if (strncmp (arg, "onthrow=", 8) == 0) {
828 /* We support multiple onthrow= options */
829 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
830 } else if (strncmp (arg, "onthrow", 7) == 0) {
831 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
832 } else if (strncmp (arg, "help", 4) == 0) {
835 } else if (strncmp (arg, "timeout=", 8) == 0) {
836 agent_config.timeout = atoi (arg + 8);
837 } else if (strncmp (arg, "launch=", 7) == 0) {
838 agent_config.launch = g_strdup (arg + 7);
839 } else if (strncmp (arg, "embedding=", 10) == 0) {
840 agent_config.embedding = atoi (arg + 10) == 1;
841 } else if (strncmp (arg, "keepalive=", 10) == 0) {
842 agent_config.keepalive = atoi (arg + 10);
849 if (agent_config.server && !agent_config.suspend) {
850 /* Waiting for deferred attachment */
851 agent_config.defer = TRUE;
852 if (agent_config.address == NULL) {
853 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
857 if (agent_config.transport == NULL) {
858 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
862 if (agent_config.address == NULL && !agent_config.server) {
863 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
868 if (!strcmp (agent_config.transport, "dt_socket")) {
869 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
870 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
877 mono_debugger_agent_init (void)
879 if (!agent_config.enabled)
884 /* Need to know whenever a thread has acquired the loader mutex */
885 mono_loader_lock_track_ownership (TRUE);
887 event_requests = g_ptr_array_new ();
889 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
890 mono_cond_init (&debugger_thread_exited_cond, NULL);
892 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
893 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
894 mono_profiler_install_runtime_initialized (runtime_initialized);
895 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
896 mono_profiler_install_thread (thread_startup, thread_end);
897 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
898 mono_profiler_install_jit_end (jit_end);
899 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
901 mono_native_tls_alloc (&debugger_tls_id, NULL);
903 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
904 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
906 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
907 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
909 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
910 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
912 pending_assembly_loads = g_ptr_array_new ();
913 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
915 log_level = agent_config.log_level;
917 embedding = agent_config.embedding;
920 if (agent_config.log_file) {
921 log_file = fopen (agent_config.log_file, "w+");
923 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
935 mini_get_debug_options ()->gen_seq_points = TRUE;
937 * This is needed because currently we don't handle liveness info.
939 mini_get_debug_options ()->mdb_optimizations = TRUE;
941 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
942 /* This is needed because we can't set local variables in registers yet */
943 mono_disable_optimizations (MONO_OPT_LINEARS);
946 if (!agent_config.onuncaught && !agent_config.onthrow)
947 finish_agent_init (TRUE);
949 /* FIXME: Is this still needed ? */
950 #if defined(__MACH__)
951 mono_thread_info_disable_new_interrupt (TRUE);
958 * Finish the initialization of the agent. This involves connecting the transport
959 * and starting the agent thread. This is either done at startup, or
960 * in response to some event like an unhandled exception.
963 finish_agent_init (gboolean on_startup)
967 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
970 if (agent_config.launch) {
973 // FIXME: Generated address
974 // FIXME: Races with transport_connect ()
976 argv [0] = agent_config.launch;
977 argv [1] = agent_config.transport;
978 argv [2] = agent_config.address;
981 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
983 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
988 transport_connect (agent_config.address);
991 /* Do some which is usually done after sending the VMStart () event */
992 vm_start_event_sent = TRUE;
993 start_debugger_thread ();
998 mono_debugger_agent_cleanup (void)
1003 stop_debugger_thread ();
1005 breakpoints_cleanup ();
1009 mono_mutex_destroy (&debugger_thread_exited_mutex);
1010 mono_cond_destroy (&debugger_thread_exited_cond);
1017 #ifndef DISABLE_SOCKET_TRANSPORT
1022 * recv() + handle incomplete reads and EINTR
1025 socket_transport_recv (void *buf, int len)
1034 res = recv (fd, (char *) buf + total, len - total, flags);
1037 if (agent_config.keepalive && res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1038 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1041 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1046 #define HAVE_GETADDRINFO 1
1050 set_keepalive (void)
1055 if (!agent_config.keepalive)
1058 tv.tv_sec = agent_config.keepalive / 1000;
1059 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1061 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1062 g_assert (result >= 0);
1066 socket_transport_accept (int socket_fd)
1068 conn_fd = accept (socket_fd, NULL, NULL);
1069 if (conn_fd == -1) {
1070 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1072 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1079 socket_transport_send (void *data, int len)
1084 res = send (conn_fd, data, len, 0);
1085 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1093 * socket_transport_connect:
1095 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1098 socket_transport_connect (const char *address)
1100 #ifdef HAVE_GETADDRINFO
1101 struct addrinfo hints;
1102 struct addrinfo *result, *rp;
1104 struct hostent *result;
1106 int sfd = -1, s, res;
1107 char port_string [128];
1111 if (agent_config.address) {
1112 res = parse_address (agent_config.address, &host, &port);
1113 g_assert (res == 0);
1123 sprintf (port_string, "%d", port);
1125 mono_network_init ();
1127 /* Obtain address(es) matching host/port */
1128 #ifdef HAVE_GETADDRINFO
1129 memset (&hints, 0, sizeof (struct addrinfo));
1130 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1131 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1133 hints.ai_protocol = 0; /* Any protocol */
1135 s = getaddrinfo (host, port_string, &hints, &result);
1137 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1141 /* The PS3 doesn't even have _r or hstrerror () */
1142 result = gethostbyname (host);
1144 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1149 if (agent_config.server) {
1150 #ifdef HAVE_GETADDRINFO
1151 /* Wait for a connection */
1153 struct sockaddr_in addr;
1156 /* No address, generate one */
1157 sfd = socket (AF_INET, SOCK_STREAM, 0);
1160 /* This will bind the socket to a random port */
1161 res = listen (sfd, 16);
1163 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1168 addrlen = sizeof (addr);
1169 memset (&addr, 0, sizeof (addr));
1170 res = getsockname (sfd, &addr, &addrlen);
1171 g_assert (res == 0);
1173 host = (char*)"127.0.0.1";
1174 port = ntohs (addr.sin_port);
1176 /* Emit the address to stdout */
1177 /* FIXME: Should print another interface, not localhost */
1178 printf ("%s:%d\n", host, port);
1180 /* Listen on the provided address */
1181 for (rp = result; rp != NULL; rp = rp->ai_next) {
1184 sfd = socket (rp->ai_family, rp->ai_socktype,
1189 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1192 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1196 res = listen (sfd, 16);
1205 * this function is not present on win2000 which we still support, and the
1206 * workaround described here:
1207 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1208 * only works with MSVC.
1210 #ifdef HAVE_GETADDRINFO
1211 freeaddrinfo (result);
1216 if (agent_config.defer)
1219 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1221 if (agent_config.timeout) {
1226 tv.tv_usec = agent_config.timeout * 1000;
1228 FD_SET (sfd, &readfds);
1229 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1231 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1236 conn_fd = socket_transport_accept (sfd);
1240 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1243 #endif /* HAVE_GETADDRINFO */
1245 /* Connect to the specified address */
1246 #ifdef HAVE_GETADDRINFO
1247 /* FIXME: Respect the timeout */
1248 for (rp = result; rp != NULL; rp = rp->ai_next) {
1249 sfd = socket (rp->ai_family, rp->ai_socktype,
1254 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1255 break; /* Success */
1261 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1265 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1267 g_assert_not_reached ();
1268 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1270 g_assert_not_reached ();
1276 /* See the comment above */
1277 #ifdef HAVE_GETADDRINFO
1278 freeaddrinfo (result);
1283 disconnected = !transport_handshake ();
1289 socket_transport_close1 (void)
1291 /* This will interrupt the agent thread */
1292 /* Close the read part only so it can still send back replies */
1293 /* Also shut down the connection listener so that we can exit normally */
1295 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1296 shutdown (conn_fd, SD_BOTH);
1297 shutdown (listen_fd, SD_BOTH);
1298 closesocket (listen_fd);
1300 shutdown (conn_fd, SHUT_RD);
1301 shutdown (listen_fd, SHUT_RDWR);
1307 socket_transport_close2 (void)
1310 shutdown (conn_fd, SD_BOTH);
1312 shutdown (conn_fd, SHUT_RDWR);
1317 register_socket_transport (void)
1319 DebuggerTransport trans;
1321 trans.name = "dt_socket";
1322 trans.connect = socket_transport_connect;
1323 trans.close1 = socket_transport_close1;
1324 trans.close2 = socket_transport_close2;
1325 trans.send = socket_transport_send;
1326 trans.recv = socket_transport_recv;
1328 register_transport (&trans);
1331 #endif /* DISABLE_SOCKET_TRANSPORT */
1337 #define MAX_TRANSPORTS 16
1339 static DebuggerTransport *transport;
1341 static DebuggerTransport transports [MAX_TRANSPORTS];
1342 static int ntransports;
1345 register_transport (DebuggerTransport *trans)
1347 g_assert (ntransports < MAX_TRANSPORTS);
1349 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1354 transport_init (void)
1358 #ifndef DISABLE_SOCKET_TRANSPORT
1359 register_socket_transport ();
1362 for (i = 0; i < ntransports; ++i) {
1363 if (!strcmp (agent_config.transport, transports [i].name))
1366 if (i == ntransports) {
1367 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1368 for (i = 0; i < ntransports; ++i)
1369 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1370 fprintf (stderr, "\n");
1373 transport = &transports [i];
1377 transport_connect (const char *address)
1379 transport->connect (address);
1383 transport_close1 (void)
1385 transport->close1 ();
1389 transport_close2 (void)
1391 transport->close2 ();
1395 transport_send (void *buf, int len)
1397 return transport->send (buf, len);
1401 transport_recv (void *buf, int len)
1403 return transport->recv (buf, len);
1407 transport_handshake (void)
1409 char handshake_msg [128];
1413 /* Write handshake message */
1414 sprintf (handshake_msg, "DWP-Handshake");
1416 res = transport_send (handshake_msg, strlen (handshake_msg));
1417 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1418 g_assert (res != -1);
1421 res = transport_recv (buf, strlen (handshake_msg));
1422 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1423 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1428 * To support older clients, the client sends its protocol version after connecting
1429 * using a command. Until that is received, default to our protocol version.
1431 major_version = MAJOR_VERSION;
1432 minor_version = MINOR_VERSION;
1433 protocol_version_set = FALSE;
1435 #ifndef DISABLE_SOCKET_TRANSPORT
1436 // FIXME: Move this somewhere else
1438 * Set TCP_NODELAY on the socket so the client receives events/command
1439 * results immediately.
1443 int result = setsockopt (conn_fd,
1448 g_assert (result >= 0);
1458 stop_debugger_thread (void)
1463 transport_close1 ();
1466 * Wait for the thread to exit.
1468 * If we continue with the shutdown without waiting for it, then the client might
1469 * not receive an answer to its last command like a resume.
1470 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1473 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1474 if (GetCurrentThreadId () != debugger_thread_id) {
1476 mono_mutex_lock (&debugger_thread_exited_mutex);
1477 if (!debugger_thread_exited) {
1479 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1480 mono_mutex_unlock (&debugger_thread_exited_mutex);
1482 mono_mutex_lock (&debugger_thread_exited_mutex);
1485 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1488 mono_mutex_unlock (&debugger_thread_exited_mutex);
1489 } while (!debugger_thread_exited);
1492 transport_close2 ();
1496 start_debugger_thread (void)
1500 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1501 g_assert (debugger_thread_handle);
1505 * Functions to decode protocol data
1509 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1512 g_assert (*endbuf <= limit);
1517 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1520 g_assert (*endbuf <= limit);
1522 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1525 static inline gint64
1526 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1528 guint32 high = decode_int (buf, &buf, limit);
1529 guint32 low = decode_int (buf, &buf, limit);
1533 return ((((guint64)high) << 32) | ((guint64)low));
1537 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1539 return decode_int (buf, endbuf, limit);
1543 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1545 int len = decode_int (buf, &buf, limit);
1553 s = g_malloc (len + 1);
1556 memcpy (s, buf, len);
1565 * Functions to encode protocol data
1569 guint8 *buf, *p, *end;
1573 buffer_init (Buffer *buf, int size)
1575 buf->buf = g_malloc (size);
1577 buf->end = buf->buf + size;
1581 buffer_make_room (Buffer *buf, int size)
1583 if (buf->end - buf->p < size) {
1584 int new_size = buf->end - buf->buf + size + 32;
1585 guint8 *p = g_realloc (buf->buf, new_size);
1586 size = buf->p - buf->buf;
1589 buf->end = buf->buf + new_size;
1594 buffer_add_byte (Buffer *buf, guint8 val)
1596 buffer_make_room (buf, 1);
1602 buffer_add_short (Buffer *buf, guint32 val)
1604 buffer_make_room (buf, 2);
1605 buf->p [0] = (val >> 8) & 0xff;
1606 buf->p [1] = (val >> 0) & 0xff;
1611 buffer_add_int (Buffer *buf, guint32 val)
1613 buffer_make_room (buf, 4);
1614 buf->p [0] = (val >> 24) & 0xff;
1615 buf->p [1] = (val >> 16) & 0xff;
1616 buf->p [2] = (val >> 8) & 0xff;
1617 buf->p [3] = (val >> 0) & 0xff;
1622 buffer_add_long (Buffer *buf, guint64 l)
1624 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1625 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1629 buffer_add_id (Buffer *buf, int id)
1631 buffer_add_int (buf, (guint64)id);
1635 buffer_add_data (Buffer *buf, guint8 *data, int len)
1637 buffer_make_room (buf, len);
1638 memcpy (buf->p, data, len);
1643 buffer_add_string (Buffer *buf, const char *str)
1648 buffer_add_int (buf, 0);
1651 buffer_add_int (buf, len);
1652 buffer_add_data (buf, (guint8*)str, len);
1657 buffer_free (Buffer *buf)
1663 send_packet (int command_set, int command, Buffer *data)
1669 id = InterlockedIncrement (&packet_id);
1671 len = data->p - data->buf + 11;
1672 buffer_init (&buf, len);
1673 buffer_add_int (&buf, len);
1674 buffer_add_int (&buf, id);
1675 buffer_add_byte (&buf, 0); /* flags */
1676 buffer_add_byte (&buf, command_set);
1677 buffer_add_byte (&buf, command);
1678 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1680 res = transport_send (buf.buf, len);
1688 send_reply_packet (int id, int error, Buffer *data)
1694 len = data->p - data->buf + 11;
1695 buffer_init (&buf, len);
1696 buffer_add_int (&buf, len);
1697 buffer_add_int (&buf, id);
1698 buffer_add_byte (&buf, 0x80); /* flags */
1699 buffer_add_byte (&buf, (error >> 8) & 0xff);
1700 buffer_add_byte (&buf, error);
1701 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1703 res = transport_send (buf.buf, len);
1715 * Represents an object accessible by the debugger client.
1718 /* Unique id used in the wire protocol to refer to objects */
1721 * A weakref gc handle pointing to the object. The gc handle is used to
1722 * detect if the object was garbage collected.
1727 /* Maps objid -> ObjRef */
1728 static GHashTable *objrefs;
1731 free_objref (gpointer value)
1735 mono_gchandle_free (o->handle);
1743 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1747 objrefs_cleanup (void)
1749 g_hash_table_destroy (objrefs);
1753 static GHashTable *obj_to_objref;
1756 * Return an ObjRef for OBJ.
1759 get_objref (MonoObject *obj)
1762 GSList *reflist = NULL, *l;
1768 mono_loader_lock ();
1771 obj_to_objref = g_hash_table_new (NULL, NULL);
1773 /* FIXME: The tables can grow indefinitely */
1775 if (mono_gc_is_moving ()) {
1777 * Objects can move, so use a hash table mapping hash codes to lists of
1778 * ObjRef structures.
1780 hash = mono_object_hash (obj);
1782 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1783 for (l = reflist; l; l = l->next) {
1785 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1786 mono_loader_unlock ();
1791 /* Use a hash table with masked pointers to internalize object references */
1792 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1793 /* ref might refer to a different object with the same addr which was GCd */
1794 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1795 mono_loader_unlock ();
1800 ref = g_new0 (ObjRef, 1);
1801 ref->id = InterlockedIncrement (&objref_id);
1802 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1804 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1806 if (mono_gc_is_moving ()) {
1807 reflist = g_slist_append (reflist, ref);
1808 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1810 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1813 mono_loader_unlock ();
1819 get_objid (MonoObject *obj)
1821 return get_objref (obj)->id;
1825 * Set OBJ to the object identified by OBJID.
1826 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1830 get_object_allow_null (int objid, MonoObject **obj)
1840 return ERR_INVALID_OBJECT;
1842 mono_loader_lock ();
1844 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1847 *obj = mono_gchandle_get_target (ref->handle);
1848 mono_loader_unlock ();
1850 return ERR_INVALID_OBJECT;
1853 mono_loader_unlock ();
1854 return ERR_INVALID_OBJECT;
1859 get_object (int objid, MonoObject **obj)
1861 int err = get_object_allow_null (objid, obj);
1866 return ERR_INVALID_OBJECT;
1871 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1873 return decode_id (buf, endbuf, limit);
1877 buffer_add_objid (Buffer *buf, MonoObject *o)
1879 buffer_add_id (buf, get_objid (o));
1898 * Represents a runtime structure accessible to the debugger client
1901 /* Unique id used in the wire protocol */
1903 /* Domain of the runtime structure, NULL if the domain was unloaded */
1910 MonoAssembly *assembly;
1911 MonoClassField *field;
1913 MonoProperty *property;
1918 /* Maps runtime structure -> Id */
1919 GHashTable *val_to_id [ID_NUM];
1920 /* Classes whose class load event has been sent */
1921 GHashTable *loaded_classes;
1922 /* Maps MonoClass->GPtrArray of file names */
1923 GHashTable *source_files;
1924 /* Maps source file basename -> GSList of classes */
1925 GHashTable *source_file_to_class;
1926 /* Same with ignore-case */
1927 GHashTable *source_file_to_class_ignorecase;
1931 static GPtrArray *ids [ID_NUM];
1938 for (i = 0; i < ID_NUM; ++i)
1939 ids [i] = g_ptr_array_new ();
1947 for (i = 0; i < ID_NUM; ++i) {
1949 for (j = 0; j < ids [i]->len; ++j)
1950 g_free (g_ptr_array_index (ids [i], j));
1951 g_ptr_array_free (ids [i], TRUE);
1958 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1960 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1962 GHashTableIter iter;
1963 GPtrArray *file_names;
1968 for (i = 0; i < ID_NUM; ++i)
1969 if (info->val_to_id [i])
1970 g_hash_table_destroy (info->val_to_id [i]);
1971 g_hash_table_destroy (info->loaded_classes);
1973 g_hash_table_iter_init (&iter, info->source_files);
1974 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
1975 for (i = 0; i < file_names->len; ++i)
1976 g_free (g_ptr_array_index (file_names, i));
1977 g_ptr_array_free (file_names, TRUE);
1980 g_hash_table_iter_init (&iter, info->source_file_to_class);
1981 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
1986 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
1987 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
1995 domain_jit_info (domain)->agent_info = NULL;
1997 /* Clear ids referencing structures in the domain */
1998 for (i = 0; i < ID_NUM; ++i) {
2000 for (j = 0; j < ids [i]->len; ++j) {
2001 Id *id = g_ptr_array_index (ids [i], j);
2002 if (id->domain == domain)
2008 mono_loader_lock ();
2009 g_hash_table_remove (domains, domain);
2010 mono_loader_unlock ();
2013 static AgentDomainInfo*
2014 get_agent_domain_info (MonoDomain *domain)
2016 AgentDomainInfo *info = NULL;
2018 mono_domain_lock (domain);
2020 info = domain_jit_info (domain)->agent_info;
2022 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2023 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2024 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2025 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2026 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2029 mono_domain_unlock (domain);
2035 get_id (MonoDomain *domain, IdType type, gpointer val)
2038 AgentDomainInfo *info;
2043 mono_loader_lock ();
2045 mono_domain_lock (domain);
2047 info = get_agent_domain_info (domain);
2049 if (info->val_to_id [type] == NULL)
2050 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2052 id = g_hash_table_lookup (info->val_to_id [type], val);
2054 mono_domain_unlock (domain);
2055 mono_loader_unlock ();
2059 id = g_new0 (Id, 1);
2061 id->id = ids [type]->len + 1;
2062 id->domain = domain;
2065 g_hash_table_insert (info->val_to_id [type], val, id);
2067 mono_domain_unlock (domain);
2069 g_ptr_array_add (ids [type], id);
2071 mono_loader_unlock ();
2076 static inline gpointer
2077 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2081 int id = decode_id (buf, endbuf, limit);
2090 // FIXME: error handling
2091 mono_loader_lock ();
2092 g_assert (id > 0 && id <= ids [type]->len);
2094 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2095 mono_loader_unlock ();
2097 if (res->domain == NULL) {
2098 *err = ERR_UNLOADED;
2103 *domain = res->domain;
2105 return res->data.val;
2109 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2111 buffer_add_id (buf, get_id (domain, type, val));
2114 static inline MonoClass*
2115 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2117 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2120 static inline MonoAssembly*
2121 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2123 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2126 static inline MonoImage*
2127 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2129 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2132 static inline MonoMethod*
2133 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2135 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2138 static inline MonoClassField*
2139 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2141 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2144 static inline MonoDomain*
2145 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2147 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2150 static inline MonoProperty*
2151 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2153 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2157 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2159 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2163 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2165 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2169 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2171 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2175 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2177 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2181 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2183 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2187 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2189 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2193 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2195 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2198 static void invoke_method (void);
2205 * save_thread_context:
2207 * Set CTX as the current threads context which is used for computing stack traces.
2208 * This function is signal-safe.
2211 save_thread_context (MonoContext *ctx)
2213 DebuggerTlsData *tls;
2215 tls = mono_native_tls_get_value (debugger_tls_id);
2219 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2221 mono_thread_state_init_from_current (&tls->context);
2224 /* The number of times the runtime is suspended */
2225 static gint32 suspend_count;
2227 /* Number of threads suspended */
2229 * If this is equal to the size of thread_to_tls, the runtime is considered
2232 static gint32 threads_suspend_count;
2234 static mono_mutex_t suspend_mutex;
2236 /* Cond variable used to wait for suspend_count becoming 0 */
2237 static mono_cond_t suspend_cond;
2239 /* Semaphore used to wait for a thread becoming suspended */
2240 static MonoSemType suspend_sem;
2245 mono_mutex_init (&suspend_mutex, NULL);
2246 mono_cond_init (&suspend_cond, NULL);
2247 MONO_SEM_INIT (&suspend_sem, 0);
2252 StackFrameInfo last_frame;
2253 gboolean last_frame_set;
2256 } GetLastFrameUserData;
2259 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2261 GetLastFrameUserData *data = user_data;
2263 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2266 if (!data->last_frame_set) {
2267 /* Store the last frame */
2268 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2269 data->last_frame_set = TRUE;
2272 /* Store the context/lmf for the frame above the last frame */
2273 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2274 data->lmf = info->lmf;
2283 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2284 * INFO is set, process the thread described by INFO.
2285 * This should be signal safe.
2288 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2292 MonoNativeThreadId tid;
2295 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2296 * guarantee the signal handler will be called that many times. Instead of tracking
2297 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2298 * has been requested that hasn't been handled yet, otherwise we can have threads
2299 * refuse to die when VM_EXIT is called
2301 #if defined(__APPLE__)
2302 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2306 * We use interrupt_count to determine whenever this interrupt should be processed
2307 * by us or the normal interrupt processing code in the signal handler.
2308 * There is no race here with notify_thread (), since the signal is sent after
2309 * incrementing interrupt_count.
2311 if (tls->interrupt_count == 0)
2314 InterlockedDecrement (&tls->interrupt_count);
2318 ip = mono_arch_ip_from_context (sigctx);
2320 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2325 tid = mono_thread_info_get_tid (info);
2327 tid = GetCurrentThreadId ();
2329 // FIXME: Races when the thread leaves managed code before hitting a single step
2333 /* Running managed code, will be suspended by the single step code */
2334 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2338 * Running native code, will be suspended when it returns to/enters
2339 * managed code. Treat it as already suspended.
2340 * This might interrupt the code in process_single_step_inner (), we use the
2341 * tls->suspending flag to avoid races when that happens.
2343 if (!tls->suspended && !tls->suspending) {
2345 GetLastFrameUserData data;
2347 // FIXME: printf is not signal safe, but this is only used during
2348 // debugger debugging
2350 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2351 //save_thread_context (&ctx);
2354 /* Already terminated */
2357 tls->context.valid = FALSE;
2360 * We are in a difficult position: we want to be able to provide stack
2361 * traces for this thread, but we can't use the current ctx+lmf, since
2362 * the thread is still running, so it might return to managed code,
2363 * making these invalid.
2364 * So we start a stack walk and save the first frame, along with the
2365 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2366 * suspended when it returns to managed code, so the parent's ctx should
2369 data.last_frame_set = FALSE;
2371 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2373 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2374 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2375 * since we are not in a JITted method.
2377 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2379 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2381 if (data.last_frame_set) {
2382 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2383 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2385 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2388 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2389 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2390 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2392 /* No managed frames */
2393 tls->async_state.valid = FALSE;
2395 mono_memory_barrier ();
2397 tls->suspended = TRUE;
2398 MONO_SEM_POST (&suspend_sem);
2405 * mono_debugger_agent_thread_interrupt:
2407 * Called by the abort signal handler.
2408 * Should be signal safe.
2411 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2413 DebuggerTlsData *tls;
2418 tls = mono_native_tls_get_value (debugger_tls_id);
2422 return thread_interrupt (tls, NULL, sigctx, ji);
2426 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2429 mono_debugger_agent_thread_interrupt (NULL, NULL);
2431 #endif /* HOST_WIN32 */
2434 * reset_native_thread_suspend_state:
2436 * Reset the suspended flag on native threads
2439 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2441 DebuggerTlsData *tls = value;
2443 if (!tls->really_suspended && tls->suspended)
2444 tls->suspended = FALSE;
2450 * Notify a thread that it needs to suspend.
2453 notify_thread (gpointer key, gpointer value, gpointer user_data)
2455 MonoInternalThread *thread = key;
2456 DebuggerTlsData *tls = value;
2457 gsize tid = thread->tid;
2460 if (GetCurrentThreadId () == tid || tls->terminated)
2463 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2466 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2467 * guarantee the signal handler will be called that many times. Instead of tracking
2468 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2469 * has been requested that hasn't been handled yet, otherwise we can have threads
2470 * refuse to die when VM_EXIT is called
2472 #if defined(__APPLE__)
2473 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2477 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2478 * of things like breaking waits etc. which we don't want.
2480 InterlockedIncrement (&tls->interrupt_count);
2483 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2485 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2487 if (mono_thread_info_new_interrupt_enabled ()) {
2488 MonoThreadInfo *info;
2491 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2494 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2496 thread_interrupt (tls, info, NULL, ji);
2498 mono_thread_info_resume (mono_thread_info_get_tid (info));
2500 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2503 * Attached thread which died without detaching.
2505 tls->terminated = TRUE;
2511 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2513 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2516 if (mono_loader_lock_is_owned_by_self ()) {
2518 * Shortcut for the check in suspend_current (). This speeds up processing
2519 * when executing long running code inside the loader lock, i.e. assembly load
2525 if (debugger_thread_id == GetCurrentThreadId ())
2528 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2529 if (suspend_count - tls->resume_count > 0)
2530 tls->suspending = TRUE;
2532 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2534 if (suspend_count - tls->resume_count == 0) {
2536 * We are executing a single threaded invoke but the single step for
2537 * suspending is still active.
2538 * FIXME: This slows down single threaded invokes.
2540 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2544 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2546 /* Can't suspend in these methods */
2547 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2550 save_thread_context (ctx);
2558 * Increase the suspend count of the VM. While the suspend count is greater
2559 * than 0, runtime threads are suspended at certain points during execution.
2564 mono_loader_lock ();
2566 mono_mutex_lock (&suspend_mutex);
2570 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2572 if (suspend_count == 1) {
2573 // FIXME: Is it safe to call this inside the lock ?
2574 start_single_stepping ();
2575 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2578 mono_mutex_unlock (&suspend_mutex);
2580 mono_loader_unlock ();
2586 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2594 g_assert (debugger_thread_id == GetCurrentThreadId ());
2596 mono_loader_lock ();
2598 mono_mutex_lock (&suspend_mutex);
2600 g_assert (suspend_count > 0);
2603 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2605 if (suspend_count == 0) {
2606 // FIXME: Is it safe to call this inside the lock ?
2607 stop_single_stepping ();
2608 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2611 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2612 err = mono_cond_broadcast (&suspend_cond);
2613 g_assert (err == 0);
2615 mono_mutex_unlock (&suspend_mutex);
2616 //g_assert (err == 0);
2618 mono_loader_unlock ();
2624 * Resume just one thread.
2627 resume_thread (MonoInternalThread *thread)
2630 DebuggerTlsData *tls;
2632 g_assert (debugger_thread_id == GetCurrentThreadId ());
2634 mono_loader_lock ();
2636 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2639 mono_mutex_lock (&suspend_mutex);
2641 g_assert (suspend_count > 0);
2643 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2645 tls->resume_count += suspend_count;
2648 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2649 * but only the one whose resume_count field is > 0 will be resumed.
2651 err = mono_cond_broadcast (&suspend_cond);
2652 g_assert (err == 0);
2654 mono_mutex_unlock (&suspend_mutex);
2655 //g_assert (err == 0);
2657 mono_loader_unlock ();
2661 invalidate_frames (DebuggerTlsData *tls)
2666 tls = mono_native_tls_get_value (debugger_tls_id);
2669 for (i = 0; i < tls->frame_count; ++i) {
2670 if (tls->frames [i]->jit)
2671 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2672 g_free (tls->frames [i]);
2674 g_free (tls->frames);
2675 tls->frame_count = 0;
2682 * Suspend the current thread until the runtime is resumed. If the thread has a
2683 * pending invoke, then the invoke is executed before this function returns.
2686 suspend_current (void)
2689 DebuggerTlsData *tls;
2691 g_assert (debugger_thread_id != GetCurrentThreadId ());
2693 if (mono_loader_lock_is_owned_by_self ()) {
2695 * If we own the loader mutex, can't suspend until we release it, since the
2696 * whole runtime can deadlock otherwise.
2701 tls = mono_native_tls_get_value (debugger_tls_id);
2704 mono_mutex_lock (&suspend_mutex);
2706 tls->suspending = FALSE;
2707 tls->really_suspended = TRUE;
2709 if (!tls->suspended) {
2710 tls->suspended = TRUE;
2711 MONO_SEM_POST (&suspend_sem);
2714 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2716 while (suspend_count - tls->resume_count > 0) {
2718 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2720 mono_mutex_unlock (&suspend_mutex);
2722 mono_mutex_lock (&suspend_mutex);
2728 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2729 g_assert (err == 0);
2733 tls->suspended = FALSE;
2734 tls->really_suspended = FALSE;
2736 threads_suspend_count --;
2738 mono_mutex_unlock (&suspend_mutex);
2740 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2742 if (tls->pending_invoke) {
2743 /* Save the original context */
2744 tls->pending_invoke->has_ctx = TRUE;
2745 tls->pending_invoke->ctx = tls->context.ctx;
2750 /* The frame info becomes invalid after a resume */
2751 tls->context.valid = FALSE;
2752 tls->async_state.valid = FALSE;
2753 invalidate_frames (NULL);
2757 count_thread (gpointer key, gpointer value, gpointer user_data)
2759 DebuggerTlsData *tls = value;
2761 if (!tls->suspended && !tls->terminated)
2762 *(int*)user_data = *(int*)user_data + 1;
2766 count_threads_to_wait_for (void)
2770 mono_loader_lock ();
2771 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2772 mono_loader_unlock ();
2780 * Wait until the runtime is completely suspended.
2783 wait_for_suspend (void)
2785 int nthreads, nwait, err;
2786 gboolean waited = FALSE;
2788 // FIXME: Threads starting/stopping ?
2789 mono_loader_lock ();
2790 nthreads = mono_g_hash_table_size (thread_to_tls);
2791 mono_loader_unlock ();
2794 nwait = count_threads_to_wait_for ();
2796 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2797 err = MONO_SEM_WAIT (&suspend_sem);
2798 g_assert (err == 0);
2806 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2812 * Return whenever the runtime is suspended.
2817 return count_threads_to_wait_for () == 0;
2820 static MonoSeqPointInfo*
2821 get_seq_points (MonoDomain *domain, MonoMethod *method)
2823 MonoSeqPointInfo *seq_points;
2825 mono_domain_lock (domain);
2826 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2827 if (!seq_points && method->is_inflated) {
2828 /* generic sharing + aot */
2829 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2831 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2833 mono_domain_unlock (domain);
2838 static MonoSeqPointInfo*
2839 find_seq_points (MonoDomain *domain, MonoMethod *method)
2841 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2844 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2845 g_assert (seq_points);
2851 * find_next_seq_point_for_native_offset:
2853 * Find the first sequence point after NATIVE_OFFSET.
2856 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2858 MonoSeqPointInfo *seq_points;
2861 seq_points = find_seq_points (domain, method);
2865 for (i = 0; i < seq_points->len; ++i) {
2866 if (seq_points->seq_points [i].native_offset >= native_offset)
2867 return &seq_points->seq_points [i];
2874 * find_prev_seq_point_for_native_offset:
2876 * Find the first sequence point before NATIVE_OFFSET.
2879 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2881 MonoSeqPointInfo *seq_points;
2884 seq_points = find_seq_points (domain, method);
2888 for (i = seq_points->len - 1; i >= 0; --i) {
2889 if (seq_points->seq_points [i].native_offset <= native_offset)
2890 return &seq_points->seq_points [i];
2899 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2900 * should be the location of a sequence point.
2902 static G_GNUC_UNUSED SeqPoint*
2903 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2905 MonoSeqPointInfo *seq_points;
2910 seq_points = get_seq_points (domain, method);
2915 for (i = 0; i < seq_points->len; ++i) {
2916 if (seq_points->seq_points [i].il_offset == il_offset)
2917 return &seq_points->seq_points [i];
2924 DebuggerTlsData *tls;
2926 } ComputeFramesUserData;
2929 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2931 ComputeFramesUserData *ud = user_data;
2933 MonoMethod *method, *actual_method;
2936 if (info->type != FRAME_TYPE_MANAGED) {
2937 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2938 /* Mark the last frame as an invoke frame */
2940 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2946 method = info->ji->method;
2948 method = info->method;
2949 actual_method = info->actual_method;
2951 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2954 if (info->il_offset == -1) {
2955 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
2956 if (ud->frames == NULL) {
2957 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
2959 info->il_offset = sp->il_offset;
2961 if (info->il_offset == -1)
2962 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2965 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));
2967 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2969 * mono_arch_find_jit_info () returns the context stored in the LMF for
2970 * native frames, but it should unwind once. This is why we have duplicate
2971 * frames on the stack sometimes.
2972 * !managed also seems to be set for dynamic methods.
2977 frame = g_new0 (StackFrame, 1);
2978 frame->method = method;
2979 frame->actual_method = actual_method;
2980 frame->il_offset = info->il_offset;
2981 frame->native_offset = info->native_offset;
2982 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
2985 frame->has_ctx = TRUE;
2987 frame->domain = info->domain;
2989 ud->frames = g_slist_append (ud->frames, frame);
2995 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2997 ComputeFramesUserData *ud = user_data;
3000 * 'tls->filter_ctx' is the location of the throw site.
3002 * mono_walk_stack() will never actually hit the throw site, but unwind
3003 * directly from the filter to the call site; we abort stack unwinding here
3004 * once this happens and resume from the throw site.
3007 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3010 return process_frame (info, ctx, user_data);
3014 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3016 ComputeFramesUserData user_data;
3018 int i, findex, new_frame_count;
3019 StackFrame **new_frames, *f;
3020 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3022 // FIXME: Locking on tls
3023 if (tls->frames && tls->frames_up_to_date)
3026 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3028 user_data.tls = tls;
3029 user_data.frames = NULL;
3030 if (tls->terminated) {
3031 tls->frame_count = 0;
3033 } if (!tls->really_suspended && tls->async_state.valid) {
3034 /* Have to use the state saved by the signal handler */
3035 process_frame (&tls->async_last_frame, NULL, &user_data);
3036 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3037 } else if (tls->filter_state.valid) {
3039 * We are inside an exception filter.
3041 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3043 if (tls->context.valid)
3044 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3046 * After that, we resume unwinding from the location where the exception has been thrown.
3048 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3049 } else if (tls->context.valid) {
3050 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3053 tls->frame_count = 0;
3057 new_frame_count = g_slist_length (user_data.frames);
3058 new_frames = g_new0 (StackFrame*, new_frame_count);
3060 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3064 * Reuse the id for already existing stack frames, so invokes don't invalidate
3065 * the still valid stack frames.
3067 for (i = 0; i < tls->frame_count; ++i) {
3068 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3069 f->id = tls->frames [i]->id;
3074 if (i >= tls->frame_count)
3075 f->id = InterlockedIncrement (&frame_id);
3077 new_frames [findex ++] = f;
3080 g_slist_free (user_data.frames);
3082 invalidate_frames (tls);
3084 tls->frames = new_frames;
3085 tls->frame_count = new_frame_count;
3086 tls->frames_up_to_date = TRUE;
3090 * GHFunc to emit an appdomain creation event
3091 * @param key Don't care
3092 * @param value A loaded appdomain
3093 * @param user_data Don't care
3096 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3098 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3099 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3103 * GHFunc to emit a thread start event
3104 * @param key A thread id
3105 * @param value A thread object
3106 * @param user_data Don't care
3109 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3111 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3112 process_profiler_event (EVENT_KIND_THREAD_START, value);
3116 * GFunc to emit an assembly load event
3117 * @param value A loaded assembly
3118 * @param user_data Don't care
3121 emit_assembly_load (gpointer value, gpointer user_data)
3123 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3127 * GFunc to emit a type load event
3128 * @param value A loaded type
3129 * @param user_data Don't care
3132 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3134 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3138 strdup_tolower (char *s)
3143 for (p = s2; *p; ++p)
3153 * create_event_list:
3155 * Return a list of event request ids matching EVENT, starting from REQS, which
3156 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3158 * We return request ids, instead of requests, to simplify threading, since
3159 * requests could be deleted anytime when the loader lock is not held.
3160 * LOCKING: Assumes the loader lock is held.
3163 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3166 GSList *events = NULL;
3168 *suspend_policy = SUSPEND_POLICY_NONE;
3171 reqs = event_requests;
3176 for (i = 0; i < reqs->len; ++i) {
3177 EventRequest *req = g_ptr_array_index (reqs, i);
3178 if (req->event_kind == event) {
3179 gboolean filtered = FALSE;
3182 for (j = 0; j < req->nmodifiers; ++j) {
3183 Modifier *mod = &req->modifiers [j];
3185 if (mod->kind == MOD_KIND_COUNT) {
3187 if (mod->data.count > 0) {
3188 if (mod->data.count > 0) {
3190 if (mod->data.count == 0)
3194 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3195 if (mod->data.thread != mono_thread_internal_current ())
3197 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3198 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3200 if (ei->caught && !mod->caught)
3202 if (!ei->caught && !mod->uncaught)
3204 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3206 gboolean found = FALSE;
3207 MonoAssembly **assemblies = mod->data.assemblies;
3210 for (k = 0; assemblies [k]; ++k)
3211 if (assemblies [k] == ji->method->klass->image->assembly)
3216 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3217 gpointer iter = NULL;
3219 MonoDebugSourceInfo *sinfo;
3220 char *source_file, *s;
3221 gboolean found = FALSE;
3223 GPtrArray *source_file_list;
3225 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3226 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3229 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL);
3230 for (i = 0; i < source_file_list->len; ++i) {
3231 sinfo = g_ptr_array_index (source_file_list, i);
3233 * Do a case-insesitive match by converting the file name to
3236 s = strdup_tolower (sinfo->source_file);
3237 if (g_hash_table_lookup (mod->data.source_files, s))
3241 g_ptr_array_free (source_file_list, TRUE);
3246 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3249 s = mono_type_full_name (&ei->klass->byval_arg);
3250 if (!g_hash_table_lookup (mod->data.type_names, s))
3257 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3258 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3263 /* Send a VM START/DEATH event by default */
3264 if (event == EVENT_KIND_VM_START)
3265 events = g_slist_append (events, GINT_TO_POINTER (0));
3266 if (event == EVENT_KIND_VM_DEATH)
3267 events = g_slist_append (events, GINT_TO_POINTER (0));
3272 static G_GNUC_UNUSED const char*
3273 event_to_string (EventKind event)
3276 case EVENT_KIND_VM_START: return "VM_START";
3277 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3278 case EVENT_KIND_THREAD_START: return "THREAD_START";
3279 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3280 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3281 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3282 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3283 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3284 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3285 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3286 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3287 case EVENT_KIND_STEP: return "STEP";
3288 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3289 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3290 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3291 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3292 case EVENT_KIND_USER_LOG: return "USER_LOG";
3294 g_assert_not_reached ();
3301 * Send an event to the client, suspending the vm if needed.
3302 * LOCKING: Since this can suspend the calling thread, no locks should be held
3304 * The EVENTS list is freed by this function.
3307 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3311 MonoDomain *domain = mono_domain_get ();
3312 MonoThread *thread = NULL;
3313 gboolean send_success = FALSE;
3318 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3322 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3323 // FIXME: We miss those events
3324 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3328 if (vm_death_event_sent) {
3329 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3333 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3334 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3339 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3343 if (event == EVENT_KIND_KEEPALIVE)
3344 suspend_policy = SUSPEND_POLICY_NONE;
3349 if (agent_config.defer) {
3350 /* Make sure the thread id is always set when doing deferred debugging */
3351 if (debugger_thread_id == GetCurrentThreadId ()) {
3352 /* Don't suspend on events from the debugger thread */
3353 suspend_policy = SUSPEND_POLICY_NONE;
3354 thread = mono_thread_get_main ();
3356 else thread = mono_thread_current ();
3358 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3359 // FIXME: Send these with a NULL thread, don't suspend the current thread
3364 nevents = g_slist_length (events);
3365 buffer_init (&buf, 128);
3366 buffer_add_byte (&buf, suspend_policy);
3367 buffer_add_int (&buf, nevents);
3369 for (l = events; l; l = l->next) {
3370 buffer_add_byte (&buf, event); // event kind
3371 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3376 thread = mono_thread_current ();
3378 if (event == EVENT_KIND_VM_START && arg != NULL)
3381 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3384 case EVENT_KIND_THREAD_START:
3385 case EVENT_KIND_THREAD_DEATH:
3387 case EVENT_KIND_APPDOMAIN_CREATE:
3388 case EVENT_KIND_APPDOMAIN_UNLOAD:
3389 buffer_add_domainid (&buf, arg);
3391 case EVENT_KIND_METHOD_ENTRY:
3392 case EVENT_KIND_METHOD_EXIT:
3393 buffer_add_methodid (&buf, domain, arg);
3395 case EVENT_KIND_ASSEMBLY_LOAD:
3396 case EVENT_KIND_ASSEMBLY_UNLOAD:
3397 buffer_add_assemblyid (&buf, domain, arg);
3399 case EVENT_KIND_TYPE_LOAD:
3400 buffer_add_typeid (&buf, domain, arg);
3402 case EVENT_KIND_BREAKPOINT:
3403 case EVENT_KIND_STEP:
3404 buffer_add_methodid (&buf, domain, arg);
3405 buffer_add_long (&buf, il_offset);
3407 case EVENT_KIND_VM_START:
3408 buffer_add_domainid (&buf, mono_get_root_domain ());
3410 case EVENT_KIND_VM_DEATH:
3412 case EVENT_KIND_EXCEPTION: {
3413 EventInfo *ei = arg;
3414 buffer_add_objid (&buf, ei->exc);
3417 case EVENT_KIND_USER_BREAK:
3419 case EVENT_KIND_USER_LOG: {
3420 EventInfo *ei = arg;
3421 buffer_add_int (&buf, ei->level);
3422 buffer_add_string (&buf, ei->category ? ei->category : "");
3423 buffer_add_string (&buf, ei->message ? ei->message : "");
3426 case EVENT_KIND_KEEPALIVE:
3427 suspend_policy = SUSPEND_POLICY_NONE;
3430 g_assert_not_reached ();
3434 if (event == EVENT_KIND_VM_START) {
3435 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3436 if (!agent_config.defer)
3437 start_debugger_thread ();
3440 if (event == EVENT_KIND_VM_DEATH) {
3441 vm_death_event_sent = TRUE;
3442 suspend_policy = SUSPEND_POLICY_NONE;
3445 if (mono_runtime_is_shutting_down ())
3446 suspend_policy = SUSPEND_POLICY_NONE;
3448 if (suspend_policy != SUSPEND_POLICY_NONE) {
3450 * Save the thread context and start suspending before sending the packet,
3451 * since we could be receiving the resume request before send_packet ()
3454 save_thread_context (ctx);
3458 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3462 g_slist_free (events);
3465 if (!send_success) {
3466 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3470 if (event == EVENT_KIND_VM_START) {
3471 vm_start_event_sent = TRUE;
3474 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3476 switch (suspend_policy) {
3477 case SUSPEND_POLICY_NONE:
3479 case SUSPEND_POLICY_ALL:
3482 case SUSPEND_POLICY_EVENT_THREAD:
3486 g_assert_not_reached ();
3491 process_profiler_event (EventKind event, gpointer arg)
3495 EventInfo ei, *ei_arg = NULL;
3497 if (event == EVENT_KIND_TYPE_LOAD) {
3502 mono_loader_lock ();
3503 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3504 mono_loader_unlock ();
3506 process_event (event, arg, 0, NULL, events, suspend_policy);
3510 runtime_initialized (MonoProfiler *prof)
3512 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3513 if (agent_config.defer)
3514 start_debugger_thread ();
3518 runtime_shutdown (MonoProfiler *prof)
3520 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3522 mono_debugger_agent_cleanup ();
3526 thread_startup (MonoProfiler *prof, uintptr_t tid)
3528 MonoInternalThread *thread = mono_thread_internal_current ();
3529 MonoInternalThread *old_thread;
3530 DebuggerTlsData *tls;
3532 if (tid == debugger_thread_id)
3535 g_assert (thread->tid == tid);
3537 mono_loader_lock ();
3538 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3539 mono_loader_unlock ();
3541 if (thread == old_thread) {
3543 * For some reason, thread_startup () might be called for the same thread
3544 * multiple times (attach ?).
3546 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3550 * thread_end () might not be called for some threads, and the tid could
3553 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3554 mono_loader_lock ();
3555 mono_g_hash_table_remove (thread_to_tls, old_thread);
3556 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3557 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3558 mono_loader_unlock ();
3562 tls = mono_native_tls_get_value (debugger_tls_id);
3564 // FIXME: Free this somewhere
3565 tls = g_new0 (DebuggerTlsData, 1);
3566 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3567 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3568 tls->thread = thread;
3569 mono_native_tls_set_value (debugger_tls_id, tls);
3571 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3573 mono_loader_lock ();
3574 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3575 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3576 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3577 mono_loader_unlock ();
3579 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3582 * suspend_vm () could have missed this thread, so wait for a resume.
3588 thread_end (MonoProfiler *prof, uintptr_t tid)
3590 MonoInternalThread *thread;
3591 DebuggerTlsData *tls = NULL;
3593 mono_loader_lock ();
3594 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3596 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3597 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3598 tls->terminated = TRUE;
3599 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3600 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3601 MONO_GC_UNREGISTER_ROOT (tls->thread);
3604 mono_loader_unlock ();
3606 /* We might be called for threads started before we registered the start callback */
3608 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3609 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3614 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3616 mono_loader_lock ();
3617 g_hash_table_insert (domains, domain, domain);
3618 mono_loader_unlock ();
3620 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3624 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3626 clear_breakpoints_for_domain (domain);
3628 mono_loader_lock ();
3629 /* Invalidate each thread's frame stack */
3630 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3631 mono_loader_unlock ();
3633 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3637 * invalidate_each_thread:
3639 * A GHFunc to invalidate frames.
3640 * value must be a DebuggerTlsData*
3643 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3645 invalidate_frames (value);
3649 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3651 /* Sent later in jit_end () */
3652 mono_loader_lock ();
3653 g_ptr_array_add (pending_assembly_loads, assembly);
3654 mono_loader_unlock ();
3658 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3660 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3662 clear_event_requests_for_assembly (assembly);
3663 clear_types_for_assembly (assembly);
3667 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3669 #if defined(HOST_WIN32) && !defined(__GNUC__)
3670 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3672 gpointer stackptr = __builtin_frame_address (1);
3674 MonoInternalThread *thread = mono_thread_internal_current ();
3675 DebuggerTlsData *tls;
3677 mono_loader_lock ();
3679 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3680 /* Could be the debugger thread with assembly/type load hooks */
3682 tls->invoke_addr = stackptr;
3684 mono_loader_unlock ();
3688 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3691 #if defined(HOST_WIN32) && !defined(__GNUC__)
3692 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3694 gpointer stackptr = __builtin_frame_address (1);
3697 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3701 * We need to stop single stepping when exiting a runtime invoke, since if it is
3702 * a step out, it may return to native code, and thus never end.
3704 mono_loader_lock ();
3705 ss_invoke_addr = NULL;
3707 for (i = 0; i < event_requests->len; ++i) {
3708 EventRequest *req = g_ptr_array_index (event_requests, i);
3710 if (req->event_kind == EVENT_KIND_STEP) {
3711 ss_destroy (req->info);
3712 g_ptr_array_remove_index_fast (event_requests, i);
3717 mono_loader_unlock ();
3721 send_type_load (MonoClass *klass)
3723 gboolean type_load = FALSE;
3724 MonoDomain *domain = mono_domain_get ();
3725 AgentDomainInfo *info = NULL;
3727 mono_loader_lock ();
3728 mono_domain_lock (domain);
3730 info = get_agent_domain_info (domain);
3732 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3734 g_hash_table_insert (info->loaded_classes, klass, klass);
3737 mono_domain_unlock (domain);
3738 mono_loader_unlock ();
3740 emit_type_load (klass, klass, NULL);
3744 * Emit load events for all types currently loaded in the domain.
3745 * Takes the loader and domain locks.
3746 * user_data is unused.
3749 send_types_for_domain (MonoDomain *domain, void *user_data)
3751 AgentDomainInfo *info = NULL;
3753 mono_loader_lock ();
3754 mono_domain_lock (domain);
3755 info = get_agent_domain_info (domain);
3757 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3758 mono_domain_unlock (domain);
3759 mono_loader_unlock ();
3763 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3766 * We emit type load events when the first method of the type is JITted,
3767 * since the class load profiler callbacks might be called with the
3768 * loader lock held. They could also occur in the debugger thread.
3769 * Same for assembly load events.
3772 MonoAssembly *assembly = NULL;
3774 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3775 mono_loader_lock ();
3776 if (pending_assembly_loads->len > 0) {
3777 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3778 g_ptr_array_remove_index (pending_assembly_loads, 0);
3780 mono_loader_unlock ();
3783 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3789 send_type_load (method->klass);
3792 add_pending_breakpoints (method, jinfo);
3796 * BREAKPOINTS/SINGLE STEPPING
3800 * Contains information about an inserted breakpoint.
3803 long il_offset, native_offset;
3808 } BreakpointInstance;
3811 * Contains generic information about a breakpoint.
3815 * The method where the breakpoint is placed. Can be NULL in which case it
3816 * is inserted into every method. This is used to implement method entry/
3817 * exit events. Can be a generic method definition, in which case the
3818 * breakpoint is inserted into every instance.
3824 * A list of BreakpointInstance structures describing where the breakpoint
3825 * was inserted. There could be more than one because of
3826 * generics/appdomains/method entry/exit.
3828 GPtrArray *children;
3831 /* List of breakpoints */
3832 static GPtrArray *breakpoints;
3833 /* Maps breakpoint locations to the number of breakpoints at that location */
3834 static GHashTable *bp_locs;
3837 breakpoints_init (void)
3839 breakpoints = g_ptr_array_new ();
3840 bp_locs = g_hash_table_new (NULL, NULL);
3844 * insert_breakpoint:
3846 * Insert the breakpoint described by BP into the method described by
3850 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3853 BreakpointInstance *inst;
3854 SeqPoint *sp = NULL;
3857 mono_error_init (error);
3859 for (i = 0; i < seq_points->len; ++i) {
3860 sp = &seq_points->seq_points [i];
3862 if (sp->il_offset == bp->il_offset)
3866 if (i == seq_points->len) {
3868 * The set of IL offsets with seq points doesn't completely match the
3869 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3871 for (i = 0; i < seq_points->len; ++i) {
3872 sp = &seq_points->seq_points [i];
3874 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3879 if (i == seq_points->len) {
3880 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (ji->method, TRUE), bp->il_offset, seq_points->len);
3882 for (i = 0; i < seq_points->len; ++i)
3883 printf ("%d\n", seq_points->seq_points [i].il_offset);
3886 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3895 inst = g_new0 (BreakpointInstance, 1);
3897 inst->native_offset = sp->native_offset;
3898 inst->ip = (guint8*)ji->code_start + sp->native_offset;
3900 inst->domain = domain;
3902 mono_loader_lock ();
3904 g_ptr_array_add (bp->children, inst);
3906 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3907 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3908 mono_loader_unlock ();
3911 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3912 mono_arch_set_breakpoint (ji, inst->ip);
3918 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
3922 remove_breakpoint (BreakpointInstance *inst)
3924 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3926 MonoJitInfo *ji = inst->ji;
3927 guint8 *ip = inst->ip;
3929 mono_loader_lock ();
3930 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3931 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3932 mono_loader_unlock ();
3934 g_assert (count > 0);
3937 mono_arch_clear_breakpoint (ji, ip);
3944 static inline gboolean
3945 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3951 if (method == bp->method)
3953 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
3956 if (bp->method->is_inflated && method->is_inflated) {
3957 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
3958 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
3960 /* Open generic methods should match closed generic methods of the same class */
3961 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
3962 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
3963 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
3965 /* FIXME: Handle !mvar */
3966 if (t1->type != MONO_TYPE_MVAR)
3977 * add_pending_breakpoints:
3979 * Insert pending breakpoints into the newly JITted method METHOD.
3982 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3985 MonoSeqPointInfo *seq_points;
3991 domain = mono_domain_get ();
3993 mono_loader_lock ();
3995 for (i = 0; i < breakpoints->len; ++i) {
3996 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3997 gboolean found = FALSE;
3999 if (!bp_matches_method (bp, method))
4002 for (j = 0; j < bp->children->len; ++j) {
4003 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4010 mono_domain_lock (domain);
4011 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4012 if (!seq_points && ji->method->is_inflated)
4013 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4014 mono_domain_unlock (domain);
4016 /* Could be AOT code */
4018 g_assert (seq_points);
4020 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4024 mono_loader_unlock ();
4028 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4034 mono_error_init (error);
4036 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4038 /* Might be AOTed code */
4039 code = mono_aot_get_method (domain, method);
4041 ji = mono_jit_info_table_find (domain, code);
4046 insert_breakpoint (seq_points, domain, ji, bp, error);
4050 clear_breakpoint (MonoBreakpoint *bp);
4055 * Set a breakpoint at IL_OFFSET in METHOD.
4056 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4057 * METHOD can also be a generic method definition, in which case a breakpoint
4058 * is placed in all instances of the method.
4059 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4062 static MonoBreakpoint*
4063 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4066 GHashTableIter iter, iter2;
4069 MonoSeqPointInfo *seq_points;
4072 mono_error_init (error);
4075 // - suspend/resume the vm to prevent code patching problems
4076 // - multiple breakpoints on the same location
4077 // - dynamic methods
4080 bp = g_new0 (MonoBreakpoint, 1);
4081 bp->method = method;
4082 bp->il_offset = il_offset;
4084 bp->children = g_ptr_array_new ();
4086 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));
4088 mono_loader_lock ();
4090 g_hash_table_iter_init (&iter, domains);
4091 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4092 mono_domain_lock (domain);
4094 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4095 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4096 if (bp_matches_method (bp, m))
4097 set_bp_in_method (domain, m, seq_points, bp, error);
4100 mono_domain_unlock (domain);
4103 mono_loader_unlock ();
4105 mono_loader_lock ();
4106 g_ptr_array_add (breakpoints, bp);
4107 mono_loader_unlock ();
4109 if (error && !mono_error_ok (error)) {
4110 clear_breakpoint (bp);
4118 clear_breakpoint (MonoBreakpoint *bp)
4122 // FIXME: locking, races
4123 for (i = 0; i < bp->children->len; ++i) {
4124 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4126 remove_breakpoint (inst);
4131 mono_loader_lock ();
4132 g_ptr_array_remove (breakpoints, bp);
4133 mono_loader_unlock ();
4135 g_ptr_array_free (bp->children, TRUE);
4140 breakpoints_cleanup (void)
4144 mono_loader_lock ();
4146 while (i < event_requests->len) {
4147 EventRequest *req = g_ptr_array_index (event_requests, i);
4149 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4150 clear_breakpoint (req->info);
4151 g_ptr_array_remove_index_fast (event_requests, i);
4158 for (i = 0; i < breakpoints->len; ++i)
4159 g_free (g_ptr_array_index (breakpoints, i));
4161 g_ptr_array_free (breakpoints, TRUE);
4162 g_hash_table_destroy (bp_locs);
4167 mono_loader_unlock ();
4171 * clear_breakpoints_for_domain:
4173 * Clear breakpoint instances which reference DOMAIN.
4176 clear_breakpoints_for_domain (MonoDomain *domain)
4180 /* This could be called after shutdown */
4184 mono_loader_lock ();
4185 for (i = 0; i < breakpoints->len; ++i) {
4186 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4189 while (j < bp->children->len) {
4190 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4192 if (inst->domain == domain) {
4193 remove_breakpoint (inst);
4197 g_ptr_array_remove_index_fast (bp->children, j);
4203 mono_loader_unlock ();
4207 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4209 return bp->method && bp->method->klass->image->assembly == assembly;
4213 process_breakpoint_inner (DebuggerTlsData *tls)
4217 int i, j, suspend_policy;
4218 guint32 native_offset;
4220 BreakpointInstance *inst;
4221 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4222 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4223 EventKind kind = EVENT_KIND_BREAKPOINT;
4224 MonoContext *ctx = &tls->restore_ctx;
4225 MonoSeqPointInfo *info;
4228 // FIXME: Speed this up
4230 ip = MONO_CONTEXT_GET_IP (ctx);
4231 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4233 g_assert (ji->method);
4235 /* Compute the native offset of the breakpoint from the ip */
4236 native_offset = ip - (guint8*)ji->code_start;
4239 * Skip the instruction causing the breakpoint signal.
4241 mono_arch_skip_breakpoint (ctx, ji);
4243 if (ji->method->wrapper_type || tls->disable_breakpoints)
4246 bp_reqs = g_ptr_array_new ();
4247 ss_reqs = g_ptr_array_new ();
4248 ss_reqs_orig = g_ptr_array_new ();
4250 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
4252 mono_loader_lock ();
4255 * The ip points to the instruction causing the breakpoint event, which is after
4256 * the offset recorded in the seq point map, so find the prev seq point before ip.
4258 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4261 for (i = 0; i < breakpoints->len; ++i) {
4262 bp = g_ptr_array_index (breakpoints, i);
4267 for (j = 0; j < bp->children->len; ++j) {
4268 inst = g_ptr_array_index (bp->children, j);
4269 if (inst->ji == ji && inst->sp == sp) {
4270 if (bp->req->event_kind == EVENT_KIND_STEP) {
4271 g_ptr_array_add (ss_reqs_orig, bp->req);
4273 g_ptr_array_add (bp_reqs, bp->req);
4278 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4279 /* Maybe a method entry/exit event */
4280 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4281 kind = EVENT_KIND_METHOD_ENTRY;
4282 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4283 kind = EVENT_KIND_METHOD_EXIT;
4286 /* Process single step requests */
4287 for (i = 0; i < ss_reqs_orig->len; ++i) {
4288 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4289 SingleStepReq *ss_req = req->info;
4290 gboolean hit = TRUE;
4292 if (ss_req->size == STEP_SIZE_LINE) {
4293 /* Have to check whenever a different source line was reached */
4294 MonoDebugMethodInfo *minfo;
4295 MonoDebugSourceLocation *loc = NULL;
4297 minfo = mono_debug_lookup_method (ji->method);
4300 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4302 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
4303 /* Have to continue single stepping */
4307 ss_req->last_method = ji->method;
4308 ss_req->last_line = loc->row;
4309 mono_debug_free_source_location (loc);
4314 g_ptr_array_add (ss_reqs, req);
4316 /* Start single stepping again from the current sequence point */
4317 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4320 if (ss_reqs->len > 0)
4321 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4322 if (bp_reqs->len > 0)
4323 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4324 if (kind != EVENT_KIND_BREAKPOINT)
4325 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4327 mono_loader_unlock ();
4329 g_ptr_array_free (bp_reqs, TRUE);
4330 g_ptr_array_free (ss_reqs, TRUE);
4333 * FIXME: The first event will suspend, so the second will only be sent after the
4337 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4339 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4340 if (enter_leave_events)
4341 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4344 /* Process a breakpoint/single step event after resuming from a signal handler */
4346 process_signal_event (void (*func) (DebuggerTlsData*))
4348 DebuggerTlsData *tls;
4349 MonoContext orig_restore_ctx, ctx;
4350 static void (*restore_context) (void *);
4352 if (!restore_context)
4353 restore_context = mono_get_restore_context ();
4355 tls = mono_native_tls_get_value (debugger_tls_id);
4356 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4357 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4358 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4362 /* This is called when resuming from a signal handler, so it shouldn't return */
4363 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4364 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4365 restore_context (&ctx);
4366 g_assert_not_reached ();
4370 process_breakpoint (void)
4372 process_signal_event (process_breakpoint_inner);
4376 resume_from_signal_handler (void *sigctx, void *func)
4378 DebuggerTlsData *tls;
4381 /* Save the original context in TLS */
4382 // FIXME: This might not work on an altstack ?
4383 tls = mono_native_tls_get_value (debugger_tls_id);
4386 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4387 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4388 // clob:c could be added to op_seq_point.
4390 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4391 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4392 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4393 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4395 MONO_CONTEXT_SET_IP (&ctx, func);
4397 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4399 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4400 mono_ppc_set_func_into_sigctx (sigctx, func);
4405 mono_debugger_agent_breakpoint_hit (void *sigctx)
4408 * We are called from a signal handler, and running code there causes all kinds of
4409 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4410 * So set up the signal context to return to the real breakpoint handler function.
4413 resume_from_signal_handler (sigctx, process_breakpoint);
4417 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4419 if (frame->managed) {
4420 *(MonoContext*)data = *ctx;
4429 * Called by System.Diagnostics.Debugger:Break ().
4432 mono_debugger_agent_user_break (void)
4434 if (agent_config.enabled) {
4439 /* Obtain a context */
4440 MONO_CONTEXT_SET_IP (&ctx, NULL);
4441 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4442 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4444 mono_loader_lock ();
4445 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4446 mono_loader_unlock ();
4448 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4455 ss_depth_to_string (StepDepth depth)
4458 case STEP_DEPTH_OVER:
4460 case STEP_DEPTH_OUT:
4462 case STEP_DEPTH_INTO:
4465 g_assert_not_reached ();
4471 process_single_step_inner (DebuggerTlsData *tls)
4476 int il_offset, suspend_policy;
4479 MonoContext *ctx = &tls->restore_ctx;
4481 MonoSeqPointInfo *info;
4483 ip = MONO_CONTEXT_GET_IP (ctx);
4485 /* Skip the instruction causing the single step */
4486 mono_arch_skip_single_step (ctx);
4488 if (suspend_count > 0) {
4489 process_suspend (tls, ctx);
4494 // FIXME: A suspend race
4497 if (mono_thread_internal_current () != ss_req->thread)
4500 if (log_level > 0) {
4501 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4503 DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_depth_to_string (ss_req->depth), mono_method_full_name (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4506 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4508 g_assert (ji->method);
4510 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4515 * Stopping in memset makes half-initialized vtypes visible.
4516 * Stopping in memcpy makes half-copied vtypes visible.
4518 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4522 * The ip points to the instruction causing the single step event, which is before
4523 * the offset recorded in the seq point map, so find the next seq point after ip.
4525 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4528 il_offset = sp->il_offset;
4530 // FIXME: No tests fail if this is disabled
4532 if (ss_req->size == STEP_SIZE_LINE) {
4536 /* Step until a different source line is reached */
4537 MonoDebugMethodInfo *minfo;
4539 minfo = mono_debug_lookup_method (ji->method);
4542 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4544 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4545 mono_debug_free_source_location (loc);
4550 * Step until we reach a location with line number info,
4551 * otherwise the client can't show a location.
4552 * This can happen for example with statics initialized inline
4553 * outside of a cctor.
4558 ss_req->last_method = ji->method;
4559 ss_req->last_line = loc->row;
4560 mono_debug_free_source_location (loc);
4566 /* Start single stepping again from the current sequence point */
4567 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4569 // FIXME: Has to lock earlier
4571 reqs = g_ptr_array_new ();
4573 mono_loader_lock ();
4575 g_ptr_array_add (reqs, ss_req->req);
4577 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4579 g_ptr_array_free (reqs, TRUE);
4581 mono_loader_unlock ();
4583 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4587 process_single_step (void)
4589 process_signal_event (process_single_step_inner);
4593 * mono_debugger_agent_single_step_event:
4595 * Called from a signal handler to handle a single step event.
4598 mono_debugger_agent_single_step_event (void *sigctx)
4600 /* Resume to process_single_step through the signal context */
4602 // FIXME: Since step out/over is implemented using step in, the step in case should
4603 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4606 if (GetCurrentThreadId () == debugger_thread_id) {
4608 * This could happen despite our best effors when the runtime calls
4609 * assembly/type resolve hooks.
4610 * FIXME: Breakpoints too.
4614 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4615 mono_arch_skip_single_step (&ctx);
4616 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4620 resume_from_signal_handler (sigctx, process_single_step);
4624 debugger_agent_single_step_from_context (MonoContext *ctx)
4626 DebuggerTlsData *tls;
4627 MonoContext orig_restore_ctx;
4629 tls = mono_native_tls_get_value (debugger_tls_id);
4632 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4633 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4634 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4636 process_single_step_inner (tls);
4638 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4639 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4643 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4645 DebuggerTlsData *tls;
4646 MonoContext orig_restore_ctx;
4648 tls = mono_native_tls_get_value (debugger_tls_id);
4650 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4651 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4653 process_breakpoint_inner (tls);
4655 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4656 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4660 * start_single_stepping:
4662 * Turn on single stepping. Can be called multiple times, for example,
4663 * by a single step event request + a suspend.
4666 start_single_stepping (void)
4668 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4669 int val = InterlockedIncrement (&ss_count);
4672 mono_arch_start_single_stepping ();
4674 if (ss_req != NULL && ss_invoke_addr == NULL) {
4675 DebuggerTlsData *tls;
4677 mono_loader_lock ();
4679 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4680 ss_invoke_addr = tls->invoke_addr;
4682 mono_loader_unlock ();
4685 g_assert_not_reached ();
4690 stop_single_stepping (void)
4692 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4693 int val = InterlockedDecrement (&ss_count);
4696 mono_arch_stop_single_stepping ();
4698 g_assert_not_reached ();
4705 * Stop the single stepping operation given by SS_REQ.
4708 ss_stop (SingleStepReq *ss_req)
4713 for (l = ss_req->bps; l; l = l->next) {
4714 clear_breakpoint (l->data);
4716 g_slist_free (ss_req->bps);
4720 if (ss_req->global) {
4721 stop_single_stepping ();
4722 ss_req->global = FALSE;
4729 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4730 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4731 * belong to the same thread as CTX.
4734 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4739 gboolean enable_global = FALSE;
4741 /* Stop the previous operation */
4745 * Implement single stepping using breakpoints if possible.
4747 if (step_to_catch) {
4748 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4749 ss_req->bps = g_slist_append (ss_req->bps, bp);
4753 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT) && ctx) {
4754 /* Need parent frames */
4755 if (!tls->context.valid)
4756 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4757 compute_frame_info (tls->thread, tls);
4761 * Find the first sequence point in the current or in a previous frame which
4762 * is not the last in its method.
4764 if (ss_req->depth == STEP_DEPTH_OUT) {
4765 /* Ignore seq points in current method */
4766 while (frame_index < tls->frame_count) {
4767 StackFrame *frame = tls->frames [frame_index];
4769 method = frame->method;
4770 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4772 if (sp && sp->next_len != 0)
4776 while (sp && sp->next_len == 0) {
4778 if (frame_index < tls->frame_count) {
4779 StackFrame *frame = tls->frames [frame_index];
4781 method = frame->method;
4782 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4788 if (sp && sp->next_len > 0) {
4789 for (i = 0; i < sp->next_len; ++i) {
4790 next_sp = &info->seq_points [sp->next [i]];
4792 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4793 ss_req->bps = g_slist_append (ss_req->bps, bp);
4797 if (ss_req->depth == STEP_DEPTH_INTO) {
4798 /* Enable global stepping so we stop at method entry too */
4799 enable_global = TRUE;
4803 * The ctx/frame info computed above will become invalid when we continue.
4805 tls->context.valid = FALSE;
4806 tls->async_state.valid = FALSE;
4807 invalidate_frames (tls);
4810 if (enable_global) {
4811 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4812 ss_req->global = TRUE;
4813 start_single_stepping ();
4814 } else if (!ss_req->bps) {
4815 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4816 ss_req->global = TRUE;
4817 start_single_stepping ();
4819 ss_req->global = FALSE;
4824 * Start single stepping of thread THREAD
4827 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4829 DebuggerTlsData *tls;
4830 MonoSeqPointInfo *info = NULL;
4831 SeqPoint *sp = NULL;
4832 MonoMethod *method = NULL;
4833 MonoDebugMethodInfo *minfo;
4834 gboolean step_to_catch = FALSE;
4836 if (suspend_count == 0)
4837 return ERR_NOT_SUSPENDED;
4839 wait_for_suspend ();
4841 // FIXME: Multiple requests
4843 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4844 return ERR_NOT_IMPLEMENTED;
4847 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4849 ss_req = g_new0 (SingleStepReq, 1);
4851 ss_req->thread = thread;
4852 ss_req->size = size;
4853 ss_req->depth = depth;
4856 mono_loader_lock ();
4857 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4858 mono_loader_unlock ();
4860 g_assert (tls->context.valid);
4861 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4863 if (tls->has_catch_ctx) {
4865 StackFrameInfo frame;
4866 MonoContext new_ctx;
4867 MonoLMF *lmf = NULL;
4870 * We are stopped at a throw site. Stepping should go to the catch site.
4873 /* Find the the jit info for the catch context */
4874 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4876 g_assert (frame.type == FRAME_TYPE_MANAGED);
4879 * Find the seq point corresponding to the landing site ip, which is the first seq
4882 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4885 method = frame.method;
4887 step_to_catch = TRUE;
4888 /* This make sure the seq point is not skipped by process_single_step () */
4889 ss_req->last_sp = NULL;
4892 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4895 /* Compute the initial line info */
4896 compute_frame_info (thread, tls);
4898 if (tls->frame_count) {
4899 frame = tls->frames [0];
4901 ss_req->last_method = frame->method;
4902 ss_req->last_line = -1;
4904 minfo = mono_debug_lookup_method (frame->method);
4905 if (minfo && frame->il_offset != -1) {
4906 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4909 ss_req->last_line = loc->row;
4916 if (!step_to_catch) {
4919 compute_frame_info (thread, tls);
4921 if (tls->frame_count) {
4922 frame = tls->frames [0];
4924 if (!method && frame->il_offset != -1) {
4925 /* FIXME: Sort the table and use a binary search */
4926 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4928 method = frame->method;
4933 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
4939 ss_destroy (SingleStepReq *req)
4942 g_assert (ss_req == req);
4951 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
4954 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
4960 if (!agent_config.enabled)
4963 mono_loader_lock ();
4964 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
4965 mono_loader_unlock ();
4968 ei.category = category ? mono_string_to_utf8 (category) : NULL;
4969 ei.message = message ? mono_string_to_utf8 (message) : NULL;
4971 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
4973 g_free (ei.category);
4974 g_free (ei.message);
4978 mono_debugger_agent_debug_log_is_enabled (void)
4980 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
4981 return agent_config.enabled;
4985 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
4986 MonoContext *catch_ctx)
4992 DebuggerTlsData *tls = NULL;
4994 if (thread_to_tls != NULL) {
4995 MonoInternalThread *thread = mono_thread_internal_current ();
4997 mono_loader_lock ();
4998 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4999 mono_loader_unlock ();
5001 if (tls && tls->abort_requested)
5003 if (tls && tls->disable_breakpoints)
5007 memset (&ei, 0, sizeof (EventInfo));
5009 /* Just-In-Time debugging */
5011 if (agent_config.onuncaught && !inited) {
5012 finish_agent_init (FALSE);
5015 * Send an unsolicited EXCEPTION event with a dummy request id.
5017 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5018 ei.exc = (MonoObject*)exc;
5019 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5022 } else if (agent_config.onthrow && !inited) {
5024 gboolean found = FALSE;
5026 for (l = agent_config.onthrow; l; l = l->next) {
5027 char *ex_type = l->data;
5028 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5030 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5037 finish_agent_init (FALSE);
5040 * Send an unsolicited EXCEPTION event with a dummy request id.
5042 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5043 ei.exc = (MonoObject*)exc;
5044 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5052 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5054 ei.exc = (MonoObject*)exc;
5055 ei.caught = catch_ctx != NULL;
5057 mono_loader_lock ();
5058 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5059 mono_loader_unlock ();
5061 if (tls && catch_ctx) {
5062 tls->catch_ctx = *catch_ctx;
5063 tls->has_catch_ctx = TRUE;
5066 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5069 tls->has_catch_ctx = FALSE;
5073 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5075 DebuggerTlsData *tls;
5080 tls = mono_native_tls_get_value (debugger_tls_id);
5085 * We're about to invoke an exception filter during the first pass of exception handling.
5087 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5088 * 'orig_ctx' is the context where the exception has been thrown.
5091 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5093 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5094 * the call site (line 37) and then continue to Main(), but it would never
5095 * include the throw site (line 32).
5097 * Since exception filters are invoked during the first pass of exception handling,
5098 * the stack frames of the throw site are still intact, so we should include them
5101 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5103 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5104 * but report the location of the 'throw' to the user.
5108 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5112 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5114 DebuggerTlsData *tls;
5119 tls = mono_native_tls_get_value (debugger_tls_id);
5123 tls->filter_state.valid = FALSE;
5127 * buffer_add_value_full:
5129 * Add the encoding of the value at ADDR described by T to the buffer.
5130 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5134 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5140 g_assert (*(void**)addr);
5141 addr = *(void**)addr;
5146 case MONO_TYPE_BOOLEAN:
5149 case MONO_TYPE_CHAR:
5169 case MONO_TYPE_VOID:
5170 buffer_add_byte (buf, t->type);
5172 case MONO_TYPE_BOOLEAN:
5175 buffer_add_byte (buf, t->type);
5176 buffer_add_int (buf, *(gint8*)addr);
5178 case MONO_TYPE_CHAR:
5181 buffer_add_byte (buf, t->type);
5182 buffer_add_int (buf, *(gint16*)addr);
5187 buffer_add_byte (buf, t->type);
5188 buffer_add_int (buf, *(gint32*)addr);
5193 buffer_add_byte (buf, t->type);
5194 buffer_add_long (buf, *(gint64*)addr);
5198 /* Treat it as a vtype */
5200 case MONO_TYPE_PTR: {
5201 gssize val = *(gssize*)addr;
5203 buffer_add_byte (buf, t->type);
5204 buffer_add_long (buf, val);
5208 case MONO_TYPE_STRING:
5209 case MONO_TYPE_SZARRAY:
5210 case MONO_TYPE_OBJECT:
5211 case MONO_TYPE_CLASS:
5212 case MONO_TYPE_ARRAY:
5213 obj = *(MonoObject**)addr;
5216 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5218 if (obj->vtable->klass->valuetype) {
5219 t = &obj->vtable->klass->byval_arg;
5220 addr = mono_object_unbox (obj);
5222 } else if (obj->vtable->klass->rank) {
5223 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5224 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5225 buffer_add_byte (buf, MONO_TYPE_CLASS);
5227 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5229 buffer_add_objid (buf, obj);
5233 case MONO_TYPE_VALUETYPE: {
5237 MonoClass *klass = mono_class_from_mono_type (t);
5239 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5240 buffer_add_byte (buf, klass->enumtype);
5241 buffer_add_typeid (buf, domain, klass);
5245 while ((f = mono_class_get_fields (klass, &iter))) {
5246 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5248 if (mono_field_is_deleted (f))
5252 buffer_add_int (buf, nfields);
5255 while ((f = mono_class_get_fields (klass, &iter))) {
5256 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5258 if (mono_field_is_deleted (f))
5260 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5264 case MONO_TYPE_GENERICINST:
5265 if (mono_type_generic_inst_is_valuetype (t)) {
5277 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5279 buffer_add_value_full (buf, t, addr, domain, FALSE);
5283 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5286 int type = decode_byte (buf, &buf, limit);
5288 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5289 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5290 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5291 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5292 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5293 char *name = mono_type_full_name (t);
5294 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5296 return ERR_INVALID_ARGUMENT;
5300 case MONO_TYPE_BOOLEAN:
5301 *(guint8*)addr = decode_int (buf, &buf, limit);
5303 case MONO_TYPE_CHAR:
5304 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5307 *(gint8*)addr = decode_int (buf, &buf, limit);
5310 *(guint8*)addr = decode_int (buf, &buf, limit);
5313 *(gint16*)addr = decode_int (buf, &buf, limit);
5316 *(guint16*)addr = decode_int (buf, &buf, limit);
5319 *(gint32*)addr = decode_int (buf, &buf, limit);
5322 *(guint32*)addr = decode_int (buf, &buf, limit);
5325 *(gint64*)addr = decode_long (buf, &buf, limit);
5328 *(guint64*)addr = decode_long (buf, &buf, limit);
5331 *(guint32*)addr = decode_int (buf, &buf, limit);
5334 *(guint64*)addr = decode_long (buf, &buf, limit);
5337 /* We send these as I8, so we get them back as such */
5338 g_assert (type == MONO_TYPE_I8);
5339 *(gssize*)addr = decode_long (buf, &buf, limit);
5341 case MONO_TYPE_GENERICINST:
5342 if (MONO_TYPE_ISSTRUCT (t)) {
5343 /* The client sends these as a valuetype */
5351 /* We send these as vtypes, so we get them back as such */
5352 g_assert (type == MONO_TYPE_VALUETYPE);
5355 case MONO_TYPE_VALUETYPE: {
5356 gboolean is_enum = decode_byte (buf, &buf, limit);
5360 gpointer iter = NULL;
5363 /* Enums are sent as a normal vtype */
5365 return ERR_NOT_IMPLEMENTED;
5366 klass = decode_typeid (buf, &buf, limit, &d, &err);
5370 if (klass != mono_class_from_mono_type (t))
5371 return ERR_INVALID_ARGUMENT;
5373 nfields = decode_int (buf, &buf, limit);
5374 while ((f = mono_class_get_fields (klass, &iter))) {
5375 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5377 if (mono_field_is_deleted (f))
5379 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5384 g_assert (nfields == 0);
5389 if (MONO_TYPE_IS_REFERENCE (t)) {
5390 if (type == MONO_TYPE_OBJECT) {
5391 int objid = decode_objid (buf, &buf, limit);
5395 err = get_object (objid, (MonoObject**)&obj);
5399 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
5400 return ERR_INVALID_ARGUMENT;
5401 if (obj && obj->vtable->domain != domain)
5402 return ERR_INVALID_ARGUMENT;
5404 mono_gc_wbarrier_generic_store (addr, obj);
5405 } else if (type == VALUE_TYPE_ID_NULL) {
5406 *(MonoObject**)addr = NULL;
5408 return ERR_INVALID_ARGUMENT;
5422 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5429 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5430 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5433 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5434 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5436 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5438 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5439 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5440 addr += (gint32)var->offset;
5442 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5444 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5446 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5450 g_assert_not_reached ();
5455 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5461 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5462 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5464 if (MONO_TYPE_IS_REFERENCE (t))
5465 size = sizeof (gpointer);
5467 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5470 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5471 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5473 gboolean is_signed = FALSE;
5475 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5480 v = is_signed ? *(gint8*)val : *(guint8*)val;
5483 v = is_signed ? *(gint16*)val : *(guint16*)val;
5486 v = is_signed ? *(gint32*)val : *(guint32*)val;
5489 v = is_signed ? *(gint64*)val : *(guint64*)val;
5492 g_assert_not_reached ();
5495 /* Set value on the stack or in the return ctx */
5496 if (reg_locations [reg]) {
5497 /* Saved on the stack */
5498 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5499 *(reg_locations [reg]) = v;
5502 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5503 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5506 // FIXME: Move these to mono-context.h/c.
5507 mono_arch_context_set_int_reg (ctx, reg, v);
5509 // FIXME: Can't set registers, so we disable linears
5514 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5515 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5516 addr += (gint32)var->offset;
5518 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5520 // FIXME: Write barriers
5521 memcpy (addr, val, size);
5523 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5527 g_assert_not_reached ();
5532 clear_event_request (int req_id, int etype)
5536 mono_loader_lock ();
5537 for (i = 0; i < event_requests->len; ++i) {
5538 EventRequest *req = g_ptr_array_index (event_requests, i);
5540 if (req->id == req_id && req->event_kind == etype) {
5541 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5542 clear_breakpoint (req->info);
5543 if (req->event_kind == EVENT_KIND_STEP)
5544 ss_destroy (req->info);
5545 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5546 clear_breakpoint (req->info);
5547 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5548 clear_breakpoint (req->info);
5549 g_ptr_array_remove_index_fast (event_requests, i);
5554 mono_loader_unlock ();
5558 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5560 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5561 return breakpoint_matches_assembly (req->info, assembly);
5565 for (i = 0; i < req->nmodifiers; ++i) {
5566 Modifier *m = &req->modifiers [i];
5568 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5570 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5571 for (j = 0; m->data.assemblies [j]; ++j)
5572 if (m->data.assemblies [j] == assembly)
5582 * clear_event_requests_for_assembly:
5584 * Clear all events requests which reference ASSEMBLY.
5587 clear_event_requests_for_assembly (MonoAssembly *assembly)
5592 mono_loader_lock ();
5596 for (i = 0; i < event_requests->len; ++i) {
5597 EventRequest *req = g_ptr_array_index (event_requests, i);
5599 if (event_req_matches_assembly (req, assembly)) {
5600 clear_event_request (req->id, req->event_kind);
5606 mono_loader_unlock ();
5610 * type_comes_from_assembly:
5612 * GHRFunc that returns TRUE if klass comes from assembly
5615 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5617 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5621 * clear_types_for_assembly:
5623 * Clears types from loaded_classes for a given assembly
5626 clear_types_for_assembly (MonoAssembly *assembly)
5628 MonoDomain *domain = mono_domain_get ();
5629 AgentDomainInfo *info = NULL;
5631 mono_loader_lock ();
5632 info = get_agent_domain_info (domain);
5633 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5634 mono_loader_unlock ();
5638 add_thread (gpointer key, gpointer value, gpointer user_data)
5640 MonoInternalThread *thread = value;
5641 Buffer *buf = user_data;
5643 buffer_add_objid (buf, (MonoObject*)thread);
5647 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5649 guint8 *p = invoke->p;
5650 guint8 *end = invoke->endp;
5653 MonoMethodSignature *sig;
5656 MonoObject *this, *res, *exc;
5659 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5662 MonoStopwatch watch;
5664 if (invoke->method) {
5666 * Invoke this method directly, currently only Environment.Exit () is supported.
5669 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>"));
5670 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5671 g_assert_not_reached ();
5674 m = decode_methodid (p, &p, end, &domain, &err);
5677 sig = mono_method_signature (m);
5679 if (m->klass->valuetype)
5680 this_buf = g_alloca (mono_class_instance_size (m->klass));
5682 this_buf = g_alloca (sizeof (MonoObject*));
5683 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5684 /* Should be null */
5685 int type = decode_byte (p, &p, end);
5686 if (type != VALUE_TYPE_ID_NULL)
5687 return ERR_INVALID_ARGUMENT;
5688 memset (this_buf, 0, mono_class_instance_size (m->klass));
5690 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5695 if (!m->klass->valuetype)
5696 this = *(MonoObject**)this_buf;
5700 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>"));
5702 if (this && this->vtable->domain != domain)
5705 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5706 if (!strcmp (m->name, ".ctor")) {
5707 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5708 return ERR_INVALID_ARGUMENT;
5710 this = mono_object_new (domain, m->klass);
5712 return ERR_INVALID_ARGUMENT;
5716 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5717 return ERR_INVALID_ARGUMENT;
5719 nargs = decode_int (p, &p, end);
5720 if (nargs != sig->param_count)
5721 return ERR_INVALID_ARGUMENT;
5722 /* Use alloca to get gc tracking */
5723 arg_buf = g_alloca (nargs * sizeof (gpointer));
5724 memset (arg_buf, 0, nargs * sizeof (gpointer));
5725 args = g_alloca (nargs * sizeof (gpointer));
5726 for (i = 0; i < nargs; ++i) {
5727 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5728 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5732 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5735 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5736 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5739 args [i] = arg_buf [i];
5746 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5747 tls->disable_breakpoints = TRUE;
5749 tls->disable_breakpoints = FALSE;
5752 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5754 /* FIXME: Move this to arch specific code */
5755 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5756 if (invoke->has_ctx) {
5759 lmf_addr = mono_get_lmf_addr ();
5762 memset (&ext, 0, sizeof (ext));
5764 ext.lmf.previous_lmf = *(lmf_addr);
5765 /* Mark that this is a MonoLMFExt */
5766 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5767 ext.lmf.rsp = (gssize)&ext;
5768 #elif defined(TARGET_X86)
5769 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5770 /* Mark that this is a MonoLMFExt */
5771 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5772 ext.lmf.ebp = (gssize)&ext;
5773 #elif defined(TARGET_ARM)
5774 ext.lmf.previous_lmf = *(lmf_addr);
5775 /* Mark that this is a MonoLMFExt */
5776 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5777 ext.lmf.sp = (gssize)&ext;
5778 #elif defined(TARGET_POWERPC)
5779 ext.lmf.previous_lmf = *(lmf_addr);
5780 /* Mark that this is a MonoLMFExt */
5781 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5782 ext.lmf.ebp = (gssize)&ext;
5783 #elif defined(TARGET_S390X)
5784 ext.lmf.previous_lmf = *(lmf_addr);
5785 /* Mark that this is a MonoLMFExt */
5786 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5787 ext.lmf.ebp = (gssize)&ext;
5788 #elif defined(TARGET_MIPS)
5789 ext.lmf.previous_lmf = *(lmf_addr);
5790 /* Mark that this is a MonoLMFExt */
5791 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5792 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5794 g_assert_not_reached ();
5797 ext.debugger_invoke = TRUE;
5798 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5800 mono_set_lmf ((MonoLMF*)&ext);
5804 mono_stopwatch_start (&watch);
5805 if (m->klass->valuetype)
5806 res = mono_runtime_invoke (m, this_buf, args, &exc);
5808 res = mono_runtime_invoke (m, this, args, &exc);
5809 mono_stopwatch_stop (&watch);
5810 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)));
5812 buffer_add_byte (buf, 0);
5813 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5815 buffer_add_byte (buf, 1);
5816 if (sig->ret->type == MONO_TYPE_VOID) {
5817 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5818 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5821 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5822 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5823 buffer_add_value (buf, sig->ret, &res, domain);
5824 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5825 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5827 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &res, domain);
5829 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5832 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5839 tls->disable_breakpoints = FALSE;
5841 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5842 if (invoke->has_ctx)
5843 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5846 // FIXME: byref arguments
5854 * Invoke the method given by tls->pending_invoke in the current thread.
5857 invoke_method (void)
5859 DebuggerTlsData *tls;
5864 static void (*restore_context) (void *);
5865 MonoContext restore_ctx;
5867 if (!restore_context)
5868 restore_context = mono_get_restore_context ();
5870 tls = mono_native_tls_get_value (debugger_tls_id);
5874 * Store the `InvokeData *' in `tls->invoke' until we're done with
5875 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5878 mono_loader_lock ();
5880 invoke = tls->pending_invoke;
5882 tls->pending_invoke = NULL;
5884 invoke->last_invoke = tls->invoke;
5885 tls->invoke = invoke;
5887 mono_loader_unlock ();
5889 tls->frames_up_to_date = FALSE;
5893 buffer_init (&buf, 128);
5895 err = do_invoke_method (tls, &buf, invoke);
5897 /* Start suspending before sending the reply */
5898 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5901 send_reply_packet (id, err, &buf);
5905 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5907 if (invoke->has_ctx)
5908 save_thread_context (&restore_ctx);
5910 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5911 g_assert (tls->resume_count);
5912 tls->resume_count -= invoke->suspend_count;
5915 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5918 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5920 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5921 * after the mono_runtime_invoke() already returned, but it doesn't matter
5922 * because we reset the abort here.
5925 mono_loader_lock ();
5927 if (tls->abort_requested)
5928 mono_thread_internal_reset_abort (tls->thread);
5930 tls->invoke = tls->invoke->last_invoke;
5931 tls->abort_requested = FALSE;
5933 mono_loader_unlock ();
5942 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5944 MonoThread *thread = value;
5945 DebuggerTlsData *tls;
5948 mono_loader_lock ();
5949 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5951 res = tls->really_suspended;
5952 mono_loader_unlock ();
5958 get_source_files_for_type (MonoClass *klass)
5960 gpointer iter = NULL;
5962 MonoDebugSourceInfo *sinfo;
5966 files = g_ptr_array_new ();
5968 while ((method = mono_class_get_methods (klass, &iter))) {
5969 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
5970 GPtrArray *source_file_list;
5973 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL);
5974 for (j = 0; j < source_file_list->len; ++j) {
5975 sinfo = g_ptr_array_index (source_file_list, j);
5976 for (i = 0; i < files->len; ++i)
5977 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
5979 if (i == files->len)
5980 g_ptr_array_add (files, g_strdup (sinfo->source_file));
5982 g_ptr_array_free (source_file_list, TRUE);
5990 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
5993 case CMD_VM_VERSION: {
5994 char *build_info, *version;
5996 build_info = mono_get_runtime_build_info ();
5997 version = g_strdup_printf ("mono %s", build_info);
5999 buffer_add_string (buf, version); /* vm version */
6000 buffer_add_int (buf, MAJOR_VERSION);
6001 buffer_add_int (buf, MINOR_VERSION);
6002 g_free (build_info);
6006 case CMD_VM_SET_PROTOCOL_VERSION: {
6007 major_version = decode_int (p, &p, end);
6008 minor_version = decode_int (p, &p, end);
6009 protocol_version_set = TRUE;
6010 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6013 case CMD_VM_ALL_THREADS: {
6015 mono_loader_lock ();
6016 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6017 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6018 mono_loader_unlock ();
6021 case CMD_VM_SUSPEND:
6023 wait_for_suspend ();
6026 if (suspend_count == 0)
6027 return ERR_NOT_SUSPENDED;
6030 case CMD_VM_DISPOSE:
6031 /* Clear all event requests */
6032 mono_loader_lock ();
6033 while (event_requests->len > 0) {
6034 EventRequest *req = g_ptr_array_index (event_requests, 0);
6036 clear_event_request (req->id, req->event_kind);
6038 mono_loader_unlock ();
6040 while (suspend_count > 0)
6042 disconnected = TRUE;
6043 vm_start_event_sent = FALSE;
6046 MonoInternalThread *thread;
6047 DebuggerTlsData *tls;
6048 MonoClass *env_class;
6049 MonoMethod *exit_method = NULL;
6053 exit_code = decode_int (p, &p, end);
6055 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6057 /* Have to send a reply before exiting */
6058 send_reply_packet (id, 0, buf);
6060 /* Clear all event requests */
6061 mono_loader_lock ();
6062 while (event_requests->len > 0) {
6063 EventRequest *req = g_ptr_array_index (event_requests, 0);
6065 clear_event_request (req->id, req->event_kind);
6067 mono_loader_unlock ();
6070 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6071 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6072 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6073 * better than doing the shutdown ourselves, since it avoids various races.
6077 wait_for_suspend ();
6079 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6081 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6083 mono_loader_lock ();
6084 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6085 mono_loader_unlock ();
6087 if (thread && exit_method) {
6088 mono_loader_lock ();
6089 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6090 mono_loader_unlock ();
6092 args = g_new0 (gpointer, 1);
6093 args [0] = g_malloc (sizeof (int));
6094 *(int*)(args [0]) = exit_code;
6096 tls->pending_invoke = g_new0 (InvokeData, 1);
6097 tls->pending_invoke->method = exit_method;
6098 tls->pending_invoke->args = args;
6100 while (suspend_count > 0)
6104 * No thread found, do it ourselves.
6105 * FIXME: This can race with normal shutdown etc.
6107 while (suspend_count > 0)
6110 mono_runtime_set_shutting_down ();
6112 mono_threads_set_shutting_down ();
6114 /* Suspend all managed threads since the runtime is going away */
6115 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6116 mono_thread_suspend_all_other_threads ();
6117 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6118 mono_runtime_quit ();
6119 transport_close2 ();
6120 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6126 case CMD_VM_INVOKE_METHOD: {
6127 int objid = decode_objid (p, &p, end);
6129 DebuggerTlsData *tls;
6132 err = get_object (objid, (MonoObject**)&thread);
6136 flags = decode_int (p, &p, end);
6138 // Wait for suspending if it already started
6140 wait_for_suspend ();
6141 if (!is_suspended ())
6142 return ERR_NOT_SUSPENDED;
6144 mono_loader_lock ();
6145 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6146 mono_loader_unlock ();
6149 if (!tls->really_suspended)
6150 /* The thread is still running native code, can't do invokes */
6151 return ERR_NOT_SUSPENDED;
6154 * Store the invoke data into tls, the thread will execute it after it is
6157 if (tls->pending_invoke)
6159 tls->pending_invoke = g_new0 (InvokeData, 1);
6160 tls->pending_invoke->id = id;
6161 tls->pending_invoke->flags = flags;
6162 tls->pending_invoke->p = g_malloc (end - p);
6163 memcpy (tls->pending_invoke->p, p, end - p);
6164 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6165 tls->pending_invoke->suspend_count = suspend_count;
6167 if (flags & INVOKE_FLAG_SINGLE_THREADED)
6168 resume_thread (THREAD_TO_INTERNAL (thread));
6173 case CMD_VM_ABORT_INVOKE: {
6174 int objid = decode_objid (p, &p, end);
6176 DebuggerTlsData *tls;
6179 err = get_object (objid, (MonoObject**)&thread);
6183 invoke_id = decode_int (p, &p, end);
6185 mono_loader_lock ();
6186 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6189 if (tls->abort_requested) {
6190 mono_loader_unlock ();
6195 * Check whether we're still inside the mono_runtime_invoke() and that it's
6196 * actually the correct invocation.
6198 * Careful, we do not stop the thread that's doing the invocation, so we can't
6199 * inspect its stack. However, invoke_method() also acquires the loader lock
6200 * when it's done, so we're safe here.
6204 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6205 mono_loader_unlock ();
6206 return ERR_NO_INVOCATION;
6209 tls->abort_requested = TRUE;
6211 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6212 mono_loader_unlock ();
6216 case CMD_VM_SET_KEEPALIVE: {
6217 int timeout = decode_int (p, &p, end);
6218 agent_config.keepalive = timeout;
6220 #ifndef DISABLE_SOCKET_TRANSPORT
6227 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6228 GHashTableIter iter, kiter;
6233 char *fname, *basename;
6234 gboolean ignore_case;
6235 GSList *class_list, *l;
6236 GPtrArray *res_classes, *res_domains;
6238 fname = decode_string (p, &p, end);
6239 ignore_case = decode_byte (p, &p, end);
6241 basename = g_path_get_basename (fname);
6243 res_classes = g_ptr_array_new ();
6244 res_domains = g_ptr_array_new ();
6246 mono_loader_lock ();
6247 g_hash_table_iter_init (&iter, domains);
6248 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6249 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6251 /* Update 'source_file_to_class' cache */
6252 g_hash_table_iter_init (&kiter, info->loaded_classes);
6253 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6254 if (!g_hash_table_lookup (info->source_files, klass)) {
6255 files = get_source_files_for_type (klass);
6256 g_hash_table_insert (info->source_files, klass, files);
6258 for (i = 0; i < files->len; ++i) {
6259 char *s = g_ptr_array_index (files, i);
6260 char *s2 = g_path_get_basename (s);
6263 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6265 class_list = g_slist_prepend (class_list, klass);
6266 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6268 class_list = g_slist_prepend (class_list, klass);
6269 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6272 /* The _ignorecase hash contains the lowercase path */
6273 s3 = strdup_tolower (s2);
6274 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6276 class_list = g_slist_prepend (class_list, klass);
6277 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6279 class_list = g_slist_prepend (class_list, klass);
6280 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6292 s = strdup_tolower (basename);
6293 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6296 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6299 for (l = class_list; l; l = l->next) {
6302 g_ptr_array_add (res_classes, klass);
6303 g_ptr_array_add (res_domains, domain);
6306 mono_loader_unlock ();
6311 buffer_add_int (buf, res_classes->len);
6312 for (i = 0; i < res_classes->len; ++i)
6313 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6314 g_ptr_array_free (res_classes, TRUE);
6315 g_ptr_array_free (res_domains, TRUE);
6318 case CMD_VM_GET_TYPES: {
6319 GHashTableIter iter;
6323 gboolean ignore_case;
6324 GPtrArray *res_classes, *res_domains;
6325 MonoTypeNameParse info;
6327 name = decode_string (p, &p, end);
6328 ignore_case = decode_byte (p, &p, end);
6330 if (!mono_reflection_parse_type (name, &info)) {
6332 mono_reflection_free_type_info (&info);
6333 return ERR_INVALID_ARGUMENT;
6336 res_classes = g_ptr_array_new ();
6337 res_domains = g_ptr_array_new ();
6339 mono_loader_lock ();
6340 g_hash_table_iter_init (&iter, domains);
6341 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6343 gboolean type_resolve;
6347 mono_domain_assemblies_lock (domain);
6348 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6352 type_resolve = TRUE;
6353 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6355 g_ptr_array_add (res_classes, mono_type_get_class (t));
6356 g_ptr_array_add (res_domains, domain);
6360 mono_domain_assemblies_unlock (domain);
6362 mono_loader_unlock ();
6365 mono_reflection_free_type_info (&info);
6367 buffer_add_int (buf, res_classes->len);
6368 for (i = 0; i < res_classes->len; ++i)
6369 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6370 g_ptr_array_free (res_classes, TRUE);
6371 g_ptr_array_free (res_domains, TRUE);
6376 return ERR_NOT_IMPLEMENTED;
6383 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6389 case CMD_EVENT_REQUEST_SET: {
6391 int i, event_kind, suspend_policy, nmodifiers, mod;
6394 MonoThread *step_thread;
6395 int size = 0, depth = 0, step_thread_id = 0;
6399 event_kind = decode_byte (p, &p, end);
6400 suspend_policy = decode_byte (p, &p, end);
6401 nmodifiers = decode_byte (p, &p, end);
6403 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6404 req->id = InterlockedIncrement (&event_request_id);
6405 req->event_kind = event_kind;
6406 req->suspend_policy = suspend_policy;
6407 req->nmodifiers = nmodifiers;
6410 for (i = 0; i < nmodifiers; ++i) {
6411 mod = decode_byte (p, &p, end);
6413 req->modifiers [i].kind = mod;
6414 if (mod == MOD_KIND_COUNT) {
6415 req->modifiers [i].data.count = decode_int (p, &p, end);
6416 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6417 method = decode_methodid (p, &p, end, &domain, &err);
6420 location = decode_long (p, &p, end);
6421 } else if (mod == MOD_KIND_STEP) {
6422 step_thread_id = decode_id (p, &p, end);
6423 size = decode_int (p, &p, end);
6424 depth = decode_int (p, &p, end);
6425 } else if (mod == MOD_KIND_THREAD_ONLY) {
6426 int id = decode_id (p, &p, end);
6428 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6433 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6434 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6438 req->modifiers [i].caught = decode_byte (p, &p, end);
6439 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6440 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : ""));
6442 req->modifiers [i].data.exc_class = exc_class;
6444 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6446 return ERR_INVALID_ARGUMENT;
6449 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6450 int n = decode_int (p, &p, end);
6453 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6454 for (j = 0; j < n; ++j) {
6455 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6457 g_free (req->modifiers [i].data.assemblies);
6461 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6462 int n = decode_int (p, &p, end);
6465 modifier = &req->modifiers [i];
6466 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6467 for (j = 0; j < n; ++j) {
6468 char *s = decode_string (p, &p, end);
6472 s2 = strdup_tolower (s);
6473 g_hash_table_insert (modifier->data.source_files, s2, s2);
6477 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6478 int n = decode_int (p, &p, end);
6481 modifier = &req->modifiers [i];
6482 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6483 for (j = 0; j < n; ++j) {
6484 char *s = decode_string (p, &p, end);
6487 g_hash_table_insert (modifier->data.type_names, s, s);
6491 return ERR_NOT_IMPLEMENTED;
6495 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6498 req->info = set_breakpoint (method, location, req, &error);
6499 if (!mono_error_ok (&error)) {
6501 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6502 mono_error_cleanup (&error);
6503 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6505 } else if (req->event_kind == EVENT_KIND_STEP) {
6506 g_assert (step_thread_id);
6508 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6514 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6519 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6520 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6521 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6522 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6523 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6524 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6526 if (req->nmodifiers) {
6528 return ERR_NOT_IMPLEMENTED;
6532 mono_loader_lock ();
6533 g_ptr_array_add (event_requests, req);
6535 if (agent_config.defer) {
6536 /* Transmit cached data to the client on receipt of the event request */
6537 switch (req->event_kind) {
6538 case EVENT_KIND_APPDOMAIN_CREATE:
6539 /* Emit load events for currently loaded domains */
6540 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6542 case EVENT_KIND_ASSEMBLY_LOAD:
6543 /* Emit load events for currently loaded assemblies */
6544 mono_assembly_foreach (emit_assembly_load, NULL);
6546 case EVENT_KIND_THREAD_START:
6547 /* Emit start events for currently started threads */
6548 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6550 case EVENT_KIND_TYPE_LOAD:
6551 /* Emit type load events for currently loaded types */
6552 mono_domain_foreach (send_types_for_domain, NULL);
6558 mono_loader_unlock ();
6560 buffer_add_int (buf, req->id);
6563 case CMD_EVENT_REQUEST_CLEAR: {
6564 int etype = decode_byte (p, &p, end);
6565 int req_id = decode_int (p, &p, end);
6567 // FIXME: Make a faster mapping from req_id to request
6568 mono_loader_lock ();
6569 clear_event_request (req_id, etype);
6570 mono_loader_unlock ();
6573 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6576 mono_loader_lock ();
6578 while (i < event_requests->len) {
6579 EventRequest *req = g_ptr_array_index (event_requests, i);
6581 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6582 clear_breakpoint (req->info);
6584 g_ptr_array_remove_index_fast (event_requests, i);
6590 mono_loader_unlock ();
6594 return ERR_NOT_IMPLEMENTED;
6601 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6607 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6608 buffer_add_domainid (buf, mono_get_root_domain ());
6611 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6612 domain = decode_domainid (p, &p, end, NULL, &err);
6615 buffer_add_string (buf, domain->friendly_name);
6618 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6623 domain = decode_domainid (p, &p, end, NULL, &err);
6626 mono_loader_lock ();
6628 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6631 buffer_add_int (buf, count);
6632 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6634 buffer_add_assemblyid (buf, domain, ass);
6636 mono_loader_unlock ();
6639 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6640 domain = decode_domainid (p, &p, end, NULL, &err);
6644 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6647 case CMD_APPDOMAIN_GET_CORLIB: {
6648 domain = decode_domainid (p, &p, end, NULL, &err);
6652 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6655 case CMD_APPDOMAIN_CREATE_STRING: {
6659 domain = decode_domainid (p, &p, end, NULL, &err);
6662 s = decode_string (p, &p, end);
6664 o = mono_string_new (domain, s);
6665 buffer_add_objid (buf, (MonoObject*)o);
6668 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6670 MonoDomain *domain2;
6673 domain = decode_domainid (p, &p, end, NULL, &err);
6676 klass = decode_typeid (p, &p, end, &domain2, &err);
6681 g_assert (domain == domain2);
6683 o = mono_object_new (domain, klass);
6685 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6689 buffer_add_objid (buf, o);
6693 return ERR_NOT_IMPLEMENTED;
6700 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6706 ass = decode_assemblyid (p, &p, end, &domain, &err);
6711 case CMD_ASSEMBLY_GET_LOCATION: {
6712 buffer_add_string (buf, mono_image_get_filename (ass->image));
6715 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6719 if (ass->image->dynamic) {
6720 buffer_add_id (buf, 0);
6722 token = mono_image_get_entry_point (ass->image);
6724 buffer_add_id (buf, 0);
6726 m = mono_get_method (ass->image, token, NULL);
6727 buffer_add_methodid (buf, domain, m);
6732 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6733 buffer_add_moduleid (buf, domain, ass->image);
6736 case CMD_ASSEMBLY_GET_OBJECT: {
6737 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
6738 buffer_add_objid (buf, o);
6741 case CMD_ASSEMBLY_GET_TYPE: {
6742 char *s = decode_string (p, &p, end);
6743 gboolean ignorecase = decode_byte (p, &p, end);
6744 MonoTypeNameParse info;
6746 gboolean type_resolve, res;
6747 MonoDomain *d = mono_domain_get ();
6749 /* This is needed to be able to find referenced assemblies */
6750 res = mono_domain_set (domain, FALSE);
6753 if (!mono_reflection_parse_type (s, &info)) {
6756 if (info.assembly.name)
6758 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6760 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6761 mono_reflection_free_type_info (&info);
6764 mono_domain_set (d, TRUE);
6768 case CMD_ASSEMBLY_GET_NAME: {
6770 MonoAssembly *mass = ass;
6772 name = g_strdup_printf (
6773 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6775 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6776 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6777 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6778 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6780 buffer_add_string (buf, name);
6785 return ERR_NOT_IMPLEMENTED;
6792 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6798 case CMD_MODULE_GET_INFO: {
6799 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
6802 basename = g_path_get_basename (image->name);
6803 buffer_add_string (buf, basename); // name
6804 buffer_add_string (buf, image->module_name); // scopename
6805 buffer_add_string (buf, image->name); // fqname
6806 buffer_add_string (buf, mono_image_get_guid (image)); // guid
6807 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
6812 return ERR_NOT_IMPLEMENTED;
6819 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6821 if (val && val->vtable->klass == mono_defaults.monotype_class) {
6822 /* Special case these so the client doesn't have to handle Type objects */
6824 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6825 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
6826 } else if (MONO_TYPE_IS_REFERENCE (t))
6827 buffer_add_value (buf, t, &val, domain);
6829 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6833 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6839 buffer_add_int (buf, 0);
6843 for (i = 0; i < cinfo->num_attrs; ++i) {
6844 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6847 buffer_add_int (buf, nattrs);
6849 for (i = 0; i < cinfo->num_attrs; ++i) {
6850 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6851 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6852 MonoArray *typed_args, *named_args;
6854 CattrNamedArg *arginfo;
6856 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6858 buffer_add_methodid (buf, domain, attr->ctor);
6862 buffer_add_int (buf, mono_array_length (typed_args));
6863 for (j = 0; j < mono_array_length (typed_args); ++j) {
6864 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6866 t = mono_method_signature (attr->ctor)->params [j];
6868 buffer_add_cattr_arg (buf, t, domain, val);
6871 buffer_add_int (buf, 0);
6876 buffer_add_int (buf, mono_array_length (named_args));
6878 for (j = 0; j < mono_array_length (named_args); ++j) {
6879 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
6881 if (arginfo [j].prop) {
6882 buffer_add_byte (buf, 0x54);
6883 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6884 } else if (arginfo [j].field) {
6885 buffer_add_byte (buf, 0x53);
6886 buffer_add_fieldid (buf, domain, arginfo [j].field);
6888 g_assert_not_reached ();
6891 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6894 buffer_add_int (buf, 0);
6900 /* FIXME: Code duplication with icall.c */
6902 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
6907 mono_class_setup_interfaces (klass, error);
6908 if (!mono_error_ok (error))
6911 for (i = 0; i < klass->interface_count; i++) {
6912 ic = klass->interfaces [i];
6913 g_hash_table_insert (ifaces, ic, ic);
6915 collect_interfaces (ic, ifaces, error);
6916 if (!mono_error_ok (error))
6922 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6932 case CMD_TYPE_GET_INFO: {
6933 buffer_add_string (buf, klass->name_space);
6934 buffer_add_string (buf, klass->name);
6936 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
6937 buffer_add_string (buf, name);
6939 buffer_add_assemblyid (buf, domain, klass->image->assembly);
6940 buffer_add_moduleid (buf, domain, klass->image);
6941 buffer_add_typeid (buf, domain, klass->parent);
6942 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
6943 buffer_add_typeid (buf, domain, klass->element_class);
6945 buffer_add_id (buf, 0);
6946 buffer_add_int (buf, klass->type_token);
6947 buffer_add_byte (buf, klass->rank);
6948 buffer_add_int (buf, klass->flags);
6950 type = &klass->byval_arg;
6951 // FIXME: Can't decide whenever a class represents a byref type
6954 if (type->type == MONO_TYPE_PTR)
6956 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
6958 if (type->type == MONO_TYPE_VALUETYPE)
6960 if (klass->enumtype)
6962 if (klass->generic_container)
6964 if (klass->generic_container || klass->generic_class)
6966 buffer_add_byte (buf, b);
6969 while ((nested = mono_class_get_nested_types (klass, &iter)))
6971 buffer_add_int (buf, nnested);
6973 while ((nested = mono_class_get_nested_types (klass, &iter)))
6974 buffer_add_typeid (buf, domain, nested);
6975 if (CHECK_PROTOCOL_VERSION (2, 12)) {
6976 if (klass->generic_container)
6977 buffer_add_typeid (buf, domain, klass);
6978 else if (klass->generic_class)
6979 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
6981 buffer_add_id (buf, 0);
6985 case CMD_TYPE_GET_METHODS: {
6988 gpointer iter = NULL;
6991 mono_class_setup_methods (klass);
6993 nmethods = mono_class_num_methods (klass);
6995 buffer_add_int (buf, nmethods);
6997 while ((m = mono_class_get_methods (klass, &iter))) {
6998 buffer_add_methodid (buf, domain, m);
7001 g_assert (i == nmethods);
7004 case CMD_TYPE_GET_FIELDS: {
7007 gpointer iter = NULL;
7010 nfields = mono_class_num_fields (klass);
7012 buffer_add_int (buf, nfields);
7014 while ((f = mono_class_get_fields (klass, &iter))) {
7015 buffer_add_fieldid (buf, domain, f);
7016 buffer_add_string (buf, f->name);
7017 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7018 buffer_add_int (buf, f->type->attrs);
7021 g_assert (i == nfields);
7024 case CMD_TYPE_GET_PROPERTIES: {
7027 gpointer iter = NULL;
7030 nprops = mono_class_num_properties (klass);
7032 buffer_add_int (buf, nprops);
7034 while ((p = mono_class_get_properties (klass, &iter))) {
7035 buffer_add_propertyid (buf, domain, p);
7036 buffer_add_string (buf, p->name);
7037 buffer_add_methodid (buf, domain, p->get);
7038 buffer_add_methodid (buf, domain, p->set);
7039 buffer_add_int (buf, p->attrs);
7042 g_assert (i == nprops);
7045 case CMD_TYPE_GET_CATTRS: {
7046 MonoClass *attr_klass;
7047 MonoCustomAttrInfo *cinfo;
7049 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7050 /* attr_klass can be NULL */
7054 cinfo = mono_custom_attrs_from_class (klass);
7056 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7059 case CMD_TYPE_GET_FIELD_CATTRS: {
7060 MonoClass *attr_klass;
7061 MonoCustomAttrInfo *cinfo;
7062 MonoClassField *field;
7064 field = decode_fieldid (p, &p, end, NULL, &err);
7067 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7071 cinfo = mono_custom_attrs_from_field (klass, field);
7073 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7076 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7077 MonoClass *attr_klass;
7078 MonoCustomAttrInfo *cinfo;
7081 prop = decode_propertyid (p, &p, end, NULL, &err);
7084 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7088 cinfo = mono_custom_attrs_from_property (klass, prop);
7090 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7093 case CMD_TYPE_GET_VALUES:
7094 case CMD_TYPE_GET_VALUES_2: {
7101 MonoThread *thread_obj;
7102 MonoInternalThread *thread = NULL;
7103 guint32 special_static_type;
7105 if (command == CMD_TYPE_GET_VALUES_2) {
7106 int objid = decode_objid (p, &p, end);
7109 err = get_object (objid, (MonoObject**)&thread_obj);
7113 thread = THREAD_TO_INTERNAL (thread_obj);
7116 len = decode_int (p, &p, end);
7117 for (i = 0; i < len; ++i) {
7118 f = decode_fieldid (p, &p, end, NULL, &err);
7122 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7123 return ERR_INVALID_FIELDID;
7124 special_static_type = mono_class_field_get_special_static_type (f);
7125 if (special_static_type != SPECIAL_STATIC_NONE) {
7126 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7127 return ERR_INVALID_FIELDID;
7130 /* Check that the field belongs to the object */
7132 for (k = klass; k; k = k->parent) {
7133 if (k == f->parent) {
7139 return ERR_INVALID_FIELDID;
7141 vtable = mono_class_vtable (domain, f->parent);
7142 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7143 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7144 buffer_add_value (buf, f->type, val, domain);
7149 case CMD_TYPE_SET_VALUES: {
7157 len = decode_int (p, &p, end);
7158 for (i = 0; i < len; ++i) {
7159 f = decode_fieldid (p, &p, end, NULL, &err);
7163 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7164 return ERR_INVALID_FIELDID;
7165 if (mono_class_field_is_special_static (f))
7166 return ERR_INVALID_FIELDID;
7168 /* Check that the field belongs to the object */
7170 for (k = klass; k; k = k->parent) {
7171 if (k == f->parent) {
7177 return ERR_INVALID_FIELDID;
7179 // FIXME: Check for literal/const
7181 vtable = mono_class_vtable (domain, f->parent);
7182 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7183 err = decode_value (f->type, domain, val, p, &p, end);
7188 if (MONO_TYPE_IS_REFERENCE (f->type))
7189 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7191 mono_field_static_set_value (vtable, f, val);
7196 case CMD_TYPE_GET_OBJECT: {
7197 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
7198 buffer_add_objid (buf, o);
7201 case CMD_TYPE_GET_SOURCE_FILES:
7202 case CMD_TYPE_GET_SOURCE_FILES_2: {
7203 char *source_file, *base;
7207 files = get_source_files_for_type (klass);
7209 buffer_add_int (buf, files->len);
7210 for (i = 0; i < files->len; ++i) {
7211 source_file = g_ptr_array_index (files, i);
7212 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7213 buffer_add_string (buf, source_file);
7215 base = g_path_get_basename (source_file);
7216 buffer_add_string (buf, base);
7219 g_free (source_file);
7221 g_ptr_array_free (files, TRUE);
7224 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7225 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7229 if (mono_class_is_assignable_from (klass, oklass))
7230 buffer_add_byte (buf, 1);
7232 buffer_add_byte (buf, 0);
7235 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7236 char *name = decode_string (p, &p, end);
7237 int i, flags = decode_int (p, &p, end);
7238 MonoException *ex = NULL;
7239 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7242 return ERR_LOADER_ERROR;
7243 buffer_add_int (buf, array->len);
7244 for (i = 0; i < array->len; ++i) {
7245 MonoMethod *method = g_ptr_array_index (array, i);
7246 buffer_add_methodid (buf, domain, method);
7249 g_ptr_array_free (array, TRUE);
7253 case CMD_TYPE_GET_INTERFACES: {
7255 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7257 MonoClass *tclass, *iface;
7258 GHashTableIter iter;
7262 for (parent = tclass; parent; parent = parent->parent) {
7263 mono_class_setup_interfaces (parent, &error);
7264 if (!mono_error_ok (&error))
7265 return ERR_LOADER_ERROR;
7266 collect_interfaces (parent, iface_hash, &error);
7267 if (!mono_error_ok (&error))
7268 return ERR_LOADER_ERROR;
7271 buffer_add_int (buf, g_hash_table_size (iface_hash));
7273 g_hash_table_iter_init (&iter, iface_hash);
7274 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7275 buffer_add_typeid (buf, domain, iface);
7276 g_hash_table_destroy (iface_hash);
7279 case CMD_TYPE_GET_INTERFACE_MAP: {
7280 int tindex, ioffset;
7281 gboolean variance_used;
7283 int len, nmethods, i;
7287 len = decode_int (p, &p, end);
7288 mono_class_setup_vtable (klass);
7290 for (tindex = 0; tindex < len; ++tindex) {
7291 iclass = decode_typeid (p, &p, end, NULL, &err);
7295 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7297 return ERR_INVALID_ARGUMENT;
7299 nmethods = mono_class_num_methods (iclass);
7300 buffer_add_int (buf, nmethods);
7303 while ((method = mono_class_get_methods (iclass, &iter))) {
7304 buffer_add_methodid (buf, domain, method);
7306 for (i = 0; i < nmethods; ++i)
7307 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7312 return ERR_NOT_IMPLEMENTED;
7319 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7322 MonoDomain *old_domain;
7326 klass = decode_typeid (p, &p, end, &domain, &err);
7330 old_domain = mono_domain_get ();
7332 mono_domain_set (domain, TRUE);
7334 err = type_commands_internal (command, klass, domain, p, end, buf);
7336 mono_domain_set (old_domain, TRUE);
7342 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7344 MonoMethodHeader *header;
7347 case CMD_METHOD_GET_NAME: {
7348 buffer_add_string (buf, method->name);
7351 case CMD_METHOD_GET_DECLARING_TYPE: {
7352 buffer_add_typeid (buf, domain, method->klass);
7355 case CMD_METHOD_GET_DEBUG_INFO: {
7356 MonoDebugMethodInfo *minfo;
7358 int i, j, n_il_offsets;
7362 GPtrArray *source_file_list;
7364 header = mono_method_get_header (method);
7366 buffer_add_int (buf, 0);
7367 buffer_add_string (buf, "");
7368 buffer_add_int (buf, 0);
7372 minfo = mono_debug_lookup_method (method);
7374 buffer_add_int (buf, header->code_size);
7375 buffer_add_string (buf, "");
7376 buffer_add_int (buf, 0);
7377 mono_metadata_free_mh (header);
7381 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &source_files);
7382 buffer_add_int (buf, header->code_size);
7383 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7384 buffer_add_int (buf, source_file_list->len);
7385 for (i = 0; i < source_file_list->len; ++i) {
7386 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7387 buffer_add_string (buf, sinfo->source_file);
7388 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7389 for (j = 0; j < 16; ++j)
7390 buffer_add_byte (buf, sinfo->hash [j]);
7394 buffer_add_string (buf, source_file);
7396 buffer_add_int (buf, n_il_offsets);
7397 DEBUG (10, printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7398 for (i = 0; i < n_il_offsets; ++i) {
7399 const char *srcfile = "";
7401 if (source_files [i] != -1) {
7402 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7403 srcfile = sinfo->source_file;
7405 DEBUG (10, printf ("IL%x -> %s:%d\n", il_offsets [i], srcfile, line_numbers [i]));
7406 buffer_add_int (buf, il_offsets [i]);
7407 buffer_add_int (buf, line_numbers [i]);
7408 if (CHECK_PROTOCOL_VERSION (2, 13))
7409 buffer_add_int (buf, source_files [i]);
7411 g_free (source_file);
7412 g_free (il_offsets);
7413 g_free (line_numbers);
7414 g_free (source_files);
7415 g_ptr_array_free (source_file_list, TRUE);
7416 mono_metadata_free_mh (header);
7419 case CMD_METHOD_GET_PARAM_INFO: {
7420 MonoMethodSignature *sig = mono_method_signature (method);
7424 /* FIXME: mono_class_from_mono_type () and byrefs */
7426 /* FIXME: Use a smaller encoding */
7427 buffer_add_int (buf, sig->call_convention);
7428 buffer_add_int (buf, sig->param_count);
7429 buffer_add_int (buf, sig->generic_param_count);
7430 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7431 for (i = 0; i < sig->param_count; ++i) {
7433 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7436 /* Emit parameter names */
7437 names = g_new (char *, sig->param_count);
7438 mono_method_get_param_names (method, (const char **) names);
7439 for (i = 0; i < sig->param_count; ++i)
7440 buffer_add_string (buf, names [i]);
7445 case CMD_METHOD_GET_LOCALS_INFO: {
7446 int i, j, num_locals;
7447 MonoDebugLocalsInfo *locals;
7449 header = mono_method_get_header (method);
7452 buffer_add_int (buf, header->num_locals);
7455 for (i = 0; i < header->num_locals; ++i)
7456 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7459 locals = mono_debug_lookup_locals (method);
7461 num_locals = locals->num_locals;
7464 for (i = 0; i < header->num_locals; ++i) {
7465 for (j = 0; j < num_locals; ++j)
7466 if (locals->locals [j].index == i)
7469 buffer_add_string (buf, locals->locals [j].name);
7471 buffer_add_string (buf, "");
7475 for (i = 0; i < header->num_locals; ++i) {
7476 for (j = 0; j < num_locals; ++j)
7477 if (locals->locals [j].index == i)
7479 if (j < num_locals && locals->locals [j].block) {
7480 buffer_add_int (buf, locals->locals [j].block->start_offset);
7481 buffer_add_int (buf, locals->locals [j].block->end_offset);
7483 buffer_add_int (buf, 0);
7484 buffer_add_int (buf, header->code_size);
7487 mono_metadata_free_mh (header);
7490 mono_debug_symfile_free_locals (locals);
7494 case CMD_METHOD_GET_INFO:
7495 buffer_add_int (buf, method->flags);
7496 buffer_add_int (buf, method->iflags);
7497 buffer_add_int (buf, method->token);
7498 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7500 if (method->is_generic)
7502 if (mono_method_signature (method)->generic_param_count)
7504 buffer_add_byte (buf, attrs);
7505 if (method->is_generic || method->is_inflated) {
7508 if (method->is_generic) {
7511 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7513 result = imethod->declaring;
7514 if (imethod->context.class_inst) {
7515 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7516 /*Generic methods gets the context of the GTD.*/
7517 if (mono_class_get_context (klass))
7518 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7522 buffer_add_methodid (buf, domain, result);
7524 buffer_add_id (buf, 0);
7528 case CMD_METHOD_GET_BODY: {
7531 header = mono_method_get_header (method);
7533 buffer_add_int (buf, 0);
7535 buffer_add_int (buf, header->code_size);
7536 for (i = 0; i < header->code_size; ++i)
7537 buffer_add_byte (buf, header->code [i]);
7539 mono_metadata_free_mh (header);
7542 case CMD_METHOD_RESOLVE_TOKEN: {
7543 guint32 token = decode_int (p, &p, end);
7546 switch (mono_metadata_token_code (token)) {
7547 case MONO_TOKEN_STRING: {
7551 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7554 s2 = mono_string_to_utf8 (s);
7556 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7557 buffer_add_string (buf, s2);
7563 MonoClass *handle_class;
7565 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7566 val = mono_method_get_wrapper_data (method, token);
7567 handle_class = mono_method_get_wrapper_data (method, token + 1);
7569 if (handle_class == NULL) {
7570 // Can't figure out the token type
7571 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7575 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7579 if (handle_class == mono_defaults.typehandle_class) {
7580 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7581 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7582 buffer_add_typeid (buf, domain, (MonoClass *) val);
7584 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7585 } else if (handle_class == mono_defaults.fieldhandle_class) {
7586 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7587 buffer_add_fieldid (buf, domain, val);
7588 } else if (handle_class == mono_defaults.methodhandle_class) {
7589 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7590 buffer_add_methodid (buf, domain, val);
7591 } else if (handle_class == mono_defaults.string_class) {
7594 s = mono_string_to_utf8 (val);
7595 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7596 buffer_add_string (buf, s);
7599 g_assert_not_reached ();
7607 return ERR_NOT_IMPLEMENTED;
7614 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7617 MonoDomain *old_domain;
7621 method = decode_methodid (p, &p, end, &domain, &err);
7625 old_domain = mono_domain_get ();
7627 mono_domain_set (domain, TRUE);
7629 err = method_commands_internal (command, method, domain, p, end, buf);
7631 mono_domain_set (old_domain, TRUE);
7637 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7639 int objid = decode_objid (p, &p, end);
7641 MonoThread *thread_obj;
7642 MonoInternalThread *thread;
7644 err = get_object (objid, (MonoObject**)&thread_obj);
7648 thread = THREAD_TO_INTERNAL (thread_obj);
7651 case CMD_THREAD_GET_NAME: {
7653 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7656 buffer_add_int (buf, 0);
7661 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7663 buffer_add_int (buf, len);
7664 buffer_add_data (buf, (guint8*)name, len);
7669 case CMD_THREAD_GET_FRAME_INFO: {
7670 DebuggerTlsData *tls;
7671 int i, start_frame, length;
7673 // Wait for suspending if it already started
7674 // FIXME: Races with suspend_count
7675 while (!is_suspended ()) {
7677 wait_for_suspend ();
7681 wait_for_suspend ();
7682 if (!is_suspended ())
7683 return ERR_NOT_SUSPENDED;
7686 start_frame = decode_int (p, &p, end);
7687 length = decode_int (p, &p, end);
7689 if (start_frame != 0 || length != -1)
7690 return ERR_NOT_IMPLEMENTED;
7692 mono_loader_lock ();
7693 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7694 mono_loader_unlock ();
7697 compute_frame_info (thread, tls);
7699 buffer_add_int (buf, tls->frame_count);
7700 for (i = 0; i < tls->frame_count; ++i) {
7701 buffer_add_int (buf, tls->frames [i]->id);
7702 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
7703 buffer_add_int (buf, tls->frames [i]->il_offset);
7705 * Instead of passing the frame type directly to the client, we associate
7706 * it with the previous frame using a set of flags. This avoids lots of
7707 * conditional code in the client, since a frame whose type isn't
7708 * FRAME_TYPE_MANAGED has no method, location, etc.
7710 buffer_add_byte (buf, tls->frames [i]->flags);
7715 case CMD_THREAD_GET_STATE:
7716 buffer_add_int (buf, thread->state);
7718 case CMD_THREAD_GET_INFO:
7719 buffer_add_byte (buf, thread->threadpool_thread);
7721 case CMD_THREAD_GET_ID:
7722 buffer_add_long (buf, (guint64)(gsize)thread);
7724 case CMD_THREAD_GET_TID:
7725 buffer_add_long (buf, (guint64)thread->tid);
7728 return ERR_NOT_IMPLEMENTED;
7735 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7739 MonoThread *thread_obj;
7740 MonoInternalThread *thread;
7741 int pos, i, len, frame_idx;
7742 DebuggerTlsData *tls;
7744 MonoDebugMethodJitInfo *jit;
7745 MonoDebugVarInfo *var;
7746 MonoMethodSignature *sig;
7748 MonoMethodHeader *header;
7750 objid = decode_objid (p, &p, end);
7751 err = get_object (objid, (MonoObject**)&thread_obj);
7755 thread = THREAD_TO_INTERNAL (thread_obj);
7757 id = decode_id (p, &p, end);
7759 mono_loader_lock ();
7760 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7761 mono_loader_unlock ();
7764 for (i = 0; i < tls->frame_count; ++i) {
7765 if (tls->frames [i]->id == id)
7768 if (i == tls->frame_count)
7769 return ERR_INVALID_FRAMEID;
7772 frame = tls->frames [frame_idx];
7774 if (!frame->has_ctx)
7776 return ERR_INVALID_FRAMEID;
7779 frame->jit = mono_debug_find_method (frame->method, frame->domain);
7780 if (!frame->jit && frame->method->is_inflated)
7781 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->method), frame->domain);
7785 /* This could happen for aot images with no jit debug info */
7786 s = mono_method_full_name (frame->method, TRUE);
7787 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
7789 return ERR_ABSENT_INFORMATION;
7794 sig = mono_method_signature (frame->actual_method);
7796 if (!get_seq_points (frame->domain, frame->actual_method))
7798 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
7800 return ERR_ABSENT_INFORMATION;
7803 case CMD_STACK_FRAME_GET_VALUES: {
7804 len = decode_int (p, &p, end);
7805 header = mono_method_get_header (frame->actual_method);
7807 for (i = 0; i < len; ++i) {
7808 pos = decode_int (p, &p, end);
7813 g_assert (pos >= 0 && pos < jit->num_params);
7815 var = &jit->params [pos];
7817 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
7819 g_assert (pos >= 0 && pos < jit->num_locals);
7821 var = &jit->locals [pos];
7823 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
7826 mono_metadata_free_mh (header);
7829 case CMD_STACK_FRAME_GET_THIS: {
7830 if (frame->method->klass->valuetype) {
7831 if (!sig->hasthis) {
7832 MonoObject *p = NULL;
7833 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
7835 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7838 if (!sig->hasthis) {
7839 MonoObject *p = NULL;
7840 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
7842 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7847 case CMD_STACK_FRAME_SET_VALUES: {
7850 MonoDebugVarInfo *var;
7852 len = decode_int (p, &p, end);
7853 header = mono_method_get_header (frame->actual_method);
7855 for (i = 0; i < len; ++i) {
7856 pos = decode_int (p, &p, end);
7861 g_assert (pos >= 0 && pos < jit->num_params);
7863 t = sig->params [pos];
7864 var = &jit->params [pos];
7866 g_assert (pos >= 0 && pos < jit->num_locals);
7868 t = header->locals [pos];
7869 var = &jit->locals [pos];
7872 if (MONO_TYPE_IS_REFERENCE (t))
7873 val_buf = g_alloca (sizeof (MonoObject*));
7875 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
7876 err = decode_value (t, frame->domain, val_buf, p, &p, end);
7880 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
7882 mono_metadata_free_mh (header);
7886 return ERR_NOT_IMPLEMENTED;
7893 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7896 int objid, err, index, len, i, esize;
7899 objid = decode_objid (p, &p, end);
7900 err = get_object (objid, (MonoObject**)&arr);
7905 case CMD_ARRAY_REF_GET_LENGTH:
7906 buffer_add_int (buf, arr->obj.vtable->klass->rank);
7908 buffer_add_int (buf, arr->max_length);
7909 buffer_add_int (buf, 0);
7911 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
7912 buffer_add_int (buf, arr->bounds [i].length);
7913 buffer_add_int (buf, arr->bounds [i].lower_bound);
7917 case CMD_ARRAY_REF_GET_VALUES:
7918 index = decode_int (p, &p, end);
7919 len = decode_int (p, &p, end);
7921 g_assert (index >= 0 && len >= 0);
7922 // Reordered to avoid integer overflow
7923 g_assert (!(index > arr->max_length - len));
7925 esize = mono_array_element_size (arr->obj.vtable->klass);
7926 for (i = index; i < index + len; ++i) {
7927 elem = (gpointer*)((char*)arr->vector + (i * esize));
7928 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
7931 case CMD_ARRAY_REF_SET_VALUES:
7932 index = decode_int (p, &p, end);
7933 len = decode_int (p, &p, end);
7935 g_assert (index >= 0 && len >= 0);
7936 // Reordered to avoid integer overflow
7937 g_assert (!(index > arr->max_length - len));
7939 esize = mono_array_element_size (arr->obj.vtable->klass);
7940 for (i = index; i < index + len; ++i) {
7941 elem = (gpointer*)((char*)arr->vector + (i * esize));
7943 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
7947 return ERR_NOT_IMPLEMENTED;
7954 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7959 int i, index, length;
7962 objid = decode_objid (p, &p, end);
7963 err = get_object (objid, (MonoObject**)&str);
7968 case CMD_STRING_REF_GET_VALUE:
7969 s = mono_string_to_utf8 (str);
7970 buffer_add_string (buf, s);
7973 case CMD_STRING_REF_GET_LENGTH:
7974 buffer_add_long (buf, mono_string_length (str));
7976 case CMD_STRING_REF_GET_CHARS:
7977 index = decode_long (p, &p, end);
7978 length = decode_long (p, &p, end);
7979 if (index > mono_string_length (str) - length)
7980 return ERR_INVALID_ARGUMENT;
7981 c = mono_string_chars (str) + index;
7982 for (i = 0; i < length; ++i)
7983 buffer_add_short (buf, c [i]);
7986 return ERR_NOT_IMPLEMENTED;
7993 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8002 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8003 objid = decode_objid (p, &p, end);
8004 err = get_object (objid, &obj);
8006 buffer_add_int (buf, 1);
8008 buffer_add_int (buf, 0);
8012 objid = decode_objid (p, &p, end);
8013 err = get_object (objid, &obj);
8018 case CMD_OBJECT_REF_GET_TYPE:
8019 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8021 case CMD_OBJECT_REF_GET_VALUES:
8022 len = decode_int (p, &p, end);
8024 for (i = 0; i < len; ++i) {
8025 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8029 /* Check that the field belongs to the object */
8031 for (k = obj->vtable->klass; k; k = k->parent) {
8032 if (k == f->parent) {
8038 return ERR_INVALID_FIELDID;
8040 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8044 if (mono_class_field_is_special_static (f))
8045 return ERR_INVALID_FIELDID;
8047 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8048 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8049 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8050 mono_field_static_get_value (vtable, f, val);
8051 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8054 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8058 case CMD_OBJECT_REF_SET_VALUES:
8059 len = decode_int (p, &p, end);
8061 for (i = 0; i < len; ++i) {
8062 f = decode_fieldid (p, &p, end, NULL, &err);
8066 /* Check that the field belongs to the object */
8068 for (k = obj->vtable->klass; k; k = k->parent) {
8069 if (k == f->parent) {
8075 return ERR_INVALID_FIELDID;
8077 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8081 if (mono_class_field_is_special_static (f))
8082 return ERR_INVALID_FIELDID;
8084 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8085 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8087 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8088 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8093 mono_field_static_set_value (vtable, f, val);
8096 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8102 case CMD_OBJECT_REF_GET_ADDRESS:
8103 buffer_add_long (buf, (gssize)obj);
8105 case CMD_OBJECT_REF_GET_DOMAIN:
8106 buffer_add_domainid (buf, obj->vtable->domain);
8108 case CMD_OBJECT_REF_GET_INFO:
8109 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8110 buffer_add_domainid (buf, obj->vtable->domain);
8113 return ERR_NOT_IMPLEMENTED;
8120 command_set_to_string (CommandSet command_set)
8122 switch (command_set) {
8125 case CMD_SET_OBJECT_REF:
8126 return "OBJECT_REF";
8127 case CMD_SET_STRING_REF:
8128 return "STRING_REF";
8129 case CMD_SET_THREAD:
8131 case CMD_SET_ARRAY_REF:
8133 case CMD_SET_EVENT_REQUEST:
8134 return "EVENT_REQUEST";
8135 case CMD_SET_STACK_FRAME:
8136 return "STACK_FRAME";
8137 case CMD_SET_APPDOMAIN:
8139 case CMD_SET_ASSEMBLY:
8141 case CMD_SET_METHOD:
8145 case CMD_SET_MODULE:
8155 cmd_to_string (CommandSet set, int command)
8160 case CMD_VM_VERSION:
8162 case CMD_VM_ALL_THREADS:
8163 return "ALL_THREADS";
8164 case CMD_VM_SUSPEND:
8170 case CMD_VM_DISPOSE:
8172 case CMD_VM_INVOKE_METHOD:
8173 return "INVOKE_METHOD";
8174 case CMD_VM_SET_PROTOCOL_VERSION:
8175 return "SET_PROTOCOL_VERSION";
8176 case CMD_VM_ABORT_INVOKE:
8177 return "ABORT_INVOKE";
8190 wait_for_attach (void)
8192 #ifndef DISABLE_SOCKET_TRANSPORT
8193 if (listen_fd == -1) {
8194 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8198 /* Block and wait for client connection */
8199 conn_fd = socket_transport_accept (listen_fd);
8200 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8201 if (conn_fd == -1) {
8202 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8206 g_assert_not_reached ();
8210 disconnected = !transport_handshake ();
8212 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8222 * This thread handles communication with the debugger client using a JDWP
8225 static guint32 WINAPI
8226 debugger_thread (void *arg)
8228 int res, len, id, flags, command_set = 0, command = 0;
8229 guint8 header [HEADER_LENGTH];
8230 guint8 *data, *p, *end;
8234 gboolean attach_failed = FALSE;
8236 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8238 debugger_thread_id = GetCurrentThreadId ();
8240 mono_jit_thread_attach (mono_get_root_domain ());
8242 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8244 mono_set_is_debugger_attached (TRUE);
8246 if (agent_config.defer) {
8247 if (!wait_for_attach ()) {
8248 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8249 attach_failed = TRUE; // Don't abort process when we can't listen
8251 /* Send start event to client */
8252 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8256 while (!attach_failed) {
8257 res = transport_recv (header, HEADER_LENGTH);
8259 /* This will break if the socket is closed during shutdown too */
8260 if (res != HEADER_LENGTH)
8264 end = header + HEADER_LENGTH;
8266 len = decode_int (p, &p, end);
8267 id = decode_int (p, &p, end);
8268 flags = decode_byte (p, &p, end);
8269 command_set = decode_byte (p, &p, end);
8270 command = decode_byte (p, &p, end);
8272 g_assert (flags == 0);
8275 const char *cmd_str;
8278 cmd_str = cmd_to_string (command_set, command);
8280 sprintf (cmd_num, "%d", command);
8284 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8287 data = g_malloc (len - HEADER_LENGTH);
8288 if (len - HEADER_LENGTH > 0)
8290 res = transport_recv (data, len - HEADER_LENGTH);
8291 if (res != len - HEADER_LENGTH)
8296 end = data + (len - HEADER_LENGTH);
8298 buffer_init (&buf, 128);
8303 /* Process the request */
8304 switch (command_set) {
8306 err = vm_commands (command, id, p, end, &buf);
8307 if (!err && command == CMD_VM_INVOKE_METHOD)
8308 /* Sent after the invoke is complete */
8311 case CMD_SET_EVENT_REQUEST:
8312 err = event_commands (command, p, end, &buf);
8314 case CMD_SET_APPDOMAIN:
8315 err = domain_commands (command, p, end, &buf);
8317 case CMD_SET_ASSEMBLY:
8318 err = assembly_commands (command, p, end, &buf);
8320 case CMD_SET_MODULE:
8321 err = module_commands (command, p, end, &buf);
8324 err = type_commands (command, p, end, &buf);
8326 case CMD_SET_METHOD:
8327 err = method_commands (command, p, end, &buf);
8329 case CMD_SET_THREAD:
8330 err = thread_commands (command, p, end, &buf);
8332 case CMD_SET_STACK_FRAME:
8333 err = frame_commands (command, p, end, &buf);
8335 case CMD_SET_ARRAY_REF:
8336 err = array_commands (command, p, end, &buf);
8338 case CMD_SET_STRING_REF:
8339 err = string_commands (command, p, end, &buf);
8341 case CMD_SET_OBJECT_REF:
8342 err = object_commands (command, p, end, &buf);
8345 err = ERR_NOT_IMPLEMENTED;
8349 send_reply_packet (id, err, &buf);
8354 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8358 mono_set_is_debugger_attached (FALSE);
8360 mono_mutex_lock (&debugger_thread_exited_mutex);
8361 debugger_thread_exited = TRUE;
8362 mono_cond_signal (&debugger_thread_exited_cond);
8363 mono_mutex_unlock (&debugger_thread_exited_mutex);
8365 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8367 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8368 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8369 start_debugger_thread ();
8375 #else /* DISABLE_DEBUGGER_AGENT */
8378 mono_debugger_agent_parse_options (char *options)
8380 g_error ("This runtime is configured with the debugger agent disabled.");
8384 mono_debugger_agent_init (void)
8389 mono_debugger_agent_breakpoint_hit (void *sigctx)
8394 mono_debugger_agent_single_step_event (void *sigctx)
8399 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8404 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8410 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8411 MonoContext *catch_ctx)
8416 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8421 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8426 mono_debugger_agent_user_break (void)
8432 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8437 mono_debugger_agent_debug_log_is_enabled (void)