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 <mono/utils/mono-threads.h>
80 #include "debugger-agent.h"
83 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
84 #define DISABLE_DEBUGGER_AGENT 1
87 #ifdef DISABLE_SOFT_DEBUG
88 #define DISABLE_DEBUGGER_AGENT 1
91 #ifndef DISABLE_DEBUGGER_AGENT
93 #include <mono/io-layer/mono-mutex.h>
95 /* Definitions to make backporting to 2.6 easier */
96 //#define MonoInternalThread MonoThread
97 //#define mono_thread_internal_current mono_thread_current
98 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
120 guint32 il_offset, native_offset;
124 * If method is gshared, this is the actual instance, otherwise this is equal to
127 MonoMethod *actual_method;
129 * This is the method which is visible to debugger clients. Same as method,
130 * except for native-to-managed wrappers.
132 MonoMethod *api_method;
134 MonoDebugMethodJitInfo *jit;
137 mgreg_t *reg_locations [MONO_MAX_IREGS];
139 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
140 * the frame can become invalid.
145 typedef struct _InvokeData InvokeData;
153 /* This is the context which needs to be restored after the invoke */
157 * If this is set, invoke this method with the arguments given by ARGS.
161 guint32 suspend_count;
164 InvokeData *last_invoke;
168 MonoThreadUnwindState context;
170 gpointer resume_event;
171 /* This is computed on demand when it is requested using the wire protocol */
172 /* It is freed up when the thread is resumed */
176 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
179 gboolean frames_up_to_date;
181 * Points to data about a pending invoke which needs to be executed after the thread
184 InvokeData *pending_invoke;
186 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
191 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
192 * within a finite amount of time.
196 * Set to TRUE if this thread is suspended in suspend_current ().
198 gboolean really_suspended;
199 /* Used to pass the context to the breakpoint/single step handler */
200 MonoContext handler_ctx;
201 /* Whenever thread_stop () was called for this thread */
204 /* Number of thread interruptions not yet processed */
205 gint32 interrupt_count;
207 /* Whenever to disable breakpoints (used during invokes) */
208 gboolean disable_breakpoints;
211 * Number of times this thread has been resumed using resume_thread ().
213 guint32 resume_count;
215 MonoInternalThread *thread;
218 * Information about the frame which transitioned to native code for running
221 StackFrameInfo async_last_frame;
224 * The context where the stack walk can be started for running threads.
226 MonoThreadUnwindState async_state;
229 * The context used for filter clauses
231 MonoThreadUnwindState filter_state;
234 * The callee address of the last mono_runtime_invoke call
236 gpointer invoke_addr;
238 gboolean abort_requested;
241 * The current mono_runtime_invoke invocation.
246 * The context where single stepping should resume while the thread is suspended because
247 * of an EXCEPTION event.
249 MonoContext catch_ctx;
251 gboolean has_catch_ctx;
254 * The context which needs to be restored after handling a single step/breakpoint
255 * event. This is the same as the ctx at step/breakpoint site, but includes changes
256 * to caller saved registers done by set_var ().
258 MonoContext restore_ctx;
263 void (*connect) (const char *address);
264 void (*close1) (void);
265 void (*close2) (void);
266 gboolean (*send) (void *buf, int len);
267 int (*recv) (void *buf, int len);
271 * Wire Protocol definitions
274 #define HEADER_LENGTH 11
276 #define MAJOR_VERSION 2
277 #define MINOR_VERSION 22
281 CMD_SET_OBJECT_REF = 9,
282 CMD_SET_STRING_REF = 10,
284 CMD_SET_ARRAY_REF = 13,
285 CMD_SET_EVENT_REQUEST = 15,
286 CMD_SET_STACK_FRAME = 16,
287 CMD_SET_APPDOMAIN = 20,
288 CMD_SET_ASSEMBLY = 21,
296 EVENT_KIND_VM_START = 0,
297 EVENT_KIND_VM_DEATH = 1,
298 EVENT_KIND_THREAD_START = 2,
299 EVENT_KIND_THREAD_DEATH = 3,
300 EVENT_KIND_APPDOMAIN_CREATE = 4,
301 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
302 EVENT_KIND_METHOD_ENTRY = 6,
303 EVENT_KIND_METHOD_EXIT = 7,
304 EVENT_KIND_ASSEMBLY_LOAD = 8,
305 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
306 EVENT_KIND_BREAKPOINT = 10,
307 EVENT_KIND_STEP = 11,
308 EVENT_KIND_TYPE_LOAD = 12,
309 EVENT_KIND_EXCEPTION = 13,
310 EVENT_KIND_KEEPALIVE = 14,
311 EVENT_KIND_USER_BREAK = 15,
312 EVENT_KIND_USER_LOG = 16
316 SUSPEND_POLICY_NONE = 0,
317 SUSPEND_POLICY_EVENT_THREAD = 1,
318 SUSPEND_POLICY_ALL = 2
323 ERR_INVALID_OBJECT = 20,
324 ERR_INVALID_FIELDID = 25,
325 ERR_INVALID_FRAMEID = 30,
326 ERR_NOT_IMPLEMENTED = 100,
327 ERR_NOT_SUSPENDED = 101,
328 ERR_INVALID_ARGUMENT = 102,
330 ERR_NO_INVOCATION = 104,
331 ERR_ABSENT_INFORMATION = 105,
332 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
333 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
338 MOD_KIND_THREAD_ONLY = 3,
339 MOD_KIND_LOCATION_ONLY = 7,
340 MOD_KIND_EXCEPTION_ONLY = 8,
342 MOD_KIND_ASSEMBLY_ONLY = 11,
343 MOD_KIND_SOURCE_FILE_ONLY = 12,
344 MOD_KIND_TYPE_NAME_ONLY = 13
359 STEP_FILTER_NONE = 0,
360 STEP_FILTER_STATIC_CTOR = 1,
361 STEP_FILTER_DEBUGGER_HIDDEN = 2
365 TOKEN_TYPE_STRING = 0,
367 TOKEN_TYPE_FIELD = 2,
368 TOKEN_TYPE_METHOD = 3,
369 TOKEN_TYPE_UNKNOWN = 4
373 VALUE_TYPE_ID_NULL = 0xf0,
374 VALUE_TYPE_ID_TYPE = 0xf1
378 FRAME_FLAG_DEBUGGER_INVOKE = 1,
379 FRAME_FLAG_NATIVE_TRANSITION = 2
383 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
384 INVOKE_FLAG_SINGLE_THREADED = 2
388 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
389 } BindingFlagsExtensions;
393 CMD_VM_ALL_THREADS = 2,
398 CMD_VM_INVOKE_METHOD = 7,
399 CMD_VM_SET_PROTOCOL_VERSION = 8,
400 CMD_VM_ABORT_INVOKE = 9,
401 CMD_VM_SET_KEEPALIVE = 10,
402 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
403 CMD_VM_GET_TYPES = 12,
404 CMD_VM_INVOKE_METHODS = 13
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,
458 CMD_METHOD_GET_CATTRS = 9,
462 CMD_TYPE_GET_INFO = 1,
463 CMD_TYPE_GET_METHODS = 2,
464 CMD_TYPE_GET_FIELDS = 3,
465 CMD_TYPE_GET_VALUES = 4,
466 CMD_TYPE_GET_OBJECT = 5,
467 CMD_TYPE_GET_SOURCE_FILES = 6,
468 CMD_TYPE_SET_VALUES = 7,
469 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
470 CMD_TYPE_GET_PROPERTIES = 9,
471 CMD_TYPE_GET_CATTRS = 10,
472 CMD_TYPE_GET_FIELD_CATTRS = 11,
473 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
474 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
475 CMD_TYPE_GET_VALUES_2 = 14,
476 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
477 CMD_TYPE_GET_INTERFACES = 16,
478 CMD_TYPE_GET_INTERFACE_MAP = 17,
482 CMD_STACK_FRAME_GET_VALUES = 1,
483 CMD_STACK_FRAME_GET_THIS = 2,
484 CMD_STACK_FRAME_SET_VALUES = 3
488 CMD_ARRAY_REF_GET_LENGTH = 1,
489 CMD_ARRAY_REF_GET_VALUES = 2,
490 CMD_ARRAY_REF_SET_VALUES = 3,
494 CMD_STRING_REF_GET_VALUE = 1,
495 CMD_STRING_REF_GET_LENGTH = 2,
496 CMD_STRING_REF_GET_CHARS = 3
500 CMD_OBJECT_REF_GET_TYPE = 1,
501 CMD_OBJECT_REF_GET_VALUES = 2,
502 CMD_OBJECT_REF_IS_COLLECTED = 3,
503 CMD_OBJECT_REF_GET_ADDRESS = 4,
504 CMD_OBJECT_REF_GET_DOMAIN = 5,
505 CMD_OBJECT_REF_SET_VALUES = 6,
506 CMD_OBJECT_REF_GET_INFO = 7,
512 int count; /* For kind == MOD_KIND_COUNT */
513 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
514 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
515 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
516 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
517 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
518 StepFilter filter; /* For kind == MOD_KIND_STEP */
520 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
529 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
533 * Describes a single step request.
537 MonoInternalThread *thread;
543 MonoMethod *last_method;
545 /* Whenever single stepping is performed using start/stop_single_stepping () */
547 /* The list of breakpoints used to implement step-over */
552 * Contains additional information for an event
555 /* For EVENT_KIND_EXCEPTION */
557 MonoContext catch_ctx;
559 /* For EVENT_KIND_USER_LOG */
561 char *category, *message;
562 /* For EVENT_KIND_TYPE_LOAD */
566 /* Dummy structure used for the profiler callbacks */
571 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
574 #define get_last_sock_error() WSAGetLastError()
575 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
576 #define MONO_EINTR WSAEINTR
578 #define get_last_sock_error() errno
579 #define MONO_EWOULDBLOCK EWOULDBLOCK
580 #define MONO_EINTR EINTR
583 #define CHECK_PROTOCOL_VERSION(major,minor) \
584 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
590 static AgentConfig agent_config;
593 * Whenever the agent is fully initialized.
594 * When using the onuncaught or onthrow options, only some parts of the agent are
595 * initialized on startup, and the full initialization which includes connection
596 * establishment and the startup of the agent thread is only done in response to
599 static gint32 inited;
601 #ifndef DISABLE_SOCKET_TRANSPORT
603 static int listen_fd;
606 static int packet_id = 0;
608 static int objref_id = 0;
610 static int event_request_id = 0;
612 static int frame_id = 0;
614 static GPtrArray *event_requests;
616 static MonoNativeTlsKey debugger_tls_id;
618 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
620 /* Maps MonoInternalThread -> DebuggerTlsData */
621 static MonoGHashTable *thread_to_tls;
623 /* Maps tid -> MonoInternalThread */
624 static MonoGHashTable *tid_to_thread;
626 /* Maps tid -> MonoThread (not MonoInternalThread) */
627 static MonoGHashTable *tid_to_thread_obj;
629 static gsize debugger_thread_id;
631 static HANDLE debugger_thread_handle;
633 static int log_level;
635 static gboolean embedding;
637 static FILE *log_file;
639 /* Assemblies whose assembly load event has no been sent yet */
640 static GPtrArray *pending_assembly_loads;
642 /* Whenever the debugger thread has exited */
643 static gboolean debugger_thread_exited;
645 /* Cond variable used to wait for debugger_thread_exited becoming true */
646 static mono_cond_t debugger_thread_exited_cond;
648 /* Mutex for the cond var above */
649 static mono_mutex_t debugger_thread_exited_mutex;
651 static DebuggerProfiler debugger_profiler;
653 /* The single step request instance */
654 static SingleStepReq *ss_req = NULL;
655 static gpointer ss_invoke_addr = NULL;
657 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
658 /* Number of single stepping operations in progress */
662 /* The protocol version of the client */
663 static int major_version, minor_version;
665 /* Whenever the variables above are set by the client */
666 static gboolean protocol_version_set;
668 /* A hash table containing all active domains */
669 static GHashTable *domains;
671 static void transport_init (void);
672 static void transport_connect (const char *address);
673 static gboolean transport_handshake (void);
674 static void register_transport (DebuggerTransport *trans);
676 static guint32 WINAPI debugger_thread (void *arg);
678 static void runtime_initialized (MonoProfiler *prof);
680 static void runtime_shutdown (MonoProfiler *prof);
682 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
684 static void thread_end (MonoProfiler *prof, uintptr_t tid);
686 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
688 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
690 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
692 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
694 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
696 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
698 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
700 static void emit_assembly_load (gpointer assembly, gpointer user_data);
702 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
704 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
706 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
708 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
710 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
712 static void start_single_stepping (void);
714 static void stop_single_stepping (void);
716 static void suspend_current (void);
718 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
720 static void clear_types_for_assembly (MonoAssembly *assembly);
722 static void clear_breakpoints_for_domain (MonoDomain *domain);
724 static void process_profiler_event (EventKind event, gpointer arg);
726 /* Submodule init/cleanup */
727 static void breakpoints_init (void);
728 static void breakpoints_cleanup (void);
730 static void objrefs_init (void);
731 static void objrefs_cleanup (void);
733 static void ids_init (void);
734 static void ids_cleanup (void);
736 static void suspend_init (void);
738 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
739 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
740 static void ss_destroy (SingleStepReq *req);
742 static void start_debugger_thread (void);
743 static void stop_debugger_thread (void);
745 static void finish_agent_init (gboolean on_startup);
747 static void process_profiler_event (EventKind event, gpointer arg);
749 static void invalidate_frames (DebuggerTlsData *tls);
751 #ifndef DISABLE_SOCKET_TRANSPORT
753 register_socket_transport (void);
757 parse_address (char *address, char **host, int *port)
759 char *pos = strchr (address, ':');
761 if (pos == NULL || pos == address)
764 *host = g_malloc (pos - address + 1);
765 strncpy (*host, address, pos - address);
766 (*host) [pos - address] = '\0';
768 *port = atoi (pos + 1);
776 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
777 fprintf (stderr, "Available options:\n");
778 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
779 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
780 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
781 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
782 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
783 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
784 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
785 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
786 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
790 parse_flag (const char *option, char *flag)
792 if (!strcmp (flag, "y"))
794 else if (!strcmp (flag, "n"))
797 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
804 mono_debugger_agent_parse_options (char *options)
811 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
812 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
816 extra = getenv ("MONO_SDB_ENV_OPTIONS");
818 options = g_strdup_printf ("%s,%s", options, extra);
820 agent_config.enabled = TRUE;
821 agent_config.suspend = TRUE;
822 agent_config.server = FALSE;
823 agent_config.defer = FALSE;
824 agent_config.address = NULL;
826 args = g_strsplit (options, ",", -1);
827 for (ptr = args; ptr && *ptr; ptr ++) {
830 if (strncmp (arg, "transport=", 10) == 0) {
831 agent_config.transport = g_strdup (arg + 10);
832 } else if (strncmp (arg, "address=", 8) == 0) {
833 agent_config.address = g_strdup (arg + 8);
834 } else if (strncmp (arg, "loglevel=", 9) == 0) {
835 agent_config.log_level = atoi (arg + 9);
836 } else if (strncmp (arg, "logfile=", 8) == 0) {
837 agent_config.log_file = g_strdup (arg + 8);
838 } else if (strncmp (arg, "suspend=", 8) == 0) {
839 agent_config.suspend = parse_flag ("suspend", arg + 8);
840 } else if (strncmp (arg, "server=", 7) == 0) {
841 agent_config.server = parse_flag ("server", arg + 7);
842 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
843 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
844 } else if (strncmp (arg, "onthrow=", 8) == 0) {
845 /* We support multiple onthrow= options */
846 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
847 } else if (strncmp (arg, "onthrow", 7) == 0) {
848 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
849 } else if (strncmp (arg, "help", 4) == 0) {
852 } else if (strncmp (arg, "timeout=", 8) == 0) {
853 agent_config.timeout = atoi (arg + 8);
854 } else if (strncmp (arg, "launch=", 7) == 0) {
855 agent_config.launch = g_strdup (arg + 7);
856 } else if (strncmp (arg, "embedding=", 10) == 0) {
857 agent_config.embedding = atoi (arg + 10) == 1;
858 } else if (strncmp (arg, "keepalive=", 10) == 0) {
859 agent_config.keepalive = atoi (arg + 10);
866 if (agent_config.server && !agent_config.suspend) {
867 /* Waiting for deferred attachment */
868 agent_config.defer = TRUE;
869 if (agent_config.address == NULL) {
870 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
874 //agent_config.log_level = 0;
876 if (agent_config.transport == NULL) {
877 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
881 if (agent_config.address == NULL && !agent_config.server) {
882 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
887 if (!strcmp (agent_config.transport, "dt_socket")) {
888 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
889 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
896 mono_debugger_agent_init (void)
898 if (!agent_config.enabled)
903 /* Need to know whenever a thread has acquired the loader mutex */
904 mono_loader_lock_track_ownership (TRUE);
906 event_requests = g_ptr_array_new ();
908 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
909 mono_cond_init (&debugger_thread_exited_cond, NULL);
911 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
912 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
913 mono_profiler_install_runtime_initialized (runtime_initialized);
914 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
915 mono_profiler_install_thread (thread_startup, thread_end);
916 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
917 mono_profiler_install_jit_end (jit_end);
918 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
920 mono_native_tls_alloc (&debugger_tls_id, NULL);
922 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
923 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
925 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
926 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
928 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
929 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
931 pending_assembly_loads = g_ptr_array_new ();
932 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
934 log_level = agent_config.log_level;
936 embedding = agent_config.embedding;
939 if (agent_config.log_file) {
940 log_file = fopen (agent_config.log_file, "w+");
942 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
954 mini_get_debug_options ()->gen_seq_points = TRUE;
956 * This is needed because currently we don't handle liveness info.
958 mini_get_debug_options ()->mdb_optimizations = TRUE;
960 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
961 /* This is needed because we can't set local variables in registers yet */
962 mono_disable_optimizations (MONO_OPT_LINEARS);
966 * The stack walk done from thread_interrupt () needs to be signal safe, but it
967 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
968 * safe (#3411). So load AOT info eagerly when the debugger is running as a
971 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
973 if (!agent_config.onuncaught && !agent_config.onthrow)
974 finish_agent_init (TRUE);
980 * Finish the initialization of the agent. This involves connecting the transport
981 * and starting the agent thread. This is either done at startup, or
982 * in response to some event like an unhandled exception.
985 finish_agent_init (gboolean on_startup)
989 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
992 if (agent_config.launch) {
995 // FIXME: Generated address
996 // FIXME: Races with transport_connect ()
998 argv [0] = agent_config.launch;
999 argv [1] = agent_config.transport;
1000 argv [2] = agent_config.address;
1003 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1005 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1010 transport_connect (agent_config.address);
1013 /* Do some which is usually done after sending the VMStart () event */
1014 vm_start_event_sent = TRUE;
1015 start_debugger_thread ();
1020 mono_debugger_agent_cleanup (void)
1025 stop_debugger_thread ();
1027 breakpoints_cleanup ();
1031 mono_mutex_destroy (&debugger_thread_exited_mutex);
1032 mono_cond_destroy (&debugger_thread_exited_cond);
1039 #ifndef DISABLE_SOCKET_TRANSPORT
1044 * recv() + handle incomplete reads and EINTR
1047 socket_transport_recv (void *buf, int len)
1053 static gint32 last_keepalive;
1058 res = recv (fd, (char *) buf + total, len - total, flags);
1061 if (agent_config.keepalive) {
1062 gboolean need_keepalive = FALSE;
1063 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1064 need_keepalive = TRUE;
1065 } else if (res == -1) {
1066 /* This could happen if recv () is interrupted repeatedly */
1067 msecs = mono_msec_ticks ();
1068 if (msecs - last_keepalive >= agent_config.keepalive) {
1069 need_keepalive = TRUE;
1070 last_keepalive = msecs;
1073 if (need_keepalive) {
1074 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1078 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1083 #define HAVE_GETADDRINFO 1
1087 set_keepalive (void)
1092 if (!agent_config.keepalive || !conn_fd)
1095 tv.tv_sec = agent_config.keepalive / 1000;
1096 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1098 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1099 g_assert (result >= 0);
1103 socket_transport_accept (int socket_fd)
1105 conn_fd = accept (socket_fd, NULL, NULL);
1106 if (conn_fd == -1) {
1107 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1109 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1116 socket_transport_send (void *data, int len)
1121 res = send (conn_fd, data, len, 0);
1122 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1130 * socket_transport_connect:
1132 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1135 socket_transport_connect (const char *address)
1137 #ifdef HAVE_GETADDRINFO
1138 struct addrinfo hints;
1139 struct addrinfo *result, *rp;
1141 struct hostent *result;
1143 int sfd = -1, s, res;
1144 char port_string [128];
1148 if (agent_config.address) {
1149 res = parse_address (agent_config.address, &host, &port);
1150 g_assert (res == 0);
1160 sprintf (port_string, "%d", port);
1162 mono_network_init ();
1164 /* Obtain address(es) matching host/port */
1165 #ifdef HAVE_GETADDRINFO
1166 memset (&hints, 0, sizeof (struct addrinfo));
1167 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1168 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1170 hints.ai_protocol = 0; /* Any protocol */
1172 s = getaddrinfo (host, port_string, &hints, &result);
1174 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1178 /* The PS3 doesn't even have _r or hstrerror () */
1179 result = gethostbyname (host);
1181 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1186 if (agent_config.server) {
1187 #ifdef HAVE_GETADDRINFO
1188 /* Wait for a connection */
1190 struct sockaddr_in addr;
1193 /* No address, generate one */
1194 sfd = socket (AF_INET, SOCK_STREAM, 0);
1197 /* This will bind the socket to a random port */
1198 res = listen (sfd, 16);
1200 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1205 addrlen = sizeof (addr);
1206 memset (&addr, 0, sizeof (addr));
1207 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1208 g_assert (res == 0);
1210 host = (char*)"127.0.0.1";
1211 port = ntohs (addr.sin_port);
1213 /* Emit the address to stdout */
1214 /* FIXME: Should print another interface, not localhost */
1215 printf ("%s:%d\n", host, port);
1217 /* Listen on the provided address */
1218 for (rp = result; rp != NULL; rp = rp->ai_next) {
1221 sfd = socket (rp->ai_family, rp->ai_socktype,
1226 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1229 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1233 res = listen (sfd, 16);
1242 * this function is not present on win2000 which we still support, and the
1243 * workaround described here:
1244 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1245 * only works with MSVC.
1247 #ifdef HAVE_GETADDRINFO
1248 freeaddrinfo (result);
1253 if (agent_config.defer)
1256 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1258 if (agent_config.timeout) {
1263 tv.tv_usec = agent_config.timeout * 1000;
1265 FD_SET (sfd, &readfds);
1266 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1268 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1273 conn_fd = socket_transport_accept (sfd);
1277 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1280 #endif /* HAVE_GETADDRINFO */
1282 /* Connect to the specified address */
1283 #ifdef HAVE_GETADDRINFO
1284 /* FIXME: Respect the timeout */
1285 for (rp = result; rp != NULL; rp = rp->ai_next) {
1286 sfd = socket (rp->ai_family, rp->ai_socktype,
1291 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1292 break; /* Success */
1298 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1302 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1304 g_assert_not_reached ();
1305 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1307 g_assert_not_reached ();
1313 /* See the comment above */
1314 #ifdef HAVE_GETADDRINFO
1315 freeaddrinfo (result);
1320 disconnected = !transport_handshake ();
1326 socket_transport_close1 (void)
1328 /* This will interrupt the agent thread */
1329 /* Close the read part only so it can still send back replies */
1330 /* Also shut down the connection listener so that we can exit normally */
1332 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1333 shutdown (conn_fd, SD_BOTH);
1334 shutdown (listen_fd, SD_BOTH);
1335 closesocket (listen_fd);
1337 shutdown (conn_fd, SHUT_RD);
1338 shutdown (listen_fd, SHUT_RDWR);
1344 socket_transport_close2 (void)
1347 shutdown (conn_fd, SD_BOTH);
1349 shutdown (conn_fd, SHUT_RDWR);
1354 register_socket_transport (void)
1356 DebuggerTransport trans;
1358 trans.name = "dt_socket";
1359 trans.connect = socket_transport_connect;
1360 trans.close1 = socket_transport_close1;
1361 trans.close2 = socket_transport_close2;
1362 trans.send = socket_transport_send;
1363 trans.recv = socket_transport_recv;
1365 register_transport (&trans);
1368 #endif /* DISABLE_SOCKET_TRANSPORT */
1374 #define MAX_TRANSPORTS 16
1376 static DebuggerTransport *transport;
1378 static DebuggerTransport transports [MAX_TRANSPORTS];
1379 static int ntransports;
1382 register_transport (DebuggerTransport *trans)
1384 g_assert (ntransports < MAX_TRANSPORTS);
1386 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1391 transport_init (void)
1395 #ifndef DISABLE_SOCKET_TRANSPORT
1396 register_socket_transport ();
1399 for (i = 0; i < ntransports; ++i) {
1400 if (!strcmp (agent_config.transport, transports [i].name))
1403 if (i == ntransports) {
1404 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1405 for (i = 0; i < ntransports; ++i)
1406 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1407 fprintf (stderr, "\n");
1410 transport = &transports [i];
1414 transport_connect (const char *address)
1416 transport->connect (address);
1420 transport_close1 (void)
1422 transport->close1 ();
1426 transport_close2 (void)
1428 transport->close2 ();
1432 transport_send (void *buf, int len)
1434 return transport->send (buf, len);
1438 transport_recv (void *buf, int len)
1440 return transport->recv (buf, len);
1444 transport_handshake (void)
1446 char handshake_msg [128];
1450 /* Write handshake message */
1451 sprintf (handshake_msg, "DWP-Handshake");
1453 res = transport_send (handshake_msg, strlen (handshake_msg));
1454 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1455 g_assert (res != -1);
1458 res = transport_recv (buf, strlen (handshake_msg));
1459 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1460 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1465 * To support older clients, the client sends its protocol version after connecting
1466 * using a command. Until that is received, default to our protocol version.
1468 major_version = MAJOR_VERSION;
1469 minor_version = MINOR_VERSION;
1470 protocol_version_set = FALSE;
1472 #ifndef DISABLE_SOCKET_TRANSPORT
1473 // FIXME: Move this somewhere else
1475 * Set TCP_NODELAY on the socket so the client receives events/command
1476 * results immediately.
1480 int result = setsockopt (conn_fd,
1485 g_assert (result >= 0);
1495 stop_debugger_thread (void)
1500 transport_close1 ();
1503 * Wait for the thread to exit.
1505 * If we continue with the shutdown without waiting for it, then the client might
1506 * not receive an answer to its last command like a resume.
1507 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1510 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1511 if (GetCurrentThreadId () != debugger_thread_id) {
1513 mono_mutex_lock (&debugger_thread_exited_mutex);
1514 if (!debugger_thread_exited) {
1516 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1517 mono_mutex_unlock (&debugger_thread_exited_mutex);
1519 mono_mutex_lock (&debugger_thread_exited_mutex);
1522 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1525 mono_mutex_unlock (&debugger_thread_exited_mutex);
1526 } while (!debugger_thread_exited);
1529 transport_close2 ();
1533 start_debugger_thread (void)
1537 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1538 g_assert (debugger_thread_handle);
1542 * Functions to decode protocol data
1546 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1549 g_assert (*endbuf <= limit);
1554 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1557 g_assert (*endbuf <= limit);
1559 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1562 static inline gint64
1563 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1565 guint32 high = decode_int (buf, &buf, limit);
1566 guint32 low = decode_int (buf, &buf, limit);
1570 return ((((guint64)high) << 32) | ((guint64)low));
1574 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1576 return decode_int (buf, endbuf, limit);
1580 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1582 int len = decode_int (buf, &buf, limit);
1590 s = g_malloc (len + 1);
1593 memcpy (s, buf, len);
1602 * Functions to encode protocol data
1606 guint8 *buf, *p, *end;
1610 buffer_init (Buffer *buf, int size)
1612 buf->buf = g_malloc (size);
1614 buf->end = buf->buf + size;
1618 buffer_make_room (Buffer *buf, int size)
1620 if (buf->end - buf->p < size) {
1621 int new_size = buf->end - buf->buf + size + 32;
1622 guint8 *p = g_realloc (buf->buf, new_size);
1623 size = buf->p - buf->buf;
1626 buf->end = buf->buf + new_size;
1631 buffer_add_byte (Buffer *buf, guint8 val)
1633 buffer_make_room (buf, 1);
1639 buffer_add_short (Buffer *buf, guint32 val)
1641 buffer_make_room (buf, 2);
1642 buf->p [0] = (val >> 8) & 0xff;
1643 buf->p [1] = (val >> 0) & 0xff;
1648 buffer_add_int (Buffer *buf, guint32 val)
1650 buffer_make_room (buf, 4);
1651 buf->p [0] = (val >> 24) & 0xff;
1652 buf->p [1] = (val >> 16) & 0xff;
1653 buf->p [2] = (val >> 8) & 0xff;
1654 buf->p [3] = (val >> 0) & 0xff;
1659 buffer_add_long (Buffer *buf, guint64 l)
1661 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1662 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1666 buffer_add_id (Buffer *buf, int id)
1668 buffer_add_int (buf, (guint64)id);
1672 buffer_add_data (Buffer *buf, guint8 *data, int len)
1674 buffer_make_room (buf, len);
1675 memcpy (buf->p, data, len);
1680 buffer_add_string (Buffer *buf, const char *str)
1685 buffer_add_int (buf, 0);
1688 buffer_add_int (buf, len);
1689 buffer_add_data (buf, (guint8*)str, len);
1694 buffer_free (Buffer *buf)
1700 send_packet (int command_set, int command, Buffer *data)
1706 id = InterlockedIncrement (&packet_id);
1708 len = data->p - data->buf + 11;
1709 buffer_init (&buf, len);
1710 buffer_add_int (&buf, len);
1711 buffer_add_int (&buf, id);
1712 buffer_add_byte (&buf, 0); /* flags */
1713 buffer_add_byte (&buf, command_set);
1714 buffer_add_byte (&buf, command);
1715 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1717 res = transport_send (buf.buf, len);
1725 send_reply_packet (int id, int error, Buffer *data)
1731 len = data->p - data->buf + 11;
1732 buffer_init (&buf, len);
1733 buffer_add_int (&buf, len);
1734 buffer_add_int (&buf, id);
1735 buffer_add_byte (&buf, 0x80); /* flags */
1736 buffer_add_byte (&buf, (error >> 8) & 0xff);
1737 buffer_add_byte (&buf, error);
1738 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1740 res = transport_send (buf.buf, len);
1752 * Represents an object accessible by the debugger client.
1755 /* Unique id used in the wire protocol to refer to objects */
1758 * A weakref gc handle pointing to the object. The gc handle is used to
1759 * detect if the object was garbage collected.
1764 /* Maps objid -> ObjRef */
1765 static GHashTable *objrefs;
1768 free_objref (gpointer value)
1772 mono_gchandle_free (o->handle);
1780 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1784 objrefs_cleanup (void)
1786 g_hash_table_destroy (objrefs);
1790 static GHashTable *obj_to_objref;
1793 * Return an ObjRef for OBJ.
1796 get_objref (MonoObject *obj)
1799 GSList *reflist = NULL, *l;
1805 mono_loader_lock ();
1808 obj_to_objref = g_hash_table_new (NULL, NULL);
1810 /* FIXME: The tables can grow indefinitely */
1812 if (mono_gc_is_moving ()) {
1814 * Objects can move, so use a hash table mapping hash codes to lists of
1815 * ObjRef structures.
1817 hash = mono_object_hash (obj);
1819 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1820 for (l = reflist; l; l = l->next) {
1822 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1823 mono_loader_unlock ();
1828 /* Use a hash table with masked pointers to internalize object references */
1829 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1830 /* ref might refer to a different object with the same addr which was GCd */
1831 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1832 mono_loader_unlock ();
1837 ref = g_new0 (ObjRef, 1);
1838 ref->id = InterlockedIncrement (&objref_id);
1839 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1841 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1843 if (mono_gc_is_moving ()) {
1844 reflist = g_slist_append (reflist, ref);
1845 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1847 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1850 mono_loader_unlock ();
1856 get_objid (MonoObject *obj)
1858 return get_objref (obj)->id;
1862 * Set OBJ to the object identified by OBJID.
1863 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1867 get_object_allow_null (int objid, MonoObject **obj)
1877 return ERR_INVALID_OBJECT;
1879 mono_loader_lock ();
1881 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1884 *obj = mono_gchandle_get_target (ref->handle);
1885 mono_loader_unlock ();
1887 return ERR_INVALID_OBJECT;
1890 mono_loader_unlock ();
1891 return ERR_INVALID_OBJECT;
1896 get_object (int objid, MonoObject **obj)
1898 int err = get_object_allow_null (objid, obj);
1903 return ERR_INVALID_OBJECT;
1908 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1910 return decode_id (buf, endbuf, limit);
1914 buffer_add_objid (Buffer *buf, MonoObject *o)
1916 buffer_add_id (buf, get_objid (o));
1935 * Represents a runtime structure accessible to the debugger client
1938 /* Unique id used in the wire protocol */
1940 /* Domain of the runtime structure, NULL if the domain was unloaded */
1947 MonoAssembly *assembly;
1948 MonoClassField *field;
1950 MonoProperty *property;
1955 /* Maps runtime structure -> Id */
1956 GHashTable *val_to_id [ID_NUM];
1957 /* Classes whose class load event has been sent */
1958 GHashTable *loaded_classes;
1959 /* Maps MonoClass->GPtrArray of file names */
1960 GHashTable *source_files;
1961 /* Maps source file basename -> GSList of classes */
1962 GHashTable *source_file_to_class;
1963 /* Same with ignore-case */
1964 GHashTable *source_file_to_class_ignorecase;
1968 static GPtrArray *ids [ID_NUM];
1975 for (i = 0; i < ID_NUM; ++i)
1976 ids [i] = g_ptr_array_new ();
1984 for (i = 0; i < ID_NUM; ++i) {
1986 for (j = 0; j < ids [i]->len; ++j)
1987 g_free (g_ptr_array_index (ids [i], j));
1988 g_ptr_array_free (ids [i], TRUE);
1995 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1997 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1999 GHashTableIter iter;
2000 GPtrArray *file_names;
2005 for (i = 0; i < ID_NUM; ++i)
2006 if (info->val_to_id [i])
2007 g_hash_table_destroy (info->val_to_id [i]);
2008 g_hash_table_destroy (info->loaded_classes);
2010 g_hash_table_iter_init (&iter, info->source_files);
2011 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2012 for (i = 0; i < file_names->len; ++i)
2013 g_free (g_ptr_array_index (file_names, i));
2014 g_ptr_array_free (file_names, TRUE);
2017 g_hash_table_iter_init (&iter, info->source_file_to_class);
2018 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2023 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2024 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2032 domain_jit_info (domain)->agent_info = NULL;
2034 /* Clear ids referencing structures in the domain */
2035 for (i = 0; i < ID_NUM; ++i) {
2037 for (j = 0; j < ids [i]->len; ++j) {
2038 Id *id = g_ptr_array_index (ids [i], j);
2039 if (id->domain == domain)
2045 mono_loader_lock ();
2046 g_hash_table_remove (domains, domain);
2047 mono_loader_unlock ();
2050 static AgentDomainInfo*
2051 get_agent_domain_info (MonoDomain *domain)
2053 AgentDomainInfo *info = NULL;
2055 mono_domain_lock (domain);
2057 info = domain_jit_info (domain)->agent_info;
2059 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2060 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2061 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2062 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2063 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2066 mono_domain_unlock (domain);
2072 get_id (MonoDomain *domain, IdType type, gpointer val)
2075 AgentDomainInfo *info;
2080 mono_loader_lock ();
2082 mono_domain_lock (domain);
2084 info = get_agent_domain_info (domain);
2086 if (info->val_to_id [type] == NULL)
2087 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2089 id = g_hash_table_lookup (info->val_to_id [type], val);
2091 mono_domain_unlock (domain);
2092 mono_loader_unlock ();
2096 id = g_new0 (Id, 1);
2098 id->id = ids [type]->len + 1;
2099 id->domain = domain;
2102 g_hash_table_insert (info->val_to_id [type], val, id);
2104 mono_domain_unlock (domain);
2106 g_ptr_array_add (ids [type], id);
2108 mono_loader_unlock ();
2113 static inline gpointer
2114 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2118 int id = decode_id (buf, endbuf, limit);
2127 // FIXME: error handling
2128 mono_loader_lock ();
2129 g_assert (id > 0 && id <= ids [type]->len);
2131 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2132 mono_loader_unlock ();
2134 if (res->domain == NULL) {
2135 *err = ERR_UNLOADED;
2140 *domain = res->domain;
2142 return res->data.val;
2146 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2148 buffer_add_id (buf, get_id (domain, type, val));
2151 static inline MonoClass*
2152 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2154 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2157 static inline MonoAssembly*
2158 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2160 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2163 static inline MonoImage*
2164 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2166 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2169 static inline MonoMethod*
2170 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2172 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2175 static inline MonoClassField*
2176 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2178 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2181 static inline MonoDomain*
2182 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2184 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2187 static inline MonoProperty*
2188 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2190 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2194 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2196 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2200 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2202 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2206 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2208 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2212 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2214 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2218 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2220 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2224 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2226 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2230 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2232 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2235 static void invoke_method (void);
2242 * save_thread_context:
2244 * Set CTX as the current threads context which is used for computing stack traces.
2245 * This function is signal-safe.
2248 save_thread_context (MonoContext *ctx)
2250 DebuggerTlsData *tls;
2252 tls = mono_native_tls_get_value (debugger_tls_id);
2256 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2258 mono_thread_state_init_from_current (&tls->context);
2261 /* The number of times the runtime is suspended */
2262 static gint32 suspend_count;
2264 /* Number of threads suspended */
2266 * If this is equal to the size of thread_to_tls, the runtime is considered
2269 static gint32 threads_suspend_count;
2271 static mono_mutex_t suspend_mutex;
2273 /* Cond variable used to wait for suspend_count becoming 0 */
2274 static mono_cond_t suspend_cond;
2276 /* Semaphore used to wait for a thread becoming suspended */
2277 static MonoSemType suspend_sem;
2282 mono_mutex_init (&suspend_mutex, NULL);
2283 mono_cond_init (&suspend_cond, NULL);
2284 MONO_SEM_INIT (&suspend_sem, 0);
2289 StackFrameInfo last_frame;
2290 gboolean last_frame_set;
2293 } GetLastFrameUserData;
2296 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2298 GetLastFrameUserData *data = user_data;
2300 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2303 if (!data->last_frame_set) {
2304 /* Store the last frame */
2305 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2306 data->last_frame_set = TRUE;
2309 /* Store the context/lmf for the frame above the last frame */
2310 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2311 data->lmf = info->lmf;
2319 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2320 * INFO is set, process the thread described by INFO.
2321 * This should be signal safe.
2324 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2328 MonoNativeThreadId tid;
2331 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2332 * guarantee the signal handler will be called that many times. Instead of tracking
2333 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2334 * has been requested that hasn't been handled yet, otherwise we can have threads
2335 * refuse to die when VM_EXIT is called
2337 #if defined(__APPLE__)
2338 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2342 * We use interrupt_count to determine whenever this interrupt should be processed
2343 * by us or the normal interrupt processing code in the signal handler.
2344 * There is no race here with notify_thread (), since the signal is sent after
2345 * incrementing interrupt_count.
2347 if (tls->interrupt_count == 0)
2350 InterlockedDecrement (&tls->interrupt_count);
2354 ip = mono_arch_ip_from_context (sigctx);
2356 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2361 tid = mono_thread_info_get_tid (info);
2363 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2365 // FIXME: Races when the thread leaves managed code before hitting a single step
2369 /* Running managed code, will be suspended by the single step code */
2370 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2374 * Running native code, will be suspended when it returns to/enters
2375 * managed code. Treat it as already suspended.
2376 * This might interrupt the code in process_single_step_inner (), we use the
2377 * tls->suspending flag to avoid races when that happens.
2379 if (!tls->suspended && !tls->suspending) {
2381 GetLastFrameUserData data;
2383 // FIXME: printf is not signal safe, but this is only used during
2384 // debugger debugging
2386 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2387 //save_thread_context (&ctx);
2390 /* Already terminated */
2393 tls->context.valid = FALSE;
2396 * We are in a difficult position: we want to be able to provide stack
2397 * traces for this thread, but we can't use the current ctx+lmf, since
2398 * the thread is still running, so it might return to managed code,
2399 * making these invalid.
2400 * So we start a stack walk and save the first frame, along with the
2401 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2402 * suspended when it returns to managed code, so the parent's ctx should
2405 data.last_frame_set = FALSE;
2407 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2409 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2410 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2411 * since we are not in a JITted method.
2413 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2415 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2417 if (data.last_frame_set) {
2418 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2419 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2421 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2424 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2425 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2426 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2428 /* No managed frames */
2429 tls->async_state.valid = FALSE;
2431 mono_memory_barrier ();
2433 tls->suspended = TRUE;
2434 MONO_SEM_POST (&suspend_sem);
2441 * mono_debugger_agent_thread_interrupt:
2443 * Called by the abort signal handler.
2444 * Should be signal safe.
2447 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2449 DebuggerTlsData *tls;
2454 tls = mono_native_tls_get_value (debugger_tls_id);
2458 return thread_interrupt (tls, NULL, sigctx, ji);
2462 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2465 mono_debugger_agent_thread_interrupt (NULL, NULL);
2467 #endif /* HOST_WIN32 */
2470 * reset_native_thread_suspend_state:
2472 * Reset the suspended flag and state on native threads
2475 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2477 DebuggerTlsData *tls = value;
2479 if (!tls->really_suspended && tls->suspended) {
2480 tls->suspended = FALSE;
2482 * The thread might still be running if it was executing native code, so the state won't be invalided by
2483 * suspend_current ().
2485 tls->context.valid = FALSE;
2486 tls->async_state.valid = FALSE;
2487 invalidate_frames (tls);
2494 * Notify a thread that it needs to suspend.
2497 notify_thread (gpointer key, gpointer value, gpointer user_data)
2499 MonoInternalThread *thread = key;
2500 DebuggerTlsData *tls = value;
2501 gsize tid = thread->tid;
2504 if (GetCurrentThreadId () == tid || tls->terminated)
2507 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2510 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2511 * guarantee the signal handler will be called that many times. Instead of tracking
2512 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2513 * has been requested that hasn't been handled yet, otherwise we can have threads
2514 * refuse to die when VM_EXIT is called
2516 #if defined(__APPLE__)
2517 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2521 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2522 * of things like breaking waits etc. which we don't want.
2524 InterlockedIncrement (&tls->interrupt_count);
2527 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2529 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2531 if (mono_thread_info_new_interrupt_enabled ()) {
2532 MonoThreadInfo *info;
2535 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2538 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2540 thread_interrupt (tls, info, NULL, ji);
2542 mono_thread_info_resume (mono_thread_info_get_tid (info));
2544 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2547 * Attached thread which died without detaching.
2549 tls->terminated = TRUE;
2555 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2557 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2560 if (mono_loader_lock_is_owned_by_self ()) {
2562 * Shortcut for the check in suspend_current (). This speeds up processing
2563 * when executing long running code inside the loader lock, i.e. assembly load
2569 if (debugger_thread_id == GetCurrentThreadId ())
2572 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2573 if (suspend_count - tls->resume_count > 0)
2574 tls->suspending = TRUE;
2576 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2578 if (suspend_count - tls->resume_count == 0) {
2580 * We are executing a single threaded invoke but the single step for
2581 * suspending is still active.
2582 * FIXME: This slows down single threaded invokes.
2584 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2588 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2590 /* Can't suspend in these methods */
2591 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2594 save_thread_context (ctx);
2602 * Increase the suspend count of the VM. While the suspend count is greater
2603 * than 0, runtime threads are suspended at certain points during execution.
2608 mono_loader_lock ();
2610 mono_mutex_lock (&suspend_mutex);
2614 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2616 if (suspend_count == 1) {
2617 // FIXME: Is it safe to call this inside the lock ?
2618 start_single_stepping ();
2619 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2622 mono_mutex_unlock (&suspend_mutex);
2624 mono_loader_unlock ();
2630 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2638 g_assert (debugger_thread_id == GetCurrentThreadId ());
2640 mono_loader_lock ();
2642 mono_mutex_lock (&suspend_mutex);
2644 g_assert (suspend_count > 0);
2647 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2649 if (suspend_count == 0) {
2650 // FIXME: Is it safe to call this inside the lock ?
2651 stop_single_stepping ();
2652 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2655 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2656 err = mono_cond_broadcast (&suspend_cond);
2657 g_assert (err == 0);
2659 mono_mutex_unlock (&suspend_mutex);
2660 //g_assert (err == 0);
2662 mono_loader_unlock ();
2668 * Resume just one thread.
2671 resume_thread (MonoInternalThread *thread)
2674 DebuggerTlsData *tls;
2676 g_assert (debugger_thread_id == GetCurrentThreadId ());
2678 mono_loader_lock ();
2680 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2683 mono_mutex_lock (&suspend_mutex);
2685 g_assert (suspend_count > 0);
2687 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2689 tls->resume_count += suspend_count;
2692 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2693 * but only the one whose resume_count field is > 0 will be resumed.
2695 err = mono_cond_broadcast (&suspend_cond);
2696 g_assert (err == 0);
2698 mono_mutex_unlock (&suspend_mutex);
2699 //g_assert (err == 0);
2701 mono_loader_unlock ();
2705 invalidate_frames (DebuggerTlsData *tls)
2710 tls = mono_native_tls_get_value (debugger_tls_id);
2713 for (i = 0; i < tls->frame_count; ++i) {
2714 if (tls->frames [i]->jit)
2715 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2716 g_free (tls->frames [i]);
2718 g_free (tls->frames);
2719 tls->frame_count = 0;
2726 * Suspend the current thread until the runtime is resumed. If the thread has a
2727 * pending invoke, then the invoke is executed before this function returns.
2730 suspend_current (void)
2733 DebuggerTlsData *tls;
2735 g_assert (debugger_thread_id != GetCurrentThreadId ());
2737 if (mono_loader_lock_is_owned_by_self ()) {
2739 * If we own the loader mutex, can't suspend until we release it, since the
2740 * whole runtime can deadlock otherwise.
2745 tls = mono_native_tls_get_value (debugger_tls_id);
2748 mono_mutex_lock (&suspend_mutex);
2750 tls->suspending = FALSE;
2751 tls->really_suspended = TRUE;
2753 if (!tls->suspended) {
2754 tls->suspended = TRUE;
2755 MONO_SEM_POST (&suspend_sem);
2758 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2760 while (suspend_count - tls->resume_count > 0) {
2762 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2764 mono_mutex_unlock (&suspend_mutex);
2766 mono_mutex_lock (&suspend_mutex);
2772 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2773 g_assert (err == 0);
2777 tls->suspended = FALSE;
2778 tls->really_suspended = FALSE;
2780 threads_suspend_count --;
2782 mono_mutex_unlock (&suspend_mutex);
2784 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2786 if (tls->pending_invoke) {
2787 /* Save the original context */
2788 tls->pending_invoke->has_ctx = TRUE;
2789 tls->pending_invoke->ctx = tls->context.ctx;
2794 /* The frame info becomes invalid after a resume */
2795 tls->context.valid = FALSE;
2796 tls->async_state.valid = FALSE;
2797 invalidate_frames (tls);
2801 count_thread (gpointer key, gpointer value, gpointer user_data)
2803 DebuggerTlsData *tls = value;
2805 if (!tls->suspended && !tls->terminated)
2806 *(int*)user_data = *(int*)user_data + 1;
2810 count_threads_to_wait_for (void)
2814 mono_loader_lock ();
2815 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2816 mono_loader_unlock ();
2824 * Wait until the runtime is completely suspended.
2827 wait_for_suspend (void)
2829 int nthreads, nwait, err;
2830 gboolean waited = FALSE;
2832 // FIXME: Threads starting/stopping ?
2833 mono_loader_lock ();
2834 nthreads = mono_g_hash_table_size (thread_to_tls);
2835 mono_loader_unlock ();
2838 nwait = count_threads_to_wait_for ();
2840 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2841 err = MONO_SEM_WAIT (&suspend_sem);
2842 g_assert (err == 0);
2850 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2856 * Return whenever the runtime is suspended.
2861 return count_threads_to_wait_for () == 0;
2864 static MonoSeqPointInfo*
2865 get_seq_points (MonoDomain *domain, MonoMethod *method)
2867 MonoSeqPointInfo *seq_points;
2869 mono_domain_lock (domain);
2870 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2871 if (!seq_points && method->is_inflated) {
2872 /* generic sharing + aot */
2873 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2875 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2877 mono_domain_unlock (domain);
2882 static MonoSeqPointInfo*
2883 find_seq_points (MonoDomain *domain, MonoMethod *method)
2885 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2888 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2889 g_assert (seq_points);
2895 * find_next_seq_point_for_native_offset:
2897 * Find the first sequence point after NATIVE_OFFSET.
2900 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2902 MonoSeqPointInfo *seq_points;
2905 seq_points = find_seq_points (domain, method);
2909 for (i = 0; i < seq_points->len; ++i) {
2910 if (seq_points->seq_points [i].native_offset >= native_offset)
2911 return &seq_points->seq_points [i];
2918 * find_prev_seq_point_for_native_offset:
2920 * Find the first sequence point before NATIVE_OFFSET.
2923 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2925 MonoSeqPointInfo *seq_points;
2928 seq_points = find_seq_points (domain, method);
2932 for (i = seq_points->len - 1; i >= 0; --i) {
2933 if (seq_points->seq_points [i].native_offset <= native_offset)
2934 return &seq_points->seq_points [i];
2943 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2944 * should be the location of a sequence point.
2946 static G_GNUC_UNUSED SeqPoint*
2947 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2949 MonoSeqPointInfo *seq_points;
2954 seq_points = get_seq_points (domain, method);
2959 for (i = 0; i < seq_points->len; ++i) {
2960 if (seq_points->seq_points [i].il_offset == il_offset)
2961 return &seq_points->seq_points [i];
2968 DebuggerTlsData *tls;
2970 } ComputeFramesUserData;
2973 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2975 ComputeFramesUserData *ud = user_data;
2977 MonoMethod *method, *actual_method, *api_method;
2981 if (info->type != FRAME_TYPE_MANAGED) {
2982 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2983 /* Mark the last frame as an invoke frame */
2985 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2991 method = info->ji->method;
2993 method = info->method;
2994 actual_method = info->actual_method;
2995 api_method = method;
3000 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3003 if (info->il_offset == -1) {
3004 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3005 if (ud->frames == NULL) {
3006 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3008 info->il_offset = sp->il_offset;
3010 if (info->il_offset == -1)
3011 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3014 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));
3016 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3017 if (!CHECK_PROTOCOL_VERSION (2, 17))
3018 /* Older clients can't handle this flag */
3020 api_method = mono_marshal_method_from_wrapper (method);
3023 actual_method = api_method;
3024 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3027 frame = g_new0 (StackFrame, 1);
3028 frame->method = method;
3029 frame->actual_method = actual_method;
3030 frame->api_method = api_method;
3031 frame->il_offset = info->il_offset;
3032 frame->native_offset = info->native_offset;
3033 frame->flags = flags;
3034 frame->ji = info->ji;
3035 if (info->reg_locations)
3036 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3039 frame->has_ctx = TRUE;
3041 frame->domain = info->domain;
3043 ud->frames = g_slist_append (ud->frames, frame);
3049 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3051 ComputeFramesUserData *ud = user_data;
3054 * 'tls->filter_ctx' is the location of the throw site.
3056 * mono_walk_stack() will never actually hit the throw site, but unwind
3057 * directly from the filter to the call site; we abort stack unwinding here
3058 * once this happens and resume from the throw site.
3061 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3064 return process_frame (info, ctx, user_data);
3068 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3070 ComputeFramesUserData user_data;
3072 int i, findex, new_frame_count;
3073 StackFrame **new_frames, *f;
3074 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3076 // FIXME: Locking on tls
3077 if (tls->frames && tls->frames_up_to_date)
3080 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3082 user_data.tls = tls;
3083 user_data.frames = NULL;
3084 if (tls->terminated) {
3085 tls->frame_count = 0;
3087 } if (!tls->really_suspended && tls->async_state.valid) {
3088 /* Have to use the state saved by the signal handler */
3089 process_frame (&tls->async_last_frame, NULL, &user_data);
3090 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3091 } else if (tls->filter_state.valid) {
3093 * We are inside an exception filter.
3095 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3097 if (tls->context.valid)
3098 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3100 * After that, we resume unwinding from the location where the exception has been thrown.
3102 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3103 } else if (tls->context.valid) {
3104 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3107 tls->frame_count = 0;
3111 new_frame_count = g_slist_length (user_data.frames);
3112 new_frames = g_new0 (StackFrame*, new_frame_count);
3114 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3118 * Reuse the id for already existing stack frames, so invokes don't invalidate
3119 * the still valid stack frames.
3121 for (i = 0; i < tls->frame_count; ++i) {
3122 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3123 f->id = tls->frames [i]->id;
3128 if (i >= tls->frame_count)
3129 f->id = InterlockedIncrement (&frame_id);
3131 new_frames [findex ++] = f;
3134 g_slist_free (user_data.frames);
3136 invalidate_frames (tls);
3138 tls->frames = new_frames;
3139 tls->frame_count = new_frame_count;
3140 tls->frames_up_to_date = TRUE;
3144 * GHFunc to emit an appdomain creation event
3145 * @param key Don't care
3146 * @param value A loaded appdomain
3147 * @param user_data Don't care
3150 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3152 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3153 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3157 * GHFunc to emit a thread start event
3158 * @param key A thread id
3159 * @param value A thread object
3160 * @param user_data Don't care
3163 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3165 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3166 process_profiler_event (EVENT_KIND_THREAD_START, value);
3170 * GFunc to emit an assembly load event
3171 * @param value A loaded assembly
3172 * @param user_data Don't care
3175 emit_assembly_load (gpointer value, gpointer user_data)
3177 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3181 * GFunc to emit a type load event
3182 * @param value A loaded type
3183 * @param user_data Don't care
3186 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3188 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3192 strdup_tolower (char *s)
3197 for (p = s2; *p; ++p)
3207 * create_event_list:
3209 * Return a list of event request ids matching EVENT, starting from REQS, which
3210 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3212 * We return request ids, instead of requests, to simplify threading, since
3213 * requests could be deleted anytime when the loader lock is not held.
3214 * LOCKING: Assumes the loader lock is held.
3217 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3220 GSList *events = NULL;
3222 *suspend_policy = SUSPEND_POLICY_NONE;
3225 reqs = event_requests;
3230 for (i = 0; i < reqs->len; ++i) {
3231 EventRequest *req = g_ptr_array_index (reqs, i);
3232 if (req->event_kind == event) {
3233 gboolean filtered = FALSE;
3236 for (j = 0; j < req->nmodifiers; ++j) {
3237 Modifier *mod = &req->modifiers [j];
3239 if (mod->kind == MOD_KIND_COUNT) {
3241 if (mod->data.count > 0) {
3242 if (mod->data.count > 0) {
3244 if (mod->data.count == 0)
3248 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3249 if (mod->data.thread != mono_thread_internal_current ())
3251 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3252 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3254 if (ei->caught && !mod->caught)
3256 if (!ei->caught && !mod->uncaught)
3258 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3260 gboolean found = FALSE;
3261 MonoAssembly **assemblies = mod->data.assemblies;
3264 for (k = 0; assemblies [k]; ++k)
3265 if (assemblies [k] == ji->method->klass->image->assembly)
3270 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3271 gpointer iter = NULL;
3273 MonoDebugSourceInfo *sinfo;
3274 char *source_file, *s;
3275 gboolean found = FALSE;
3277 GPtrArray *source_file_list;
3279 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3280 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3283 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3284 for (i = 0; i < source_file_list->len; ++i) {
3285 sinfo = g_ptr_array_index (source_file_list, i);
3287 * Do a case-insesitive match by converting the file name to
3290 s = strdup_tolower (sinfo->source_file);
3291 if (g_hash_table_lookup (mod->data.source_files, s))
3295 g_ptr_array_free (source_file_list, TRUE);
3300 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3303 s = mono_type_full_name (&ei->klass->byval_arg);
3304 if (!g_hash_table_lookup (mod->data.type_names, s))
3307 } else if (mod->kind == MOD_KIND_STEP) {
3308 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3309 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3310 !strcmp (ji->method->name, ".cctor"))
3312 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3313 MonoCustomAttrInfo *ainfo;
3314 static MonoClass *klass;
3317 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3320 if (!ji->dbg_hidden_inited) {
3321 ainfo = mono_custom_attrs_from_method (ji->method);
3323 if (mono_custom_attrs_has_attr (ainfo, klass))
3324 ji->dbg_hidden = TRUE;
3325 mono_custom_attrs_free (ainfo);
3327 ji->dbg_hidden_inited = TRUE;
3336 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3337 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3342 /* Send a VM START/DEATH event by default */
3343 if (event == EVENT_KIND_VM_START)
3344 events = g_slist_append (events, GINT_TO_POINTER (0));
3345 if (event == EVENT_KIND_VM_DEATH)
3346 events = g_slist_append (events, GINT_TO_POINTER (0));
3351 static G_GNUC_UNUSED const char*
3352 event_to_string (EventKind event)
3355 case EVENT_KIND_VM_START: return "VM_START";
3356 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3357 case EVENT_KIND_THREAD_START: return "THREAD_START";
3358 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3359 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3360 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3361 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3362 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3363 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3364 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3365 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3366 case EVENT_KIND_STEP: return "STEP";
3367 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3368 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3369 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3370 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3371 case EVENT_KIND_USER_LOG: return "USER_LOG";
3373 g_assert_not_reached ();
3380 * Send an event to the client, suspending the vm if needed.
3381 * LOCKING: Since this can suspend the calling thread, no locks should be held
3383 * The EVENTS list is freed by this function.
3386 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3390 MonoDomain *domain = mono_domain_get ();
3391 MonoThread *thread = NULL;
3392 gboolean send_success = FALSE;
3397 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3401 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3402 // FIXME: We miss those events
3403 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3407 if (vm_death_event_sent) {
3408 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3412 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3413 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3418 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3422 if (event == EVENT_KIND_KEEPALIVE)
3423 suspend_policy = SUSPEND_POLICY_NONE;
3428 if (agent_config.defer) {
3429 /* Make sure the thread id is always set when doing deferred debugging */
3430 if (debugger_thread_id == GetCurrentThreadId ()) {
3431 /* Don't suspend on events from the debugger thread */
3432 suspend_policy = SUSPEND_POLICY_NONE;
3433 thread = mono_thread_get_main ();
3435 else thread = mono_thread_current ();
3437 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3438 // FIXME: Send these with a NULL thread, don't suspend the current thread
3443 nevents = g_slist_length (events);
3444 buffer_init (&buf, 128);
3445 buffer_add_byte (&buf, suspend_policy);
3446 buffer_add_int (&buf, nevents);
3448 for (l = events; l; l = l->next) {
3449 buffer_add_byte (&buf, event); // event kind
3450 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3455 thread = mono_thread_current ();
3457 if (event == EVENT_KIND_VM_START && arg != NULL)
3460 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3463 case EVENT_KIND_THREAD_START:
3464 case EVENT_KIND_THREAD_DEATH:
3466 case EVENT_KIND_APPDOMAIN_CREATE:
3467 case EVENT_KIND_APPDOMAIN_UNLOAD:
3468 buffer_add_domainid (&buf, arg);
3470 case EVENT_KIND_METHOD_ENTRY:
3471 case EVENT_KIND_METHOD_EXIT:
3472 buffer_add_methodid (&buf, domain, arg);
3474 case EVENT_KIND_ASSEMBLY_LOAD:
3475 case EVENT_KIND_ASSEMBLY_UNLOAD:
3476 buffer_add_assemblyid (&buf, domain, arg);
3478 case EVENT_KIND_TYPE_LOAD:
3479 buffer_add_typeid (&buf, domain, arg);
3481 case EVENT_KIND_BREAKPOINT:
3482 case EVENT_KIND_STEP:
3483 buffer_add_methodid (&buf, domain, arg);
3484 buffer_add_long (&buf, il_offset);
3486 case EVENT_KIND_VM_START:
3487 buffer_add_domainid (&buf, mono_get_root_domain ());
3489 case EVENT_KIND_VM_DEATH:
3491 case EVENT_KIND_EXCEPTION: {
3492 EventInfo *ei = arg;
3493 buffer_add_objid (&buf, ei->exc);
3496 case EVENT_KIND_USER_BREAK:
3498 case EVENT_KIND_USER_LOG: {
3499 EventInfo *ei = arg;
3500 buffer_add_int (&buf, ei->level);
3501 buffer_add_string (&buf, ei->category ? ei->category : "");
3502 buffer_add_string (&buf, ei->message ? ei->message : "");
3505 case EVENT_KIND_KEEPALIVE:
3506 suspend_policy = SUSPEND_POLICY_NONE;
3509 g_assert_not_reached ();
3513 if (event == EVENT_KIND_VM_START) {
3514 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3515 if (!agent_config.defer)
3516 start_debugger_thread ();
3519 if (event == EVENT_KIND_VM_DEATH) {
3520 vm_death_event_sent = TRUE;
3521 suspend_policy = SUSPEND_POLICY_NONE;
3524 if (mono_runtime_is_shutting_down ())
3525 suspend_policy = SUSPEND_POLICY_NONE;
3527 if (suspend_policy != SUSPEND_POLICY_NONE) {
3529 * Save the thread context and start suspending before sending the packet,
3530 * since we could be receiving the resume request before send_packet ()
3533 save_thread_context (ctx);
3537 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3541 g_slist_free (events);
3544 if (!send_success) {
3545 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3549 if (event == EVENT_KIND_VM_START) {
3550 vm_start_event_sent = TRUE;
3553 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3555 switch (suspend_policy) {
3556 case SUSPEND_POLICY_NONE:
3558 case SUSPEND_POLICY_ALL:
3561 case SUSPEND_POLICY_EVENT_THREAD:
3565 g_assert_not_reached ();
3570 process_profiler_event (EventKind event, gpointer arg)
3574 EventInfo ei, *ei_arg = NULL;
3576 if (event == EVENT_KIND_TYPE_LOAD) {
3581 mono_loader_lock ();
3582 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3583 mono_loader_unlock ();
3585 process_event (event, arg, 0, NULL, events, suspend_policy);
3589 runtime_initialized (MonoProfiler *prof)
3591 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3592 if (agent_config.defer)
3593 start_debugger_thread ();
3597 runtime_shutdown (MonoProfiler *prof)
3599 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3601 mono_debugger_agent_cleanup ();
3605 thread_startup (MonoProfiler *prof, uintptr_t tid)
3607 MonoInternalThread *thread = mono_thread_internal_current ();
3608 MonoInternalThread *old_thread;
3609 DebuggerTlsData *tls;
3611 if (tid == debugger_thread_id)
3614 g_assert (thread->tid == tid);
3616 mono_loader_lock ();
3617 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3618 mono_loader_unlock ();
3620 if (thread == old_thread) {
3622 * For some reason, thread_startup () might be called for the same thread
3623 * multiple times (attach ?).
3625 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3629 * thread_end () might not be called for some threads, and the tid could
3632 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3633 mono_loader_lock ();
3634 mono_g_hash_table_remove (thread_to_tls, old_thread);
3635 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3636 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3637 mono_loader_unlock ();
3641 tls = mono_native_tls_get_value (debugger_tls_id);
3643 // FIXME: Free this somewhere
3644 tls = g_new0 (DebuggerTlsData, 1);
3645 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3646 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3647 tls->thread = thread;
3648 mono_native_tls_set_value (debugger_tls_id, tls);
3650 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3652 mono_loader_lock ();
3653 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3654 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3655 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3656 mono_loader_unlock ();
3658 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3661 * suspend_vm () could have missed this thread, so wait for a resume.
3667 thread_end (MonoProfiler *prof, uintptr_t tid)
3669 MonoInternalThread *thread;
3670 DebuggerTlsData *tls = NULL;
3672 mono_loader_lock ();
3673 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3675 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3676 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3678 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3679 tls->terminated = TRUE;
3680 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3681 MONO_GC_UNREGISTER_ROOT (tls->thread);
3685 mono_loader_unlock ();
3687 /* We might be called for threads started before we registered the start callback */
3689 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3690 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3695 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3697 mono_loader_lock ();
3698 g_hash_table_insert (domains, domain, domain);
3699 mono_loader_unlock ();
3701 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3705 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3707 clear_breakpoints_for_domain (domain);
3709 mono_loader_lock ();
3710 /* Invalidate each thread's frame stack */
3711 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3712 mono_loader_unlock ();
3714 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3718 * invalidate_each_thread:
3720 * A GHFunc to invalidate frames.
3721 * value must be a DebuggerTlsData*
3724 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3726 invalidate_frames (value);
3730 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3732 /* Sent later in jit_end () */
3733 mono_loader_lock ();
3734 g_ptr_array_add (pending_assembly_loads, assembly);
3735 mono_loader_unlock ();
3739 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3741 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3743 clear_event_requests_for_assembly (assembly);
3744 clear_types_for_assembly (assembly);
3748 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3750 #if defined(HOST_WIN32) && !defined(__GNUC__)
3751 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3753 gpointer stackptr = __builtin_frame_address (1);
3755 MonoInternalThread *thread = mono_thread_internal_current ();
3756 DebuggerTlsData *tls;
3758 mono_loader_lock ();
3760 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3761 /* Could be the debugger thread with assembly/type load hooks */
3763 tls->invoke_addr = stackptr;
3765 mono_loader_unlock ();
3769 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3772 #if defined(HOST_WIN32) && !defined(__GNUC__)
3773 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3775 gpointer stackptr = __builtin_frame_address (1);
3778 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3782 * We need to stop single stepping when exiting a runtime invoke, since if it is
3783 * a step out, it may return to native code, and thus never end.
3785 mono_loader_lock ();
3786 ss_invoke_addr = NULL;
3788 for (i = 0; i < event_requests->len; ++i) {
3789 EventRequest *req = g_ptr_array_index (event_requests, i);
3791 if (req->event_kind == EVENT_KIND_STEP) {
3792 ss_destroy (req->info);
3793 g_ptr_array_remove_index_fast (event_requests, i);
3798 mono_loader_unlock ();
3802 send_type_load (MonoClass *klass)
3804 gboolean type_load = FALSE;
3805 MonoDomain *domain = mono_domain_get ();
3806 AgentDomainInfo *info = NULL;
3808 mono_loader_lock ();
3809 mono_domain_lock (domain);
3811 info = get_agent_domain_info (domain);
3813 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3815 g_hash_table_insert (info->loaded_classes, klass, klass);
3818 mono_domain_unlock (domain);
3819 mono_loader_unlock ();
3821 emit_type_load (klass, klass, NULL);
3825 * Emit load events for all types currently loaded in the domain.
3826 * Takes the loader and domain locks.
3827 * user_data is unused.
3830 send_types_for_domain (MonoDomain *domain, void *user_data)
3832 AgentDomainInfo *info = NULL;
3834 mono_loader_lock ();
3835 mono_domain_lock (domain);
3836 info = get_agent_domain_info (domain);
3838 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3839 mono_domain_unlock (domain);
3840 mono_loader_unlock ();
3844 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3847 * We emit type load events when the first method of the type is JITted,
3848 * since the class load profiler callbacks might be called with the
3849 * loader lock held. They could also occur in the debugger thread.
3850 * Same for assembly load events.
3853 MonoAssembly *assembly = NULL;
3855 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3856 mono_loader_lock ();
3857 if (pending_assembly_loads->len > 0) {
3858 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3859 g_ptr_array_remove_index (pending_assembly_loads, 0);
3861 mono_loader_unlock ();
3864 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3870 send_type_load (method->klass);
3873 add_pending_breakpoints (method, jinfo);
3877 * BREAKPOINTS/SINGLE STEPPING
3881 * Contains information about an inserted breakpoint.
3884 long il_offset, native_offset;
3889 } BreakpointInstance;
3892 * Contains generic information about a breakpoint.
3896 * The method where the breakpoint is placed. Can be NULL in which case it
3897 * is inserted into every method. This is used to implement method entry/
3898 * exit events. Can be a generic method definition, in which case the
3899 * breakpoint is inserted into every instance.
3905 * A list of BreakpointInstance structures describing where the breakpoint
3906 * was inserted. There could be more than one because of
3907 * generics/appdomains/method entry/exit.
3909 GPtrArray *children;
3912 /* List of breakpoints */
3913 static GPtrArray *breakpoints;
3914 /* Maps breakpoint locations to the number of breakpoints at that location */
3915 static GHashTable *bp_locs;
3918 breakpoints_init (void)
3920 breakpoints = g_ptr_array_new ();
3921 bp_locs = g_hash_table_new (NULL, NULL);
3925 * insert_breakpoint:
3927 * Insert the breakpoint described by BP into the method described by
3931 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3934 BreakpointInstance *inst;
3935 SeqPoint *sp = NULL;
3938 mono_error_init (error);
3940 for (i = 0; i < seq_points->len; ++i) {
3941 sp = &seq_points->seq_points [i];
3943 if (sp->il_offset == bp->il_offset)
3947 if (i == seq_points->len) {
3949 * The set of IL offsets with seq points doesn't completely match the
3950 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3952 for (i = 0; i < seq_points->len; ++i) {
3953 sp = &seq_points->seq_points [i];
3955 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3960 if (i == seq_points->len) {
3961 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);
3963 for (i = 0; i < seq_points->len; ++i)
3964 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
3967 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3976 inst = g_new0 (BreakpointInstance, 1);
3978 inst->native_offset = sp->native_offset;
3979 inst->ip = (guint8*)ji->code_start + sp->native_offset;
3981 inst->domain = domain;
3983 mono_loader_lock ();
3985 g_ptr_array_add (bp->children, inst);
3987 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3988 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3989 mono_loader_unlock ();
3992 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3993 mono_arch_set_breakpoint (ji, inst->ip);
3999 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4003 remove_breakpoint (BreakpointInstance *inst)
4005 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4007 MonoJitInfo *ji = inst->ji;
4008 guint8 *ip = inst->ip;
4010 mono_loader_lock ();
4011 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4012 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4013 mono_loader_unlock ();
4015 g_assert (count > 0);
4018 mono_arch_clear_breakpoint (ji, ip);
4025 static inline gboolean
4026 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4032 if (method == bp->method)
4034 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4037 if (bp->method->is_inflated && method->is_inflated) {
4038 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4039 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4041 /* Open generic methods should match closed generic methods of the same class */
4042 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4043 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4044 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4046 /* FIXME: Handle !mvar */
4047 if (t1->type != MONO_TYPE_MVAR)
4058 * add_pending_breakpoints:
4060 * Insert pending breakpoints into the newly JITted method METHOD.
4063 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4066 MonoSeqPointInfo *seq_points;
4072 domain = mono_domain_get ();
4074 mono_loader_lock ();
4076 for (i = 0; i < breakpoints->len; ++i) {
4077 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4078 gboolean found = FALSE;
4080 if (!bp_matches_method (bp, method))
4083 for (j = 0; j < bp->children->len; ++j) {
4084 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4091 mono_domain_lock (domain);
4092 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4093 if (!seq_points && ji->method->is_inflated)
4094 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4095 mono_domain_unlock (domain);
4097 /* Could be AOT code */
4099 g_assert (seq_points);
4101 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4105 mono_loader_unlock ();
4109 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4115 mono_error_init (error);
4117 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4119 /* Might be AOTed code */
4120 code = mono_aot_get_method (domain, method);
4122 ji = mono_jit_info_table_find (domain, code);
4127 insert_breakpoint (seq_points, domain, ji, bp, error);
4131 clear_breakpoint (MonoBreakpoint *bp);
4136 * Set a breakpoint at IL_OFFSET in METHOD.
4137 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4138 * METHOD can also be a generic method definition, in which case a breakpoint
4139 * is placed in all instances of the method.
4140 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4143 static MonoBreakpoint*
4144 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4147 GHashTableIter iter, iter2;
4150 MonoSeqPointInfo *seq_points;
4153 mono_error_init (error);
4156 // - suspend/resume the vm to prevent code patching problems
4157 // - multiple breakpoints on the same location
4158 // - dynamic methods
4161 bp = g_new0 (MonoBreakpoint, 1);
4162 bp->method = method;
4163 bp->il_offset = il_offset;
4165 bp->children = g_ptr_array_new ();
4167 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));
4169 mono_loader_lock ();
4171 g_hash_table_iter_init (&iter, domains);
4172 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4173 mono_domain_lock (domain);
4175 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4176 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4177 if (bp_matches_method (bp, m))
4178 set_bp_in_method (domain, m, seq_points, bp, error);
4181 mono_domain_unlock (domain);
4184 mono_loader_unlock ();
4186 mono_loader_lock ();
4187 g_ptr_array_add (breakpoints, bp);
4188 mono_loader_unlock ();
4190 if (error && !mono_error_ok (error)) {
4191 clear_breakpoint (bp);
4199 clear_breakpoint (MonoBreakpoint *bp)
4203 // FIXME: locking, races
4204 for (i = 0; i < bp->children->len; ++i) {
4205 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4207 remove_breakpoint (inst);
4212 mono_loader_lock ();
4213 g_ptr_array_remove (breakpoints, bp);
4214 mono_loader_unlock ();
4216 g_ptr_array_free (bp->children, TRUE);
4221 breakpoints_cleanup (void)
4225 mono_loader_lock ();
4227 while (i < event_requests->len) {
4228 EventRequest *req = g_ptr_array_index (event_requests, i);
4230 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4231 clear_breakpoint (req->info);
4232 g_ptr_array_remove_index_fast (event_requests, i);
4239 for (i = 0; i < breakpoints->len; ++i)
4240 g_free (g_ptr_array_index (breakpoints, i));
4242 g_ptr_array_free (breakpoints, TRUE);
4243 g_hash_table_destroy (bp_locs);
4248 mono_loader_unlock ();
4252 * clear_breakpoints_for_domain:
4254 * Clear breakpoint instances which reference DOMAIN.
4257 clear_breakpoints_for_domain (MonoDomain *domain)
4261 /* This could be called after shutdown */
4265 mono_loader_lock ();
4266 for (i = 0; i < breakpoints->len; ++i) {
4267 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4270 while (j < bp->children->len) {
4271 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4273 if (inst->domain == domain) {
4274 remove_breakpoint (inst);
4278 g_ptr_array_remove_index_fast (bp->children, j);
4284 mono_loader_unlock ();
4288 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4290 return bp->method && bp->method->klass->image->assembly == assembly;
4294 process_breakpoint_inner (DebuggerTlsData *tls)
4298 int i, j, suspend_policy;
4299 guint32 native_offset;
4301 BreakpointInstance *inst;
4302 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4303 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4304 EventKind kind = EVENT_KIND_BREAKPOINT;
4305 MonoContext *ctx = &tls->restore_ctx;
4306 MonoSeqPointInfo *info;
4309 // FIXME: Speed this up
4311 ip = MONO_CONTEXT_GET_IP (ctx);
4312 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4314 g_assert (ji->method);
4316 /* Compute the native offset of the breakpoint from the ip */
4317 native_offset = ip - (guint8*)ji->code_start;
4320 * Skip the instruction causing the breakpoint signal.
4322 mono_arch_skip_breakpoint (ctx, ji);
4324 if (ji->method->wrapper_type || tls->disable_breakpoints)
4327 bp_reqs = g_ptr_array_new ();
4328 ss_reqs = g_ptr_array_new ();
4329 ss_reqs_orig = g_ptr_array_new ();
4331 mono_loader_lock ();
4334 * The ip points to the instruction causing the breakpoint event, which is after
4335 * the offset recorded in the seq point map, so find the prev seq point before ip.
4337 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4339 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));
4342 for (i = 0; i < breakpoints->len; ++i) {
4343 bp = g_ptr_array_index (breakpoints, i);
4348 for (j = 0; j < bp->children->len; ++j) {
4349 inst = g_ptr_array_index (bp->children, j);
4350 if (inst->ji == ji && inst->sp == sp) {
4351 if (bp->req->event_kind == EVENT_KIND_STEP) {
4352 g_ptr_array_add (ss_reqs_orig, bp->req);
4354 g_ptr_array_add (bp_reqs, bp->req);
4359 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4360 /* Maybe a method entry/exit event */
4361 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4362 kind = EVENT_KIND_METHOD_ENTRY;
4363 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4364 kind = EVENT_KIND_METHOD_EXIT;
4367 /* Process single step requests */
4368 for (i = 0; i < ss_reqs_orig->len; ++i) {
4369 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4370 SingleStepReq *ss_req = req->info;
4371 gboolean hit = TRUE;
4373 if (ss_req->size == STEP_SIZE_LINE) {
4374 /* Have to check whenever a different source line was reached */
4375 MonoDebugMethodInfo *minfo;
4376 MonoDebugSourceLocation *loc = NULL;
4378 minfo = mono_debug_lookup_method (ji->method);
4381 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4383 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4384 /* Have to continue single stepping */
4385 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4390 ss_req->last_method = ji->method;
4391 ss_req->last_line = loc->row;
4392 mono_debug_free_source_location (loc);
4397 g_ptr_array_add (ss_reqs, req);
4399 /* Start single stepping again from the current sequence point */
4400 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4403 if (ss_reqs->len > 0)
4404 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4405 if (bp_reqs->len > 0)
4406 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4407 if (kind != EVENT_KIND_BREAKPOINT)
4408 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4410 mono_loader_unlock ();
4412 g_ptr_array_free (bp_reqs, TRUE);
4413 g_ptr_array_free (ss_reqs, TRUE);
4416 * FIXME: The first event will suspend, so the second will only be sent after the
4420 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4422 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4423 if (enter_leave_events)
4424 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4427 /* Process a breakpoint/single step event after resuming from a signal handler */
4429 process_signal_event (void (*func) (DebuggerTlsData*))
4431 DebuggerTlsData *tls;
4432 MonoContext orig_restore_ctx, ctx;
4433 static void (*restore_context) (void *);
4435 if (!restore_context)
4436 restore_context = mono_get_restore_context ();
4438 tls = mono_native_tls_get_value (debugger_tls_id);
4439 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4440 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4441 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4445 /* This is called when resuming from a signal handler, so it shouldn't return */
4446 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4447 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4448 restore_context (&ctx);
4449 g_assert_not_reached ();
4453 process_breakpoint (void)
4455 process_signal_event (process_breakpoint_inner);
4459 resume_from_signal_handler (void *sigctx, void *func)
4461 DebuggerTlsData *tls;
4464 /* Save the original context in TLS */
4465 // FIXME: This might not work on an altstack ?
4466 tls = mono_native_tls_get_value (debugger_tls_id);
4469 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4470 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4471 // clob:c could be added to op_seq_point.
4473 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4474 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4475 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4476 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4478 MONO_CONTEXT_SET_IP (&ctx, func);
4480 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4482 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4483 mono_ppc_set_func_into_sigctx (sigctx, func);
4488 mono_debugger_agent_breakpoint_hit (void *sigctx)
4491 * We are called from a signal handler, and running code there causes all kinds of
4492 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4493 * So set up the signal context to return to the real breakpoint handler function.
4495 resume_from_signal_handler (sigctx, process_breakpoint);
4499 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4501 if (frame->managed) {
4502 *(MonoContext*)data = *ctx;
4511 * Called by System.Diagnostics.Debugger:Break ().
4514 mono_debugger_agent_user_break (void)
4516 if (agent_config.enabled) {
4521 /* Obtain a context */
4522 MONO_CONTEXT_SET_IP (&ctx, NULL);
4523 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4524 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4526 mono_loader_lock ();
4527 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4528 mono_loader_unlock ();
4530 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4537 ss_depth_to_string (StepDepth depth)
4540 case STEP_DEPTH_OVER:
4542 case STEP_DEPTH_OUT:
4544 case STEP_DEPTH_INTO:
4547 g_assert_not_reached ();
4553 process_single_step_inner (DebuggerTlsData *tls)
4558 int il_offset, suspend_policy;
4561 MonoContext *ctx = &tls->restore_ctx;
4563 MonoSeqPointInfo *info;
4565 ip = MONO_CONTEXT_GET_IP (ctx);
4567 /* Skip the instruction causing the single step */
4568 mono_arch_skip_single_step (ctx);
4570 if (suspend_count > 0) {
4571 process_suspend (tls, ctx);
4576 // FIXME: A suspend race
4579 if (mono_thread_internal_current () != ss_req->thread)
4582 if (log_level > 0) {
4583 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4585 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));
4588 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4590 g_assert (ji->method);
4592 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4597 * Stopping in memset makes half-initialized vtypes visible.
4598 * Stopping in memcpy makes half-copied vtypes visible.
4600 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4604 * The ip points to the instruction causing the single step event, which is before
4605 * the offset recorded in the seq point map, so find the next seq point after ip.
4607 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4610 il_offset = sp->il_offset;
4612 // FIXME: No tests fail if this is disabled
4614 if (ss_req->size == STEP_SIZE_LINE) {
4618 /* Step until a different source line is reached */
4619 MonoDebugMethodInfo *minfo;
4621 minfo = mono_debug_lookup_method (ji->method);
4624 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4626 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4627 mono_debug_free_source_location (loc);
4632 * Step until we reach a location with line number info,
4633 * otherwise the client can't show a location.
4634 * This can happen for example with statics initialized inline
4635 * outside of a cctor.
4640 ss_req->last_method = ji->method;
4641 ss_req->last_line = loc->row;
4642 mono_debug_free_source_location (loc);
4648 /* Start single stepping again from the current sequence point */
4649 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4651 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4652 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4653 !strcmp (ji->method->name, ".cctor"))
4656 // FIXME: Has to lock earlier
4658 reqs = g_ptr_array_new ();
4660 mono_loader_lock ();
4662 g_ptr_array_add (reqs, ss_req->req);
4664 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4666 g_ptr_array_free (reqs, TRUE);
4668 mono_loader_unlock ();
4670 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4674 process_single_step (void)
4676 process_signal_event (process_single_step_inner);
4680 * mono_debugger_agent_single_step_event:
4682 * Called from a signal handler to handle a single step event.
4685 mono_debugger_agent_single_step_event (void *sigctx)
4687 /* Resume to process_single_step through the signal context */
4689 // FIXME: Since step out/over is implemented using step in, the step in case should
4690 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4693 if (GetCurrentThreadId () == debugger_thread_id) {
4695 * This could happen despite our best effors when the runtime calls
4696 * assembly/type resolve hooks.
4697 * FIXME: Breakpoints too.
4701 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4702 mono_arch_skip_single_step (&ctx);
4703 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4707 resume_from_signal_handler (sigctx, process_single_step);
4711 debugger_agent_single_step_from_context (MonoContext *ctx)
4713 DebuggerTlsData *tls;
4714 MonoContext orig_restore_ctx;
4716 tls = mono_native_tls_get_value (debugger_tls_id);
4719 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4720 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4721 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4723 process_single_step_inner (tls);
4725 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4726 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4730 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4732 DebuggerTlsData *tls;
4733 MonoContext orig_restore_ctx;
4735 tls = mono_native_tls_get_value (debugger_tls_id);
4737 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4738 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4740 process_breakpoint_inner (tls);
4742 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4743 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4747 * start_single_stepping:
4749 * Turn on single stepping. Can be called multiple times, for example,
4750 * by a single step event request + a suspend.
4753 start_single_stepping (void)
4755 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4756 int val = InterlockedIncrement (&ss_count);
4759 mono_arch_start_single_stepping ();
4761 if (ss_req != NULL && ss_invoke_addr == NULL) {
4762 DebuggerTlsData *tls;
4764 mono_loader_lock ();
4766 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4767 ss_invoke_addr = tls->invoke_addr;
4769 mono_loader_unlock ();
4772 g_assert_not_reached ();
4777 stop_single_stepping (void)
4779 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4780 int val = InterlockedDecrement (&ss_count);
4783 mono_arch_stop_single_stepping ();
4785 g_assert_not_reached ();
4792 * Stop the single stepping operation given by SS_REQ.
4795 ss_stop (SingleStepReq *ss_req)
4800 for (l = ss_req->bps; l; l = l->next) {
4801 clear_breakpoint (l->data);
4803 g_slist_free (ss_req->bps);
4807 if (ss_req->global) {
4808 stop_single_stepping ();
4809 ss_req->global = FALSE;
4816 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4817 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4818 * belong to the same thread as CTX.
4821 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4823 int i, j, frame_index;
4826 gboolean enable_global = FALSE;
4828 /* Stop the previous operation */
4832 * Implement single stepping using breakpoints if possible.
4834 if (step_to_catch) {
4835 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4836 ss_req->bps = g_slist_append (ss_req->bps, bp);
4840 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4841 /* Need parent frames */
4842 if (!tls->context.valid)
4843 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4844 compute_frame_info (tls->thread, tls);
4848 * Find the first sequence point in the current or in a previous frame which
4849 * is not the last in its method.
4851 if (ss_req->depth == STEP_DEPTH_OUT) {
4852 /* Ignore seq points in current method */
4853 while (frame_index < tls->frame_count) {
4854 StackFrame *frame = tls->frames [frame_index];
4856 method = frame->method;
4857 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4859 if (sp && sp->next_len != 0)
4862 // There could be method calls before the next seq point in the caller when using nested calls
4863 //enable_global = TRUE;
4865 while (sp && sp->next_len == 0) {
4867 if (frame_index < tls->frame_count) {
4868 StackFrame *frame = tls->frames [frame_index];
4870 method = frame->method;
4871 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4877 if (sp && sp->next_len > 0) {
4878 for (i = 0; i < sp->next_len; ++i) {
4879 next_sp = &info->seq_points [sp->next [i]];
4881 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4882 ss_req->bps = g_slist_append (ss_req->bps, bp);
4886 if (ss_req->depth == STEP_DEPTH_OVER) {
4887 /* Need to stop in catch clauses as well */
4888 for (i = 0; i < tls->frame_count; ++i) {
4889 StackFrame *frame = tls->frames [i];
4892 MonoJitInfo *jinfo = frame->ji;
4893 for (j = 0; j < jinfo->num_clauses; ++j) {
4894 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4896 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4898 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4899 ss_req->bps = g_slist_append (ss_req->bps, bp);
4907 if (ss_req->depth == STEP_DEPTH_INTO) {
4908 /* Enable global stepping so we stop at method entry too */
4909 enable_global = TRUE;
4913 * The ctx/frame info computed above will become invalid when we continue.
4915 tls->context.valid = FALSE;
4916 tls->async_state.valid = FALSE;
4917 invalidate_frames (tls);
4920 if (enable_global) {
4921 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4922 ss_req->global = TRUE;
4923 start_single_stepping ();
4924 } else if (!ss_req->bps) {
4925 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4926 ss_req->global = TRUE;
4927 start_single_stepping ();
4929 ss_req->global = FALSE;
4934 * Start single stepping of thread THREAD
4937 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4939 DebuggerTlsData *tls;
4940 MonoSeqPointInfo *info = NULL;
4941 SeqPoint *sp = NULL;
4942 MonoMethod *method = NULL;
4943 MonoDebugMethodInfo *minfo;
4944 gboolean step_to_catch = FALSE;
4946 if (suspend_count == 0)
4947 return ERR_NOT_SUSPENDED;
4949 wait_for_suspend ();
4951 // FIXME: Multiple requests
4953 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4954 return ERR_NOT_IMPLEMENTED;
4957 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4959 ss_req = g_new0 (SingleStepReq, 1);
4961 ss_req->thread = thread;
4962 ss_req->size = size;
4963 ss_req->depth = depth;
4966 mono_loader_lock ();
4967 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4968 mono_loader_unlock ();
4970 g_assert (tls->context.valid);
4971 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4973 if (tls->has_catch_ctx) {
4975 StackFrameInfo frame;
4976 MonoContext new_ctx;
4977 MonoLMF *lmf = NULL;
4980 * We are stopped at a throw site. Stepping should go to the catch site.
4983 /* Find the the jit info for the catch context */
4984 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4986 g_assert (frame.type == FRAME_TYPE_MANAGED);
4989 * Find the seq point corresponding to the landing site ip, which is the first seq
4992 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4995 method = frame.method;
4997 step_to_catch = TRUE;
4998 /* This make sure the seq point is not skipped by process_single_step () */
4999 ss_req->last_sp = NULL;
5002 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5005 /* Compute the initial line info */
5006 compute_frame_info (thread, tls);
5008 if (tls->frame_count) {
5009 frame = tls->frames [0];
5011 ss_req->last_method = frame->method;
5012 ss_req->last_line = -1;
5014 minfo = mono_debug_lookup_method (frame->method);
5015 if (minfo && frame->il_offset != -1) {
5016 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5019 ss_req->last_line = loc->row;
5026 if (!step_to_catch) {
5029 compute_frame_info (thread, tls);
5031 if (tls->frame_count) {
5032 frame = tls->frames [0];
5034 if (!method && frame->il_offset != -1) {
5035 /* FIXME: Sort the table and use a binary search */
5036 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5038 method = frame->method;
5043 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5049 ss_destroy (SingleStepReq *req)
5052 g_assert (ss_req == req);
5061 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5064 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5070 if (!agent_config.enabled)
5073 mono_loader_lock ();
5074 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5075 mono_loader_unlock ();
5078 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5079 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5081 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5083 g_free (ei.category);
5084 g_free (ei.message);
5088 mono_debugger_agent_debug_log_is_enabled (void)
5090 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5091 return agent_config.enabled;
5095 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5096 MonoContext *catch_ctx)
5102 DebuggerTlsData *tls = NULL;
5104 if (thread_to_tls != NULL) {
5105 MonoInternalThread *thread = mono_thread_internal_current ();
5107 mono_loader_lock ();
5108 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5109 mono_loader_unlock ();
5111 if (tls && tls->abort_requested)
5113 if (tls && tls->disable_breakpoints)
5117 memset (&ei, 0, sizeof (EventInfo));
5119 /* Just-In-Time debugging */
5121 if (agent_config.onuncaught && !inited) {
5122 finish_agent_init (FALSE);
5125 * Send an unsolicited EXCEPTION event with a dummy request id.
5127 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5128 ei.exc = (MonoObject*)exc;
5129 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5132 } else if (agent_config.onthrow && !inited) {
5134 gboolean found = FALSE;
5136 for (l = agent_config.onthrow; l; l = l->next) {
5137 char *ex_type = l->data;
5138 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5140 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5147 finish_agent_init (FALSE);
5150 * Send an unsolicited EXCEPTION event with a dummy request id.
5152 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5153 ei.exc = (MonoObject*)exc;
5154 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5162 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5164 ei.exc = (MonoObject*)exc;
5165 ei.caught = catch_ctx != NULL;
5167 mono_loader_lock ();
5168 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5169 mono_loader_unlock ();
5171 if (tls && catch_ctx) {
5172 tls->catch_ctx = *catch_ctx;
5173 tls->has_catch_ctx = TRUE;
5176 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5179 tls->has_catch_ctx = FALSE;
5183 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5185 DebuggerTlsData *tls;
5190 tls = mono_native_tls_get_value (debugger_tls_id);
5195 * We're about to invoke an exception filter during the first pass of exception handling.
5197 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5198 * 'orig_ctx' is the context where the exception has been thrown.
5201 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5203 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5204 * the call site (line 37) and then continue to Main(), but it would never
5205 * include the throw site (line 32).
5207 * Since exception filters are invoked during the first pass of exception handling,
5208 * the stack frames of the throw site are still intact, so we should include them
5211 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5213 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5214 * but report the location of the 'throw' to the user.
5218 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5222 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5224 DebuggerTlsData *tls;
5229 tls = mono_native_tls_get_value (debugger_tls_id);
5233 tls->filter_state.valid = FALSE;
5237 * buffer_add_value_full:
5239 * Add the encoding of the value at ADDR described by T to the buffer.
5240 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5244 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5250 g_assert (*(void**)addr);
5251 addr = *(void**)addr;
5256 case MONO_TYPE_BOOLEAN:
5259 case MONO_TYPE_CHAR:
5279 case MONO_TYPE_VOID:
5280 buffer_add_byte (buf, t->type);
5282 case MONO_TYPE_BOOLEAN:
5285 buffer_add_byte (buf, t->type);
5286 buffer_add_int (buf, *(gint8*)addr);
5288 case MONO_TYPE_CHAR:
5291 buffer_add_byte (buf, t->type);
5292 buffer_add_int (buf, *(gint16*)addr);
5297 buffer_add_byte (buf, t->type);
5298 buffer_add_int (buf, *(gint32*)addr);
5303 buffer_add_byte (buf, t->type);
5304 buffer_add_long (buf, *(gint64*)addr);
5308 /* Treat it as a vtype */
5310 case MONO_TYPE_PTR: {
5311 gssize val = *(gssize*)addr;
5313 buffer_add_byte (buf, t->type);
5314 buffer_add_long (buf, val);
5318 case MONO_TYPE_STRING:
5319 case MONO_TYPE_SZARRAY:
5320 case MONO_TYPE_OBJECT:
5321 case MONO_TYPE_CLASS:
5322 case MONO_TYPE_ARRAY:
5323 obj = *(MonoObject**)addr;
5326 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5328 if (obj->vtable->klass->valuetype) {
5329 t = &obj->vtable->klass->byval_arg;
5330 addr = mono_object_unbox (obj);
5332 } else if (obj->vtable->klass->rank) {
5333 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5334 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5335 buffer_add_byte (buf, MONO_TYPE_CLASS);
5337 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5339 buffer_add_objid (buf, obj);
5343 case MONO_TYPE_VALUETYPE: {
5347 MonoClass *klass = mono_class_from_mono_type (t);
5349 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5350 buffer_add_byte (buf, klass->enumtype);
5351 buffer_add_typeid (buf, domain, klass);
5355 while ((f = mono_class_get_fields (klass, &iter))) {
5356 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5358 if (mono_field_is_deleted (f))
5362 buffer_add_int (buf, nfields);
5365 while ((f = mono_class_get_fields (klass, &iter))) {
5366 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5368 if (mono_field_is_deleted (f))
5370 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5374 case MONO_TYPE_GENERICINST:
5375 if (mono_type_generic_inst_is_valuetype (t)) {
5387 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5389 buffer_add_value_full (buf, t, addr, domain, FALSE);
5393 obj_is_of_type (MonoObject *obj, MonoType *t)
5395 MonoClass *klass = obj->vtable->klass;
5396 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5397 if (klass == mono_defaults.transparent_proxy_class) {
5398 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5399 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5409 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5412 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5416 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5417 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5418 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5419 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5420 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5421 char *name = mono_type_full_name (t);
5422 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5424 return ERR_INVALID_ARGUMENT;
5428 case MONO_TYPE_BOOLEAN:
5429 *(guint8*)addr = decode_int (buf, &buf, limit);
5431 case MONO_TYPE_CHAR:
5432 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5435 *(gint8*)addr = decode_int (buf, &buf, limit);
5438 *(guint8*)addr = decode_int (buf, &buf, limit);
5441 *(gint16*)addr = decode_int (buf, &buf, limit);
5444 *(guint16*)addr = decode_int (buf, &buf, limit);
5447 *(gint32*)addr = decode_int (buf, &buf, limit);
5450 *(guint32*)addr = decode_int (buf, &buf, limit);
5453 *(gint64*)addr = decode_long (buf, &buf, limit);
5456 *(guint64*)addr = decode_long (buf, &buf, limit);
5459 *(guint32*)addr = decode_int (buf, &buf, limit);
5462 *(guint64*)addr = decode_long (buf, &buf, limit);
5465 /* We send these as I8, so we get them back as such */
5466 g_assert (type == MONO_TYPE_I8);
5467 *(gssize*)addr = decode_long (buf, &buf, limit);
5469 case MONO_TYPE_GENERICINST:
5470 if (MONO_TYPE_ISSTRUCT (t)) {
5471 /* The client sends these as a valuetype */
5479 /* We send these as vtypes, so we get them back as such */
5480 g_assert (type == MONO_TYPE_VALUETYPE);
5483 case MONO_TYPE_VALUETYPE: {
5484 gboolean is_enum = decode_byte (buf, &buf, limit);
5488 gpointer iter = NULL;
5491 /* Enums are sent as a normal vtype */
5493 return ERR_NOT_IMPLEMENTED;
5494 klass = decode_typeid (buf, &buf, limit, &d, &err);
5498 if (klass != mono_class_from_mono_type (t))
5499 return ERR_INVALID_ARGUMENT;
5501 nfields = decode_int (buf, &buf, limit);
5502 while ((f = mono_class_get_fields (klass, &iter))) {
5503 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5505 if (mono_field_is_deleted (f))
5507 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5512 g_assert (nfields == 0);
5517 if (MONO_TYPE_IS_REFERENCE (t)) {
5518 if (type == MONO_TYPE_OBJECT) {
5519 int objid = decode_objid (buf, &buf, limit);
5523 err = get_object (objid, (MonoObject**)&obj);
5528 if (!obj_is_of_type (obj, t)) {
5529 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5530 return ERR_INVALID_ARGUMENT;
5533 if (obj && obj->vtable->domain != domain)
5534 return ERR_INVALID_ARGUMENT;
5536 mono_gc_wbarrier_generic_store (addr, obj);
5537 } else if (type == VALUE_TYPE_ID_NULL) {
5538 *(MonoObject**)addr = NULL;
5540 return ERR_INVALID_ARGUMENT;
5554 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5557 int type = decode_byte (buf, &buf, limit);
5559 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5560 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5561 guint8 *nullable_buf;
5564 * First try decoding it as a Nullable`1
5566 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5571 * Then try decoding as a primitive value or null.
5573 if (targ->type == type) {
5574 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5575 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5577 g_free (nullable_buf);
5580 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5581 g_free (nullable_buf);
5584 } else if (type == VALUE_TYPE_ID_NULL) {
5585 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5591 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5595 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5602 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5603 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5606 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5607 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5609 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5611 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5612 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5613 addr += (gint32)var->offset;
5615 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5617 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5619 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5623 g_assert_not_reached ();
5628 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5634 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5635 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5637 if (MONO_TYPE_IS_REFERENCE (t))
5638 size = sizeof (gpointer);
5640 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5643 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5644 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5646 gboolean is_signed = FALSE;
5648 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5653 v = is_signed ? *(gint8*)val : *(guint8*)val;
5656 v = is_signed ? *(gint16*)val : *(guint16*)val;
5659 v = is_signed ? *(gint32*)val : *(guint32*)val;
5662 v = is_signed ? *(gint64*)val : *(guint64*)val;
5665 g_assert_not_reached ();
5671 /* Set value on the stack or in the return ctx */
5672 if (reg_locations [reg]) {
5673 /* Saved on the stack */
5674 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5675 *(reg_locations [reg]) = v;
5678 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5679 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5682 // FIXME: Move these to mono-context.h/c.
5683 mono_arch_context_set_int_reg (ctx, reg, v);
5685 // FIXME: Can't set registers, so we disable linears
5690 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5691 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5692 addr += (gint32)var->offset;
5694 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5697 addr = *(guint8**)addr;
5703 // FIXME: Write barriers
5704 mono_gc_memmove (addr, val, size);
5706 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5710 g_assert_not_reached ();
5715 clear_event_request (int req_id, int etype)
5719 mono_loader_lock ();
5720 for (i = 0; i < event_requests->len; ++i) {
5721 EventRequest *req = g_ptr_array_index (event_requests, i);
5723 if (req->id == req_id && req->event_kind == etype) {
5724 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5725 clear_breakpoint (req->info);
5726 if (req->event_kind == EVENT_KIND_STEP)
5727 ss_destroy (req->info);
5728 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5729 clear_breakpoint (req->info);
5730 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5731 clear_breakpoint (req->info);
5732 g_ptr_array_remove_index_fast (event_requests, i);
5737 mono_loader_unlock ();
5741 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5743 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5744 return breakpoint_matches_assembly (req->info, assembly);
5748 for (i = 0; i < req->nmodifiers; ++i) {
5749 Modifier *m = &req->modifiers [i];
5751 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5753 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5754 for (j = 0; m->data.assemblies [j]; ++j)
5755 if (m->data.assemblies [j] == assembly)
5765 * clear_event_requests_for_assembly:
5767 * Clear all events requests which reference ASSEMBLY.
5770 clear_event_requests_for_assembly (MonoAssembly *assembly)
5775 mono_loader_lock ();
5779 for (i = 0; i < event_requests->len; ++i) {
5780 EventRequest *req = g_ptr_array_index (event_requests, i);
5782 if (event_req_matches_assembly (req, assembly)) {
5783 clear_event_request (req->id, req->event_kind);
5789 mono_loader_unlock ();
5793 * type_comes_from_assembly:
5795 * GHRFunc that returns TRUE if klass comes from assembly
5798 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5800 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5804 * clear_types_for_assembly:
5806 * Clears types from loaded_classes for a given assembly
5809 clear_types_for_assembly (MonoAssembly *assembly)
5811 MonoDomain *domain = mono_domain_get ();
5812 AgentDomainInfo *info = NULL;
5814 mono_loader_lock ();
5815 info = get_agent_domain_info (domain);
5816 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5817 mono_loader_unlock ();
5821 add_thread (gpointer key, gpointer value, gpointer user_data)
5823 MonoInternalThread *thread = value;
5824 Buffer *buf = user_data;
5826 buffer_add_objid (buf, (MonoObject*)thread);
5830 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5832 guint8 *end = invoke->endp;
5835 MonoMethodSignature *sig;
5838 MonoObject *this, *res, *exc;
5841 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5844 MonoStopwatch watch;
5846 if (invoke->method) {
5848 * Invoke this method directly, currently only Environment.Exit () is supported.
5851 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>"));
5852 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5853 g_assert_not_reached ();
5856 m = decode_methodid (p, &p, end, &domain, &err);
5859 sig = mono_method_signature (m);
5861 if (m->klass->valuetype)
5862 this_buf = g_alloca (mono_class_instance_size (m->klass));
5864 this_buf = g_alloca (sizeof (MonoObject*));
5865 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5866 /* Should be null */
5867 int type = decode_byte (p, &p, end);
5868 if (type != VALUE_TYPE_ID_NULL)
5869 return ERR_INVALID_ARGUMENT;
5870 memset (this_buf, 0, mono_class_instance_size (m->klass));
5872 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5877 if (!m->klass->valuetype)
5878 this = *(MonoObject**)this_buf;
5882 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>"));
5884 if (this && this->vtable->domain != domain)
5887 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5888 if (!strcmp (m->name, ".ctor")) {
5889 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5890 return ERR_INVALID_ARGUMENT;
5892 this = mono_object_new (domain, m->klass);
5894 return ERR_INVALID_ARGUMENT;
5898 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
5899 return ERR_INVALID_ARGUMENT;
5901 nargs = decode_int (p, &p, end);
5902 if (nargs != sig->param_count)
5903 return ERR_INVALID_ARGUMENT;
5904 /* Use alloca to get gc tracking */
5905 arg_buf = g_alloca (nargs * sizeof (gpointer));
5906 memset (arg_buf, 0, nargs * sizeof (gpointer));
5907 args = g_alloca (nargs * sizeof (gpointer));
5908 for (i = 0; i < nargs; ++i) {
5909 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5910 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5914 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5917 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5918 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5921 args [i] = arg_buf [i];
5928 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5929 tls->disable_breakpoints = TRUE;
5931 tls->disable_breakpoints = FALSE;
5934 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5936 /* FIXME: Move this to arch specific code */
5937 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5938 if (invoke->has_ctx) {
5941 lmf_addr = mono_get_lmf_addr ();
5944 memset (&ext, 0, sizeof (ext));
5946 ext.lmf.previous_lmf = *(lmf_addr);
5947 /* Mark that this is a MonoLMFExt */
5948 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5949 ext.lmf.rsp = (gssize)&ext;
5950 #elif defined(TARGET_X86)
5951 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5952 /* Mark that this is a MonoLMFExt */
5953 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5954 ext.lmf.ebp = (gssize)&ext;
5955 #elif defined(TARGET_ARM)
5956 ext.lmf.previous_lmf = *(lmf_addr);
5957 /* Mark that this is a MonoLMFExt */
5958 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5959 ext.lmf.sp = (gssize)&ext;
5960 #elif defined(TARGET_POWERPC)
5961 ext.lmf.previous_lmf = *(lmf_addr);
5962 /* Mark that this is a MonoLMFExt */
5963 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5964 ext.lmf.ebp = (gssize)&ext;
5965 #elif defined(TARGET_S390X)
5966 ext.lmf.previous_lmf = *(lmf_addr);
5967 /* Mark that this is a MonoLMFExt */
5968 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5969 ext.lmf.ebp = (gssize)&ext;
5970 #elif defined(TARGET_MIPS)
5971 ext.lmf.previous_lmf = *(lmf_addr);
5972 /* Mark that this is a MonoLMFExt */
5973 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5974 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5976 g_assert_not_reached ();
5979 ext.debugger_invoke = TRUE;
5980 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5982 mono_set_lmf ((MonoLMF*)&ext);
5986 mono_stopwatch_start (&watch);
5987 if (m->klass->valuetype)
5988 res = mono_runtime_invoke (m, this_buf, args, &exc);
5990 res = mono_runtime_invoke (m, this, args, &exc);
5991 mono_stopwatch_stop (&watch);
5992 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)));
5994 buffer_add_byte (buf, 0);
5995 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5997 buffer_add_byte (buf, 1);
5998 if (sig->ret->type == MONO_TYPE_VOID) {
5999 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6000 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6003 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6004 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6005 buffer_add_value (buf, sig->ret, &res, domain);
6006 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6007 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6008 MonoClass *k = mono_class_from_mono_type (sig->ret);
6009 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6011 g_assert (nullable_buf);
6012 mono_nullable_init (nullable_buf, res, k);
6013 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6016 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6023 tls->disable_breakpoints = FALSE;
6025 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6026 if (invoke->has_ctx)
6027 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6031 // FIXME: byref arguments
6039 * Invoke the method given by tls->pending_invoke in the current thread.
6042 invoke_method (void)
6044 DebuggerTlsData *tls;
6049 static void (*restore_context) (void *);
6050 MonoContext restore_ctx;
6053 if (!restore_context)
6054 restore_context = mono_get_restore_context ();
6056 tls = mono_native_tls_get_value (debugger_tls_id);
6060 * Store the `InvokeData *' in `tls->invoke' until we're done with
6061 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6064 mono_loader_lock ();
6066 invoke = tls->pending_invoke;
6068 tls->pending_invoke = NULL;
6070 invoke->last_invoke = tls->invoke;
6071 tls->invoke = invoke;
6073 mono_loader_unlock ();
6075 tls->frames_up_to_date = FALSE;
6081 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6082 buffer_init (&buf, 128);
6085 /* Fail the other invokes as well */
6087 err = do_invoke_method (tls, &buf, invoke, p, &p);
6090 /* Start suspending before sending the reply */
6091 if (mindex == invoke->nmethods - 1) {
6092 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6093 for (i = 0; i < invoke->suspend_count; ++i)
6098 send_reply_packet (id, err, &buf);
6103 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6105 if (invoke->has_ctx)
6106 save_thread_context (&restore_ctx);
6108 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6109 g_assert (tls->resume_count);
6110 tls->resume_count -= invoke->suspend_count;
6113 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6116 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6118 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6119 * after the mono_runtime_invoke() already returned, but it doesn't matter
6120 * because we reset the abort here.
6123 mono_loader_lock ();
6125 if (tls->abort_requested)
6126 mono_thread_internal_reset_abort (tls->thread);
6128 tls->invoke = tls->invoke->last_invoke;
6129 tls->abort_requested = FALSE;
6131 mono_loader_unlock ();
6140 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6142 MonoThread *thread = value;
6143 DebuggerTlsData *tls;
6146 mono_loader_lock ();
6147 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6149 res = tls->really_suspended;
6150 mono_loader_unlock ();
6156 get_source_files_for_type (MonoClass *klass)
6158 gpointer iter = NULL;
6160 MonoDebugSourceInfo *sinfo;
6164 files = g_ptr_array_new ();
6166 while ((method = mono_class_get_methods (klass, &iter))) {
6167 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6168 GPtrArray *source_file_list;
6171 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6172 for (j = 0; j < source_file_list->len; ++j) {
6173 sinfo = g_ptr_array_index (source_file_list, j);
6174 for (i = 0; i < files->len; ++i)
6175 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6177 if (i == files->len)
6178 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6180 g_ptr_array_free (source_file_list, TRUE);
6188 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6191 case CMD_VM_VERSION: {
6192 char *build_info, *version;
6194 build_info = mono_get_runtime_build_info ();
6195 version = g_strdup_printf ("mono %s", build_info);
6197 buffer_add_string (buf, version); /* vm version */
6198 buffer_add_int (buf, MAJOR_VERSION);
6199 buffer_add_int (buf, MINOR_VERSION);
6200 g_free (build_info);
6204 case CMD_VM_SET_PROTOCOL_VERSION: {
6205 major_version = decode_int (p, &p, end);
6206 minor_version = decode_int (p, &p, end);
6207 protocol_version_set = TRUE;
6208 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6211 case CMD_VM_ALL_THREADS: {
6213 mono_loader_lock ();
6214 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6215 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6216 mono_loader_unlock ();
6219 case CMD_VM_SUSPEND:
6221 wait_for_suspend ();
6224 if (suspend_count == 0)
6225 return ERR_NOT_SUSPENDED;
6228 case CMD_VM_DISPOSE:
6229 /* Clear all event requests */
6230 mono_loader_lock ();
6231 while (event_requests->len > 0) {
6232 EventRequest *req = g_ptr_array_index (event_requests, 0);
6234 clear_event_request (req->id, req->event_kind);
6236 mono_loader_unlock ();
6238 while (suspend_count > 0)
6240 disconnected = TRUE;
6241 vm_start_event_sent = FALSE;
6244 MonoInternalThread *thread;
6245 DebuggerTlsData *tls;
6246 MonoClass *env_class;
6247 MonoMethod *exit_method = NULL;
6251 exit_code = decode_int (p, &p, end);
6253 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6255 /* Have to send a reply before exiting */
6256 send_reply_packet (id, 0, buf);
6258 /* Clear all event requests */
6259 mono_loader_lock ();
6260 while (event_requests->len > 0) {
6261 EventRequest *req = g_ptr_array_index (event_requests, 0);
6263 clear_event_request (req->id, req->event_kind);
6265 mono_loader_unlock ();
6268 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6269 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6270 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6271 * better than doing the shutdown ourselves, since it avoids various races.
6275 wait_for_suspend ();
6277 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6279 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6281 mono_loader_lock ();
6282 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6283 mono_loader_unlock ();
6285 if (thread && exit_method) {
6286 mono_loader_lock ();
6287 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6288 mono_loader_unlock ();
6290 args = g_new0 (gpointer, 1);
6291 args [0] = g_malloc (sizeof (int));
6292 *(int*)(args [0]) = exit_code;
6294 tls->pending_invoke = g_new0 (InvokeData, 1);
6295 tls->pending_invoke->method = exit_method;
6296 tls->pending_invoke->args = args;
6297 tls->pending_invoke->nmethods = 1;
6299 while (suspend_count > 0)
6303 * No thread found, do it ourselves.
6304 * FIXME: This can race with normal shutdown etc.
6306 while (suspend_count > 0)
6309 mono_runtime_set_shutting_down ();
6311 mono_threads_set_shutting_down ();
6313 /* Suspend all managed threads since the runtime is going away */
6314 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6315 mono_thread_suspend_all_other_threads ();
6316 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6317 mono_runtime_quit ();
6318 transport_close2 ();
6319 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6325 case CMD_VM_INVOKE_METHOD:
6326 case CMD_VM_INVOKE_METHODS: {
6327 int objid = decode_objid (p, &p, end);
6329 DebuggerTlsData *tls;
6330 int i, count, err, flags, nmethods;
6332 err = get_object (objid, (MonoObject**)&thread);
6336 flags = decode_int (p, &p, end);
6338 if (command == CMD_VM_INVOKE_METHODS)
6339 nmethods = decode_int (p, &p, end);
6343 // Wait for suspending if it already started
6345 wait_for_suspend ();
6346 if (!is_suspended ())
6347 return ERR_NOT_SUSPENDED;
6349 mono_loader_lock ();
6350 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6351 mono_loader_unlock ();
6354 if (!tls->really_suspended)
6355 /* The thread is still running native code, can't do invokes */
6356 return ERR_NOT_SUSPENDED;
6359 * Store the invoke data into tls, the thread will execute it after it is
6362 if (tls->pending_invoke)
6363 return ERR_NOT_SUSPENDED;
6364 tls->pending_invoke = g_new0 (InvokeData, 1);
6365 tls->pending_invoke->id = id;
6366 tls->pending_invoke->flags = flags;
6367 tls->pending_invoke->p = g_malloc (end - p);
6368 memcpy (tls->pending_invoke->p, p, end - p);
6369 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6370 tls->pending_invoke->suspend_count = suspend_count;
6371 tls->pending_invoke->nmethods = nmethods;
6373 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6374 resume_thread (THREAD_TO_INTERNAL (thread));
6377 count = suspend_count;
6378 for (i = 0; i < count; ++i)
6383 case CMD_VM_ABORT_INVOKE: {
6384 int objid = decode_objid (p, &p, end);
6386 DebuggerTlsData *tls;
6389 err = get_object (objid, (MonoObject**)&thread);
6393 invoke_id = decode_int (p, &p, end);
6395 mono_loader_lock ();
6396 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6399 if (tls->abort_requested) {
6400 mono_loader_unlock ();
6405 * Check whether we're still inside the mono_runtime_invoke() and that it's
6406 * actually the correct invocation.
6408 * Careful, we do not stop the thread that's doing the invocation, so we can't
6409 * inspect its stack. However, invoke_method() also acquires the loader lock
6410 * when it's done, so we're safe here.
6414 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6415 mono_loader_unlock ();
6416 return ERR_NO_INVOCATION;
6419 tls->abort_requested = TRUE;
6421 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6422 mono_loader_unlock ();
6426 case CMD_VM_SET_KEEPALIVE: {
6427 int timeout = decode_int (p, &p, end);
6428 agent_config.keepalive = timeout;
6430 #ifndef DISABLE_SOCKET_TRANSPORT
6437 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6438 GHashTableIter iter, kiter;
6443 char *fname, *basename;
6444 gboolean ignore_case;
6445 GSList *class_list, *l;
6446 GPtrArray *res_classes, *res_domains;
6448 fname = decode_string (p, &p, end);
6449 ignore_case = decode_byte (p, &p, end);
6451 basename = g_path_get_basename (fname);
6453 res_classes = g_ptr_array_new ();
6454 res_domains = g_ptr_array_new ();
6456 mono_loader_lock ();
6457 g_hash_table_iter_init (&iter, domains);
6458 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6459 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6461 /* Update 'source_file_to_class' cache */
6462 g_hash_table_iter_init (&kiter, info->loaded_classes);
6463 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6464 if (!g_hash_table_lookup (info->source_files, klass)) {
6465 files = get_source_files_for_type (klass);
6466 g_hash_table_insert (info->source_files, klass, files);
6468 for (i = 0; i < files->len; ++i) {
6469 char *s = g_ptr_array_index (files, i);
6470 char *s2 = g_path_get_basename (s);
6473 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6475 class_list = g_slist_prepend (class_list, klass);
6476 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6478 class_list = g_slist_prepend (class_list, klass);
6479 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6482 /* The _ignorecase hash contains the lowercase path */
6483 s3 = strdup_tolower (s2);
6484 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6486 class_list = g_slist_prepend (class_list, klass);
6487 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6489 class_list = g_slist_prepend (class_list, klass);
6490 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6502 s = strdup_tolower (basename);
6503 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6506 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6509 for (l = class_list; l; l = l->next) {
6512 g_ptr_array_add (res_classes, klass);
6513 g_ptr_array_add (res_domains, domain);
6516 mono_loader_unlock ();
6521 buffer_add_int (buf, res_classes->len);
6522 for (i = 0; i < res_classes->len; ++i)
6523 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6524 g_ptr_array_free (res_classes, TRUE);
6525 g_ptr_array_free (res_domains, TRUE);
6528 case CMD_VM_GET_TYPES: {
6529 GHashTableIter iter;
6533 gboolean ignore_case;
6534 GPtrArray *res_classes, *res_domains;
6535 MonoTypeNameParse info;
6537 name = decode_string (p, &p, end);
6538 ignore_case = decode_byte (p, &p, end);
6540 if (!mono_reflection_parse_type (name, &info)) {
6542 mono_reflection_free_type_info (&info);
6543 return ERR_INVALID_ARGUMENT;
6546 res_classes = g_ptr_array_new ();
6547 res_domains = g_ptr_array_new ();
6549 mono_loader_lock ();
6550 g_hash_table_iter_init (&iter, domains);
6551 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6553 gboolean type_resolve;
6557 mono_domain_assemblies_lock (domain);
6558 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6562 type_resolve = TRUE;
6563 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6565 g_ptr_array_add (res_classes, mono_type_get_class (t));
6566 g_ptr_array_add (res_domains, domain);
6570 mono_domain_assemblies_unlock (domain);
6572 mono_loader_unlock ();
6575 mono_reflection_free_type_info (&info);
6577 buffer_add_int (buf, res_classes->len);
6578 for (i = 0; i < res_classes->len; ++i)
6579 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6580 g_ptr_array_free (res_classes, TRUE);
6581 g_ptr_array_free (res_domains, TRUE);
6586 return ERR_NOT_IMPLEMENTED;
6593 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6599 case CMD_EVENT_REQUEST_SET: {
6601 int i, event_kind, suspend_policy, nmodifiers, mod;
6604 MonoThread *step_thread;
6605 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6609 event_kind = decode_byte (p, &p, end);
6610 suspend_policy = decode_byte (p, &p, end);
6611 nmodifiers = decode_byte (p, &p, end);
6613 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6614 req->id = InterlockedIncrement (&event_request_id);
6615 req->event_kind = event_kind;
6616 req->suspend_policy = suspend_policy;
6617 req->nmodifiers = nmodifiers;
6620 for (i = 0; i < nmodifiers; ++i) {
6621 mod = decode_byte (p, &p, end);
6623 req->modifiers [i].kind = mod;
6624 if (mod == MOD_KIND_COUNT) {
6625 req->modifiers [i].data.count = decode_int (p, &p, end);
6626 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6627 method = decode_methodid (p, &p, end, &domain, &err);
6630 location = decode_long (p, &p, end);
6631 } else if (mod == MOD_KIND_STEP) {
6632 step_thread_id = decode_id (p, &p, end);
6633 size = decode_int (p, &p, end);
6634 depth = decode_int (p, &p, end);
6635 if (CHECK_PROTOCOL_VERSION (2, 16))
6636 filter = decode_int (p, &p, end);
6637 req->modifiers [i].data.filter = filter;
6638 } else if (mod == MOD_KIND_THREAD_ONLY) {
6639 int id = decode_id (p, &p, end);
6641 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6646 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6647 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6651 req->modifiers [i].caught = decode_byte (p, &p, end);
6652 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6653 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" : ""));
6655 req->modifiers [i].data.exc_class = exc_class;
6657 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6659 return ERR_INVALID_ARGUMENT;
6662 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6663 int n = decode_int (p, &p, end);
6666 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6667 for (j = 0; j < n; ++j) {
6668 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6670 g_free (req->modifiers [i].data.assemblies);
6674 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6675 int n = decode_int (p, &p, end);
6678 modifier = &req->modifiers [i];
6679 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6680 for (j = 0; j < n; ++j) {
6681 char *s = decode_string (p, &p, end);
6685 s2 = strdup_tolower (s);
6686 g_hash_table_insert (modifier->data.source_files, s2, s2);
6690 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6691 int n = decode_int (p, &p, end);
6694 modifier = &req->modifiers [i];
6695 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6696 for (j = 0; j < n; ++j) {
6697 char *s = decode_string (p, &p, end);
6700 g_hash_table_insert (modifier->data.type_names, s, s);
6704 return ERR_NOT_IMPLEMENTED;
6708 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6711 req->info = set_breakpoint (method, location, req, &error);
6712 if (!mono_error_ok (&error)) {
6714 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6715 mono_error_cleanup (&error);
6716 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6718 } else if (req->event_kind == EVENT_KIND_STEP) {
6719 g_assert (step_thread_id);
6721 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6727 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6732 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6733 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6734 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6735 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6736 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6737 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6739 if (req->nmodifiers) {
6741 return ERR_NOT_IMPLEMENTED;
6745 mono_loader_lock ();
6746 g_ptr_array_add (event_requests, req);
6748 if (agent_config.defer) {
6749 /* Transmit cached data to the client on receipt of the event request */
6750 switch (req->event_kind) {
6751 case EVENT_KIND_APPDOMAIN_CREATE:
6752 /* Emit load events for currently loaded domains */
6753 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6755 case EVENT_KIND_ASSEMBLY_LOAD:
6756 /* Emit load events for currently loaded assemblies */
6757 mono_assembly_foreach (emit_assembly_load, NULL);
6759 case EVENT_KIND_THREAD_START:
6760 /* Emit start events for currently started threads */
6761 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6763 case EVENT_KIND_TYPE_LOAD:
6764 /* Emit type load events for currently loaded types */
6765 mono_domain_foreach (send_types_for_domain, NULL);
6771 mono_loader_unlock ();
6773 buffer_add_int (buf, req->id);
6776 case CMD_EVENT_REQUEST_CLEAR: {
6777 int etype = decode_byte (p, &p, end);
6778 int req_id = decode_int (p, &p, end);
6780 // FIXME: Make a faster mapping from req_id to request
6781 mono_loader_lock ();
6782 clear_event_request (req_id, etype);
6783 mono_loader_unlock ();
6786 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6789 mono_loader_lock ();
6791 while (i < event_requests->len) {
6792 EventRequest *req = g_ptr_array_index (event_requests, i);
6794 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6795 clear_breakpoint (req->info);
6797 g_ptr_array_remove_index_fast (event_requests, i);
6803 mono_loader_unlock ();
6807 return ERR_NOT_IMPLEMENTED;
6814 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6820 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6821 buffer_add_domainid (buf, mono_get_root_domain ());
6824 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6825 domain = decode_domainid (p, &p, end, NULL, &err);
6828 buffer_add_string (buf, domain->friendly_name);
6831 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6836 domain = decode_domainid (p, &p, end, NULL, &err);
6839 mono_loader_lock ();
6841 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6844 buffer_add_int (buf, count);
6845 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6847 buffer_add_assemblyid (buf, domain, ass);
6849 mono_loader_unlock ();
6852 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6853 domain = decode_domainid (p, &p, end, NULL, &err);
6857 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6860 case CMD_APPDOMAIN_GET_CORLIB: {
6861 domain = decode_domainid (p, &p, end, NULL, &err);
6865 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6868 case CMD_APPDOMAIN_CREATE_STRING: {
6872 domain = decode_domainid (p, &p, end, NULL, &err);
6875 s = decode_string (p, &p, end);
6877 o = mono_string_new (domain, s);
6878 buffer_add_objid (buf, (MonoObject*)o);
6881 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6883 MonoDomain *domain2;
6886 domain = decode_domainid (p, &p, end, NULL, &err);
6889 klass = decode_typeid (p, &p, end, &domain2, &err);
6894 g_assert (domain == domain2);
6896 o = mono_object_new (domain, klass);
6898 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6902 buffer_add_objid (buf, o);
6906 return ERR_NOT_IMPLEMENTED;
6913 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6919 ass = decode_assemblyid (p, &p, end, &domain, &err);
6924 case CMD_ASSEMBLY_GET_LOCATION: {
6925 buffer_add_string (buf, mono_image_get_filename (ass->image));
6928 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6932 if (ass->image->dynamic) {
6933 buffer_add_id (buf, 0);
6935 token = mono_image_get_entry_point (ass->image);
6937 buffer_add_id (buf, 0);
6939 m = mono_get_method (ass->image, token, NULL);
6940 buffer_add_methodid (buf, domain, m);
6945 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6946 buffer_add_moduleid (buf, domain, ass->image);
6949 case CMD_ASSEMBLY_GET_OBJECT: {
6950 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
6951 buffer_add_objid (buf, o);
6954 case CMD_ASSEMBLY_GET_TYPE: {
6955 char *s = decode_string (p, &p, end);
6956 gboolean ignorecase = decode_byte (p, &p, end);
6957 MonoTypeNameParse info;
6959 gboolean type_resolve, res;
6960 MonoDomain *d = mono_domain_get ();
6962 /* This is needed to be able to find referenced assemblies */
6963 res = mono_domain_set (domain, FALSE);
6966 if (!mono_reflection_parse_type (s, &info)) {
6969 if (info.assembly.name)
6971 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6973 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6974 mono_reflection_free_type_info (&info);
6977 mono_domain_set (d, TRUE);
6981 case CMD_ASSEMBLY_GET_NAME: {
6983 MonoAssembly *mass = ass;
6985 name = g_strdup_printf (
6986 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6988 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6989 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6990 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6991 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6993 buffer_add_string (buf, name);
6998 return ERR_NOT_IMPLEMENTED;
7005 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7011 case CMD_MODULE_GET_INFO: {
7012 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7015 basename = g_path_get_basename (image->name);
7016 buffer_add_string (buf, basename); // name
7017 buffer_add_string (buf, image->module_name); // scopename
7018 buffer_add_string (buf, image->name); // fqname
7019 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7020 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7025 return ERR_NOT_IMPLEMENTED;
7032 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7034 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7035 /* Special case these so the client doesn't have to handle Type objects */
7037 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7038 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7039 } else if (MONO_TYPE_IS_REFERENCE (t))
7040 buffer_add_value (buf, t, &val, domain);
7042 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7046 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7052 buffer_add_int (buf, 0);
7056 for (i = 0; i < cinfo->num_attrs; ++i) {
7057 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7060 buffer_add_int (buf, nattrs);
7062 for (i = 0; i < cinfo->num_attrs; ++i) {
7063 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7064 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7065 MonoArray *typed_args, *named_args;
7067 CattrNamedArg *arginfo;
7069 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7071 buffer_add_methodid (buf, domain, attr->ctor);
7075 buffer_add_int (buf, mono_array_length (typed_args));
7076 for (j = 0; j < mono_array_length (typed_args); ++j) {
7077 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7079 t = mono_method_signature (attr->ctor)->params [j];
7081 buffer_add_cattr_arg (buf, t, domain, val);
7084 buffer_add_int (buf, 0);
7089 buffer_add_int (buf, mono_array_length (named_args));
7091 for (j = 0; j < mono_array_length (named_args); ++j) {
7092 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7094 if (arginfo [j].prop) {
7095 buffer_add_byte (buf, 0x54);
7096 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7097 } else if (arginfo [j].field) {
7098 buffer_add_byte (buf, 0x53);
7099 buffer_add_fieldid (buf, domain, arginfo [j].field);
7101 g_assert_not_reached ();
7104 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7107 buffer_add_int (buf, 0);
7113 /* FIXME: Code duplication with icall.c */
7115 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7120 mono_class_setup_interfaces (klass, error);
7121 if (!mono_error_ok (error))
7124 for (i = 0; i < klass->interface_count; i++) {
7125 ic = klass->interfaces [i];
7126 g_hash_table_insert (ifaces, ic, ic);
7128 collect_interfaces (ic, ifaces, error);
7129 if (!mono_error_ok (error))
7135 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7145 case CMD_TYPE_GET_INFO: {
7146 buffer_add_string (buf, klass->name_space);
7147 buffer_add_string (buf, klass->name);
7149 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7150 buffer_add_string (buf, name);
7152 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7153 buffer_add_moduleid (buf, domain, klass->image);
7154 buffer_add_typeid (buf, domain, klass->parent);
7155 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7156 buffer_add_typeid (buf, domain, klass->element_class);
7158 buffer_add_id (buf, 0);
7159 buffer_add_int (buf, klass->type_token);
7160 buffer_add_byte (buf, klass->rank);
7161 buffer_add_int (buf, klass->flags);
7163 type = &klass->byval_arg;
7164 // FIXME: Can't decide whenever a class represents a byref type
7167 if (type->type == MONO_TYPE_PTR)
7169 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7171 if (type->type == MONO_TYPE_VALUETYPE)
7173 if (klass->enumtype)
7175 if (klass->generic_container)
7177 if (klass->generic_container || klass->generic_class)
7179 buffer_add_byte (buf, b);
7182 while ((nested = mono_class_get_nested_types (klass, &iter)))
7184 buffer_add_int (buf, nnested);
7186 while ((nested = mono_class_get_nested_types (klass, &iter)))
7187 buffer_add_typeid (buf, domain, nested);
7188 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7189 if (klass->generic_container)
7190 buffer_add_typeid (buf, domain, klass);
7191 else if (klass->generic_class)
7192 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7194 buffer_add_id (buf, 0);
7196 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7199 if (klass->generic_class) {
7200 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7202 count = inst->type_argc;
7203 buffer_add_int (buf, count);
7204 for (i = 0; i < count; i++)
7205 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7206 } else if (klass->generic_container) {
7207 MonoGenericContainer *container = klass->generic_container;
7210 count = container->type_argc;
7211 buffer_add_int (buf, count);
7212 for (i = 0; i < count; i++) {
7213 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7214 buffer_add_typeid (buf, domain, pklass);
7217 buffer_add_int (buf, 0);
7222 case CMD_TYPE_GET_METHODS: {
7225 gpointer iter = NULL;
7228 mono_class_setup_methods (klass);
7230 nmethods = mono_class_num_methods (klass);
7232 buffer_add_int (buf, nmethods);
7234 while ((m = mono_class_get_methods (klass, &iter))) {
7235 buffer_add_methodid (buf, domain, m);
7238 g_assert (i == nmethods);
7241 case CMD_TYPE_GET_FIELDS: {
7244 gpointer iter = NULL;
7247 nfields = mono_class_num_fields (klass);
7249 buffer_add_int (buf, nfields);
7251 while ((f = mono_class_get_fields (klass, &iter))) {
7252 buffer_add_fieldid (buf, domain, f);
7253 buffer_add_string (buf, f->name);
7254 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7255 buffer_add_int (buf, f->type->attrs);
7258 g_assert (i == nfields);
7261 case CMD_TYPE_GET_PROPERTIES: {
7264 gpointer iter = NULL;
7267 nprops = mono_class_num_properties (klass);
7269 buffer_add_int (buf, nprops);
7271 while ((p = mono_class_get_properties (klass, &iter))) {
7272 buffer_add_propertyid (buf, domain, p);
7273 buffer_add_string (buf, p->name);
7274 buffer_add_methodid (buf, domain, p->get);
7275 buffer_add_methodid (buf, domain, p->set);
7276 buffer_add_int (buf, p->attrs);
7279 g_assert (i == nprops);
7282 case CMD_TYPE_GET_CATTRS: {
7283 MonoClass *attr_klass;
7284 MonoCustomAttrInfo *cinfo;
7286 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7287 /* attr_klass can be NULL */
7291 cinfo = mono_custom_attrs_from_class (klass);
7293 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7296 case CMD_TYPE_GET_FIELD_CATTRS: {
7297 MonoClass *attr_klass;
7298 MonoCustomAttrInfo *cinfo;
7299 MonoClassField *field;
7301 field = decode_fieldid (p, &p, end, NULL, &err);
7304 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7308 cinfo = mono_custom_attrs_from_field (klass, field);
7310 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7313 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7314 MonoClass *attr_klass;
7315 MonoCustomAttrInfo *cinfo;
7318 prop = decode_propertyid (p, &p, end, NULL, &err);
7321 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7325 cinfo = mono_custom_attrs_from_property (klass, prop);
7327 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7330 case CMD_TYPE_GET_VALUES:
7331 case CMD_TYPE_GET_VALUES_2: {
7338 MonoThread *thread_obj;
7339 MonoInternalThread *thread = NULL;
7340 guint32 special_static_type;
7342 if (command == CMD_TYPE_GET_VALUES_2) {
7343 int objid = decode_objid (p, &p, end);
7346 err = get_object (objid, (MonoObject**)&thread_obj);
7350 thread = THREAD_TO_INTERNAL (thread_obj);
7353 len = decode_int (p, &p, end);
7354 for (i = 0; i < len; ++i) {
7355 f = decode_fieldid (p, &p, end, NULL, &err);
7359 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7360 return ERR_INVALID_FIELDID;
7361 special_static_type = mono_class_field_get_special_static_type (f);
7362 if (special_static_type != SPECIAL_STATIC_NONE) {
7363 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7364 return ERR_INVALID_FIELDID;
7367 /* Check that the field belongs to the object */
7369 for (k = klass; k; k = k->parent) {
7370 if (k == f->parent) {
7376 return ERR_INVALID_FIELDID;
7378 vtable = mono_class_vtable (domain, f->parent);
7379 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7380 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7381 buffer_add_value (buf, f->type, val, domain);
7386 case CMD_TYPE_SET_VALUES: {
7394 len = decode_int (p, &p, end);
7395 for (i = 0; i < len; ++i) {
7396 f = decode_fieldid (p, &p, end, NULL, &err);
7400 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7401 return ERR_INVALID_FIELDID;
7402 if (mono_class_field_is_special_static (f))
7403 return ERR_INVALID_FIELDID;
7405 /* Check that the field belongs to the object */
7407 for (k = klass; k; k = k->parent) {
7408 if (k == f->parent) {
7414 return ERR_INVALID_FIELDID;
7416 // FIXME: Check for literal/const
7418 vtable = mono_class_vtable (domain, f->parent);
7419 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7420 err = decode_value (f->type, domain, val, p, &p, end);
7425 if (MONO_TYPE_IS_REFERENCE (f->type))
7426 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7428 mono_field_static_set_value (vtable, f, val);
7433 case CMD_TYPE_GET_OBJECT: {
7434 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7435 buffer_add_objid (buf, o);
7438 case CMD_TYPE_GET_SOURCE_FILES:
7439 case CMD_TYPE_GET_SOURCE_FILES_2: {
7440 char *source_file, *base;
7444 files = get_source_files_for_type (klass);
7446 buffer_add_int (buf, files->len);
7447 for (i = 0; i < files->len; ++i) {
7448 source_file = g_ptr_array_index (files, i);
7449 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7450 buffer_add_string (buf, source_file);
7452 base = g_path_get_basename (source_file);
7453 buffer_add_string (buf, base);
7456 g_free (source_file);
7458 g_ptr_array_free (files, TRUE);
7461 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7462 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7466 if (mono_class_is_assignable_from (klass, oklass))
7467 buffer_add_byte (buf, 1);
7469 buffer_add_byte (buf, 0);
7472 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7473 char *name = decode_string (p, &p, end);
7474 int i, flags = decode_int (p, &p, end);
7475 MonoException *ex = NULL;
7476 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7479 return ERR_LOADER_ERROR;
7480 buffer_add_int (buf, array->len);
7481 for (i = 0; i < array->len; ++i) {
7482 MonoMethod *method = g_ptr_array_index (array, i);
7483 buffer_add_methodid (buf, domain, method);
7486 g_ptr_array_free (array, TRUE);
7490 case CMD_TYPE_GET_INTERFACES: {
7492 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7494 MonoClass *tclass, *iface;
7495 GHashTableIter iter;
7499 for (parent = tclass; parent; parent = parent->parent) {
7500 mono_class_setup_interfaces (parent, &error);
7501 if (!mono_error_ok (&error))
7502 return ERR_LOADER_ERROR;
7503 collect_interfaces (parent, iface_hash, &error);
7504 if (!mono_error_ok (&error))
7505 return ERR_LOADER_ERROR;
7508 buffer_add_int (buf, g_hash_table_size (iface_hash));
7510 g_hash_table_iter_init (&iter, iface_hash);
7511 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7512 buffer_add_typeid (buf, domain, iface);
7513 g_hash_table_destroy (iface_hash);
7516 case CMD_TYPE_GET_INTERFACE_MAP: {
7517 int tindex, ioffset;
7518 gboolean variance_used;
7520 int len, nmethods, i;
7524 len = decode_int (p, &p, end);
7525 mono_class_setup_vtable (klass);
7527 for (tindex = 0; tindex < len; ++tindex) {
7528 iclass = decode_typeid (p, &p, end, NULL, &err);
7532 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7534 return ERR_INVALID_ARGUMENT;
7536 nmethods = mono_class_num_methods (iclass);
7537 buffer_add_int (buf, nmethods);
7540 while ((method = mono_class_get_methods (iclass, &iter))) {
7541 buffer_add_methodid (buf, domain, method);
7543 for (i = 0; i < nmethods; ++i)
7544 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7549 return ERR_NOT_IMPLEMENTED;
7556 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7559 MonoDomain *old_domain;
7563 klass = decode_typeid (p, &p, end, &domain, &err);
7567 old_domain = mono_domain_get ();
7569 mono_domain_set (domain, TRUE);
7571 err = type_commands_internal (command, klass, domain, p, end, buf);
7573 mono_domain_set (old_domain, TRUE);
7579 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7581 MonoMethodHeader *header;
7585 case CMD_METHOD_GET_NAME: {
7586 buffer_add_string (buf, method->name);
7589 case CMD_METHOD_GET_DECLARING_TYPE: {
7590 buffer_add_typeid (buf, domain, method->klass);
7593 case CMD_METHOD_GET_DEBUG_INFO: {
7594 MonoDebugMethodInfo *minfo;
7596 int i, j, n_il_offsets;
7599 int *column_numbers;
7601 GPtrArray *source_file_list;
7603 header = mono_method_get_header (method);
7605 buffer_add_int (buf, 0);
7606 buffer_add_string (buf, "");
7607 buffer_add_int (buf, 0);
7611 minfo = mono_debug_lookup_method (method);
7613 buffer_add_int (buf, header->code_size);
7614 buffer_add_string (buf, "");
7615 buffer_add_int (buf, 0);
7616 mono_metadata_free_mh (header);
7620 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7621 buffer_add_int (buf, header->code_size);
7622 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7623 buffer_add_int (buf, source_file_list->len);
7624 for (i = 0; i < source_file_list->len; ++i) {
7625 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7626 buffer_add_string (buf, sinfo->source_file);
7627 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7628 for (j = 0; j < 16; ++j)
7629 buffer_add_byte (buf, sinfo->hash [j]);
7633 buffer_add_string (buf, source_file);
7635 buffer_add_int (buf, n_il_offsets);
7636 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7637 for (i = 0; i < n_il_offsets; ++i) {
7638 const char *srcfile = "";
7640 if (source_files [i] != -1) {
7641 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7642 srcfile = sinfo->source_file;
7644 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7645 buffer_add_int (buf, il_offsets [i]);
7646 buffer_add_int (buf, line_numbers [i]);
7647 if (CHECK_PROTOCOL_VERSION (2, 13))
7648 buffer_add_int (buf, source_files [i]);
7649 if (CHECK_PROTOCOL_VERSION (2, 19))
7650 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7652 g_free (source_file);
7653 g_free (il_offsets);
7654 g_free (line_numbers);
7655 g_free (source_files);
7656 g_ptr_array_free (source_file_list, TRUE);
7657 mono_metadata_free_mh (header);
7660 case CMD_METHOD_GET_PARAM_INFO: {
7661 MonoMethodSignature *sig = mono_method_signature (method);
7665 /* FIXME: mono_class_from_mono_type () and byrefs */
7667 /* FIXME: Use a smaller encoding */
7668 buffer_add_int (buf, sig->call_convention);
7669 buffer_add_int (buf, sig->param_count);
7670 buffer_add_int (buf, sig->generic_param_count);
7671 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7672 for (i = 0; i < sig->param_count; ++i) {
7674 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7677 /* Emit parameter names */
7678 names = g_new (char *, sig->param_count);
7679 mono_method_get_param_names (method, (const char **) names);
7680 for (i = 0; i < sig->param_count; ++i)
7681 buffer_add_string (buf, names [i]);
7686 case CMD_METHOD_GET_LOCALS_INFO: {
7687 int i, j, num_locals;
7688 MonoDebugLocalsInfo *locals;
7690 header = mono_method_get_header (method);
7692 return ERR_INVALID_ARGUMENT;
7694 buffer_add_int (buf, header->num_locals);
7697 for (i = 0; i < header->num_locals; ++i)
7698 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7701 locals = mono_debug_lookup_locals (method);
7703 num_locals = locals->num_locals;
7706 for (i = 0; i < header->num_locals; ++i) {
7707 for (j = 0; j < num_locals; ++j)
7708 if (locals->locals [j].index == i)
7711 buffer_add_string (buf, locals->locals [j].name);
7713 buffer_add_string (buf, "");
7717 for (i = 0; i < header->num_locals; ++i) {
7718 for (j = 0; j < num_locals; ++j)
7719 if (locals->locals [j].index == i)
7721 if (j < num_locals && locals->locals [j].block) {
7722 buffer_add_int (buf, locals->locals [j].block->start_offset);
7723 buffer_add_int (buf, locals->locals [j].block->end_offset);
7725 buffer_add_int (buf, 0);
7726 buffer_add_int (buf, header->code_size);
7729 mono_metadata_free_mh (header);
7732 mono_debug_symfile_free_locals (locals);
7736 case CMD_METHOD_GET_INFO:
7737 buffer_add_int (buf, method->flags);
7738 buffer_add_int (buf, method->iflags);
7739 buffer_add_int (buf, method->token);
7740 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7742 if (method->is_generic)
7744 if (mono_method_signature (method)->generic_param_count)
7746 buffer_add_byte (buf, attrs);
7747 if (method->is_generic || method->is_inflated) {
7750 if (method->is_generic) {
7753 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7755 result = imethod->declaring;
7756 if (imethod->context.class_inst) {
7757 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7758 /*Generic methods gets the context of the GTD.*/
7759 if (mono_class_get_context (klass))
7760 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7764 buffer_add_methodid (buf, domain, result);
7766 buffer_add_id (buf, 0);
7768 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7769 if (mono_method_signature (method)->generic_param_count) {
7772 if (method->is_inflated) {
7773 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7775 count = inst->type_argc;
7776 buffer_add_int (buf, count);
7778 for (i = 0; i < count; i++)
7779 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7781 buffer_add_int (buf, 0);
7783 } else if (method->is_generic) {
7784 MonoGenericContainer *container = mono_method_get_generic_container (method);
7786 count = mono_method_signature (method)->generic_param_count;
7787 buffer_add_int (buf, count);
7788 for (i = 0; i < count; i++) {
7789 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7790 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7791 buffer_add_typeid (buf, domain, pklass);
7794 buffer_add_int (buf, 0);
7797 buffer_add_int (buf, 0);
7802 case CMD_METHOD_GET_BODY: {
7805 header = mono_method_get_header (method);
7807 buffer_add_int (buf, 0);
7809 if (CHECK_PROTOCOL_VERSION (2, 18))
7810 buffer_add_int (buf, 0);
7812 buffer_add_int (buf, header->code_size);
7813 for (i = 0; i < header->code_size; ++i)
7814 buffer_add_byte (buf, header->code [i]);
7816 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7817 buffer_add_int (buf, header->num_clauses);
7818 for (i = 0; i < header->num_clauses; ++i) {
7819 MonoExceptionClause *clause = &header->clauses [i];
7821 buffer_add_int (buf, clause->flags);
7822 buffer_add_int (buf, clause->try_offset);
7823 buffer_add_int (buf, clause->try_len);
7824 buffer_add_int (buf, clause->handler_offset);
7825 buffer_add_int (buf, clause->handler_len);
7826 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7827 buffer_add_typeid (buf, domain, clause->data.catch_class);
7828 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7829 buffer_add_int (buf, clause->data.filter_offset);
7833 mono_metadata_free_mh (header);
7838 case CMD_METHOD_RESOLVE_TOKEN: {
7839 guint32 token = decode_int (p, &p, end);
7842 switch (mono_metadata_token_code (token)) {
7843 case MONO_TOKEN_STRING: {
7847 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7850 s2 = mono_string_to_utf8 (s);
7852 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7853 buffer_add_string (buf, s2);
7859 MonoClass *handle_class;
7861 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7862 val = mono_method_get_wrapper_data (method, token);
7863 handle_class = mono_method_get_wrapper_data (method, token + 1);
7865 if (handle_class == NULL) {
7866 // Can't figure out the token type
7867 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7871 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7875 if (handle_class == mono_defaults.typehandle_class) {
7876 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7877 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7878 buffer_add_typeid (buf, domain, (MonoClass *) val);
7880 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7881 } else if (handle_class == mono_defaults.fieldhandle_class) {
7882 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7883 buffer_add_fieldid (buf, domain, val);
7884 } else if (handle_class == mono_defaults.methodhandle_class) {
7885 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7886 buffer_add_methodid (buf, domain, val);
7887 } else if (handle_class == mono_defaults.string_class) {
7890 s = mono_string_to_utf8 (val);
7891 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7892 buffer_add_string (buf, s);
7895 g_assert_not_reached ();
7902 case CMD_METHOD_GET_CATTRS: {
7903 MonoClass *attr_klass;
7904 MonoCustomAttrInfo *cinfo;
7906 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7907 /* attr_klass can be NULL */
7911 cinfo = mono_custom_attrs_from_method (method);
7913 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
7917 return ERR_NOT_IMPLEMENTED;
7924 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7927 MonoDomain *old_domain;
7931 method = decode_methodid (p, &p, end, &domain, &err);
7935 old_domain = mono_domain_get ();
7937 mono_domain_set (domain, TRUE);
7939 err = method_commands_internal (command, method, domain, p, end, buf);
7941 mono_domain_set (old_domain, TRUE);
7947 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7949 int objid = decode_objid (p, &p, end);
7951 MonoThread *thread_obj;
7952 MonoInternalThread *thread;
7954 err = get_object (objid, (MonoObject**)&thread_obj);
7958 thread = THREAD_TO_INTERNAL (thread_obj);
7961 case CMD_THREAD_GET_NAME: {
7963 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7966 buffer_add_int (buf, 0);
7971 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7973 buffer_add_int (buf, len);
7974 buffer_add_data (buf, (guint8*)name, len);
7979 case CMD_THREAD_GET_FRAME_INFO: {
7980 DebuggerTlsData *tls;
7981 int i, start_frame, length;
7983 // Wait for suspending if it already started
7984 // FIXME: Races with suspend_count
7985 while (!is_suspended ()) {
7987 wait_for_suspend ();
7991 wait_for_suspend ();
7992 if (!is_suspended ())
7993 return ERR_NOT_SUSPENDED;
7996 start_frame = decode_int (p, &p, end);
7997 length = decode_int (p, &p, end);
7999 if (start_frame != 0 || length != -1)
8000 return ERR_NOT_IMPLEMENTED;
8002 mono_loader_lock ();
8003 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8004 mono_loader_unlock ();
8007 compute_frame_info (thread, tls);
8009 buffer_add_int (buf, tls->frame_count);
8010 for (i = 0; i < tls->frame_count; ++i) {
8011 buffer_add_int (buf, tls->frames [i]->id);
8012 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8013 buffer_add_int (buf, tls->frames [i]->il_offset);
8015 * Instead of passing the frame type directly to the client, we associate
8016 * it with the previous frame using a set of flags. This avoids lots of
8017 * conditional code in the client, since a frame whose type isn't
8018 * FRAME_TYPE_MANAGED has no method, location, etc.
8020 buffer_add_byte (buf, tls->frames [i]->flags);
8025 case CMD_THREAD_GET_STATE:
8026 buffer_add_int (buf, thread->state);
8028 case CMD_THREAD_GET_INFO:
8029 buffer_add_byte (buf, thread->threadpool_thread);
8031 case CMD_THREAD_GET_ID:
8032 buffer_add_long (buf, (guint64)(gsize)thread);
8034 case CMD_THREAD_GET_TID:
8035 buffer_add_long (buf, (guint64)thread->tid);
8038 return ERR_NOT_IMPLEMENTED;
8045 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8049 MonoThread *thread_obj;
8050 MonoInternalThread *thread;
8051 int pos, i, len, frame_idx;
8052 DebuggerTlsData *tls;
8054 MonoDebugMethodJitInfo *jit;
8055 MonoDebugVarInfo *var;
8056 MonoMethodSignature *sig;
8058 MonoMethodHeader *header;
8060 objid = decode_objid (p, &p, end);
8061 err = get_object (objid, (MonoObject**)&thread_obj);
8065 thread = THREAD_TO_INTERNAL (thread_obj);
8067 id = decode_id (p, &p, end);
8069 mono_loader_lock ();
8070 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8071 mono_loader_unlock ();
8074 for (i = 0; i < tls->frame_count; ++i) {
8075 if (tls->frames [i]->id == id)
8078 if (i == tls->frame_count)
8079 return ERR_INVALID_FRAMEID;
8082 frame = tls->frames [frame_idx];
8084 if (!frame->has_ctx)
8086 return ERR_INVALID_FRAMEID;
8089 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8090 if (!frame->jit && frame->api_method->is_inflated)
8091 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8095 /* This could happen for aot images with no jit debug info */
8096 s = mono_method_full_name (frame->api_method, TRUE);
8097 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8099 return ERR_ABSENT_INFORMATION;
8104 sig = mono_method_signature (frame->actual_method);
8106 if (!get_seq_points (frame->domain, frame->actual_method))
8108 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8110 return ERR_ABSENT_INFORMATION;
8113 case CMD_STACK_FRAME_GET_VALUES: {
8114 len = decode_int (p, &p, end);
8115 header = mono_method_get_header (frame->actual_method);
8117 for (i = 0; i < len; ++i) {
8118 pos = decode_int (p, &p, end);
8123 g_assert (pos >= 0 && pos < jit->num_params);
8125 var = &jit->params [pos];
8127 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8129 g_assert (pos >= 0 && pos < jit->num_locals);
8131 var = &jit->locals [pos];
8133 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8136 mono_metadata_free_mh (header);
8139 case CMD_STACK_FRAME_GET_THIS: {
8140 if (frame->api_method->klass->valuetype) {
8141 if (!sig->hasthis) {
8142 MonoObject *p = NULL;
8143 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8145 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8148 if (!sig->hasthis) {
8149 MonoObject *p = NULL;
8150 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8152 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8157 case CMD_STACK_FRAME_SET_VALUES: {
8160 MonoDebugVarInfo *var;
8162 len = decode_int (p, &p, end);
8163 header = mono_method_get_header (frame->actual_method);
8165 for (i = 0; i < len; ++i) {
8166 pos = decode_int (p, &p, end);
8171 g_assert (pos >= 0 && pos < jit->num_params);
8173 t = sig->params [pos];
8174 var = &jit->params [pos];
8176 g_assert (pos >= 0 && pos < jit->num_locals);
8178 t = header->locals [pos];
8179 var = &jit->locals [pos];
8182 if (MONO_TYPE_IS_REFERENCE (t))
8183 val_buf = g_alloca (sizeof (MonoObject*));
8185 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8186 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8190 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8192 mono_metadata_free_mh (header);
8196 return ERR_NOT_IMPLEMENTED;
8203 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8206 int objid, err, index, len, i, esize;
8209 objid = decode_objid (p, &p, end);
8210 err = get_object (objid, (MonoObject**)&arr);
8215 case CMD_ARRAY_REF_GET_LENGTH:
8216 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8218 buffer_add_int (buf, arr->max_length);
8219 buffer_add_int (buf, 0);
8221 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8222 buffer_add_int (buf, arr->bounds [i].length);
8223 buffer_add_int (buf, arr->bounds [i].lower_bound);
8227 case CMD_ARRAY_REF_GET_VALUES:
8228 index = decode_int (p, &p, end);
8229 len = decode_int (p, &p, end);
8231 g_assert (index >= 0 && len >= 0);
8232 // Reordered to avoid integer overflow
8233 g_assert (!(index > arr->max_length - len));
8235 esize = mono_array_element_size (arr->obj.vtable->klass);
8236 for (i = index; i < index + len; ++i) {
8237 elem = (gpointer*)((char*)arr->vector + (i * esize));
8238 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8241 case CMD_ARRAY_REF_SET_VALUES:
8242 index = decode_int (p, &p, end);
8243 len = decode_int (p, &p, end);
8245 g_assert (index >= 0 && len >= 0);
8246 // Reordered to avoid integer overflow
8247 g_assert (!(index > arr->max_length - len));
8249 esize = mono_array_element_size (arr->obj.vtable->klass);
8250 for (i = index; i < index + len; ++i) {
8251 elem = (gpointer*)((char*)arr->vector + (i * esize));
8253 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8257 return ERR_NOT_IMPLEMENTED;
8264 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8269 int i, index, length;
8272 objid = decode_objid (p, &p, end);
8273 err = get_object (objid, (MonoObject**)&str);
8278 case CMD_STRING_REF_GET_VALUE:
8279 s = mono_string_to_utf8 (str);
8280 buffer_add_string (buf, s);
8283 case CMD_STRING_REF_GET_LENGTH:
8284 buffer_add_long (buf, mono_string_length (str));
8286 case CMD_STRING_REF_GET_CHARS:
8287 index = decode_long (p, &p, end);
8288 length = decode_long (p, &p, end);
8289 if (index > mono_string_length (str) - length)
8290 return ERR_INVALID_ARGUMENT;
8291 c = mono_string_chars (str) + index;
8292 for (i = 0; i < length; ++i)
8293 buffer_add_short (buf, c [i]);
8296 return ERR_NOT_IMPLEMENTED;
8303 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8312 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8313 objid = decode_objid (p, &p, end);
8314 err = get_object (objid, &obj);
8316 buffer_add_int (buf, 1);
8318 buffer_add_int (buf, 0);
8322 objid = decode_objid (p, &p, end);
8323 err = get_object (objid, &obj);
8328 case CMD_OBJECT_REF_GET_TYPE:
8329 /* This handles transparent proxies too */
8330 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8332 case CMD_OBJECT_REF_GET_VALUES:
8333 len = decode_int (p, &p, end);
8335 for (i = 0; i < len; ++i) {
8336 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8340 /* Check that the field belongs to the object */
8342 for (k = obj->vtable->klass; k; k = k->parent) {
8343 if (k == f->parent) {
8349 return ERR_INVALID_FIELDID;
8351 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8355 if (mono_class_field_is_special_static (f))
8356 return ERR_INVALID_FIELDID;
8358 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8359 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8360 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8361 mono_field_static_get_value (vtable, f, val);
8362 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8365 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8369 case CMD_OBJECT_REF_SET_VALUES:
8370 len = decode_int (p, &p, end);
8372 for (i = 0; i < len; ++i) {
8373 f = decode_fieldid (p, &p, end, NULL, &err);
8377 /* Check that the field belongs to the object */
8379 for (k = obj->vtable->klass; k; k = k->parent) {
8380 if (k == f->parent) {
8386 return ERR_INVALID_FIELDID;
8388 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8392 if (mono_class_field_is_special_static (f))
8393 return ERR_INVALID_FIELDID;
8395 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8396 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8398 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8399 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8404 mono_field_static_set_value (vtable, f, val);
8407 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8413 case CMD_OBJECT_REF_GET_ADDRESS:
8414 buffer_add_long (buf, (gssize)obj);
8416 case CMD_OBJECT_REF_GET_DOMAIN:
8417 buffer_add_domainid (buf, obj->vtable->domain);
8419 case CMD_OBJECT_REF_GET_INFO:
8420 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8421 buffer_add_domainid (buf, obj->vtable->domain);
8424 return ERR_NOT_IMPLEMENTED;
8431 command_set_to_string (CommandSet command_set)
8433 switch (command_set) {
8436 case CMD_SET_OBJECT_REF:
8437 return "OBJECT_REF";
8438 case CMD_SET_STRING_REF:
8439 return "STRING_REF";
8440 case CMD_SET_THREAD:
8442 case CMD_SET_ARRAY_REF:
8444 case CMD_SET_EVENT_REQUEST:
8445 return "EVENT_REQUEST";
8446 case CMD_SET_STACK_FRAME:
8447 return "STACK_FRAME";
8448 case CMD_SET_APPDOMAIN:
8450 case CMD_SET_ASSEMBLY:
8452 case CMD_SET_METHOD:
8456 case CMD_SET_MODULE:
8466 cmd_to_string (CommandSet set, int command)
8471 case CMD_VM_VERSION:
8473 case CMD_VM_ALL_THREADS:
8474 return "ALL_THREADS";
8475 case CMD_VM_SUSPEND:
8481 case CMD_VM_DISPOSE:
8483 case CMD_VM_INVOKE_METHOD:
8484 return "INVOKE_METHOD";
8485 case CMD_VM_SET_PROTOCOL_VERSION:
8486 return "SET_PROTOCOL_VERSION";
8487 case CMD_VM_ABORT_INVOKE:
8488 return "ABORT_INVOKE";
8489 case CMD_VM_SET_KEEPALIVE:
8490 return "SET_KEEPALIVE";
8503 wait_for_attach (void)
8505 #ifndef DISABLE_SOCKET_TRANSPORT
8506 if (listen_fd == -1) {
8507 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8511 /* Block and wait for client connection */
8512 conn_fd = socket_transport_accept (listen_fd);
8513 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8514 if (conn_fd == -1) {
8515 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8519 g_assert_not_reached ();
8523 disconnected = !transport_handshake ();
8525 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8535 * This thread handles communication with the debugger client using a JDWP
8538 static guint32 WINAPI
8539 debugger_thread (void *arg)
8541 int res, len, id, flags, command_set = 0, command = 0;
8542 guint8 header [HEADER_LENGTH];
8543 guint8 *data, *p, *end;
8547 gboolean attach_failed = FALSE;
8549 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8551 debugger_thread_id = GetCurrentThreadId ();
8553 mono_jit_thread_attach (mono_get_root_domain ());
8555 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8557 mono_set_is_debugger_attached (TRUE);
8559 if (agent_config.defer) {
8560 if (!wait_for_attach ()) {
8561 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8562 attach_failed = TRUE; // Don't abort process when we can't listen
8564 /* Send start event to client */
8565 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8569 while (!attach_failed) {
8570 res = transport_recv (header, HEADER_LENGTH);
8572 /* This will break if the socket is closed during shutdown too */
8573 if (res != HEADER_LENGTH)
8577 end = header + HEADER_LENGTH;
8579 len = decode_int (p, &p, end);
8580 id = decode_int (p, &p, end);
8581 flags = decode_byte (p, &p, end);
8582 command_set = decode_byte (p, &p, end);
8583 command = decode_byte (p, &p, end);
8585 g_assert (flags == 0);
8588 const char *cmd_str;
8591 cmd_str = cmd_to_string (command_set, command);
8593 sprintf (cmd_num, "%d", command);
8597 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8600 data = g_malloc (len - HEADER_LENGTH);
8601 if (len - HEADER_LENGTH > 0)
8603 res = transport_recv (data, len - HEADER_LENGTH);
8604 if (res != len - HEADER_LENGTH)
8609 end = data + (len - HEADER_LENGTH);
8611 buffer_init (&buf, 128);
8616 /* Process the request */
8617 switch (command_set) {
8619 err = vm_commands (command, id, p, end, &buf);
8620 if (!err && command == CMD_VM_INVOKE_METHOD)
8621 /* Sent after the invoke is complete */
8624 case CMD_SET_EVENT_REQUEST:
8625 err = event_commands (command, p, end, &buf);
8627 case CMD_SET_APPDOMAIN:
8628 err = domain_commands (command, p, end, &buf);
8630 case CMD_SET_ASSEMBLY:
8631 err = assembly_commands (command, p, end, &buf);
8633 case CMD_SET_MODULE:
8634 err = module_commands (command, p, end, &buf);
8637 err = type_commands (command, p, end, &buf);
8639 case CMD_SET_METHOD:
8640 err = method_commands (command, p, end, &buf);
8642 case CMD_SET_THREAD:
8643 err = thread_commands (command, p, end, &buf);
8645 case CMD_SET_STACK_FRAME:
8646 err = frame_commands (command, p, end, &buf);
8648 case CMD_SET_ARRAY_REF:
8649 err = array_commands (command, p, end, &buf);
8651 case CMD_SET_STRING_REF:
8652 err = string_commands (command, p, end, &buf);
8654 case CMD_SET_OBJECT_REF:
8655 err = object_commands (command, p, end, &buf);
8658 err = ERR_NOT_IMPLEMENTED;
8662 send_reply_packet (id, err, &buf);
8667 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8671 mono_set_is_debugger_attached (FALSE);
8673 mono_mutex_lock (&debugger_thread_exited_mutex);
8674 debugger_thread_exited = TRUE;
8675 mono_cond_signal (&debugger_thread_exited_cond);
8676 mono_mutex_unlock (&debugger_thread_exited_mutex);
8678 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8680 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8681 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8682 start_debugger_thread ();
8688 #else /* DISABLE_DEBUGGER_AGENT */
8691 mono_debugger_agent_parse_options (char *options)
8693 g_error ("This runtime is configured with the debugger agent disabled.");
8697 mono_debugger_agent_init (void)
8702 mono_debugger_agent_breakpoint_hit (void *sigctx)
8707 mono_debugger_agent_single_step_event (void *sigctx)
8712 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8717 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8723 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8724 MonoContext *catch_ctx)
8729 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8734 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8739 mono_debugger_agent_user_break (void)
8745 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8750 mono_debugger_agent_debug_log_is_enabled (void)