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 * This is the method which is visible to debugger clients. Same as method,
133 * except for native-to-managed wrappers.
135 MonoMethod *api_method;
137 MonoDebugMethodJitInfo *jit;
140 mgreg_t *reg_locations [MONO_MAX_IREGS];
142 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
143 * the frame can become invalid.
148 typedef struct _InvokeData InvokeData;
156 /* This is the context which needs to be restored after the invoke */
160 * If this is set, invoke this method with the arguments given by ARGS.
164 guint32 suspend_count;
166 InvokeData *last_invoke;
170 MonoThreadUnwindState context;
172 gpointer resume_event;
173 /* This is computed on demand when it is requested using the wire protocol */
174 /* It is freed up when the thread is resumed */
178 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
181 gboolean frames_up_to_date;
183 * Points to data about a pending invoke which needs to be executed after the thread
186 InvokeData *pending_invoke;
188 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
193 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
194 * within a finite amount of time.
198 * Set to TRUE if this thread is suspended in suspend_current ().
200 gboolean really_suspended;
201 /* Used to pass the context to the breakpoint/single step handler */
202 MonoContext handler_ctx;
203 /* Whenever thread_stop () was called for this thread */
206 /* Number of thread interruptions not yet processed */
207 gint32 interrupt_count;
209 /* Whenever to disable breakpoints (used during invokes) */
210 gboolean disable_breakpoints;
213 * Number of times this thread has been resumed using resume_thread ().
215 guint32 resume_count;
217 MonoInternalThread *thread;
220 * Information about the frame which transitioned to native code for running
223 StackFrameInfo async_last_frame;
226 * The context where the stack walk can be started for running threads.
228 MonoThreadUnwindState async_state;
231 * The context used for filter clauses
233 MonoThreadUnwindState filter_state;
236 * The callee address of the last mono_runtime_invoke call
238 gpointer invoke_addr;
240 gboolean abort_requested;
243 * The current mono_runtime_invoke invocation.
248 * The context where single stepping should resume while the thread is suspended because
249 * of an EXCEPTION event.
251 MonoContext catch_ctx;
253 gboolean has_catch_ctx;
256 * The context which needs to be restored after handling a single step/breakpoint
257 * event. This is the same as the ctx at step/breakpoint site, but includes changes
258 * to caller saved registers done by set_var ().
260 MonoContext restore_ctx;
265 void (*connect) (const char *address);
266 void (*close1) (void);
267 void (*close2) (void);
268 gboolean (*send) (void *buf, int len);
269 int (*recv) (void *buf, int len);
273 * Wire Protocol definitions
276 #define HEADER_LENGTH 11
278 #define MAJOR_VERSION 2
279 #define MINOR_VERSION 18
283 CMD_SET_OBJECT_REF = 9,
284 CMD_SET_STRING_REF = 10,
286 CMD_SET_ARRAY_REF = 13,
287 CMD_SET_EVENT_REQUEST = 15,
288 CMD_SET_STACK_FRAME = 16,
289 CMD_SET_APPDOMAIN = 20,
290 CMD_SET_ASSEMBLY = 21,
298 EVENT_KIND_VM_START = 0,
299 EVENT_KIND_VM_DEATH = 1,
300 EVENT_KIND_THREAD_START = 2,
301 EVENT_KIND_THREAD_DEATH = 3,
302 EVENT_KIND_APPDOMAIN_CREATE = 4,
303 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
304 EVENT_KIND_METHOD_ENTRY = 6,
305 EVENT_KIND_METHOD_EXIT = 7,
306 EVENT_KIND_ASSEMBLY_LOAD = 8,
307 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
308 EVENT_KIND_BREAKPOINT = 10,
309 EVENT_KIND_STEP = 11,
310 EVENT_KIND_TYPE_LOAD = 12,
311 EVENT_KIND_EXCEPTION = 13,
312 EVENT_KIND_KEEPALIVE = 14,
313 EVENT_KIND_USER_BREAK = 15,
314 EVENT_KIND_USER_LOG = 16
318 SUSPEND_POLICY_NONE = 0,
319 SUSPEND_POLICY_EVENT_THREAD = 1,
320 SUSPEND_POLICY_ALL = 2
325 ERR_INVALID_OBJECT = 20,
326 ERR_INVALID_FIELDID = 25,
327 ERR_INVALID_FRAMEID = 30,
328 ERR_NOT_IMPLEMENTED = 100,
329 ERR_NOT_SUSPENDED = 101,
330 ERR_INVALID_ARGUMENT = 102,
332 ERR_NO_INVOCATION = 104,
333 ERR_ABSENT_INFORMATION = 105,
334 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
335 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
340 MOD_KIND_THREAD_ONLY = 3,
341 MOD_KIND_LOCATION_ONLY = 7,
342 MOD_KIND_EXCEPTION_ONLY = 8,
344 MOD_KIND_ASSEMBLY_ONLY = 11,
345 MOD_KIND_SOURCE_FILE_ONLY = 12,
346 MOD_KIND_TYPE_NAME_ONLY = 13
361 STEP_FILTER_NONE = 0,
362 STEP_FILTER_STATIC_CTOR = 1
366 TOKEN_TYPE_STRING = 0,
368 TOKEN_TYPE_FIELD = 2,
369 TOKEN_TYPE_METHOD = 3,
370 TOKEN_TYPE_UNKNOWN = 4
374 VALUE_TYPE_ID_NULL = 0xf0,
375 VALUE_TYPE_ID_TYPE = 0xf1
379 FRAME_FLAG_DEBUGGER_INVOKE = 1,
380 FRAME_FLAG_NATIVE_TRANSITION = 2
384 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
385 INVOKE_FLAG_SINGLE_THREADED = 2
389 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
390 } BindingFlagsExtensions;
394 CMD_VM_ALL_THREADS = 2,
399 CMD_VM_INVOKE_METHOD = 7,
400 CMD_VM_SET_PROTOCOL_VERSION = 8,
401 CMD_VM_ABORT_INVOKE = 9,
402 CMD_VM_SET_KEEPALIVE = 10,
403 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
404 CMD_VM_GET_TYPES = 12
408 CMD_THREAD_GET_FRAME_INFO = 1,
409 CMD_THREAD_GET_NAME = 2,
410 CMD_THREAD_GET_STATE = 3,
411 CMD_THREAD_GET_INFO = 4,
412 CMD_THREAD_GET_ID = 5,
413 CMD_THREAD_GET_TID = 6
417 CMD_EVENT_REQUEST_SET = 1,
418 CMD_EVENT_REQUEST_CLEAR = 2,
419 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
427 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
428 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
429 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
430 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
431 CMD_APPDOMAIN_CREATE_STRING = 5,
432 CMD_APPDOMAIN_GET_CORLIB = 6,
433 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
437 CMD_ASSEMBLY_GET_LOCATION = 1,
438 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
439 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
440 CMD_ASSEMBLY_GET_OBJECT = 4,
441 CMD_ASSEMBLY_GET_TYPE = 5,
442 CMD_ASSEMBLY_GET_NAME = 6
446 CMD_MODULE_GET_INFO = 1,
450 CMD_METHOD_GET_NAME = 1,
451 CMD_METHOD_GET_DECLARING_TYPE = 2,
452 CMD_METHOD_GET_DEBUG_INFO = 3,
453 CMD_METHOD_GET_PARAM_INFO = 4,
454 CMD_METHOD_GET_LOCALS_INFO = 5,
455 CMD_METHOD_GET_INFO = 6,
456 CMD_METHOD_GET_BODY = 7,
457 CMD_METHOD_RESOLVE_TOKEN = 8,
461 CMD_TYPE_GET_INFO = 1,
462 CMD_TYPE_GET_METHODS = 2,
463 CMD_TYPE_GET_FIELDS = 3,
464 CMD_TYPE_GET_VALUES = 4,
465 CMD_TYPE_GET_OBJECT = 5,
466 CMD_TYPE_GET_SOURCE_FILES = 6,
467 CMD_TYPE_SET_VALUES = 7,
468 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
469 CMD_TYPE_GET_PROPERTIES = 9,
470 CMD_TYPE_GET_CATTRS = 10,
471 CMD_TYPE_GET_FIELD_CATTRS = 11,
472 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
473 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
474 CMD_TYPE_GET_VALUES_2 = 14,
475 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
476 CMD_TYPE_GET_INTERFACES = 16,
477 CMD_TYPE_GET_INTERFACE_MAP = 17,
481 CMD_STACK_FRAME_GET_VALUES = 1,
482 CMD_STACK_FRAME_GET_THIS = 2,
483 CMD_STACK_FRAME_SET_VALUES = 3
487 CMD_ARRAY_REF_GET_LENGTH = 1,
488 CMD_ARRAY_REF_GET_VALUES = 2,
489 CMD_ARRAY_REF_SET_VALUES = 3,
493 CMD_STRING_REF_GET_VALUE = 1,
494 CMD_STRING_REF_GET_LENGTH = 2,
495 CMD_STRING_REF_GET_CHARS = 3
499 CMD_OBJECT_REF_GET_TYPE = 1,
500 CMD_OBJECT_REF_GET_VALUES = 2,
501 CMD_OBJECT_REF_IS_COLLECTED = 3,
502 CMD_OBJECT_REF_GET_ADDRESS = 4,
503 CMD_OBJECT_REF_GET_DOMAIN = 5,
504 CMD_OBJECT_REF_SET_VALUES = 6,
505 CMD_OBJECT_REF_GET_INFO = 7,
511 int count; /* For kind == MOD_KIND_COUNT */
512 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
513 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
514 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
515 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
516 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
517 StepFilter filter; /* For kind == MOD_KIND_STEP */
519 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
528 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
532 * Describes a single step request.
536 MonoInternalThread *thread;
542 MonoMethod *last_method;
544 /* Whenever single stepping is performed using start/stop_single_stepping () */
546 /* The list of breakpoints used to implement step-over */
551 * Contains additional information for an event
554 /* For EVENT_KIND_EXCEPTION */
556 MonoContext catch_ctx;
558 /* For EVENT_KIND_USER_LOG */
560 char *category, *message;
561 /* For EVENT_KIND_TYPE_LOAD */
565 /* Dummy structure used for the profiler callbacks */
570 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
573 #define get_last_sock_error() WSAGetLastError()
574 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
575 #define MONO_EINTR WSAEINTR
577 #define get_last_sock_error() errno
578 #define MONO_EWOULDBLOCK EWOULDBLOCK
579 #define MONO_EINTR EINTR
582 #define CHECK_PROTOCOL_VERSION(major,minor) \
583 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
589 static AgentConfig agent_config;
592 * Whenever the agent is fully initialized.
593 * When using the onuncaught or onthrow options, only some parts of the agent are
594 * initialized on startup, and the full initialization which includes connection
595 * establishment and the startup of the agent thread is only done in response to
598 static gint32 inited;
600 #ifndef DISABLE_SOCKET_TRANSPORT
602 static int listen_fd;
605 static int packet_id = 0;
607 static int objref_id = 0;
609 static int event_request_id = 0;
611 static int frame_id = 0;
613 static GPtrArray *event_requests;
615 static MonoNativeTlsKey debugger_tls_id;
617 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
619 /* Maps MonoInternalThread -> DebuggerTlsData */
620 static MonoGHashTable *thread_to_tls;
622 /* Maps tid -> MonoInternalThread */
623 static MonoGHashTable *tid_to_thread;
625 /* Maps tid -> MonoThread (not MonoInternalThread) */
626 static MonoGHashTable *tid_to_thread_obj;
628 static gsize debugger_thread_id;
630 static HANDLE debugger_thread_handle;
632 static int log_level;
634 static gboolean embedding;
636 static FILE *log_file;
638 /* Assemblies whose assembly load event has no been sent yet */
639 static GPtrArray *pending_assembly_loads;
641 /* Whenever the debugger thread has exited */
642 static gboolean debugger_thread_exited;
644 /* Cond variable used to wait for debugger_thread_exited becoming true */
645 static mono_cond_t debugger_thread_exited_cond;
647 /* Mutex for the cond var above */
648 static mono_mutex_t debugger_thread_exited_mutex;
650 static DebuggerProfiler debugger_profiler;
652 /* The single step request instance */
653 static SingleStepReq *ss_req = NULL;
654 static gpointer ss_invoke_addr = NULL;
656 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
657 /* Number of single stepping operations in progress */
661 /* The protocol version of the client */
662 static int major_version, minor_version;
664 /* Whenever the variables above are set by the client */
665 static gboolean protocol_version_set;
667 /* A hash table containing all active domains */
668 static GHashTable *domains;
670 static void transport_init (void);
671 static void transport_connect (const char *address);
672 static gboolean transport_handshake (void);
673 static void register_transport (DebuggerTransport *trans);
675 static guint32 WINAPI debugger_thread (void *arg);
677 static void runtime_initialized (MonoProfiler *prof);
679 static void runtime_shutdown (MonoProfiler *prof);
681 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
683 static void thread_end (MonoProfiler *prof, uintptr_t tid);
685 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
687 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
689 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
691 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
693 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
695 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
697 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
699 static void emit_assembly_load (gpointer assembly, gpointer user_data);
701 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
703 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
705 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
707 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
709 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
711 static void start_single_stepping (void);
713 static void stop_single_stepping (void);
715 static void suspend_current (void);
717 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
719 static void clear_types_for_assembly (MonoAssembly *assembly);
721 static void clear_breakpoints_for_domain (MonoDomain *domain);
723 static void process_profiler_event (EventKind event, gpointer arg);
725 /* Submodule init/cleanup */
726 static void breakpoints_init (void);
727 static void breakpoints_cleanup (void);
729 static void objrefs_init (void);
730 static void objrefs_cleanup (void);
732 static void ids_init (void);
733 static void ids_cleanup (void);
735 static void suspend_init (void);
737 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
738 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
739 static void ss_destroy (SingleStepReq *req);
741 static void start_debugger_thread (void);
742 static void stop_debugger_thread (void);
744 static void finish_agent_init (gboolean on_startup);
746 static void process_profiler_event (EventKind event, gpointer arg);
748 static void invalidate_frames (DebuggerTlsData *tls);
750 #ifndef DISABLE_SOCKET_TRANSPORT
752 register_socket_transport (void);
756 parse_address (char *address, char **host, int *port)
758 char *pos = strchr (address, ':');
760 if (pos == NULL || pos == address)
763 *host = g_malloc (pos - address + 1);
764 strncpy (*host, address, pos - address);
765 (*host) [pos - address] = '\0';
767 *port = atoi (pos + 1);
775 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
776 fprintf (stderr, "Available options:\n");
777 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
778 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
779 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
780 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
781 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
782 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
783 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
784 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
785 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
789 parse_flag (const char *option, char *flag)
791 if (!strcmp (flag, "y"))
793 else if (!strcmp (flag, "n"))
796 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
803 mono_debugger_agent_parse_options (char *options)
810 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
811 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
815 extra = getenv ("MONO_SDB_ENV_OPTIONS");
817 options = g_strdup_printf ("%s,%s", options, extra);
819 agent_config.enabled = TRUE;
820 agent_config.suspend = TRUE;
821 agent_config.server = FALSE;
822 agent_config.defer = FALSE;
823 agent_config.address = NULL;
825 args = g_strsplit (options, ",", -1);
826 for (ptr = args; ptr && *ptr; ptr ++) {
829 if (strncmp (arg, "transport=", 10) == 0) {
830 agent_config.transport = g_strdup (arg + 10);
831 } else if (strncmp (arg, "address=", 8) == 0) {
832 agent_config.address = g_strdup (arg + 8);
833 } else if (strncmp (arg, "loglevel=", 9) == 0) {
834 agent_config.log_level = atoi (arg + 9);
835 } else if (strncmp (arg, "logfile=", 8) == 0) {
836 agent_config.log_file = g_strdup (arg + 8);
837 } else if (strncmp (arg, "suspend=", 8) == 0) {
838 agent_config.suspend = parse_flag ("suspend", arg + 8);
839 } else if (strncmp (arg, "server=", 7) == 0) {
840 agent_config.server = parse_flag ("server", arg + 7);
841 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
842 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
843 } else if (strncmp (arg, "onthrow=", 8) == 0) {
844 /* We support multiple onthrow= options */
845 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
846 } else if (strncmp (arg, "onthrow", 7) == 0) {
847 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
848 } else if (strncmp (arg, "help", 4) == 0) {
851 } else if (strncmp (arg, "timeout=", 8) == 0) {
852 agent_config.timeout = atoi (arg + 8);
853 } else if (strncmp (arg, "launch=", 7) == 0) {
854 agent_config.launch = g_strdup (arg + 7);
855 } else if (strncmp (arg, "embedding=", 10) == 0) {
856 agent_config.embedding = atoi (arg + 10) == 1;
857 } else if (strncmp (arg, "keepalive=", 10) == 0) {
858 agent_config.keepalive = atoi (arg + 10);
865 if (agent_config.server && !agent_config.suspend) {
866 /* Waiting for deferred attachment */
867 agent_config.defer = TRUE;
868 if (agent_config.address == NULL) {
869 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
873 //agent_config.log_level = 0;
875 if (agent_config.transport == NULL) {
876 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
880 if (agent_config.address == NULL && !agent_config.server) {
881 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
886 if (!strcmp (agent_config.transport, "dt_socket")) {
887 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
888 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
895 mono_debugger_agent_init (void)
897 if (!agent_config.enabled)
902 /* Need to know whenever a thread has acquired the loader mutex */
903 mono_loader_lock_track_ownership (TRUE);
905 event_requests = g_ptr_array_new ();
907 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
908 mono_cond_init (&debugger_thread_exited_cond, NULL);
910 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
911 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
912 mono_profiler_install_runtime_initialized (runtime_initialized);
913 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
914 mono_profiler_install_thread (thread_startup, thread_end);
915 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
916 mono_profiler_install_jit_end (jit_end);
917 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
919 mono_native_tls_alloc (&debugger_tls_id, NULL);
921 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
922 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
924 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
925 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
927 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
928 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
930 pending_assembly_loads = g_ptr_array_new ();
931 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
933 log_level = agent_config.log_level;
935 embedding = agent_config.embedding;
938 if (agent_config.log_file) {
939 log_file = fopen (agent_config.log_file, "w+");
941 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
953 mini_get_debug_options ()->gen_seq_points = TRUE;
955 * This is needed because currently we don't handle liveness info.
957 mini_get_debug_options ()->mdb_optimizations = TRUE;
959 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
960 /* This is needed because we can't set local variables in registers yet */
961 mono_disable_optimizations (MONO_OPT_LINEARS);
965 * The stack walk done from thread_interrupt () needs to be signal safe, but it
966 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
967 * safe (#3411). So load AOT info eagerly when the debugger is running as a
970 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
972 if (!agent_config.onuncaught && !agent_config.onthrow)
973 finish_agent_init (TRUE);
975 /* FIXME: Is this still needed ? */
976 #if defined(__MACH__)
977 mono_thread_info_disable_new_interrupt (TRUE);
984 * Finish the initialization of the agent. This involves connecting the transport
985 * and starting the agent thread. This is either done at startup, or
986 * in response to some event like an unhandled exception.
989 finish_agent_init (gboolean on_startup)
993 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
996 if (agent_config.launch) {
999 // FIXME: Generated address
1000 // FIXME: Races with transport_connect ()
1002 argv [0] = agent_config.launch;
1003 argv [1] = agent_config.transport;
1004 argv [2] = agent_config.address;
1007 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1009 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1014 transport_connect (agent_config.address);
1017 /* Do some which is usually done after sending the VMStart () event */
1018 vm_start_event_sent = TRUE;
1019 start_debugger_thread ();
1024 mono_debugger_agent_cleanup (void)
1029 stop_debugger_thread ();
1031 breakpoints_cleanup ();
1035 mono_mutex_destroy (&debugger_thread_exited_mutex);
1036 mono_cond_destroy (&debugger_thread_exited_cond);
1043 #ifndef DISABLE_SOCKET_TRANSPORT
1048 * recv() + handle incomplete reads and EINTR
1051 socket_transport_recv (void *buf, int len)
1060 res = recv (fd, (char *) buf + total, len - total, flags);
1063 if (agent_config.keepalive && res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1064 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1067 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1072 #define HAVE_GETADDRINFO 1
1076 set_keepalive (void)
1081 if (!agent_config.keepalive)
1084 tv.tv_sec = agent_config.keepalive / 1000;
1085 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1087 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1088 g_assert (result >= 0);
1092 socket_transport_accept (int socket_fd)
1094 conn_fd = accept (socket_fd, NULL, NULL);
1095 if (conn_fd == -1) {
1096 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1098 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1105 socket_transport_send (void *data, int len)
1110 res = send (conn_fd, data, len, 0);
1111 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1119 * socket_transport_connect:
1121 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1124 socket_transport_connect (const char *address)
1126 #ifdef HAVE_GETADDRINFO
1127 struct addrinfo hints;
1128 struct addrinfo *result, *rp;
1130 struct hostent *result;
1132 int sfd = -1, s, res;
1133 char port_string [128];
1137 if (agent_config.address) {
1138 res = parse_address (agent_config.address, &host, &port);
1139 g_assert (res == 0);
1149 sprintf (port_string, "%d", port);
1151 mono_network_init ();
1153 /* Obtain address(es) matching host/port */
1154 #ifdef HAVE_GETADDRINFO
1155 memset (&hints, 0, sizeof (struct addrinfo));
1156 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1157 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1159 hints.ai_protocol = 0; /* Any protocol */
1161 s = getaddrinfo (host, port_string, &hints, &result);
1163 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1167 /* The PS3 doesn't even have _r or hstrerror () */
1168 result = gethostbyname (host);
1170 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1175 if (agent_config.server) {
1176 #ifdef HAVE_GETADDRINFO
1177 /* Wait for a connection */
1179 struct sockaddr_in addr;
1182 /* No address, generate one */
1183 sfd = socket (AF_INET, SOCK_STREAM, 0);
1186 /* This will bind the socket to a random port */
1187 res = listen (sfd, 16);
1189 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1194 addrlen = sizeof (addr);
1195 memset (&addr, 0, sizeof (addr));
1196 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1197 g_assert (res == 0);
1199 host = (char*)"127.0.0.1";
1200 port = ntohs (addr.sin_port);
1202 /* Emit the address to stdout */
1203 /* FIXME: Should print another interface, not localhost */
1204 printf ("%s:%d\n", host, port);
1206 /* Listen on the provided address */
1207 for (rp = result; rp != NULL; rp = rp->ai_next) {
1210 sfd = socket (rp->ai_family, rp->ai_socktype,
1215 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1218 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1222 res = listen (sfd, 16);
1231 * this function is not present on win2000 which we still support, and the
1232 * workaround described here:
1233 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1234 * only works with MSVC.
1236 #ifdef HAVE_GETADDRINFO
1237 freeaddrinfo (result);
1242 if (agent_config.defer)
1245 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1247 if (agent_config.timeout) {
1252 tv.tv_usec = agent_config.timeout * 1000;
1254 FD_SET (sfd, &readfds);
1255 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1257 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1262 conn_fd = socket_transport_accept (sfd);
1266 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1269 #endif /* HAVE_GETADDRINFO */
1271 /* Connect to the specified address */
1272 #ifdef HAVE_GETADDRINFO
1273 /* FIXME: Respect the timeout */
1274 for (rp = result; rp != NULL; rp = rp->ai_next) {
1275 sfd = socket (rp->ai_family, rp->ai_socktype,
1280 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1281 break; /* Success */
1287 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1291 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1293 g_assert_not_reached ();
1294 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1296 g_assert_not_reached ();
1302 /* See the comment above */
1303 #ifdef HAVE_GETADDRINFO
1304 freeaddrinfo (result);
1309 disconnected = !transport_handshake ();
1315 socket_transport_close1 (void)
1317 /* This will interrupt the agent thread */
1318 /* Close the read part only so it can still send back replies */
1319 /* Also shut down the connection listener so that we can exit normally */
1321 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1322 shutdown (conn_fd, SD_BOTH);
1323 shutdown (listen_fd, SD_BOTH);
1324 closesocket (listen_fd);
1326 shutdown (conn_fd, SHUT_RD);
1327 shutdown (listen_fd, SHUT_RDWR);
1333 socket_transport_close2 (void)
1336 shutdown (conn_fd, SD_BOTH);
1338 shutdown (conn_fd, SHUT_RDWR);
1343 register_socket_transport (void)
1345 DebuggerTransport trans;
1347 trans.name = "dt_socket";
1348 trans.connect = socket_transport_connect;
1349 trans.close1 = socket_transport_close1;
1350 trans.close2 = socket_transport_close2;
1351 trans.send = socket_transport_send;
1352 trans.recv = socket_transport_recv;
1354 register_transport (&trans);
1357 #endif /* DISABLE_SOCKET_TRANSPORT */
1363 #define MAX_TRANSPORTS 16
1365 static DebuggerTransport *transport;
1367 static DebuggerTransport transports [MAX_TRANSPORTS];
1368 static int ntransports;
1371 register_transport (DebuggerTransport *trans)
1373 g_assert (ntransports < MAX_TRANSPORTS);
1375 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1380 transport_init (void)
1384 #ifndef DISABLE_SOCKET_TRANSPORT
1385 register_socket_transport ();
1388 for (i = 0; i < ntransports; ++i) {
1389 if (!strcmp (agent_config.transport, transports [i].name))
1392 if (i == ntransports) {
1393 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1394 for (i = 0; i < ntransports; ++i)
1395 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1396 fprintf (stderr, "\n");
1399 transport = &transports [i];
1403 transport_connect (const char *address)
1405 transport->connect (address);
1409 transport_close1 (void)
1411 transport->close1 ();
1415 transport_close2 (void)
1417 transport->close2 ();
1421 transport_send (void *buf, int len)
1423 return transport->send (buf, len);
1427 transport_recv (void *buf, int len)
1429 return transport->recv (buf, len);
1433 transport_handshake (void)
1435 char handshake_msg [128];
1439 /* Write handshake message */
1440 sprintf (handshake_msg, "DWP-Handshake");
1442 res = transport_send (handshake_msg, strlen (handshake_msg));
1443 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1444 g_assert (res != -1);
1447 res = transport_recv (buf, strlen (handshake_msg));
1448 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1449 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1454 * To support older clients, the client sends its protocol version after connecting
1455 * using a command. Until that is received, default to our protocol version.
1457 major_version = MAJOR_VERSION;
1458 minor_version = MINOR_VERSION;
1459 protocol_version_set = FALSE;
1461 #ifndef DISABLE_SOCKET_TRANSPORT
1462 // FIXME: Move this somewhere else
1464 * Set TCP_NODELAY on the socket so the client receives events/command
1465 * results immediately.
1469 int result = setsockopt (conn_fd,
1474 g_assert (result >= 0);
1484 stop_debugger_thread (void)
1489 transport_close1 ();
1492 * Wait for the thread to exit.
1494 * If we continue with the shutdown without waiting for it, then the client might
1495 * not receive an answer to its last command like a resume.
1496 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1499 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1500 if (GetCurrentThreadId () != debugger_thread_id) {
1502 mono_mutex_lock (&debugger_thread_exited_mutex);
1503 if (!debugger_thread_exited) {
1505 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1506 mono_mutex_unlock (&debugger_thread_exited_mutex);
1508 mono_mutex_lock (&debugger_thread_exited_mutex);
1511 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1514 mono_mutex_unlock (&debugger_thread_exited_mutex);
1515 } while (!debugger_thread_exited);
1518 transport_close2 ();
1522 start_debugger_thread (void)
1526 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1527 g_assert (debugger_thread_handle);
1531 * Functions to decode protocol data
1535 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1538 g_assert (*endbuf <= limit);
1543 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1546 g_assert (*endbuf <= limit);
1548 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1551 static inline gint64
1552 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1554 guint32 high = decode_int (buf, &buf, limit);
1555 guint32 low = decode_int (buf, &buf, limit);
1559 return ((((guint64)high) << 32) | ((guint64)low));
1563 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1565 return decode_int (buf, endbuf, limit);
1569 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1571 int len = decode_int (buf, &buf, limit);
1579 s = g_malloc (len + 1);
1582 memcpy (s, buf, len);
1591 * Functions to encode protocol data
1595 guint8 *buf, *p, *end;
1599 buffer_init (Buffer *buf, int size)
1601 buf->buf = g_malloc (size);
1603 buf->end = buf->buf + size;
1607 buffer_make_room (Buffer *buf, int size)
1609 if (buf->end - buf->p < size) {
1610 int new_size = buf->end - buf->buf + size + 32;
1611 guint8 *p = g_realloc (buf->buf, new_size);
1612 size = buf->p - buf->buf;
1615 buf->end = buf->buf + new_size;
1620 buffer_add_byte (Buffer *buf, guint8 val)
1622 buffer_make_room (buf, 1);
1628 buffer_add_short (Buffer *buf, guint32 val)
1630 buffer_make_room (buf, 2);
1631 buf->p [0] = (val >> 8) & 0xff;
1632 buf->p [1] = (val >> 0) & 0xff;
1637 buffer_add_int (Buffer *buf, guint32 val)
1639 buffer_make_room (buf, 4);
1640 buf->p [0] = (val >> 24) & 0xff;
1641 buf->p [1] = (val >> 16) & 0xff;
1642 buf->p [2] = (val >> 8) & 0xff;
1643 buf->p [3] = (val >> 0) & 0xff;
1648 buffer_add_long (Buffer *buf, guint64 l)
1650 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1651 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1655 buffer_add_id (Buffer *buf, int id)
1657 buffer_add_int (buf, (guint64)id);
1661 buffer_add_data (Buffer *buf, guint8 *data, int len)
1663 buffer_make_room (buf, len);
1664 memcpy (buf->p, data, len);
1669 buffer_add_string (Buffer *buf, const char *str)
1674 buffer_add_int (buf, 0);
1677 buffer_add_int (buf, len);
1678 buffer_add_data (buf, (guint8*)str, len);
1683 buffer_free (Buffer *buf)
1689 send_packet (int command_set, int command, Buffer *data)
1695 id = InterlockedIncrement (&packet_id);
1697 len = data->p - data->buf + 11;
1698 buffer_init (&buf, len);
1699 buffer_add_int (&buf, len);
1700 buffer_add_int (&buf, id);
1701 buffer_add_byte (&buf, 0); /* flags */
1702 buffer_add_byte (&buf, command_set);
1703 buffer_add_byte (&buf, command);
1704 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1706 res = transport_send (buf.buf, len);
1714 send_reply_packet (int id, int error, Buffer *data)
1720 len = data->p - data->buf + 11;
1721 buffer_init (&buf, len);
1722 buffer_add_int (&buf, len);
1723 buffer_add_int (&buf, id);
1724 buffer_add_byte (&buf, 0x80); /* flags */
1725 buffer_add_byte (&buf, (error >> 8) & 0xff);
1726 buffer_add_byte (&buf, error);
1727 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1729 res = transport_send (buf.buf, len);
1741 * Represents an object accessible by the debugger client.
1744 /* Unique id used in the wire protocol to refer to objects */
1747 * A weakref gc handle pointing to the object. The gc handle is used to
1748 * detect if the object was garbage collected.
1753 /* Maps objid -> ObjRef */
1754 static GHashTable *objrefs;
1757 free_objref (gpointer value)
1761 mono_gchandle_free (o->handle);
1769 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1773 objrefs_cleanup (void)
1775 g_hash_table_destroy (objrefs);
1779 static GHashTable *obj_to_objref;
1782 * Return an ObjRef for OBJ.
1785 get_objref (MonoObject *obj)
1788 GSList *reflist = NULL, *l;
1794 mono_loader_lock ();
1797 obj_to_objref = g_hash_table_new (NULL, NULL);
1799 /* FIXME: The tables can grow indefinitely */
1801 if (mono_gc_is_moving ()) {
1803 * Objects can move, so use a hash table mapping hash codes to lists of
1804 * ObjRef structures.
1806 hash = mono_object_hash (obj);
1808 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1809 for (l = reflist; l; l = l->next) {
1811 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1812 mono_loader_unlock ();
1817 /* Use a hash table with masked pointers to internalize object references */
1818 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1819 /* ref might refer to a different object with the same addr which was GCd */
1820 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1821 mono_loader_unlock ();
1826 ref = g_new0 (ObjRef, 1);
1827 ref->id = InterlockedIncrement (&objref_id);
1828 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1830 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1832 if (mono_gc_is_moving ()) {
1833 reflist = g_slist_append (reflist, ref);
1834 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1836 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1839 mono_loader_unlock ();
1845 get_objid (MonoObject *obj)
1847 return get_objref (obj)->id;
1851 * Set OBJ to the object identified by OBJID.
1852 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1856 get_object_allow_null (int objid, MonoObject **obj)
1866 return ERR_INVALID_OBJECT;
1868 mono_loader_lock ();
1870 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1873 *obj = mono_gchandle_get_target (ref->handle);
1874 mono_loader_unlock ();
1876 return ERR_INVALID_OBJECT;
1879 mono_loader_unlock ();
1880 return ERR_INVALID_OBJECT;
1885 get_object (int objid, MonoObject **obj)
1887 int err = get_object_allow_null (objid, obj);
1892 return ERR_INVALID_OBJECT;
1897 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1899 return decode_id (buf, endbuf, limit);
1903 buffer_add_objid (Buffer *buf, MonoObject *o)
1905 buffer_add_id (buf, get_objid (o));
1924 * Represents a runtime structure accessible to the debugger client
1927 /* Unique id used in the wire protocol */
1929 /* Domain of the runtime structure, NULL if the domain was unloaded */
1936 MonoAssembly *assembly;
1937 MonoClassField *field;
1939 MonoProperty *property;
1944 /* Maps runtime structure -> Id */
1945 GHashTable *val_to_id [ID_NUM];
1946 /* Classes whose class load event has been sent */
1947 GHashTable *loaded_classes;
1948 /* Maps MonoClass->GPtrArray of file names */
1949 GHashTable *source_files;
1950 /* Maps source file basename -> GSList of classes */
1951 GHashTable *source_file_to_class;
1952 /* Same with ignore-case */
1953 GHashTable *source_file_to_class_ignorecase;
1957 static GPtrArray *ids [ID_NUM];
1964 for (i = 0; i < ID_NUM; ++i)
1965 ids [i] = g_ptr_array_new ();
1973 for (i = 0; i < ID_NUM; ++i) {
1975 for (j = 0; j < ids [i]->len; ++j)
1976 g_free (g_ptr_array_index (ids [i], j));
1977 g_ptr_array_free (ids [i], TRUE);
1984 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1986 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1988 GHashTableIter iter;
1989 GPtrArray *file_names;
1994 for (i = 0; i < ID_NUM; ++i)
1995 if (info->val_to_id [i])
1996 g_hash_table_destroy (info->val_to_id [i]);
1997 g_hash_table_destroy (info->loaded_classes);
1999 g_hash_table_iter_init (&iter, info->source_files);
2000 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2001 for (i = 0; i < file_names->len; ++i)
2002 g_free (g_ptr_array_index (file_names, i));
2003 g_ptr_array_free (file_names, TRUE);
2006 g_hash_table_iter_init (&iter, info->source_file_to_class);
2007 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2012 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2013 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2021 domain_jit_info (domain)->agent_info = NULL;
2023 /* Clear ids referencing structures in the domain */
2024 for (i = 0; i < ID_NUM; ++i) {
2026 for (j = 0; j < ids [i]->len; ++j) {
2027 Id *id = g_ptr_array_index (ids [i], j);
2028 if (id->domain == domain)
2034 mono_loader_lock ();
2035 g_hash_table_remove (domains, domain);
2036 mono_loader_unlock ();
2039 static AgentDomainInfo*
2040 get_agent_domain_info (MonoDomain *domain)
2042 AgentDomainInfo *info = NULL;
2044 mono_domain_lock (domain);
2046 info = domain_jit_info (domain)->agent_info;
2048 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2049 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2050 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2051 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2052 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2055 mono_domain_unlock (domain);
2061 get_id (MonoDomain *domain, IdType type, gpointer val)
2064 AgentDomainInfo *info;
2069 mono_loader_lock ();
2071 mono_domain_lock (domain);
2073 info = get_agent_domain_info (domain);
2075 if (info->val_to_id [type] == NULL)
2076 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2078 id = g_hash_table_lookup (info->val_to_id [type], val);
2080 mono_domain_unlock (domain);
2081 mono_loader_unlock ();
2085 id = g_new0 (Id, 1);
2087 id->id = ids [type]->len + 1;
2088 id->domain = domain;
2091 g_hash_table_insert (info->val_to_id [type], val, id);
2093 mono_domain_unlock (domain);
2095 g_ptr_array_add (ids [type], id);
2097 mono_loader_unlock ();
2102 static inline gpointer
2103 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2107 int id = decode_id (buf, endbuf, limit);
2116 // FIXME: error handling
2117 mono_loader_lock ();
2118 g_assert (id > 0 && id <= ids [type]->len);
2120 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2121 mono_loader_unlock ();
2123 if (res->domain == NULL) {
2124 *err = ERR_UNLOADED;
2129 *domain = res->domain;
2131 return res->data.val;
2135 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2137 buffer_add_id (buf, get_id (domain, type, val));
2140 static inline MonoClass*
2141 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2143 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2146 static inline MonoAssembly*
2147 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2149 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2152 static inline MonoImage*
2153 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2155 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2158 static inline MonoMethod*
2159 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2161 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2164 static inline MonoClassField*
2165 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2167 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2170 static inline MonoDomain*
2171 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2173 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2176 static inline MonoProperty*
2177 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2179 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2183 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2185 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2189 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2191 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2195 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2197 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2201 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2203 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2207 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2209 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2213 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2215 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2219 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2221 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2224 static void invoke_method (void);
2231 * save_thread_context:
2233 * Set CTX as the current threads context which is used for computing stack traces.
2234 * This function is signal-safe.
2237 save_thread_context (MonoContext *ctx)
2239 DebuggerTlsData *tls;
2241 tls = mono_native_tls_get_value (debugger_tls_id);
2245 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2247 mono_thread_state_init_from_current (&tls->context);
2250 /* The number of times the runtime is suspended */
2251 static gint32 suspend_count;
2253 /* Number of threads suspended */
2255 * If this is equal to the size of thread_to_tls, the runtime is considered
2258 static gint32 threads_suspend_count;
2260 static mono_mutex_t suspend_mutex;
2262 /* Cond variable used to wait for suspend_count becoming 0 */
2263 static mono_cond_t suspend_cond;
2265 /* Semaphore used to wait for a thread becoming suspended */
2266 static MonoSemType suspend_sem;
2271 mono_mutex_init (&suspend_mutex, NULL);
2272 mono_cond_init (&suspend_cond, NULL);
2273 MONO_SEM_INIT (&suspend_sem, 0);
2278 StackFrameInfo last_frame;
2279 gboolean last_frame_set;
2282 } GetLastFrameUserData;
2285 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2287 GetLastFrameUserData *data = user_data;
2289 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2292 if (!data->last_frame_set) {
2293 /* Store the last frame */
2294 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2295 data->last_frame_set = TRUE;
2298 /* Store the context/lmf for the frame above the last frame */
2299 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2300 data->lmf = info->lmf;
2308 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2309 * INFO is set, process the thread described by INFO.
2310 * This should be signal safe.
2313 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2317 MonoNativeThreadId tid;
2320 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2321 * guarantee the signal handler will be called that many times. Instead of tracking
2322 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2323 * has been requested that hasn't been handled yet, otherwise we can have threads
2324 * refuse to die when VM_EXIT is called
2326 #if defined(__APPLE__)
2327 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2331 * We use interrupt_count to determine whenever this interrupt should be processed
2332 * by us or the normal interrupt processing code in the signal handler.
2333 * There is no race here with notify_thread (), since the signal is sent after
2334 * incrementing interrupt_count.
2336 if (tls->interrupt_count == 0)
2339 InterlockedDecrement (&tls->interrupt_count);
2343 ip = mono_arch_ip_from_context (sigctx);
2345 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2350 tid = mono_thread_info_get_tid (info);
2352 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2354 // FIXME: Races when the thread leaves managed code before hitting a single step
2358 /* Running managed code, will be suspended by the single step code */
2359 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2363 * Running native code, will be suspended when it returns to/enters
2364 * managed code. Treat it as already suspended.
2365 * This might interrupt the code in process_single_step_inner (), we use the
2366 * tls->suspending flag to avoid races when that happens.
2368 if (!tls->suspended && !tls->suspending) {
2370 GetLastFrameUserData data;
2372 // FIXME: printf is not signal safe, but this is only used during
2373 // debugger debugging
2375 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2376 //save_thread_context (&ctx);
2379 /* Already terminated */
2382 tls->context.valid = FALSE;
2385 * We are in a difficult position: we want to be able to provide stack
2386 * traces for this thread, but we can't use the current ctx+lmf, since
2387 * the thread is still running, so it might return to managed code,
2388 * making these invalid.
2389 * So we start a stack walk and save the first frame, along with the
2390 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2391 * suspended when it returns to managed code, so the parent's ctx should
2394 data.last_frame_set = FALSE;
2396 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2398 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2399 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2400 * since we are not in a JITted method.
2402 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2404 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2406 if (data.last_frame_set) {
2407 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2408 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2410 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2413 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2414 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2415 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2417 /* No managed frames */
2418 tls->async_state.valid = FALSE;
2420 mono_memory_barrier ();
2422 tls->suspended = TRUE;
2423 MONO_SEM_POST (&suspend_sem);
2430 * mono_debugger_agent_thread_interrupt:
2432 * Called by the abort signal handler.
2433 * Should be signal safe.
2436 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2438 DebuggerTlsData *tls;
2443 tls = mono_native_tls_get_value (debugger_tls_id);
2447 return thread_interrupt (tls, NULL, sigctx, ji);
2451 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2454 mono_debugger_agent_thread_interrupt (NULL, NULL);
2456 #endif /* HOST_WIN32 */
2459 * reset_native_thread_suspend_state:
2461 * Reset the suspended flag and state on native threads
2464 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2466 DebuggerTlsData *tls = value;
2468 if (!tls->really_suspended && tls->suspended) {
2469 tls->suspended = FALSE;
2471 * The thread might still be running if it was executing native code, so the state won't be invalided by
2472 * suspend_current ().
2474 tls->context.valid = FALSE;
2475 tls->async_state.valid = FALSE;
2476 invalidate_frames (tls);
2483 * Notify a thread that it needs to suspend.
2486 notify_thread (gpointer key, gpointer value, gpointer user_data)
2488 MonoInternalThread *thread = key;
2489 DebuggerTlsData *tls = value;
2490 gsize tid = thread->tid;
2493 if (GetCurrentThreadId () == tid || tls->terminated)
2496 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2499 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2500 * guarantee the signal handler will be called that many times. Instead of tracking
2501 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2502 * has been requested that hasn't been handled yet, otherwise we can have threads
2503 * refuse to die when VM_EXIT is called
2505 #if defined(__APPLE__)
2506 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2510 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2511 * of things like breaking waits etc. which we don't want.
2513 InterlockedIncrement (&tls->interrupt_count);
2516 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2518 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2520 if (mono_thread_info_new_interrupt_enabled ()) {
2521 MonoThreadInfo *info;
2524 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2527 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2529 thread_interrupt (tls, info, NULL, ji);
2531 mono_thread_info_resume (mono_thread_info_get_tid (info));
2533 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2536 * Attached thread which died without detaching.
2538 tls->terminated = TRUE;
2544 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2546 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2549 if (mono_loader_lock_is_owned_by_self ()) {
2551 * Shortcut for the check in suspend_current (). This speeds up processing
2552 * when executing long running code inside the loader lock, i.e. assembly load
2558 if (debugger_thread_id == GetCurrentThreadId ())
2561 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2562 if (suspend_count - tls->resume_count > 0)
2563 tls->suspending = TRUE;
2565 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2567 if (suspend_count - tls->resume_count == 0) {
2569 * We are executing a single threaded invoke but the single step for
2570 * suspending is still active.
2571 * FIXME: This slows down single threaded invokes.
2573 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2577 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2579 /* Can't suspend in these methods */
2580 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2583 save_thread_context (ctx);
2591 * Increase the suspend count of the VM. While the suspend count is greater
2592 * than 0, runtime threads are suspended at certain points during execution.
2597 mono_loader_lock ();
2599 mono_mutex_lock (&suspend_mutex);
2603 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2605 if (suspend_count == 1) {
2606 // FIXME: Is it safe to call this inside the lock ?
2607 start_single_stepping ();
2608 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2611 mono_mutex_unlock (&suspend_mutex);
2613 mono_loader_unlock ();
2619 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2627 g_assert (debugger_thread_id == GetCurrentThreadId ());
2629 mono_loader_lock ();
2631 mono_mutex_lock (&suspend_mutex);
2633 g_assert (suspend_count > 0);
2636 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2638 if (suspend_count == 0) {
2639 // FIXME: Is it safe to call this inside the lock ?
2640 stop_single_stepping ();
2641 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2644 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2645 err = mono_cond_broadcast (&suspend_cond);
2646 g_assert (err == 0);
2648 mono_mutex_unlock (&suspend_mutex);
2649 //g_assert (err == 0);
2651 mono_loader_unlock ();
2657 * Resume just one thread.
2660 resume_thread (MonoInternalThread *thread)
2663 DebuggerTlsData *tls;
2665 g_assert (debugger_thread_id == GetCurrentThreadId ());
2667 mono_loader_lock ();
2669 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2672 mono_mutex_lock (&suspend_mutex);
2674 g_assert (suspend_count > 0);
2676 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2678 tls->resume_count += suspend_count;
2681 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2682 * but only the one whose resume_count field is > 0 will be resumed.
2684 err = mono_cond_broadcast (&suspend_cond);
2685 g_assert (err == 0);
2687 mono_mutex_unlock (&suspend_mutex);
2688 //g_assert (err == 0);
2690 mono_loader_unlock ();
2694 invalidate_frames (DebuggerTlsData *tls)
2699 tls = mono_native_tls_get_value (debugger_tls_id);
2702 for (i = 0; i < tls->frame_count; ++i) {
2703 if (tls->frames [i]->jit)
2704 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2705 g_free (tls->frames [i]);
2707 g_free (tls->frames);
2708 tls->frame_count = 0;
2715 * Suspend the current thread until the runtime is resumed. If the thread has a
2716 * pending invoke, then the invoke is executed before this function returns.
2719 suspend_current (void)
2722 DebuggerTlsData *tls;
2724 g_assert (debugger_thread_id != GetCurrentThreadId ());
2726 if (mono_loader_lock_is_owned_by_self ()) {
2728 * If we own the loader mutex, can't suspend until we release it, since the
2729 * whole runtime can deadlock otherwise.
2734 tls = mono_native_tls_get_value (debugger_tls_id);
2737 mono_mutex_lock (&suspend_mutex);
2739 tls->suspending = FALSE;
2740 tls->really_suspended = TRUE;
2742 if (!tls->suspended) {
2743 tls->suspended = TRUE;
2744 MONO_SEM_POST (&suspend_sem);
2747 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2749 while (suspend_count - tls->resume_count > 0) {
2751 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2753 mono_mutex_unlock (&suspend_mutex);
2755 mono_mutex_lock (&suspend_mutex);
2761 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2762 g_assert (err == 0);
2766 tls->suspended = FALSE;
2767 tls->really_suspended = FALSE;
2769 threads_suspend_count --;
2771 mono_mutex_unlock (&suspend_mutex);
2773 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2775 if (tls->pending_invoke) {
2776 /* Save the original context */
2777 tls->pending_invoke->has_ctx = TRUE;
2778 tls->pending_invoke->ctx = tls->context.ctx;
2783 /* The frame info becomes invalid after a resume */
2784 tls->context.valid = FALSE;
2785 tls->async_state.valid = FALSE;
2786 invalidate_frames (tls);
2790 count_thread (gpointer key, gpointer value, gpointer user_data)
2792 DebuggerTlsData *tls = value;
2794 if (!tls->suspended && !tls->terminated)
2795 *(int*)user_data = *(int*)user_data + 1;
2799 count_threads_to_wait_for (void)
2803 mono_loader_lock ();
2804 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2805 mono_loader_unlock ();
2813 * Wait until the runtime is completely suspended.
2816 wait_for_suspend (void)
2818 int nthreads, nwait, err;
2819 gboolean waited = FALSE;
2821 // FIXME: Threads starting/stopping ?
2822 mono_loader_lock ();
2823 nthreads = mono_g_hash_table_size (thread_to_tls);
2824 mono_loader_unlock ();
2827 nwait = count_threads_to_wait_for ();
2829 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2830 err = MONO_SEM_WAIT (&suspend_sem);
2831 g_assert (err == 0);
2839 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2845 * Return whenever the runtime is suspended.
2850 return count_threads_to_wait_for () == 0;
2853 static MonoSeqPointInfo*
2854 get_seq_points (MonoDomain *domain, MonoMethod *method)
2856 MonoSeqPointInfo *seq_points;
2858 mono_domain_lock (domain);
2859 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2860 if (!seq_points && method->is_inflated) {
2861 /* generic sharing + aot */
2862 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2864 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2866 mono_domain_unlock (domain);
2871 static MonoSeqPointInfo*
2872 find_seq_points (MonoDomain *domain, MonoMethod *method)
2874 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2877 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2878 g_assert (seq_points);
2884 * find_next_seq_point_for_native_offset:
2886 * Find the first sequence point after NATIVE_OFFSET.
2889 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2891 MonoSeqPointInfo *seq_points;
2894 seq_points = find_seq_points (domain, method);
2898 for (i = 0; i < seq_points->len; ++i) {
2899 if (seq_points->seq_points [i].native_offset >= native_offset)
2900 return &seq_points->seq_points [i];
2907 * find_prev_seq_point_for_native_offset:
2909 * Find the first sequence point before NATIVE_OFFSET.
2912 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2914 MonoSeqPointInfo *seq_points;
2917 seq_points = find_seq_points (domain, method);
2921 for (i = seq_points->len - 1; i >= 0; --i) {
2922 if (seq_points->seq_points [i].native_offset <= native_offset)
2923 return &seq_points->seq_points [i];
2932 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2933 * should be the location of a sequence point.
2935 static G_GNUC_UNUSED SeqPoint*
2936 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2938 MonoSeqPointInfo *seq_points;
2943 seq_points = get_seq_points (domain, method);
2948 for (i = 0; i < seq_points->len; ++i) {
2949 if (seq_points->seq_points [i].il_offset == il_offset)
2950 return &seq_points->seq_points [i];
2957 DebuggerTlsData *tls;
2959 } ComputeFramesUserData;
2962 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2964 ComputeFramesUserData *ud = user_data;
2966 MonoMethod *method, *actual_method, *api_method;
2970 if (info->type != FRAME_TYPE_MANAGED) {
2971 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2972 /* Mark the last frame as an invoke frame */
2974 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2980 method = info->ji->method;
2982 method = info->method;
2983 actual_method = info->actual_method;
2984 api_method = method;
2989 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
2992 if (info->il_offset == -1) {
2993 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
2994 if (ud->frames == NULL) {
2995 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
2997 info->il_offset = sp->il_offset;
2999 if (info->il_offset == -1)
3000 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3003 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));
3005 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3006 if (!CHECK_PROTOCOL_VERSION (2, 17))
3007 /* Older clients can't handle this flag */
3009 api_method = mono_marshal_method_from_wrapper (method);
3012 actual_method = api_method;
3013 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3016 frame = g_new0 (StackFrame, 1);
3017 frame->method = method;
3018 frame->actual_method = actual_method;
3019 frame->api_method = api_method;
3020 frame->il_offset = info->il_offset;
3021 frame->native_offset = info->native_offset;
3022 frame->flags = flags;
3023 frame->ji = info->ji;
3024 if (info->reg_locations)
3025 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3028 frame->has_ctx = TRUE;
3030 frame->domain = info->domain;
3032 ud->frames = g_slist_append (ud->frames, frame);
3038 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3040 ComputeFramesUserData *ud = user_data;
3043 * 'tls->filter_ctx' is the location of the throw site.
3045 * mono_walk_stack() will never actually hit the throw site, but unwind
3046 * directly from the filter to the call site; we abort stack unwinding here
3047 * once this happens and resume from the throw site.
3050 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3053 return process_frame (info, ctx, user_data);
3057 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3059 ComputeFramesUserData user_data;
3061 int i, findex, new_frame_count;
3062 StackFrame **new_frames, *f;
3063 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3065 // FIXME: Locking on tls
3066 if (tls->frames && tls->frames_up_to_date)
3069 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3071 user_data.tls = tls;
3072 user_data.frames = NULL;
3073 if (tls->terminated) {
3074 tls->frame_count = 0;
3076 } if (!tls->really_suspended && tls->async_state.valid) {
3077 /* Have to use the state saved by the signal handler */
3078 process_frame (&tls->async_last_frame, NULL, &user_data);
3079 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3080 } else if (tls->filter_state.valid) {
3082 * We are inside an exception filter.
3084 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3086 if (tls->context.valid)
3087 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3089 * After that, we resume unwinding from the location where the exception has been thrown.
3091 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3092 } else if (tls->context.valid) {
3093 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3096 tls->frame_count = 0;
3100 new_frame_count = g_slist_length (user_data.frames);
3101 new_frames = g_new0 (StackFrame*, new_frame_count);
3103 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3107 * Reuse the id for already existing stack frames, so invokes don't invalidate
3108 * the still valid stack frames.
3110 for (i = 0; i < tls->frame_count; ++i) {
3111 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3112 f->id = tls->frames [i]->id;
3117 if (i >= tls->frame_count)
3118 f->id = InterlockedIncrement (&frame_id);
3120 new_frames [findex ++] = f;
3123 g_slist_free (user_data.frames);
3125 invalidate_frames (tls);
3127 tls->frames = new_frames;
3128 tls->frame_count = new_frame_count;
3129 tls->frames_up_to_date = TRUE;
3133 * GHFunc to emit an appdomain creation event
3134 * @param key Don't care
3135 * @param value A loaded appdomain
3136 * @param user_data Don't care
3139 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3141 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3142 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3146 * GHFunc to emit a thread start event
3147 * @param key A thread id
3148 * @param value A thread object
3149 * @param user_data Don't care
3152 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3154 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3155 process_profiler_event (EVENT_KIND_THREAD_START, value);
3159 * GFunc to emit an assembly load event
3160 * @param value A loaded assembly
3161 * @param user_data Don't care
3164 emit_assembly_load (gpointer value, gpointer user_data)
3166 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3170 * GFunc to emit a type load event
3171 * @param value A loaded type
3172 * @param user_data Don't care
3175 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3177 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3181 strdup_tolower (char *s)
3186 for (p = s2; *p; ++p)
3196 * create_event_list:
3198 * Return a list of event request ids matching EVENT, starting from REQS, which
3199 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3201 * We return request ids, instead of requests, to simplify threading, since
3202 * requests could be deleted anytime when the loader lock is not held.
3203 * LOCKING: Assumes the loader lock is held.
3206 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3209 GSList *events = NULL;
3211 *suspend_policy = SUSPEND_POLICY_NONE;
3214 reqs = event_requests;
3219 for (i = 0; i < reqs->len; ++i) {
3220 EventRequest *req = g_ptr_array_index (reqs, i);
3221 if (req->event_kind == event) {
3222 gboolean filtered = FALSE;
3225 for (j = 0; j < req->nmodifiers; ++j) {
3226 Modifier *mod = &req->modifiers [j];
3228 if (mod->kind == MOD_KIND_COUNT) {
3230 if (mod->data.count > 0) {
3231 if (mod->data.count > 0) {
3233 if (mod->data.count == 0)
3237 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3238 if (mod->data.thread != mono_thread_internal_current ())
3240 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3241 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3243 if (ei->caught && !mod->caught)
3245 if (!ei->caught && !mod->uncaught)
3247 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3249 gboolean found = FALSE;
3250 MonoAssembly **assemblies = mod->data.assemblies;
3253 for (k = 0; assemblies [k]; ++k)
3254 if (assemblies [k] == ji->method->klass->image->assembly)
3259 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3260 gpointer iter = NULL;
3262 MonoDebugSourceInfo *sinfo;
3263 char *source_file, *s;
3264 gboolean found = FALSE;
3266 GPtrArray *source_file_list;
3268 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3269 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3272 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL);
3273 for (i = 0; i < source_file_list->len; ++i) {
3274 sinfo = g_ptr_array_index (source_file_list, i);
3276 * Do a case-insesitive match by converting the file name to
3279 s = strdup_tolower (sinfo->source_file);
3280 if (g_hash_table_lookup (mod->data.source_files, s))
3284 g_ptr_array_free (source_file_list, TRUE);
3289 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3292 s = mono_type_full_name (&ei->klass->byval_arg);
3293 if (!g_hash_table_lookup (mod->data.type_names, s))
3296 } else if (mod->kind == MOD_KIND_STEP) {
3297 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3298 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3299 !strcmp (ji->method->name, ".cctor"))
3305 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3306 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3311 /* Send a VM START/DEATH event by default */
3312 if (event == EVENT_KIND_VM_START)
3313 events = g_slist_append (events, GINT_TO_POINTER (0));
3314 if (event == EVENT_KIND_VM_DEATH)
3315 events = g_slist_append (events, GINT_TO_POINTER (0));
3320 static G_GNUC_UNUSED const char*
3321 event_to_string (EventKind event)
3324 case EVENT_KIND_VM_START: return "VM_START";
3325 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3326 case EVENT_KIND_THREAD_START: return "THREAD_START";
3327 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3328 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3329 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3330 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3331 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3332 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3333 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3334 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3335 case EVENT_KIND_STEP: return "STEP";
3336 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3337 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3338 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3339 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3340 case EVENT_KIND_USER_LOG: return "USER_LOG";
3342 g_assert_not_reached ();
3349 * Send an event to the client, suspending the vm if needed.
3350 * LOCKING: Since this can suspend the calling thread, no locks should be held
3352 * The EVENTS list is freed by this function.
3355 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3359 MonoDomain *domain = mono_domain_get ();
3360 MonoThread *thread = NULL;
3361 gboolean send_success = FALSE;
3366 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3370 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3371 // FIXME: We miss those events
3372 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3376 if (vm_death_event_sent) {
3377 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3381 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3382 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3387 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3391 if (event == EVENT_KIND_KEEPALIVE)
3392 suspend_policy = SUSPEND_POLICY_NONE;
3397 if (agent_config.defer) {
3398 /* Make sure the thread id is always set when doing deferred debugging */
3399 if (debugger_thread_id == GetCurrentThreadId ()) {
3400 /* Don't suspend on events from the debugger thread */
3401 suspend_policy = SUSPEND_POLICY_NONE;
3402 thread = mono_thread_get_main ();
3404 else thread = mono_thread_current ();
3406 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3407 // FIXME: Send these with a NULL thread, don't suspend the current thread
3412 nevents = g_slist_length (events);
3413 buffer_init (&buf, 128);
3414 buffer_add_byte (&buf, suspend_policy);
3415 buffer_add_int (&buf, nevents);
3417 for (l = events; l; l = l->next) {
3418 buffer_add_byte (&buf, event); // event kind
3419 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3424 thread = mono_thread_current ();
3426 if (event == EVENT_KIND_VM_START && arg != NULL)
3429 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3432 case EVENT_KIND_THREAD_START:
3433 case EVENT_KIND_THREAD_DEATH:
3435 case EVENT_KIND_APPDOMAIN_CREATE:
3436 case EVENT_KIND_APPDOMAIN_UNLOAD:
3437 buffer_add_domainid (&buf, arg);
3439 case EVENT_KIND_METHOD_ENTRY:
3440 case EVENT_KIND_METHOD_EXIT:
3441 buffer_add_methodid (&buf, domain, arg);
3443 case EVENT_KIND_ASSEMBLY_LOAD:
3444 case EVENT_KIND_ASSEMBLY_UNLOAD:
3445 buffer_add_assemblyid (&buf, domain, arg);
3447 case EVENT_KIND_TYPE_LOAD:
3448 buffer_add_typeid (&buf, domain, arg);
3450 case EVENT_KIND_BREAKPOINT:
3451 case EVENT_KIND_STEP:
3452 buffer_add_methodid (&buf, domain, arg);
3453 buffer_add_long (&buf, il_offset);
3455 case EVENT_KIND_VM_START:
3456 buffer_add_domainid (&buf, mono_get_root_domain ());
3458 case EVENT_KIND_VM_DEATH:
3460 case EVENT_KIND_EXCEPTION: {
3461 EventInfo *ei = arg;
3462 buffer_add_objid (&buf, ei->exc);
3465 case EVENT_KIND_USER_BREAK:
3467 case EVENT_KIND_USER_LOG: {
3468 EventInfo *ei = arg;
3469 buffer_add_int (&buf, ei->level);
3470 buffer_add_string (&buf, ei->category ? ei->category : "");
3471 buffer_add_string (&buf, ei->message ? ei->message : "");
3474 case EVENT_KIND_KEEPALIVE:
3475 suspend_policy = SUSPEND_POLICY_NONE;
3478 g_assert_not_reached ();
3482 if (event == EVENT_KIND_VM_START) {
3483 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3484 if (!agent_config.defer)
3485 start_debugger_thread ();
3488 if (event == EVENT_KIND_VM_DEATH) {
3489 vm_death_event_sent = TRUE;
3490 suspend_policy = SUSPEND_POLICY_NONE;
3493 if (mono_runtime_is_shutting_down ())
3494 suspend_policy = SUSPEND_POLICY_NONE;
3496 if (suspend_policy != SUSPEND_POLICY_NONE) {
3498 * Save the thread context and start suspending before sending the packet,
3499 * since we could be receiving the resume request before send_packet ()
3502 save_thread_context (ctx);
3506 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3510 g_slist_free (events);
3513 if (!send_success) {
3514 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3518 if (event == EVENT_KIND_VM_START) {
3519 vm_start_event_sent = TRUE;
3522 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3524 switch (suspend_policy) {
3525 case SUSPEND_POLICY_NONE:
3527 case SUSPEND_POLICY_ALL:
3530 case SUSPEND_POLICY_EVENT_THREAD:
3534 g_assert_not_reached ();
3539 process_profiler_event (EventKind event, gpointer arg)
3543 EventInfo ei, *ei_arg = NULL;
3545 if (event == EVENT_KIND_TYPE_LOAD) {
3550 mono_loader_lock ();
3551 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3552 mono_loader_unlock ();
3554 process_event (event, arg, 0, NULL, events, suspend_policy);
3558 runtime_initialized (MonoProfiler *prof)
3560 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3561 if (agent_config.defer)
3562 start_debugger_thread ();
3566 runtime_shutdown (MonoProfiler *prof)
3568 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3570 mono_debugger_agent_cleanup ();
3574 thread_startup (MonoProfiler *prof, uintptr_t tid)
3576 MonoInternalThread *thread = mono_thread_internal_current ();
3577 MonoInternalThread *old_thread;
3578 DebuggerTlsData *tls;
3580 if (tid == debugger_thread_id)
3583 g_assert (thread->tid == tid);
3585 mono_loader_lock ();
3586 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3587 mono_loader_unlock ();
3589 if (thread == old_thread) {
3591 * For some reason, thread_startup () might be called for the same thread
3592 * multiple times (attach ?).
3594 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3598 * thread_end () might not be called for some threads, and the tid could
3601 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3602 mono_loader_lock ();
3603 mono_g_hash_table_remove (thread_to_tls, old_thread);
3604 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3605 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3606 mono_loader_unlock ();
3610 tls = mono_native_tls_get_value (debugger_tls_id);
3612 // FIXME: Free this somewhere
3613 tls = g_new0 (DebuggerTlsData, 1);
3614 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3615 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3616 tls->thread = thread;
3617 mono_native_tls_set_value (debugger_tls_id, tls);
3619 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3621 mono_loader_lock ();
3622 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3623 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3624 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3625 mono_loader_unlock ();
3627 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3630 * suspend_vm () could have missed this thread, so wait for a resume.
3636 thread_end (MonoProfiler *prof, uintptr_t tid)
3638 MonoInternalThread *thread;
3639 DebuggerTlsData *tls = NULL;
3641 mono_loader_lock ();
3642 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3644 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3645 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3647 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3648 tls->terminated = TRUE;
3649 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3650 MONO_GC_UNREGISTER_ROOT (tls->thread);
3654 mono_loader_unlock ();
3656 /* We might be called for threads started before we registered the start callback */
3658 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3659 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3664 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3666 mono_loader_lock ();
3667 g_hash_table_insert (domains, domain, domain);
3668 mono_loader_unlock ();
3670 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3674 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3676 clear_breakpoints_for_domain (domain);
3678 mono_loader_lock ();
3679 /* Invalidate each thread's frame stack */
3680 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3681 mono_loader_unlock ();
3683 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3687 * invalidate_each_thread:
3689 * A GHFunc to invalidate frames.
3690 * value must be a DebuggerTlsData*
3693 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3695 invalidate_frames (value);
3699 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3701 /* Sent later in jit_end () */
3702 mono_loader_lock ();
3703 g_ptr_array_add (pending_assembly_loads, assembly);
3704 mono_loader_unlock ();
3708 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3710 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3712 clear_event_requests_for_assembly (assembly);
3713 clear_types_for_assembly (assembly);
3717 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3719 #if defined(HOST_WIN32) && !defined(__GNUC__)
3720 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3722 gpointer stackptr = __builtin_frame_address (1);
3724 MonoInternalThread *thread = mono_thread_internal_current ();
3725 DebuggerTlsData *tls;
3727 mono_loader_lock ();
3729 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3730 /* Could be the debugger thread with assembly/type load hooks */
3732 tls->invoke_addr = stackptr;
3734 mono_loader_unlock ();
3738 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3741 #if defined(HOST_WIN32) && !defined(__GNUC__)
3742 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3744 gpointer stackptr = __builtin_frame_address (1);
3747 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3751 * We need to stop single stepping when exiting a runtime invoke, since if it is
3752 * a step out, it may return to native code, and thus never end.
3754 mono_loader_lock ();
3755 ss_invoke_addr = NULL;
3757 for (i = 0; i < event_requests->len; ++i) {
3758 EventRequest *req = g_ptr_array_index (event_requests, i);
3760 if (req->event_kind == EVENT_KIND_STEP) {
3761 ss_destroy (req->info);
3762 g_ptr_array_remove_index_fast (event_requests, i);
3767 mono_loader_unlock ();
3771 send_type_load (MonoClass *klass)
3773 gboolean type_load = FALSE;
3774 MonoDomain *domain = mono_domain_get ();
3775 AgentDomainInfo *info = NULL;
3777 mono_loader_lock ();
3778 mono_domain_lock (domain);
3780 info = get_agent_domain_info (domain);
3782 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3784 g_hash_table_insert (info->loaded_classes, klass, klass);
3787 mono_domain_unlock (domain);
3788 mono_loader_unlock ();
3790 emit_type_load (klass, klass, NULL);
3794 * Emit load events for all types currently loaded in the domain.
3795 * Takes the loader and domain locks.
3796 * user_data is unused.
3799 send_types_for_domain (MonoDomain *domain, void *user_data)
3801 AgentDomainInfo *info = NULL;
3803 mono_loader_lock ();
3804 mono_domain_lock (domain);
3805 info = get_agent_domain_info (domain);
3807 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3808 mono_domain_unlock (domain);
3809 mono_loader_unlock ();
3813 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3816 * We emit type load events when the first method of the type is JITted,
3817 * since the class load profiler callbacks might be called with the
3818 * loader lock held. They could also occur in the debugger thread.
3819 * Same for assembly load events.
3822 MonoAssembly *assembly = NULL;
3824 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3825 mono_loader_lock ();
3826 if (pending_assembly_loads->len > 0) {
3827 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3828 g_ptr_array_remove_index (pending_assembly_loads, 0);
3830 mono_loader_unlock ();
3833 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3839 send_type_load (method->klass);
3842 add_pending_breakpoints (method, jinfo);
3846 * BREAKPOINTS/SINGLE STEPPING
3850 * Contains information about an inserted breakpoint.
3853 long il_offset, native_offset;
3858 } BreakpointInstance;
3861 * Contains generic information about a breakpoint.
3865 * The method where the breakpoint is placed. Can be NULL in which case it
3866 * is inserted into every method. This is used to implement method entry/
3867 * exit events. Can be a generic method definition, in which case the
3868 * breakpoint is inserted into every instance.
3874 * A list of BreakpointInstance structures describing where the breakpoint
3875 * was inserted. There could be more than one because of
3876 * generics/appdomains/method entry/exit.
3878 GPtrArray *children;
3881 /* List of breakpoints */
3882 static GPtrArray *breakpoints;
3883 /* Maps breakpoint locations to the number of breakpoints at that location */
3884 static GHashTable *bp_locs;
3887 breakpoints_init (void)
3889 breakpoints = g_ptr_array_new ();
3890 bp_locs = g_hash_table_new (NULL, NULL);
3894 * insert_breakpoint:
3896 * Insert the breakpoint described by BP into the method described by
3900 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3903 BreakpointInstance *inst;
3904 SeqPoint *sp = NULL;
3907 mono_error_init (error);
3909 for (i = 0; i < seq_points->len; ++i) {
3910 sp = &seq_points->seq_points [i];
3912 if (sp->il_offset == bp->il_offset)
3916 if (i == seq_points->len) {
3918 * The set of IL offsets with seq points doesn't completely match the
3919 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3921 for (i = 0; i < seq_points->len; ++i) {
3922 sp = &seq_points->seq_points [i];
3924 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3929 if (i == seq_points->len) {
3930 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);
3932 for (i = 0; i < seq_points->len; ++i)
3933 printf ("%d\n", seq_points->seq_points [i].il_offset);
3936 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3945 inst = g_new0 (BreakpointInstance, 1);
3947 inst->native_offset = sp->native_offset;
3948 inst->ip = (guint8*)ji->code_start + sp->native_offset;
3950 inst->domain = domain;
3952 mono_loader_lock ();
3954 g_ptr_array_add (bp->children, inst);
3956 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3957 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3958 mono_loader_unlock ();
3961 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3962 mono_arch_set_breakpoint (ji, inst->ip);
3968 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
3972 remove_breakpoint (BreakpointInstance *inst)
3974 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3976 MonoJitInfo *ji = inst->ji;
3977 guint8 *ip = inst->ip;
3979 mono_loader_lock ();
3980 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3981 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3982 mono_loader_unlock ();
3984 g_assert (count > 0);
3987 mono_arch_clear_breakpoint (ji, ip);
3994 static inline gboolean
3995 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4001 if (method == bp->method)
4003 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4006 if (bp->method->is_inflated && method->is_inflated) {
4007 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4008 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4010 /* Open generic methods should match closed generic methods of the same class */
4011 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4012 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4013 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4015 /* FIXME: Handle !mvar */
4016 if (t1->type != MONO_TYPE_MVAR)
4027 * add_pending_breakpoints:
4029 * Insert pending breakpoints into the newly JITted method METHOD.
4032 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4035 MonoSeqPointInfo *seq_points;
4041 domain = mono_domain_get ();
4043 mono_loader_lock ();
4045 for (i = 0; i < breakpoints->len; ++i) {
4046 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4047 gboolean found = FALSE;
4049 if (!bp_matches_method (bp, method))
4052 for (j = 0; j < bp->children->len; ++j) {
4053 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4060 mono_domain_lock (domain);
4061 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4062 if (!seq_points && ji->method->is_inflated)
4063 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4064 mono_domain_unlock (domain);
4066 /* Could be AOT code */
4068 g_assert (seq_points);
4070 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4074 mono_loader_unlock ();
4078 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4084 mono_error_init (error);
4086 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4088 /* Might be AOTed code */
4089 code = mono_aot_get_method (domain, method);
4091 ji = mono_jit_info_table_find (domain, code);
4096 insert_breakpoint (seq_points, domain, ji, bp, error);
4100 clear_breakpoint (MonoBreakpoint *bp);
4105 * Set a breakpoint at IL_OFFSET in METHOD.
4106 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4107 * METHOD can also be a generic method definition, in which case a breakpoint
4108 * is placed in all instances of the method.
4109 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4112 static MonoBreakpoint*
4113 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4116 GHashTableIter iter, iter2;
4119 MonoSeqPointInfo *seq_points;
4122 mono_error_init (error);
4125 // - suspend/resume the vm to prevent code patching problems
4126 // - multiple breakpoints on the same location
4127 // - dynamic methods
4130 bp = g_new0 (MonoBreakpoint, 1);
4131 bp->method = method;
4132 bp->il_offset = il_offset;
4134 bp->children = g_ptr_array_new ();
4136 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));
4138 mono_loader_lock ();
4140 g_hash_table_iter_init (&iter, domains);
4141 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4142 mono_domain_lock (domain);
4144 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4145 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4146 if (bp_matches_method (bp, m))
4147 set_bp_in_method (domain, m, seq_points, bp, error);
4150 mono_domain_unlock (domain);
4153 mono_loader_unlock ();
4155 mono_loader_lock ();
4156 g_ptr_array_add (breakpoints, bp);
4157 mono_loader_unlock ();
4159 if (error && !mono_error_ok (error)) {
4160 clear_breakpoint (bp);
4168 clear_breakpoint (MonoBreakpoint *bp)
4172 // FIXME: locking, races
4173 for (i = 0; i < bp->children->len; ++i) {
4174 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4176 remove_breakpoint (inst);
4181 mono_loader_lock ();
4182 g_ptr_array_remove (breakpoints, bp);
4183 mono_loader_unlock ();
4185 g_ptr_array_free (bp->children, TRUE);
4190 breakpoints_cleanup (void)
4194 mono_loader_lock ();
4196 while (i < event_requests->len) {
4197 EventRequest *req = g_ptr_array_index (event_requests, i);
4199 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4200 clear_breakpoint (req->info);
4201 g_ptr_array_remove_index_fast (event_requests, i);
4208 for (i = 0; i < breakpoints->len; ++i)
4209 g_free (g_ptr_array_index (breakpoints, i));
4211 g_ptr_array_free (breakpoints, TRUE);
4212 g_hash_table_destroy (bp_locs);
4217 mono_loader_unlock ();
4221 * clear_breakpoints_for_domain:
4223 * Clear breakpoint instances which reference DOMAIN.
4226 clear_breakpoints_for_domain (MonoDomain *domain)
4230 /* This could be called after shutdown */
4234 mono_loader_lock ();
4235 for (i = 0; i < breakpoints->len; ++i) {
4236 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4239 while (j < bp->children->len) {
4240 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4242 if (inst->domain == domain) {
4243 remove_breakpoint (inst);
4247 g_ptr_array_remove_index_fast (bp->children, j);
4253 mono_loader_unlock ();
4257 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4259 return bp->method && bp->method->klass->image->assembly == assembly;
4263 process_breakpoint_inner (DebuggerTlsData *tls)
4267 int i, j, suspend_policy;
4268 guint32 native_offset;
4270 BreakpointInstance *inst;
4271 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4272 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4273 EventKind kind = EVENT_KIND_BREAKPOINT;
4274 MonoContext *ctx = &tls->restore_ctx;
4275 MonoSeqPointInfo *info;
4278 // FIXME: Speed this up
4280 ip = MONO_CONTEXT_GET_IP (ctx);
4281 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4283 g_assert (ji->method);
4285 /* Compute the native offset of the breakpoint from the ip */
4286 native_offset = ip - (guint8*)ji->code_start;
4289 * Skip the instruction causing the breakpoint signal.
4291 mono_arch_skip_breakpoint (ctx, ji);
4293 if (ji->method->wrapper_type || tls->disable_breakpoints)
4296 bp_reqs = g_ptr_array_new ();
4297 ss_reqs = g_ptr_array_new ();
4298 ss_reqs_orig = g_ptr_array_new ();
4300 mono_loader_lock ();
4303 * The ip points to the instruction causing the breakpoint event, which is after
4304 * the offset recorded in the seq point map, so find the prev seq point before ip.
4306 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4308 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, ip, native_offset, sp ? sp->il_offset : -1));
4311 for (i = 0; i < breakpoints->len; ++i) {
4312 bp = g_ptr_array_index (breakpoints, i);
4317 for (j = 0; j < bp->children->len; ++j) {
4318 inst = g_ptr_array_index (bp->children, j);
4319 if (inst->ji == ji && inst->sp == sp) {
4320 if (bp->req->event_kind == EVENT_KIND_STEP) {
4321 g_ptr_array_add (ss_reqs_orig, bp->req);
4323 g_ptr_array_add (bp_reqs, bp->req);
4328 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4329 /* Maybe a method entry/exit event */
4330 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4331 kind = EVENT_KIND_METHOD_ENTRY;
4332 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4333 kind = EVENT_KIND_METHOD_EXIT;
4336 /* Process single step requests */
4337 for (i = 0; i < ss_reqs_orig->len; ++i) {
4338 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4339 SingleStepReq *ss_req = req->info;
4340 gboolean hit = TRUE;
4342 if (ss_req->size == STEP_SIZE_LINE) {
4343 /* Have to check whenever a different source line was reached */
4344 MonoDebugMethodInfo *minfo;
4345 MonoDebugSourceLocation *loc = NULL;
4347 minfo = mono_debug_lookup_method (ji->method);
4350 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4352 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4353 /* Have to continue single stepping */
4354 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4359 ss_req->last_method = ji->method;
4360 ss_req->last_line = loc->row;
4361 mono_debug_free_source_location (loc);
4366 g_ptr_array_add (ss_reqs, req);
4368 /* Start single stepping again from the current sequence point */
4369 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4372 if (ss_reqs->len > 0)
4373 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4374 if (bp_reqs->len > 0)
4375 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4376 if (kind != EVENT_KIND_BREAKPOINT)
4377 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4379 mono_loader_unlock ();
4381 g_ptr_array_free (bp_reqs, TRUE);
4382 g_ptr_array_free (ss_reqs, TRUE);
4385 * FIXME: The first event will suspend, so the second will only be sent after the
4389 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4391 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4392 if (enter_leave_events)
4393 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4396 /* Process a breakpoint/single step event after resuming from a signal handler */
4398 process_signal_event (void (*func) (DebuggerTlsData*))
4400 DebuggerTlsData *tls;
4401 MonoContext orig_restore_ctx, ctx;
4402 static void (*restore_context) (void *);
4404 if (!restore_context)
4405 restore_context = mono_get_restore_context ();
4407 tls = mono_native_tls_get_value (debugger_tls_id);
4408 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4409 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4410 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4414 /* This is called when resuming from a signal handler, so it shouldn't return */
4415 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4416 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4417 restore_context (&ctx);
4418 g_assert_not_reached ();
4422 process_breakpoint (void)
4424 process_signal_event (process_breakpoint_inner);
4428 resume_from_signal_handler (void *sigctx, void *func)
4430 DebuggerTlsData *tls;
4433 /* Save the original context in TLS */
4434 // FIXME: This might not work on an altstack ?
4435 tls = mono_native_tls_get_value (debugger_tls_id);
4438 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4439 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4440 // clob:c could be added to op_seq_point.
4442 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4443 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4444 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4445 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4447 MONO_CONTEXT_SET_IP (&ctx, func);
4449 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4451 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4452 mono_ppc_set_func_into_sigctx (sigctx, func);
4457 mono_debugger_agent_breakpoint_hit (void *sigctx)
4460 * We are called from a signal handler, and running code there causes all kinds of
4461 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4462 * So set up the signal context to return to the real breakpoint handler function.
4464 resume_from_signal_handler (sigctx, process_breakpoint);
4468 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4470 if (frame->managed) {
4471 *(MonoContext*)data = *ctx;
4480 * Called by System.Diagnostics.Debugger:Break ().
4483 mono_debugger_agent_user_break (void)
4485 if (agent_config.enabled) {
4490 /* Obtain a context */
4491 MONO_CONTEXT_SET_IP (&ctx, NULL);
4492 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4493 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4495 mono_loader_lock ();
4496 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4497 mono_loader_unlock ();
4499 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4506 ss_depth_to_string (StepDepth depth)
4509 case STEP_DEPTH_OVER:
4511 case STEP_DEPTH_OUT:
4513 case STEP_DEPTH_INTO:
4516 g_assert_not_reached ();
4522 process_single_step_inner (DebuggerTlsData *tls)
4527 int il_offset, suspend_policy;
4530 MonoContext *ctx = &tls->restore_ctx;
4532 MonoSeqPointInfo *info;
4534 ip = MONO_CONTEXT_GET_IP (ctx);
4536 /* Skip the instruction causing the single step */
4537 mono_arch_skip_single_step (ctx);
4539 if (suspend_count > 0) {
4540 process_suspend (tls, ctx);
4545 // FIXME: A suspend race
4548 if (mono_thread_internal_current () != ss_req->thread)
4551 if (log_level > 0) {
4552 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4554 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));
4557 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4559 g_assert (ji->method);
4561 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4566 * Stopping in memset makes half-initialized vtypes visible.
4567 * Stopping in memcpy makes half-copied vtypes visible.
4569 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4573 * The ip points to the instruction causing the single step event, which is before
4574 * the offset recorded in the seq point map, so find the next seq point after ip.
4576 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4579 il_offset = sp->il_offset;
4581 // FIXME: No tests fail if this is disabled
4583 if (ss_req->size == STEP_SIZE_LINE) {
4587 /* Step until a different source line is reached */
4588 MonoDebugMethodInfo *minfo;
4590 minfo = mono_debug_lookup_method (ji->method);
4593 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4595 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4596 mono_debug_free_source_location (loc);
4601 * Step until we reach a location with line number info,
4602 * otherwise the client can't show a location.
4603 * This can happen for example with statics initialized inline
4604 * outside of a cctor.
4609 ss_req->last_method = ji->method;
4610 ss_req->last_line = loc->row;
4611 mono_debug_free_source_location (loc);
4617 /* Start single stepping again from the current sequence point */
4618 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4620 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4621 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4622 !strcmp (ji->method->name, ".cctor"))
4625 // FIXME: Has to lock earlier
4627 reqs = g_ptr_array_new ();
4629 mono_loader_lock ();
4631 g_ptr_array_add (reqs, ss_req->req);
4633 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4635 g_ptr_array_free (reqs, TRUE);
4637 mono_loader_unlock ();
4639 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4643 process_single_step (void)
4645 process_signal_event (process_single_step_inner);
4649 * mono_debugger_agent_single_step_event:
4651 * Called from a signal handler to handle a single step event.
4654 mono_debugger_agent_single_step_event (void *sigctx)
4656 /* Resume to process_single_step through the signal context */
4658 // FIXME: Since step out/over is implemented using step in, the step in case should
4659 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4662 if (GetCurrentThreadId () == debugger_thread_id) {
4664 * This could happen despite our best effors when the runtime calls
4665 * assembly/type resolve hooks.
4666 * FIXME: Breakpoints too.
4670 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4671 mono_arch_skip_single_step (&ctx);
4672 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4676 resume_from_signal_handler (sigctx, process_single_step);
4680 debugger_agent_single_step_from_context (MonoContext *ctx)
4682 DebuggerTlsData *tls;
4683 MonoContext orig_restore_ctx;
4685 tls = mono_native_tls_get_value (debugger_tls_id);
4688 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4689 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4690 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4692 process_single_step_inner (tls);
4694 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4695 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4699 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4701 DebuggerTlsData *tls;
4702 MonoContext orig_restore_ctx;
4704 tls = mono_native_tls_get_value (debugger_tls_id);
4706 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4707 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4709 process_breakpoint_inner (tls);
4711 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4712 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4716 * start_single_stepping:
4718 * Turn on single stepping. Can be called multiple times, for example,
4719 * by a single step event request + a suspend.
4722 start_single_stepping (void)
4724 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4725 int val = InterlockedIncrement (&ss_count);
4728 mono_arch_start_single_stepping ();
4730 if (ss_req != NULL && ss_invoke_addr == NULL) {
4731 DebuggerTlsData *tls;
4733 mono_loader_lock ();
4735 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4736 ss_invoke_addr = tls->invoke_addr;
4738 mono_loader_unlock ();
4741 g_assert_not_reached ();
4746 stop_single_stepping (void)
4748 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4749 int val = InterlockedDecrement (&ss_count);
4752 mono_arch_stop_single_stepping ();
4754 g_assert_not_reached ();
4761 * Stop the single stepping operation given by SS_REQ.
4764 ss_stop (SingleStepReq *ss_req)
4769 for (l = ss_req->bps; l; l = l->next) {
4770 clear_breakpoint (l->data);
4772 g_slist_free (ss_req->bps);
4776 if (ss_req->global) {
4777 stop_single_stepping ();
4778 ss_req->global = FALSE;
4785 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4786 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4787 * belong to the same thread as CTX.
4790 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4792 int i, j, frame_index;
4795 gboolean enable_global = FALSE;
4797 /* Stop the previous operation */
4801 * Implement single stepping using breakpoints if possible.
4803 if (step_to_catch) {
4804 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4805 ss_req->bps = g_slist_append (ss_req->bps, bp);
4809 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4810 /* Need parent frames */
4811 if (!tls->context.valid)
4812 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4813 compute_frame_info (tls->thread, tls);
4817 * Find the first sequence point in the current or in a previous frame which
4818 * is not the last in its method.
4820 if (ss_req->depth == STEP_DEPTH_OUT) {
4821 /* Ignore seq points in current method */
4822 while (frame_index < tls->frame_count) {
4823 StackFrame *frame = tls->frames [frame_index];
4825 method = frame->method;
4826 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4828 if (sp && sp->next_len != 0)
4831 // There could be method calls before the next seq point in the caller when using nested calls
4832 //enable_global = TRUE;
4834 while (sp && sp->next_len == 0) {
4836 if (frame_index < tls->frame_count) {
4837 StackFrame *frame = tls->frames [frame_index];
4839 method = frame->method;
4840 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4846 if (sp && sp->next_len > 0) {
4847 for (i = 0; i < sp->next_len; ++i) {
4848 next_sp = &info->seq_points [sp->next [i]];
4850 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4851 ss_req->bps = g_slist_append (ss_req->bps, bp);
4855 if (ss_req->depth == STEP_DEPTH_OVER) {
4856 /* Need to stop in catch clauses as well */
4857 for (i = 0; i < tls->frame_count; ++i) {
4858 StackFrame *frame = tls->frames [i];
4861 MonoJitInfo *jinfo = frame->ji;
4862 for (j = 0; j < jinfo->num_clauses; ++j) {
4863 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4865 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4867 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4868 ss_req->bps = g_slist_append (ss_req->bps, bp);
4876 if (ss_req->depth == STEP_DEPTH_INTO) {
4877 /* Enable global stepping so we stop at method entry too */
4878 enable_global = TRUE;
4882 * The ctx/frame info computed above will become invalid when we continue.
4884 tls->context.valid = FALSE;
4885 tls->async_state.valid = FALSE;
4886 invalidate_frames (tls);
4889 if (enable_global) {
4890 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4891 ss_req->global = TRUE;
4892 start_single_stepping ();
4893 } else if (!ss_req->bps) {
4894 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4895 ss_req->global = TRUE;
4896 start_single_stepping ();
4898 ss_req->global = FALSE;
4903 * Start single stepping of thread THREAD
4906 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4908 DebuggerTlsData *tls;
4909 MonoSeqPointInfo *info = NULL;
4910 SeqPoint *sp = NULL;
4911 MonoMethod *method = NULL;
4912 MonoDebugMethodInfo *minfo;
4913 gboolean step_to_catch = FALSE;
4915 if (suspend_count == 0)
4916 return ERR_NOT_SUSPENDED;
4918 wait_for_suspend ();
4920 // FIXME: Multiple requests
4922 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4923 return ERR_NOT_IMPLEMENTED;
4926 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4928 ss_req = g_new0 (SingleStepReq, 1);
4930 ss_req->thread = thread;
4931 ss_req->size = size;
4932 ss_req->depth = depth;
4935 mono_loader_lock ();
4936 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4937 mono_loader_unlock ();
4939 g_assert (tls->context.valid);
4940 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4942 if (tls->has_catch_ctx) {
4944 StackFrameInfo frame;
4945 MonoContext new_ctx;
4946 MonoLMF *lmf = NULL;
4949 * We are stopped at a throw site. Stepping should go to the catch site.
4952 /* Find the the jit info for the catch context */
4953 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4955 g_assert (frame.type == FRAME_TYPE_MANAGED);
4958 * Find the seq point corresponding to the landing site ip, which is the first seq
4961 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4964 method = frame.method;
4966 step_to_catch = TRUE;
4967 /* This make sure the seq point is not skipped by process_single_step () */
4968 ss_req->last_sp = NULL;
4971 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4974 /* Compute the initial line info */
4975 compute_frame_info (thread, tls);
4977 if (tls->frame_count) {
4978 frame = tls->frames [0];
4980 ss_req->last_method = frame->method;
4981 ss_req->last_line = -1;
4983 minfo = mono_debug_lookup_method (frame->method);
4984 if (minfo && frame->il_offset != -1) {
4985 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4988 ss_req->last_line = loc->row;
4995 if (!step_to_catch) {
4998 compute_frame_info (thread, tls);
5000 if (tls->frame_count) {
5001 frame = tls->frames [0];
5003 if (!method && frame->il_offset != -1) {
5004 /* FIXME: Sort the table and use a binary search */
5005 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5007 method = frame->method;
5012 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5018 ss_destroy (SingleStepReq *req)
5021 g_assert (ss_req == req);
5030 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5033 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5039 if (!agent_config.enabled)
5042 mono_loader_lock ();
5043 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5044 mono_loader_unlock ();
5047 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5048 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5050 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5052 g_free (ei.category);
5053 g_free (ei.message);
5057 mono_debugger_agent_debug_log_is_enabled (void)
5059 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5060 return agent_config.enabled;
5064 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5065 MonoContext *catch_ctx)
5071 DebuggerTlsData *tls = NULL;
5073 if (thread_to_tls != NULL) {
5074 MonoInternalThread *thread = mono_thread_internal_current ();
5076 mono_loader_lock ();
5077 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5078 mono_loader_unlock ();
5080 if (tls && tls->abort_requested)
5082 if (tls && tls->disable_breakpoints)
5086 memset (&ei, 0, sizeof (EventInfo));
5088 /* Just-In-Time debugging */
5090 if (agent_config.onuncaught && !inited) {
5091 finish_agent_init (FALSE);
5094 * Send an unsolicited EXCEPTION event with a dummy request id.
5096 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5097 ei.exc = (MonoObject*)exc;
5098 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5101 } else if (agent_config.onthrow && !inited) {
5103 gboolean found = FALSE;
5105 for (l = agent_config.onthrow; l; l = l->next) {
5106 char *ex_type = l->data;
5107 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5109 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5116 finish_agent_init (FALSE);
5119 * Send an unsolicited EXCEPTION event with a dummy request id.
5121 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5122 ei.exc = (MonoObject*)exc;
5123 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5131 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5133 ei.exc = (MonoObject*)exc;
5134 ei.caught = catch_ctx != NULL;
5136 mono_loader_lock ();
5137 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5138 mono_loader_unlock ();
5140 if (tls && catch_ctx) {
5141 tls->catch_ctx = *catch_ctx;
5142 tls->has_catch_ctx = TRUE;
5145 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5148 tls->has_catch_ctx = FALSE;
5152 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5154 DebuggerTlsData *tls;
5159 tls = mono_native_tls_get_value (debugger_tls_id);
5164 * We're about to invoke an exception filter during the first pass of exception handling.
5166 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5167 * 'orig_ctx' is the context where the exception has been thrown.
5170 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5172 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5173 * the call site (line 37) and then continue to Main(), but it would never
5174 * include the throw site (line 32).
5176 * Since exception filters are invoked during the first pass of exception handling,
5177 * the stack frames of the throw site are still intact, so we should include them
5180 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5182 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5183 * but report the location of the 'throw' to the user.
5187 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5191 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5193 DebuggerTlsData *tls;
5198 tls = mono_native_tls_get_value (debugger_tls_id);
5202 tls->filter_state.valid = FALSE;
5206 * buffer_add_value_full:
5208 * Add the encoding of the value at ADDR described by T to the buffer.
5209 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5213 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5219 g_assert (*(void**)addr);
5220 addr = *(void**)addr;
5225 case MONO_TYPE_BOOLEAN:
5228 case MONO_TYPE_CHAR:
5248 case MONO_TYPE_VOID:
5249 buffer_add_byte (buf, t->type);
5251 case MONO_TYPE_BOOLEAN:
5254 buffer_add_byte (buf, t->type);
5255 buffer_add_int (buf, *(gint8*)addr);
5257 case MONO_TYPE_CHAR:
5260 buffer_add_byte (buf, t->type);
5261 buffer_add_int (buf, *(gint16*)addr);
5266 buffer_add_byte (buf, t->type);
5267 buffer_add_int (buf, *(gint32*)addr);
5272 buffer_add_byte (buf, t->type);
5273 buffer_add_long (buf, *(gint64*)addr);
5277 /* Treat it as a vtype */
5279 case MONO_TYPE_PTR: {
5280 gssize val = *(gssize*)addr;
5282 buffer_add_byte (buf, t->type);
5283 buffer_add_long (buf, val);
5287 case MONO_TYPE_STRING:
5288 case MONO_TYPE_SZARRAY:
5289 case MONO_TYPE_OBJECT:
5290 case MONO_TYPE_CLASS:
5291 case MONO_TYPE_ARRAY:
5292 obj = *(MonoObject**)addr;
5295 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5297 if (obj->vtable->klass->valuetype) {
5298 t = &obj->vtable->klass->byval_arg;
5299 addr = mono_object_unbox (obj);
5301 } else if (obj->vtable->klass->rank) {
5302 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5303 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5304 buffer_add_byte (buf, MONO_TYPE_CLASS);
5306 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5308 buffer_add_objid (buf, obj);
5312 case MONO_TYPE_VALUETYPE: {
5316 MonoClass *klass = mono_class_from_mono_type (t);
5318 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5319 buffer_add_byte (buf, klass->enumtype);
5320 buffer_add_typeid (buf, domain, klass);
5324 while ((f = mono_class_get_fields (klass, &iter))) {
5325 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5327 if (mono_field_is_deleted (f))
5331 buffer_add_int (buf, nfields);
5334 while ((f = mono_class_get_fields (klass, &iter))) {
5335 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5337 if (mono_field_is_deleted (f))
5339 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5343 case MONO_TYPE_GENERICINST:
5344 if (mono_type_generic_inst_is_valuetype (t)) {
5356 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5358 buffer_add_value_full (buf, t, addr, domain, FALSE);
5362 obj_is_of_type (MonoObject *obj, MonoType *t)
5364 MonoClass *klass = obj->vtable->klass;
5365 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5366 if (klass == mono_defaults.transparent_proxy_class) {
5367 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5368 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5378 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5381 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5385 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5386 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5387 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5388 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5389 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5390 char *name = mono_type_full_name (t);
5391 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5393 return ERR_INVALID_ARGUMENT;
5397 case MONO_TYPE_BOOLEAN:
5398 *(guint8*)addr = decode_int (buf, &buf, limit);
5400 case MONO_TYPE_CHAR:
5401 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5404 *(gint8*)addr = decode_int (buf, &buf, limit);
5407 *(guint8*)addr = decode_int (buf, &buf, limit);
5410 *(gint16*)addr = decode_int (buf, &buf, limit);
5413 *(guint16*)addr = decode_int (buf, &buf, limit);
5416 *(gint32*)addr = decode_int (buf, &buf, limit);
5419 *(guint32*)addr = decode_int (buf, &buf, limit);
5422 *(gint64*)addr = decode_long (buf, &buf, limit);
5425 *(guint64*)addr = decode_long (buf, &buf, limit);
5428 *(guint32*)addr = decode_int (buf, &buf, limit);
5431 *(guint64*)addr = decode_long (buf, &buf, limit);
5434 /* We send these as I8, so we get them back as such */
5435 g_assert (type == MONO_TYPE_I8);
5436 *(gssize*)addr = decode_long (buf, &buf, limit);
5438 case MONO_TYPE_GENERICINST:
5439 if (MONO_TYPE_ISSTRUCT (t)) {
5440 /* The client sends these as a valuetype */
5448 /* We send these as vtypes, so we get them back as such */
5449 g_assert (type == MONO_TYPE_VALUETYPE);
5452 case MONO_TYPE_VALUETYPE: {
5453 gboolean is_enum = decode_byte (buf, &buf, limit);
5457 gpointer iter = NULL;
5460 /* Enums are sent as a normal vtype */
5462 return ERR_NOT_IMPLEMENTED;
5463 klass = decode_typeid (buf, &buf, limit, &d, &err);
5467 if (klass != mono_class_from_mono_type (t))
5468 return ERR_INVALID_ARGUMENT;
5470 nfields = decode_int (buf, &buf, limit);
5471 while ((f = mono_class_get_fields (klass, &iter))) {
5472 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5474 if (mono_field_is_deleted (f))
5476 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5481 g_assert (nfields == 0);
5486 if (MONO_TYPE_IS_REFERENCE (t)) {
5487 if (type == MONO_TYPE_OBJECT) {
5488 int objid = decode_objid (buf, &buf, limit);
5492 err = get_object (objid, (MonoObject**)&obj);
5497 if (!obj_is_of_type (obj, t)) {
5498 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5499 return ERR_INVALID_ARGUMENT;
5502 if (obj && obj->vtable->domain != domain)
5503 return ERR_INVALID_ARGUMENT;
5505 mono_gc_wbarrier_generic_store (addr, obj);
5506 } else if (type == VALUE_TYPE_ID_NULL) {
5507 *(MonoObject**)addr = NULL;
5509 return ERR_INVALID_ARGUMENT;
5523 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5526 int type = decode_byte (buf, &buf, limit);
5528 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5529 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5530 guint8 *nullable_buf;
5533 * First try decoding it as a Nullable`1
5535 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5540 * Then try decoding as a primitive value or null.
5542 if (targ->type == type) {
5543 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5544 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5546 g_free (nullable_buf);
5549 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5550 g_free (nullable_buf);
5553 } else if (type == VALUE_TYPE_ID_NULL) {
5554 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5560 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5564 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5571 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5572 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5575 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5576 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5578 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5580 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5581 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5582 addr += (gint32)var->offset;
5584 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5586 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5588 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5592 g_assert_not_reached ();
5597 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5603 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5604 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5606 if (MONO_TYPE_IS_REFERENCE (t))
5607 size = sizeof (gpointer);
5609 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5612 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5613 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5615 gboolean is_signed = FALSE;
5617 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5622 v = is_signed ? *(gint8*)val : *(guint8*)val;
5625 v = is_signed ? *(gint16*)val : *(guint16*)val;
5628 v = is_signed ? *(gint32*)val : *(guint32*)val;
5631 v = is_signed ? *(gint64*)val : *(guint64*)val;
5634 g_assert_not_reached ();
5640 /* Set value on the stack or in the return ctx */
5641 if (reg_locations [reg]) {
5642 /* Saved on the stack */
5643 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5644 *(reg_locations [reg]) = v;
5647 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5648 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5651 // FIXME: Move these to mono-context.h/c.
5652 mono_arch_context_set_int_reg (ctx, reg, v);
5654 // FIXME: Can't set registers, so we disable linears
5659 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5660 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5661 addr += (gint32)var->offset;
5663 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5666 addr = *(guint8**)addr;
5672 // FIXME: Write barriers
5673 mono_gc_memmove (addr, val, size);
5675 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5679 g_assert_not_reached ();
5684 clear_event_request (int req_id, int etype)
5688 mono_loader_lock ();
5689 for (i = 0; i < event_requests->len; ++i) {
5690 EventRequest *req = g_ptr_array_index (event_requests, i);
5692 if (req->id == req_id && req->event_kind == etype) {
5693 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5694 clear_breakpoint (req->info);
5695 if (req->event_kind == EVENT_KIND_STEP)
5696 ss_destroy (req->info);
5697 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5698 clear_breakpoint (req->info);
5699 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5700 clear_breakpoint (req->info);
5701 g_ptr_array_remove_index_fast (event_requests, i);
5706 mono_loader_unlock ();
5710 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5712 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5713 return breakpoint_matches_assembly (req->info, assembly);
5717 for (i = 0; i < req->nmodifiers; ++i) {
5718 Modifier *m = &req->modifiers [i];
5720 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5722 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5723 for (j = 0; m->data.assemblies [j]; ++j)
5724 if (m->data.assemblies [j] == assembly)
5734 * clear_event_requests_for_assembly:
5736 * Clear all events requests which reference ASSEMBLY.
5739 clear_event_requests_for_assembly (MonoAssembly *assembly)
5744 mono_loader_lock ();
5748 for (i = 0; i < event_requests->len; ++i) {
5749 EventRequest *req = g_ptr_array_index (event_requests, i);
5751 if (event_req_matches_assembly (req, assembly)) {
5752 clear_event_request (req->id, req->event_kind);
5758 mono_loader_unlock ();
5762 * type_comes_from_assembly:
5764 * GHRFunc that returns TRUE if klass comes from assembly
5767 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5769 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5773 * clear_types_for_assembly:
5775 * Clears types from loaded_classes for a given assembly
5778 clear_types_for_assembly (MonoAssembly *assembly)
5780 MonoDomain *domain = mono_domain_get ();
5781 AgentDomainInfo *info = NULL;
5783 mono_loader_lock ();
5784 info = get_agent_domain_info (domain);
5785 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5786 mono_loader_unlock ();
5790 add_thread (gpointer key, gpointer value, gpointer user_data)
5792 MonoInternalThread *thread = value;
5793 Buffer *buf = user_data;
5795 buffer_add_objid (buf, (MonoObject*)thread);
5799 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5801 guint8 *p = invoke->p;
5802 guint8 *end = invoke->endp;
5805 MonoMethodSignature *sig;
5808 MonoObject *this, *res, *exc;
5811 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5814 MonoStopwatch watch;
5816 if (invoke->method) {
5818 * Invoke this method directly, currently only Environment.Exit () is supported.
5821 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>"));
5822 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5823 g_assert_not_reached ();
5826 m = decode_methodid (p, &p, end, &domain, &err);
5829 sig = mono_method_signature (m);
5831 if (m->klass->valuetype)
5832 this_buf = g_alloca (mono_class_instance_size (m->klass));
5834 this_buf = g_alloca (sizeof (MonoObject*));
5835 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5836 /* Should be null */
5837 int type = decode_byte (p, &p, end);
5838 if (type != VALUE_TYPE_ID_NULL)
5839 return ERR_INVALID_ARGUMENT;
5840 memset (this_buf, 0, mono_class_instance_size (m->klass));
5842 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5847 if (!m->klass->valuetype)
5848 this = *(MonoObject**)this_buf;
5852 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>"));
5854 if (this && this->vtable->domain != domain)
5857 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5858 if (!strcmp (m->name, ".ctor")) {
5859 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5860 return ERR_INVALID_ARGUMENT;
5862 this = mono_object_new (domain, m->klass);
5864 return ERR_INVALID_ARGUMENT;
5868 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
5869 return ERR_INVALID_ARGUMENT;
5871 nargs = decode_int (p, &p, end);
5872 if (nargs != sig->param_count)
5873 return ERR_INVALID_ARGUMENT;
5874 /* Use alloca to get gc tracking */
5875 arg_buf = g_alloca (nargs * sizeof (gpointer));
5876 memset (arg_buf, 0, nargs * sizeof (gpointer));
5877 args = g_alloca (nargs * sizeof (gpointer));
5878 for (i = 0; i < nargs; ++i) {
5879 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5880 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5884 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5887 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5888 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5891 args [i] = arg_buf [i];
5898 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5899 tls->disable_breakpoints = TRUE;
5901 tls->disable_breakpoints = FALSE;
5904 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5906 /* FIXME: Move this to arch specific code */
5907 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5908 if (invoke->has_ctx) {
5911 lmf_addr = mono_get_lmf_addr ();
5914 memset (&ext, 0, sizeof (ext));
5916 ext.lmf.previous_lmf = *(lmf_addr);
5917 /* Mark that this is a MonoLMFExt */
5918 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5919 ext.lmf.rsp = (gssize)&ext;
5920 #elif defined(TARGET_X86)
5921 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5922 /* Mark that this is a MonoLMFExt */
5923 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5924 ext.lmf.ebp = (gssize)&ext;
5925 #elif defined(TARGET_ARM)
5926 ext.lmf.previous_lmf = *(lmf_addr);
5927 /* Mark that this is a MonoLMFExt */
5928 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5929 ext.lmf.sp = (gssize)&ext;
5930 #elif defined(TARGET_POWERPC)
5931 ext.lmf.previous_lmf = *(lmf_addr);
5932 /* Mark that this is a MonoLMFExt */
5933 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5934 ext.lmf.ebp = (gssize)&ext;
5935 #elif defined(TARGET_S390X)
5936 ext.lmf.previous_lmf = *(lmf_addr);
5937 /* Mark that this is a MonoLMFExt */
5938 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5939 ext.lmf.ebp = (gssize)&ext;
5940 #elif defined(TARGET_MIPS)
5941 ext.lmf.previous_lmf = *(lmf_addr);
5942 /* Mark that this is a MonoLMFExt */
5943 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5944 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5946 g_assert_not_reached ();
5949 ext.debugger_invoke = TRUE;
5950 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5952 mono_set_lmf ((MonoLMF*)&ext);
5956 mono_stopwatch_start (&watch);
5957 if (m->klass->valuetype)
5958 res = mono_runtime_invoke (m, this_buf, args, &exc);
5960 res = mono_runtime_invoke (m, this, args, &exc);
5961 mono_stopwatch_stop (&watch);
5962 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)));
5964 buffer_add_byte (buf, 0);
5965 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5967 buffer_add_byte (buf, 1);
5968 if (sig->ret->type == MONO_TYPE_VOID) {
5969 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5970 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5973 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5974 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5975 buffer_add_value (buf, sig->ret, &res, domain);
5976 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
5977 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5978 MonoClass *k = mono_class_from_mono_type (sig->ret);
5979 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
5981 g_assert (nullable_buf);
5982 mono_nullable_init (nullable_buf, res, k);
5983 buffer_add_value (buf, sig->ret, nullable_buf, domain);
5986 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5993 tls->disable_breakpoints = FALSE;
5995 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5996 if (invoke->has_ctx)
5997 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6000 // FIXME: byref arguments
6008 * Invoke the method given by tls->pending_invoke in the current thread.
6011 invoke_method (void)
6013 DebuggerTlsData *tls;
6018 static void (*restore_context) (void *);
6019 MonoContext restore_ctx;
6021 if (!restore_context)
6022 restore_context = mono_get_restore_context ();
6024 tls = mono_native_tls_get_value (debugger_tls_id);
6028 * Store the `InvokeData *' in `tls->invoke' until we're done with
6029 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6032 mono_loader_lock ();
6034 invoke = tls->pending_invoke;
6036 tls->pending_invoke = NULL;
6038 invoke->last_invoke = tls->invoke;
6039 tls->invoke = invoke;
6041 mono_loader_unlock ();
6043 tls->frames_up_to_date = FALSE;
6047 buffer_init (&buf, 128);
6049 err = do_invoke_method (tls, &buf, invoke);
6051 /* Start suspending before sending the reply */
6052 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6053 for (i = 0; i < invoke->suspend_count; ++i)
6057 send_reply_packet (id, err, &buf);
6061 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6063 if (invoke->has_ctx)
6064 save_thread_context (&restore_ctx);
6066 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6067 g_assert (tls->resume_count);
6068 tls->resume_count -= invoke->suspend_count;
6071 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6074 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6076 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6077 * after the mono_runtime_invoke() already returned, but it doesn't matter
6078 * because we reset the abort here.
6081 mono_loader_lock ();
6083 if (tls->abort_requested)
6084 mono_thread_internal_reset_abort (tls->thread);
6086 tls->invoke = tls->invoke->last_invoke;
6087 tls->abort_requested = FALSE;
6089 mono_loader_unlock ();
6098 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6100 MonoThread *thread = value;
6101 DebuggerTlsData *tls;
6104 mono_loader_lock ();
6105 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6107 res = tls->really_suspended;
6108 mono_loader_unlock ();
6114 get_source_files_for_type (MonoClass *klass)
6116 gpointer iter = NULL;
6118 MonoDebugSourceInfo *sinfo;
6122 files = g_ptr_array_new ();
6124 while ((method = mono_class_get_methods (klass, &iter))) {
6125 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6126 GPtrArray *source_file_list;
6129 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL);
6130 for (j = 0; j < source_file_list->len; ++j) {
6131 sinfo = g_ptr_array_index (source_file_list, j);
6132 for (i = 0; i < files->len; ++i)
6133 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6135 if (i == files->len)
6136 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6138 g_ptr_array_free (source_file_list, TRUE);
6146 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6149 case CMD_VM_VERSION: {
6150 char *build_info, *version;
6152 build_info = mono_get_runtime_build_info ();
6153 version = g_strdup_printf ("mono %s", build_info);
6155 buffer_add_string (buf, version); /* vm version */
6156 buffer_add_int (buf, MAJOR_VERSION);
6157 buffer_add_int (buf, MINOR_VERSION);
6158 g_free (build_info);
6162 case CMD_VM_SET_PROTOCOL_VERSION: {
6163 major_version = decode_int (p, &p, end);
6164 minor_version = decode_int (p, &p, end);
6165 protocol_version_set = TRUE;
6166 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6169 case CMD_VM_ALL_THREADS: {
6171 mono_loader_lock ();
6172 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6173 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6174 mono_loader_unlock ();
6177 case CMD_VM_SUSPEND:
6179 wait_for_suspend ();
6182 if (suspend_count == 0)
6183 return ERR_NOT_SUSPENDED;
6186 case CMD_VM_DISPOSE:
6187 /* Clear all event requests */
6188 mono_loader_lock ();
6189 while (event_requests->len > 0) {
6190 EventRequest *req = g_ptr_array_index (event_requests, 0);
6192 clear_event_request (req->id, req->event_kind);
6194 mono_loader_unlock ();
6196 while (suspend_count > 0)
6198 disconnected = TRUE;
6199 vm_start_event_sent = FALSE;
6202 MonoInternalThread *thread;
6203 DebuggerTlsData *tls;
6204 MonoClass *env_class;
6205 MonoMethod *exit_method = NULL;
6209 exit_code = decode_int (p, &p, end);
6211 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6213 /* Have to send a reply before exiting */
6214 send_reply_packet (id, 0, buf);
6216 /* Clear all event requests */
6217 mono_loader_lock ();
6218 while (event_requests->len > 0) {
6219 EventRequest *req = g_ptr_array_index (event_requests, 0);
6221 clear_event_request (req->id, req->event_kind);
6223 mono_loader_unlock ();
6226 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6227 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6228 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6229 * better than doing the shutdown ourselves, since it avoids various races.
6233 wait_for_suspend ();
6235 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6237 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6239 mono_loader_lock ();
6240 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6241 mono_loader_unlock ();
6243 if (thread && exit_method) {
6244 mono_loader_lock ();
6245 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6246 mono_loader_unlock ();
6248 args = g_new0 (gpointer, 1);
6249 args [0] = g_malloc (sizeof (int));
6250 *(int*)(args [0]) = exit_code;
6252 tls->pending_invoke = g_new0 (InvokeData, 1);
6253 tls->pending_invoke->method = exit_method;
6254 tls->pending_invoke->args = args;
6256 while (suspend_count > 0)
6260 * No thread found, do it ourselves.
6261 * FIXME: This can race with normal shutdown etc.
6263 while (suspend_count > 0)
6266 mono_runtime_set_shutting_down ();
6268 mono_threads_set_shutting_down ();
6270 /* Suspend all managed threads since the runtime is going away */
6271 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6272 mono_thread_suspend_all_other_threads ();
6273 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6274 mono_runtime_quit ();
6275 transport_close2 ();
6276 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6282 case CMD_VM_INVOKE_METHOD: {
6283 int objid = decode_objid (p, &p, end);
6285 DebuggerTlsData *tls;
6286 int i, count, err, flags;
6288 err = get_object (objid, (MonoObject**)&thread);
6292 flags = decode_int (p, &p, end);
6294 // Wait for suspending if it already started
6296 wait_for_suspend ();
6297 if (!is_suspended ())
6298 return ERR_NOT_SUSPENDED;
6300 mono_loader_lock ();
6301 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6302 mono_loader_unlock ();
6305 if (!tls->really_suspended)
6306 /* The thread is still running native code, can't do invokes */
6307 return ERR_NOT_SUSPENDED;
6310 * Store the invoke data into tls, the thread will execute it after it is
6313 if (tls->pending_invoke)
6314 return ERR_NOT_SUSPENDED;
6315 tls->pending_invoke = g_new0 (InvokeData, 1);
6316 tls->pending_invoke->id = id;
6317 tls->pending_invoke->flags = flags;
6318 tls->pending_invoke->p = g_malloc (end - p);
6319 memcpy (tls->pending_invoke->p, p, end - p);
6320 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6321 tls->pending_invoke->suspend_count = suspend_count;
6323 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6324 resume_thread (THREAD_TO_INTERNAL (thread));
6327 count = suspend_count;
6328 for (i = 0; i < count; ++i)
6333 case CMD_VM_ABORT_INVOKE: {
6334 int objid = decode_objid (p, &p, end);
6336 DebuggerTlsData *tls;
6339 err = get_object (objid, (MonoObject**)&thread);
6343 invoke_id = decode_int (p, &p, end);
6345 mono_loader_lock ();
6346 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6349 if (tls->abort_requested) {
6350 mono_loader_unlock ();
6355 * Check whether we're still inside the mono_runtime_invoke() and that it's
6356 * actually the correct invocation.
6358 * Careful, we do not stop the thread that's doing the invocation, so we can't
6359 * inspect its stack. However, invoke_method() also acquires the loader lock
6360 * when it's done, so we're safe here.
6364 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6365 mono_loader_unlock ();
6366 return ERR_NO_INVOCATION;
6369 tls->abort_requested = TRUE;
6371 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6372 mono_loader_unlock ();
6376 case CMD_VM_SET_KEEPALIVE: {
6377 int timeout = decode_int (p, &p, end);
6378 agent_config.keepalive = timeout;
6380 #ifndef DISABLE_SOCKET_TRANSPORT
6387 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6388 GHashTableIter iter, kiter;
6393 char *fname, *basename;
6394 gboolean ignore_case;
6395 GSList *class_list, *l;
6396 GPtrArray *res_classes, *res_domains;
6398 fname = decode_string (p, &p, end);
6399 ignore_case = decode_byte (p, &p, end);
6401 basename = g_path_get_basename (fname);
6403 res_classes = g_ptr_array_new ();
6404 res_domains = g_ptr_array_new ();
6406 mono_loader_lock ();
6407 g_hash_table_iter_init (&iter, domains);
6408 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6409 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6411 /* Update 'source_file_to_class' cache */
6412 g_hash_table_iter_init (&kiter, info->loaded_classes);
6413 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6414 if (!g_hash_table_lookup (info->source_files, klass)) {
6415 files = get_source_files_for_type (klass);
6416 g_hash_table_insert (info->source_files, klass, files);
6418 for (i = 0; i < files->len; ++i) {
6419 char *s = g_ptr_array_index (files, i);
6420 char *s2 = g_path_get_basename (s);
6423 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6425 class_list = g_slist_prepend (class_list, klass);
6426 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6428 class_list = g_slist_prepend (class_list, klass);
6429 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6432 /* The _ignorecase hash contains the lowercase path */
6433 s3 = strdup_tolower (s2);
6434 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6436 class_list = g_slist_prepend (class_list, klass);
6437 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6439 class_list = g_slist_prepend (class_list, klass);
6440 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6452 s = strdup_tolower (basename);
6453 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6456 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6459 for (l = class_list; l; l = l->next) {
6462 g_ptr_array_add (res_classes, klass);
6463 g_ptr_array_add (res_domains, domain);
6466 mono_loader_unlock ();
6471 buffer_add_int (buf, res_classes->len);
6472 for (i = 0; i < res_classes->len; ++i)
6473 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6474 g_ptr_array_free (res_classes, TRUE);
6475 g_ptr_array_free (res_domains, TRUE);
6478 case CMD_VM_GET_TYPES: {
6479 GHashTableIter iter;
6483 gboolean ignore_case;
6484 GPtrArray *res_classes, *res_domains;
6485 MonoTypeNameParse info;
6487 name = decode_string (p, &p, end);
6488 ignore_case = decode_byte (p, &p, end);
6490 if (!mono_reflection_parse_type (name, &info)) {
6492 mono_reflection_free_type_info (&info);
6493 return ERR_INVALID_ARGUMENT;
6496 res_classes = g_ptr_array_new ();
6497 res_domains = g_ptr_array_new ();
6499 mono_loader_lock ();
6500 g_hash_table_iter_init (&iter, domains);
6501 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6503 gboolean type_resolve;
6507 mono_domain_assemblies_lock (domain);
6508 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6512 type_resolve = TRUE;
6513 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6515 g_ptr_array_add (res_classes, mono_type_get_class (t));
6516 g_ptr_array_add (res_domains, domain);
6520 mono_domain_assemblies_unlock (domain);
6522 mono_loader_unlock ();
6525 mono_reflection_free_type_info (&info);
6527 buffer_add_int (buf, res_classes->len);
6528 for (i = 0; i < res_classes->len; ++i)
6529 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6530 g_ptr_array_free (res_classes, TRUE);
6531 g_ptr_array_free (res_domains, TRUE);
6536 return ERR_NOT_IMPLEMENTED;
6543 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6549 case CMD_EVENT_REQUEST_SET: {
6551 int i, event_kind, suspend_policy, nmodifiers, mod;
6554 MonoThread *step_thread;
6555 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6559 event_kind = decode_byte (p, &p, end);
6560 suspend_policy = decode_byte (p, &p, end);
6561 nmodifiers = decode_byte (p, &p, end);
6563 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6564 req->id = InterlockedIncrement (&event_request_id);
6565 req->event_kind = event_kind;
6566 req->suspend_policy = suspend_policy;
6567 req->nmodifiers = nmodifiers;
6570 for (i = 0; i < nmodifiers; ++i) {
6571 mod = decode_byte (p, &p, end);
6573 req->modifiers [i].kind = mod;
6574 if (mod == MOD_KIND_COUNT) {
6575 req->modifiers [i].data.count = decode_int (p, &p, end);
6576 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6577 method = decode_methodid (p, &p, end, &domain, &err);
6580 location = decode_long (p, &p, end);
6581 } else if (mod == MOD_KIND_STEP) {
6582 step_thread_id = decode_id (p, &p, end);
6583 size = decode_int (p, &p, end);
6584 depth = decode_int (p, &p, end);
6585 if (CHECK_PROTOCOL_VERSION (2, 16))
6586 filter = decode_int (p, &p, end);
6587 req->modifiers [i].data.filter = filter;
6588 } else if (mod == MOD_KIND_THREAD_ONLY) {
6589 int id = decode_id (p, &p, end);
6591 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6596 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6597 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6601 req->modifiers [i].caught = decode_byte (p, &p, end);
6602 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6603 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" : ""));
6605 req->modifiers [i].data.exc_class = exc_class;
6607 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6609 return ERR_INVALID_ARGUMENT;
6612 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6613 int n = decode_int (p, &p, end);
6616 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6617 for (j = 0; j < n; ++j) {
6618 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6620 g_free (req->modifiers [i].data.assemblies);
6624 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6625 int n = decode_int (p, &p, end);
6628 modifier = &req->modifiers [i];
6629 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6630 for (j = 0; j < n; ++j) {
6631 char *s = decode_string (p, &p, end);
6635 s2 = strdup_tolower (s);
6636 g_hash_table_insert (modifier->data.source_files, s2, s2);
6640 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6641 int n = decode_int (p, &p, end);
6644 modifier = &req->modifiers [i];
6645 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6646 for (j = 0; j < n; ++j) {
6647 char *s = decode_string (p, &p, end);
6650 g_hash_table_insert (modifier->data.type_names, s, s);
6654 return ERR_NOT_IMPLEMENTED;
6658 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6661 req->info = set_breakpoint (method, location, req, &error);
6662 if (!mono_error_ok (&error)) {
6664 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6665 mono_error_cleanup (&error);
6666 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6668 } else if (req->event_kind == EVENT_KIND_STEP) {
6669 g_assert (step_thread_id);
6671 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6677 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6682 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6683 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6684 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6685 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6686 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6687 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6689 if (req->nmodifiers) {
6691 return ERR_NOT_IMPLEMENTED;
6695 mono_loader_lock ();
6696 g_ptr_array_add (event_requests, req);
6698 if (agent_config.defer) {
6699 /* Transmit cached data to the client on receipt of the event request */
6700 switch (req->event_kind) {
6701 case EVENT_KIND_APPDOMAIN_CREATE:
6702 /* Emit load events for currently loaded domains */
6703 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6705 case EVENT_KIND_ASSEMBLY_LOAD:
6706 /* Emit load events for currently loaded assemblies */
6707 mono_assembly_foreach (emit_assembly_load, NULL);
6709 case EVENT_KIND_THREAD_START:
6710 /* Emit start events for currently started threads */
6711 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6713 case EVENT_KIND_TYPE_LOAD:
6714 /* Emit type load events for currently loaded types */
6715 mono_domain_foreach (send_types_for_domain, NULL);
6721 mono_loader_unlock ();
6723 buffer_add_int (buf, req->id);
6726 case CMD_EVENT_REQUEST_CLEAR: {
6727 int etype = decode_byte (p, &p, end);
6728 int req_id = decode_int (p, &p, end);
6730 // FIXME: Make a faster mapping from req_id to request
6731 mono_loader_lock ();
6732 clear_event_request (req_id, etype);
6733 mono_loader_unlock ();
6736 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6739 mono_loader_lock ();
6741 while (i < event_requests->len) {
6742 EventRequest *req = g_ptr_array_index (event_requests, i);
6744 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6745 clear_breakpoint (req->info);
6747 g_ptr_array_remove_index_fast (event_requests, i);
6753 mono_loader_unlock ();
6757 return ERR_NOT_IMPLEMENTED;
6764 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6770 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6771 buffer_add_domainid (buf, mono_get_root_domain ());
6774 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6775 domain = decode_domainid (p, &p, end, NULL, &err);
6778 buffer_add_string (buf, domain->friendly_name);
6781 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6786 domain = decode_domainid (p, &p, end, NULL, &err);
6789 mono_loader_lock ();
6791 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6794 buffer_add_int (buf, count);
6795 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6797 buffer_add_assemblyid (buf, domain, ass);
6799 mono_loader_unlock ();
6802 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6803 domain = decode_domainid (p, &p, end, NULL, &err);
6807 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6810 case CMD_APPDOMAIN_GET_CORLIB: {
6811 domain = decode_domainid (p, &p, end, NULL, &err);
6815 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6818 case CMD_APPDOMAIN_CREATE_STRING: {
6822 domain = decode_domainid (p, &p, end, NULL, &err);
6825 s = decode_string (p, &p, end);
6827 o = mono_string_new (domain, s);
6828 buffer_add_objid (buf, (MonoObject*)o);
6831 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6833 MonoDomain *domain2;
6836 domain = decode_domainid (p, &p, end, NULL, &err);
6839 klass = decode_typeid (p, &p, end, &domain2, &err);
6844 g_assert (domain == domain2);
6846 o = mono_object_new (domain, klass);
6848 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6852 buffer_add_objid (buf, o);
6856 return ERR_NOT_IMPLEMENTED;
6863 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6869 ass = decode_assemblyid (p, &p, end, &domain, &err);
6874 case CMD_ASSEMBLY_GET_LOCATION: {
6875 buffer_add_string (buf, mono_image_get_filename (ass->image));
6878 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6882 if (ass->image->dynamic) {
6883 buffer_add_id (buf, 0);
6885 token = mono_image_get_entry_point (ass->image);
6887 buffer_add_id (buf, 0);
6889 m = mono_get_method (ass->image, token, NULL);
6890 buffer_add_methodid (buf, domain, m);
6895 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6896 buffer_add_moduleid (buf, domain, ass->image);
6899 case CMD_ASSEMBLY_GET_OBJECT: {
6900 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
6901 buffer_add_objid (buf, o);
6904 case CMD_ASSEMBLY_GET_TYPE: {
6905 char *s = decode_string (p, &p, end);
6906 gboolean ignorecase = decode_byte (p, &p, end);
6907 MonoTypeNameParse info;
6909 gboolean type_resolve, res;
6910 MonoDomain *d = mono_domain_get ();
6912 /* This is needed to be able to find referenced assemblies */
6913 res = mono_domain_set (domain, FALSE);
6916 if (!mono_reflection_parse_type (s, &info)) {
6919 if (info.assembly.name)
6921 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6923 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6924 mono_reflection_free_type_info (&info);
6927 mono_domain_set (d, TRUE);
6931 case CMD_ASSEMBLY_GET_NAME: {
6933 MonoAssembly *mass = ass;
6935 name = g_strdup_printf (
6936 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6938 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6939 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6940 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6941 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6943 buffer_add_string (buf, name);
6948 return ERR_NOT_IMPLEMENTED;
6955 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6961 case CMD_MODULE_GET_INFO: {
6962 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
6965 basename = g_path_get_basename (image->name);
6966 buffer_add_string (buf, basename); // name
6967 buffer_add_string (buf, image->module_name); // scopename
6968 buffer_add_string (buf, image->name); // fqname
6969 buffer_add_string (buf, mono_image_get_guid (image)); // guid
6970 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
6975 return ERR_NOT_IMPLEMENTED;
6982 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6984 if (val && val->vtable->klass == mono_defaults.monotype_class) {
6985 /* Special case these so the client doesn't have to handle Type objects */
6987 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6988 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
6989 } else if (MONO_TYPE_IS_REFERENCE (t))
6990 buffer_add_value (buf, t, &val, domain);
6992 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6996 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7002 buffer_add_int (buf, 0);
7006 for (i = 0; i < cinfo->num_attrs; ++i) {
7007 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7010 buffer_add_int (buf, nattrs);
7012 for (i = 0; i < cinfo->num_attrs; ++i) {
7013 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7014 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7015 MonoArray *typed_args, *named_args;
7017 CattrNamedArg *arginfo;
7019 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7021 buffer_add_methodid (buf, domain, attr->ctor);
7025 buffer_add_int (buf, mono_array_length (typed_args));
7026 for (j = 0; j < mono_array_length (typed_args); ++j) {
7027 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7029 t = mono_method_signature (attr->ctor)->params [j];
7031 buffer_add_cattr_arg (buf, t, domain, val);
7034 buffer_add_int (buf, 0);
7039 buffer_add_int (buf, mono_array_length (named_args));
7041 for (j = 0; j < mono_array_length (named_args); ++j) {
7042 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7044 if (arginfo [j].prop) {
7045 buffer_add_byte (buf, 0x54);
7046 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7047 } else if (arginfo [j].field) {
7048 buffer_add_byte (buf, 0x53);
7049 buffer_add_fieldid (buf, domain, arginfo [j].field);
7051 g_assert_not_reached ();
7054 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7057 buffer_add_int (buf, 0);
7063 /* FIXME: Code duplication with icall.c */
7065 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7070 mono_class_setup_interfaces (klass, error);
7071 if (!mono_error_ok (error))
7074 for (i = 0; i < klass->interface_count; i++) {
7075 ic = klass->interfaces [i];
7076 g_hash_table_insert (ifaces, ic, ic);
7078 collect_interfaces (ic, ifaces, error);
7079 if (!mono_error_ok (error))
7085 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7095 case CMD_TYPE_GET_INFO: {
7096 buffer_add_string (buf, klass->name_space);
7097 buffer_add_string (buf, klass->name);
7099 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7100 buffer_add_string (buf, name);
7102 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7103 buffer_add_moduleid (buf, domain, klass->image);
7104 buffer_add_typeid (buf, domain, klass->parent);
7105 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7106 buffer_add_typeid (buf, domain, klass->element_class);
7108 buffer_add_id (buf, 0);
7109 buffer_add_int (buf, klass->type_token);
7110 buffer_add_byte (buf, klass->rank);
7111 buffer_add_int (buf, klass->flags);
7113 type = &klass->byval_arg;
7114 // FIXME: Can't decide whenever a class represents a byref type
7117 if (type->type == MONO_TYPE_PTR)
7119 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7121 if (type->type == MONO_TYPE_VALUETYPE)
7123 if (klass->enumtype)
7125 if (klass->generic_container)
7127 if (klass->generic_container || klass->generic_class)
7129 buffer_add_byte (buf, b);
7132 while ((nested = mono_class_get_nested_types (klass, &iter)))
7134 buffer_add_int (buf, nnested);
7136 while ((nested = mono_class_get_nested_types (klass, &iter)))
7137 buffer_add_typeid (buf, domain, nested);
7138 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7139 if (klass->generic_container)
7140 buffer_add_typeid (buf, domain, klass);
7141 else if (klass->generic_class)
7142 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7144 buffer_add_id (buf, 0);
7146 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7149 if (klass->generic_class) {
7150 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7152 count = inst->type_argc;
7153 buffer_add_int (buf, count);
7154 for (i = 0; i < count; i++)
7155 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7156 } else if (klass->generic_container) {
7157 MonoGenericContainer *container = klass->generic_container;
7160 count = container->type_argc;
7161 buffer_add_int (buf, count);
7162 for (i = 0; i < count; i++) {
7163 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7164 buffer_add_typeid (buf, domain, pklass);
7167 buffer_add_int (buf, 0);
7172 case CMD_TYPE_GET_METHODS: {
7175 gpointer iter = NULL;
7178 mono_class_setup_methods (klass);
7180 nmethods = mono_class_num_methods (klass);
7182 buffer_add_int (buf, nmethods);
7184 while ((m = mono_class_get_methods (klass, &iter))) {
7185 buffer_add_methodid (buf, domain, m);
7188 g_assert (i == nmethods);
7191 case CMD_TYPE_GET_FIELDS: {
7194 gpointer iter = NULL;
7197 nfields = mono_class_num_fields (klass);
7199 buffer_add_int (buf, nfields);
7201 while ((f = mono_class_get_fields (klass, &iter))) {
7202 buffer_add_fieldid (buf, domain, f);
7203 buffer_add_string (buf, f->name);
7204 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7205 buffer_add_int (buf, f->type->attrs);
7208 g_assert (i == nfields);
7211 case CMD_TYPE_GET_PROPERTIES: {
7214 gpointer iter = NULL;
7217 nprops = mono_class_num_properties (klass);
7219 buffer_add_int (buf, nprops);
7221 while ((p = mono_class_get_properties (klass, &iter))) {
7222 buffer_add_propertyid (buf, domain, p);
7223 buffer_add_string (buf, p->name);
7224 buffer_add_methodid (buf, domain, p->get);
7225 buffer_add_methodid (buf, domain, p->set);
7226 buffer_add_int (buf, p->attrs);
7229 g_assert (i == nprops);
7232 case CMD_TYPE_GET_CATTRS: {
7233 MonoClass *attr_klass;
7234 MonoCustomAttrInfo *cinfo;
7236 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7237 /* attr_klass can be NULL */
7241 cinfo = mono_custom_attrs_from_class (klass);
7243 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7246 case CMD_TYPE_GET_FIELD_CATTRS: {
7247 MonoClass *attr_klass;
7248 MonoCustomAttrInfo *cinfo;
7249 MonoClassField *field;
7251 field = decode_fieldid (p, &p, end, NULL, &err);
7254 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7258 cinfo = mono_custom_attrs_from_field (klass, field);
7260 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7263 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7264 MonoClass *attr_klass;
7265 MonoCustomAttrInfo *cinfo;
7268 prop = decode_propertyid (p, &p, end, NULL, &err);
7271 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7275 cinfo = mono_custom_attrs_from_property (klass, prop);
7277 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7280 case CMD_TYPE_GET_VALUES:
7281 case CMD_TYPE_GET_VALUES_2: {
7288 MonoThread *thread_obj;
7289 MonoInternalThread *thread = NULL;
7290 guint32 special_static_type;
7292 if (command == CMD_TYPE_GET_VALUES_2) {
7293 int objid = decode_objid (p, &p, end);
7296 err = get_object (objid, (MonoObject**)&thread_obj);
7300 thread = THREAD_TO_INTERNAL (thread_obj);
7303 len = decode_int (p, &p, end);
7304 for (i = 0; i < len; ++i) {
7305 f = decode_fieldid (p, &p, end, NULL, &err);
7309 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7310 return ERR_INVALID_FIELDID;
7311 special_static_type = mono_class_field_get_special_static_type (f);
7312 if (special_static_type != SPECIAL_STATIC_NONE) {
7313 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7314 return ERR_INVALID_FIELDID;
7317 /* Check that the field belongs to the object */
7319 for (k = klass; k; k = k->parent) {
7320 if (k == f->parent) {
7326 return ERR_INVALID_FIELDID;
7328 vtable = mono_class_vtable (domain, f->parent);
7329 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7330 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7331 buffer_add_value (buf, f->type, val, domain);
7336 case CMD_TYPE_SET_VALUES: {
7344 len = decode_int (p, &p, end);
7345 for (i = 0; i < len; ++i) {
7346 f = decode_fieldid (p, &p, end, NULL, &err);
7350 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7351 return ERR_INVALID_FIELDID;
7352 if (mono_class_field_is_special_static (f))
7353 return ERR_INVALID_FIELDID;
7355 /* Check that the field belongs to the object */
7357 for (k = klass; k; k = k->parent) {
7358 if (k == f->parent) {
7364 return ERR_INVALID_FIELDID;
7366 // FIXME: Check for literal/const
7368 vtable = mono_class_vtable (domain, f->parent);
7369 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7370 err = decode_value (f->type, domain, val, p, &p, end);
7375 if (MONO_TYPE_IS_REFERENCE (f->type))
7376 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7378 mono_field_static_set_value (vtable, f, val);
7383 case CMD_TYPE_GET_OBJECT: {
7384 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7385 buffer_add_objid (buf, o);
7388 case CMD_TYPE_GET_SOURCE_FILES:
7389 case CMD_TYPE_GET_SOURCE_FILES_2: {
7390 char *source_file, *base;
7394 files = get_source_files_for_type (klass);
7396 buffer_add_int (buf, files->len);
7397 for (i = 0; i < files->len; ++i) {
7398 source_file = g_ptr_array_index (files, i);
7399 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7400 buffer_add_string (buf, source_file);
7402 base = g_path_get_basename (source_file);
7403 buffer_add_string (buf, base);
7406 g_free (source_file);
7408 g_ptr_array_free (files, TRUE);
7411 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7412 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7416 if (mono_class_is_assignable_from (klass, oklass))
7417 buffer_add_byte (buf, 1);
7419 buffer_add_byte (buf, 0);
7422 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7423 char *name = decode_string (p, &p, end);
7424 int i, flags = decode_int (p, &p, end);
7425 MonoException *ex = NULL;
7426 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7429 return ERR_LOADER_ERROR;
7430 buffer_add_int (buf, array->len);
7431 for (i = 0; i < array->len; ++i) {
7432 MonoMethod *method = g_ptr_array_index (array, i);
7433 buffer_add_methodid (buf, domain, method);
7436 g_ptr_array_free (array, TRUE);
7440 case CMD_TYPE_GET_INTERFACES: {
7442 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7444 MonoClass *tclass, *iface;
7445 GHashTableIter iter;
7449 for (parent = tclass; parent; parent = parent->parent) {
7450 mono_class_setup_interfaces (parent, &error);
7451 if (!mono_error_ok (&error))
7452 return ERR_LOADER_ERROR;
7453 collect_interfaces (parent, iface_hash, &error);
7454 if (!mono_error_ok (&error))
7455 return ERR_LOADER_ERROR;
7458 buffer_add_int (buf, g_hash_table_size (iface_hash));
7460 g_hash_table_iter_init (&iter, iface_hash);
7461 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7462 buffer_add_typeid (buf, domain, iface);
7463 g_hash_table_destroy (iface_hash);
7466 case CMD_TYPE_GET_INTERFACE_MAP: {
7467 int tindex, ioffset;
7468 gboolean variance_used;
7470 int len, nmethods, i;
7474 len = decode_int (p, &p, end);
7475 mono_class_setup_vtable (klass);
7477 for (tindex = 0; tindex < len; ++tindex) {
7478 iclass = decode_typeid (p, &p, end, NULL, &err);
7482 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7484 return ERR_INVALID_ARGUMENT;
7486 nmethods = mono_class_num_methods (iclass);
7487 buffer_add_int (buf, nmethods);
7490 while ((method = mono_class_get_methods (iclass, &iter))) {
7491 buffer_add_methodid (buf, domain, method);
7493 for (i = 0; i < nmethods; ++i)
7494 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7499 return ERR_NOT_IMPLEMENTED;
7506 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7509 MonoDomain *old_domain;
7513 klass = decode_typeid (p, &p, end, &domain, &err);
7517 old_domain = mono_domain_get ();
7519 mono_domain_set (domain, TRUE);
7521 err = type_commands_internal (command, klass, domain, p, end, buf);
7523 mono_domain_set (old_domain, TRUE);
7529 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7531 MonoMethodHeader *header;
7534 case CMD_METHOD_GET_NAME: {
7535 buffer_add_string (buf, method->name);
7538 case CMD_METHOD_GET_DECLARING_TYPE: {
7539 buffer_add_typeid (buf, domain, method->klass);
7542 case CMD_METHOD_GET_DEBUG_INFO: {
7543 MonoDebugMethodInfo *minfo;
7545 int i, j, n_il_offsets;
7549 GPtrArray *source_file_list;
7551 header = mono_method_get_header (method);
7553 buffer_add_int (buf, 0);
7554 buffer_add_string (buf, "");
7555 buffer_add_int (buf, 0);
7559 minfo = mono_debug_lookup_method (method);
7561 buffer_add_int (buf, header->code_size);
7562 buffer_add_string (buf, "");
7563 buffer_add_int (buf, 0);
7564 mono_metadata_free_mh (header);
7568 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &source_files);
7569 buffer_add_int (buf, header->code_size);
7570 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7571 buffer_add_int (buf, source_file_list->len);
7572 for (i = 0; i < source_file_list->len; ++i) {
7573 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7574 buffer_add_string (buf, sinfo->source_file);
7575 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7576 for (j = 0; j < 16; ++j)
7577 buffer_add_byte (buf, sinfo->hash [j]);
7581 buffer_add_string (buf, source_file);
7583 buffer_add_int (buf, n_il_offsets);
7584 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7585 for (i = 0; i < n_il_offsets; ++i) {
7586 const char *srcfile = "";
7588 if (source_files [i] != -1) {
7589 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7590 srcfile = sinfo->source_file;
7592 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d\n", il_offsets [i], srcfile, line_numbers [i]));
7593 buffer_add_int (buf, il_offsets [i]);
7594 buffer_add_int (buf, line_numbers [i]);
7595 if (CHECK_PROTOCOL_VERSION (2, 13))
7596 buffer_add_int (buf, source_files [i]);
7598 g_free (source_file);
7599 g_free (il_offsets);
7600 g_free (line_numbers);
7601 g_free (source_files);
7602 g_ptr_array_free (source_file_list, TRUE);
7603 mono_metadata_free_mh (header);
7606 case CMD_METHOD_GET_PARAM_INFO: {
7607 MonoMethodSignature *sig = mono_method_signature (method);
7611 /* FIXME: mono_class_from_mono_type () and byrefs */
7613 /* FIXME: Use a smaller encoding */
7614 buffer_add_int (buf, sig->call_convention);
7615 buffer_add_int (buf, sig->param_count);
7616 buffer_add_int (buf, sig->generic_param_count);
7617 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7618 for (i = 0; i < sig->param_count; ++i) {
7620 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7623 /* Emit parameter names */
7624 names = g_new (char *, sig->param_count);
7625 mono_method_get_param_names (method, (const char **) names);
7626 for (i = 0; i < sig->param_count; ++i)
7627 buffer_add_string (buf, names [i]);
7632 case CMD_METHOD_GET_LOCALS_INFO: {
7633 int i, j, num_locals;
7634 MonoDebugLocalsInfo *locals;
7636 header = mono_method_get_header (method);
7638 return ERR_INVALID_ARGUMENT;
7640 buffer_add_int (buf, header->num_locals);
7643 for (i = 0; i < header->num_locals; ++i)
7644 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7647 locals = mono_debug_lookup_locals (method);
7649 num_locals = locals->num_locals;
7652 for (i = 0; i < header->num_locals; ++i) {
7653 for (j = 0; j < num_locals; ++j)
7654 if (locals->locals [j].index == i)
7657 buffer_add_string (buf, locals->locals [j].name);
7659 buffer_add_string (buf, "");
7663 for (i = 0; i < header->num_locals; ++i) {
7664 for (j = 0; j < num_locals; ++j)
7665 if (locals->locals [j].index == i)
7667 if (j < num_locals && locals->locals [j].block) {
7668 buffer_add_int (buf, locals->locals [j].block->start_offset);
7669 buffer_add_int (buf, locals->locals [j].block->end_offset);
7671 buffer_add_int (buf, 0);
7672 buffer_add_int (buf, header->code_size);
7675 mono_metadata_free_mh (header);
7678 mono_debug_symfile_free_locals (locals);
7682 case CMD_METHOD_GET_INFO:
7683 buffer_add_int (buf, method->flags);
7684 buffer_add_int (buf, method->iflags);
7685 buffer_add_int (buf, method->token);
7686 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7688 if (method->is_generic)
7690 if (mono_method_signature (method)->generic_param_count)
7692 buffer_add_byte (buf, attrs);
7693 if (method->is_generic || method->is_inflated) {
7696 if (method->is_generic) {
7699 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7701 result = imethod->declaring;
7702 if (imethod->context.class_inst) {
7703 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7704 /*Generic methods gets the context of the GTD.*/
7705 if (mono_class_get_context (klass))
7706 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7710 buffer_add_methodid (buf, domain, result);
7712 buffer_add_id (buf, 0);
7714 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7715 if (mono_method_signature (method)->generic_param_count) {
7718 if (method->is_inflated) {
7719 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7721 count = inst->type_argc;
7722 buffer_add_int (buf, count);
7724 for (i = 0; i < count; i++)
7725 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7727 buffer_add_int (buf, 0);
7729 } else if (method->is_generic) {
7730 MonoGenericContainer *container = mono_method_get_generic_container (method);
7732 count = mono_method_signature (method)->generic_param_count;
7733 buffer_add_int (buf, count);
7734 for (i = 0; i < count; i++) {
7735 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7736 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7737 buffer_add_typeid (buf, domain, pklass);
7740 buffer_add_int (buf, 0);
7743 buffer_add_int (buf, 0);
7748 case CMD_METHOD_GET_BODY: {
7751 header = mono_method_get_header (method);
7753 buffer_add_int (buf, 0);
7755 if (CHECK_PROTOCOL_VERSION (2, 18))
7756 buffer_add_int (buf, 0);
7758 buffer_add_int (buf, header->code_size);
7759 for (i = 0; i < header->code_size; ++i)
7760 buffer_add_byte (buf, header->code [i]);
7762 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7763 buffer_add_int (buf, header->num_clauses);
7764 for (i = 0; i < header->num_clauses; ++i) {
7765 MonoExceptionClause *clause = &header->clauses [i];
7767 buffer_add_int (buf, clause->flags);
7768 buffer_add_int (buf, clause->try_offset);
7769 buffer_add_int (buf, clause->try_len);
7770 buffer_add_int (buf, clause->handler_offset);
7771 buffer_add_int (buf, clause->handler_len);
7772 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7773 buffer_add_typeid (buf, domain, clause->data.catch_class);
7774 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7775 buffer_add_int (buf, clause->data.filter_offset);
7779 mono_metadata_free_mh (header);
7784 case CMD_METHOD_RESOLVE_TOKEN: {
7785 guint32 token = decode_int (p, &p, end);
7788 switch (mono_metadata_token_code (token)) {
7789 case MONO_TOKEN_STRING: {
7793 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7796 s2 = mono_string_to_utf8 (s);
7798 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7799 buffer_add_string (buf, s2);
7805 MonoClass *handle_class;
7807 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7808 val = mono_method_get_wrapper_data (method, token);
7809 handle_class = mono_method_get_wrapper_data (method, token + 1);
7811 if (handle_class == NULL) {
7812 // Can't figure out the token type
7813 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7817 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7821 if (handle_class == mono_defaults.typehandle_class) {
7822 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7823 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7824 buffer_add_typeid (buf, domain, (MonoClass *) val);
7826 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7827 } else if (handle_class == mono_defaults.fieldhandle_class) {
7828 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7829 buffer_add_fieldid (buf, domain, val);
7830 } else if (handle_class == mono_defaults.methodhandle_class) {
7831 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7832 buffer_add_methodid (buf, domain, val);
7833 } else if (handle_class == mono_defaults.string_class) {
7836 s = mono_string_to_utf8 (val);
7837 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7838 buffer_add_string (buf, s);
7841 g_assert_not_reached ();
7849 return ERR_NOT_IMPLEMENTED;
7856 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7859 MonoDomain *old_domain;
7863 method = decode_methodid (p, &p, end, &domain, &err);
7867 old_domain = mono_domain_get ();
7869 mono_domain_set (domain, TRUE);
7871 err = method_commands_internal (command, method, domain, p, end, buf);
7873 mono_domain_set (old_domain, TRUE);
7879 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7881 int objid = decode_objid (p, &p, end);
7883 MonoThread *thread_obj;
7884 MonoInternalThread *thread;
7886 err = get_object (objid, (MonoObject**)&thread_obj);
7890 thread = THREAD_TO_INTERNAL (thread_obj);
7893 case CMD_THREAD_GET_NAME: {
7895 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7898 buffer_add_int (buf, 0);
7903 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7905 buffer_add_int (buf, len);
7906 buffer_add_data (buf, (guint8*)name, len);
7911 case CMD_THREAD_GET_FRAME_INFO: {
7912 DebuggerTlsData *tls;
7913 int i, start_frame, length;
7915 // Wait for suspending if it already started
7916 // FIXME: Races with suspend_count
7917 while (!is_suspended ()) {
7919 wait_for_suspend ();
7923 wait_for_suspend ();
7924 if (!is_suspended ())
7925 return ERR_NOT_SUSPENDED;
7928 start_frame = decode_int (p, &p, end);
7929 length = decode_int (p, &p, end);
7931 if (start_frame != 0 || length != -1)
7932 return ERR_NOT_IMPLEMENTED;
7934 mono_loader_lock ();
7935 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7936 mono_loader_unlock ();
7939 compute_frame_info (thread, tls);
7941 buffer_add_int (buf, tls->frame_count);
7942 for (i = 0; i < tls->frame_count; ++i) {
7943 buffer_add_int (buf, tls->frames [i]->id);
7944 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
7945 buffer_add_int (buf, tls->frames [i]->il_offset);
7947 * Instead of passing the frame type directly to the client, we associate
7948 * it with the previous frame using a set of flags. This avoids lots of
7949 * conditional code in the client, since a frame whose type isn't
7950 * FRAME_TYPE_MANAGED has no method, location, etc.
7952 buffer_add_byte (buf, tls->frames [i]->flags);
7957 case CMD_THREAD_GET_STATE:
7958 buffer_add_int (buf, thread->state);
7960 case CMD_THREAD_GET_INFO:
7961 buffer_add_byte (buf, thread->threadpool_thread);
7963 case CMD_THREAD_GET_ID:
7964 buffer_add_long (buf, (guint64)(gsize)thread);
7966 case CMD_THREAD_GET_TID:
7967 buffer_add_long (buf, (guint64)thread->tid);
7970 return ERR_NOT_IMPLEMENTED;
7977 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7981 MonoThread *thread_obj;
7982 MonoInternalThread *thread;
7983 int pos, i, len, frame_idx;
7984 DebuggerTlsData *tls;
7986 MonoDebugMethodJitInfo *jit;
7987 MonoDebugVarInfo *var;
7988 MonoMethodSignature *sig;
7990 MonoMethodHeader *header;
7992 objid = decode_objid (p, &p, end);
7993 err = get_object (objid, (MonoObject**)&thread_obj);
7997 thread = THREAD_TO_INTERNAL (thread_obj);
7999 id = decode_id (p, &p, end);
8001 mono_loader_lock ();
8002 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8003 mono_loader_unlock ();
8006 for (i = 0; i < tls->frame_count; ++i) {
8007 if (tls->frames [i]->id == id)
8010 if (i == tls->frame_count)
8011 return ERR_INVALID_FRAMEID;
8014 frame = tls->frames [frame_idx];
8016 if (!frame->has_ctx)
8018 return ERR_INVALID_FRAMEID;
8021 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8022 if (!frame->jit && frame->api_method->is_inflated)
8023 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8027 /* This could happen for aot images with no jit debug info */
8028 s = mono_method_full_name (frame->api_method, TRUE);
8029 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8031 return ERR_ABSENT_INFORMATION;
8036 sig = mono_method_signature (frame->actual_method);
8038 if (!get_seq_points (frame->domain, frame->actual_method))
8040 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8042 return ERR_ABSENT_INFORMATION;
8045 case CMD_STACK_FRAME_GET_VALUES: {
8046 len = decode_int (p, &p, end);
8047 header = mono_method_get_header (frame->actual_method);
8049 for (i = 0; i < len; ++i) {
8050 pos = decode_int (p, &p, end);
8055 g_assert (pos >= 0 && pos < jit->num_params);
8057 var = &jit->params [pos];
8059 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8061 g_assert (pos >= 0 && pos < jit->num_locals);
8063 var = &jit->locals [pos];
8065 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8068 mono_metadata_free_mh (header);
8071 case CMD_STACK_FRAME_GET_THIS: {
8072 if (frame->api_method->klass->valuetype) {
8073 if (!sig->hasthis) {
8074 MonoObject *p = NULL;
8075 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8077 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8080 if (!sig->hasthis) {
8081 MonoObject *p = NULL;
8082 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8084 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8089 case CMD_STACK_FRAME_SET_VALUES: {
8092 MonoDebugVarInfo *var;
8094 len = decode_int (p, &p, end);
8095 header = mono_method_get_header (frame->actual_method);
8097 for (i = 0; i < len; ++i) {
8098 pos = decode_int (p, &p, end);
8103 g_assert (pos >= 0 && pos < jit->num_params);
8105 t = sig->params [pos];
8106 var = &jit->params [pos];
8108 g_assert (pos >= 0 && pos < jit->num_locals);
8110 t = header->locals [pos];
8111 var = &jit->locals [pos];
8114 if (MONO_TYPE_IS_REFERENCE (t))
8115 val_buf = g_alloca (sizeof (MonoObject*));
8117 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8118 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8122 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8124 mono_metadata_free_mh (header);
8128 return ERR_NOT_IMPLEMENTED;
8135 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8138 int objid, err, index, len, i, esize;
8141 objid = decode_objid (p, &p, end);
8142 err = get_object (objid, (MonoObject**)&arr);
8147 case CMD_ARRAY_REF_GET_LENGTH:
8148 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8150 buffer_add_int (buf, arr->max_length);
8151 buffer_add_int (buf, 0);
8153 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8154 buffer_add_int (buf, arr->bounds [i].length);
8155 buffer_add_int (buf, arr->bounds [i].lower_bound);
8159 case CMD_ARRAY_REF_GET_VALUES:
8160 index = decode_int (p, &p, end);
8161 len = decode_int (p, &p, end);
8163 g_assert (index >= 0 && len >= 0);
8164 // Reordered to avoid integer overflow
8165 g_assert (!(index > arr->max_length - len));
8167 esize = mono_array_element_size (arr->obj.vtable->klass);
8168 for (i = index; i < index + len; ++i) {
8169 elem = (gpointer*)((char*)arr->vector + (i * esize));
8170 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8173 case CMD_ARRAY_REF_SET_VALUES:
8174 index = decode_int (p, &p, end);
8175 len = decode_int (p, &p, end);
8177 g_assert (index >= 0 && len >= 0);
8178 // Reordered to avoid integer overflow
8179 g_assert (!(index > arr->max_length - len));
8181 esize = mono_array_element_size (arr->obj.vtable->klass);
8182 for (i = index; i < index + len; ++i) {
8183 elem = (gpointer*)((char*)arr->vector + (i * esize));
8185 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8189 return ERR_NOT_IMPLEMENTED;
8196 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8201 int i, index, length;
8204 objid = decode_objid (p, &p, end);
8205 err = get_object (objid, (MonoObject**)&str);
8210 case CMD_STRING_REF_GET_VALUE:
8211 s = mono_string_to_utf8 (str);
8212 buffer_add_string (buf, s);
8215 case CMD_STRING_REF_GET_LENGTH:
8216 buffer_add_long (buf, mono_string_length (str));
8218 case CMD_STRING_REF_GET_CHARS:
8219 index = decode_long (p, &p, end);
8220 length = decode_long (p, &p, end);
8221 if (index > mono_string_length (str) - length)
8222 return ERR_INVALID_ARGUMENT;
8223 c = mono_string_chars (str) + index;
8224 for (i = 0; i < length; ++i)
8225 buffer_add_short (buf, c [i]);
8228 return ERR_NOT_IMPLEMENTED;
8235 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8244 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8245 objid = decode_objid (p, &p, end);
8246 err = get_object (objid, &obj);
8248 buffer_add_int (buf, 1);
8250 buffer_add_int (buf, 0);
8254 objid = decode_objid (p, &p, end);
8255 err = get_object (objid, &obj);
8260 case CMD_OBJECT_REF_GET_TYPE:
8261 /* This handles transparent proxies too */
8262 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8264 case CMD_OBJECT_REF_GET_VALUES:
8265 len = decode_int (p, &p, end);
8267 for (i = 0; i < len; ++i) {
8268 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8272 /* Check that the field belongs to the object */
8274 for (k = obj->vtable->klass; k; k = k->parent) {
8275 if (k == f->parent) {
8281 return ERR_INVALID_FIELDID;
8283 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8287 if (mono_class_field_is_special_static (f))
8288 return ERR_INVALID_FIELDID;
8290 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8291 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8292 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8293 mono_field_static_get_value (vtable, f, val);
8294 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8297 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8301 case CMD_OBJECT_REF_SET_VALUES:
8302 len = decode_int (p, &p, end);
8304 for (i = 0; i < len; ++i) {
8305 f = decode_fieldid (p, &p, end, NULL, &err);
8309 /* Check that the field belongs to the object */
8311 for (k = obj->vtable->klass; k; k = k->parent) {
8312 if (k == f->parent) {
8318 return ERR_INVALID_FIELDID;
8320 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8324 if (mono_class_field_is_special_static (f))
8325 return ERR_INVALID_FIELDID;
8327 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8328 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8330 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8331 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8336 mono_field_static_set_value (vtable, f, val);
8339 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8345 case CMD_OBJECT_REF_GET_ADDRESS:
8346 buffer_add_long (buf, (gssize)obj);
8348 case CMD_OBJECT_REF_GET_DOMAIN:
8349 buffer_add_domainid (buf, obj->vtable->domain);
8351 case CMD_OBJECT_REF_GET_INFO:
8352 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8353 buffer_add_domainid (buf, obj->vtable->domain);
8356 return ERR_NOT_IMPLEMENTED;
8363 command_set_to_string (CommandSet command_set)
8365 switch (command_set) {
8368 case CMD_SET_OBJECT_REF:
8369 return "OBJECT_REF";
8370 case CMD_SET_STRING_REF:
8371 return "STRING_REF";
8372 case CMD_SET_THREAD:
8374 case CMD_SET_ARRAY_REF:
8376 case CMD_SET_EVENT_REQUEST:
8377 return "EVENT_REQUEST";
8378 case CMD_SET_STACK_FRAME:
8379 return "STACK_FRAME";
8380 case CMD_SET_APPDOMAIN:
8382 case CMD_SET_ASSEMBLY:
8384 case CMD_SET_METHOD:
8388 case CMD_SET_MODULE:
8398 cmd_to_string (CommandSet set, int command)
8403 case CMD_VM_VERSION:
8405 case CMD_VM_ALL_THREADS:
8406 return "ALL_THREADS";
8407 case CMD_VM_SUSPEND:
8413 case CMD_VM_DISPOSE:
8415 case CMD_VM_INVOKE_METHOD:
8416 return "INVOKE_METHOD";
8417 case CMD_VM_SET_PROTOCOL_VERSION:
8418 return "SET_PROTOCOL_VERSION";
8419 case CMD_VM_ABORT_INVOKE:
8420 return "ABORT_INVOKE";
8433 wait_for_attach (void)
8435 #ifndef DISABLE_SOCKET_TRANSPORT
8436 if (listen_fd == -1) {
8437 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8441 /* Block and wait for client connection */
8442 conn_fd = socket_transport_accept (listen_fd);
8443 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8444 if (conn_fd == -1) {
8445 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8449 g_assert_not_reached ();
8453 disconnected = !transport_handshake ();
8455 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8465 * This thread handles communication with the debugger client using a JDWP
8468 static guint32 WINAPI
8469 debugger_thread (void *arg)
8471 int res, len, id, flags, command_set = 0, command = 0;
8472 guint8 header [HEADER_LENGTH];
8473 guint8 *data, *p, *end;
8477 gboolean attach_failed = FALSE;
8479 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8481 debugger_thread_id = GetCurrentThreadId ();
8483 mono_jit_thread_attach (mono_get_root_domain ());
8485 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8487 mono_set_is_debugger_attached (TRUE);
8489 if (agent_config.defer) {
8490 if (!wait_for_attach ()) {
8491 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8492 attach_failed = TRUE; // Don't abort process when we can't listen
8494 /* Send start event to client */
8495 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8499 while (!attach_failed) {
8500 res = transport_recv (header, HEADER_LENGTH);
8502 /* This will break if the socket is closed during shutdown too */
8503 if (res != HEADER_LENGTH)
8507 end = header + HEADER_LENGTH;
8509 len = decode_int (p, &p, end);
8510 id = decode_int (p, &p, end);
8511 flags = decode_byte (p, &p, end);
8512 command_set = decode_byte (p, &p, end);
8513 command = decode_byte (p, &p, end);
8515 g_assert (flags == 0);
8518 const char *cmd_str;
8521 cmd_str = cmd_to_string (command_set, command);
8523 sprintf (cmd_num, "%d", command);
8527 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8530 data = g_malloc (len - HEADER_LENGTH);
8531 if (len - HEADER_LENGTH > 0)
8533 res = transport_recv (data, len - HEADER_LENGTH);
8534 if (res != len - HEADER_LENGTH)
8539 end = data + (len - HEADER_LENGTH);
8541 buffer_init (&buf, 128);
8546 /* Process the request */
8547 switch (command_set) {
8549 err = vm_commands (command, id, p, end, &buf);
8550 if (!err && command == CMD_VM_INVOKE_METHOD)
8551 /* Sent after the invoke is complete */
8554 case CMD_SET_EVENT_REQUEST:
8555 err = event_commands (command, p, end, &buf);
8557 case CMD_SET_APPDOMAIN:
8558 err = domain_commands (command, p, end, &buf);
8560 case CMD_SET_ASSEMBLY:
8561 err = assembly_commands (command, p, end, &buf);
8563 case CMD_SET_MODULE:
8564 err = module_commands (command, p, end, &buf);
8567 err = type_commands (command, p, end, &buf);
8569 case CMD_SET_METHOD:
8570 err = method_commands (command, p, end, &buf);
8572 case CMD_SET_THREAD:
8573 err = thread_commands (command, p, end, &buf);
8575 case CMD_SET_STACK_FRAME:
8576 err = frame_commands (command, p, end, &buf);
8578 case CMD_SET_ARRAY_REF:
8579 err = array_commands (command, p, end, &buf);
8581 case CMD_SET_STRING_REF:
8582 err = string_commands (command, p, end, &buf);
8584 case CMD_SET_OBJECT_REF:
8585 err = object_commands (command, p, end, &buf);
8588 err = ERR_NOT_IMPLEMENTED;
8592 send_reply_packet (id, err, &buf);
8597 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8601 mono_set_is_debugger_attached (FALSE);
8603 mono_mutex_lock (&debugger_thread_exited_mutex);
8604 debugger_thread_exited = TRUE;
8605 mono_cond_signal (&debugger_thread_exited_cond);
8606 mono_mutex_unlock (&debugger_thread_exited_mutex);
8608 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8610 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8611 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8612 start_debugger_thread ();
8618 #else /* DISABLE_DEBUGGER_AGENT */
8621 mono_debugger_agent_parse_options (char *options)
8623 g_error ("This runtime is configured with the debugger agent disabled.");
8627 mono_debugger_agent_init (void)
8632 mono_debugger_agent_breakpoint_hit (void *sigctx)
8637 mono_debugger_agent_single_step_event (void *sigctx)
8642 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8647 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8653 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8654 MonoContext *catch_ctx)
8659 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8664 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8669 mono_debugger_agent_user_break (void)
8675 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8680 mono_debugger_agent_debug_log_is_enabled (void)