2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
43 #ifdef HAVE_UCONTEXT_H
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
62 #ifdef PLATFORM_ANDROID
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/utils/mono-semaphore.h>
76 #include <mono/utils/mono-error-internals.h>
77 #include <mono/utils/mono-stack-unwinding.h>
78 #include <mono/utils/mono-time.h>
79 #include "debugger-agent.h"
82 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
83 #define DISABLE_DEBUGGER_AGENT 1
86 #ifdef DISABLE_SOFT_DEBUG
87 #define DISABLE_DEBUGGER_AGENT 1
91 #include <mono/utils/mono-threads.h>
94 #ifndef DISABLE_DEBUGGER_AGENT
96 #include <mono/io-layer/mono-mutex.h>
98 /* Definitions to make backporting to 2.6 easier */
99 //#define MonoInternalThread MonoThread
100 //#define mono_thread_internal_current mono_thread_current
101 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
123 guint32 il_offset, native_offset;
127 * If method is gshared, this is the actual instance, otherwise this is equal to
130 MonoMethod *actual_method;
132 * This is the method which is visible to debugger clients. Same as method,
133 * except for native-to-managed wrappers.
135 MonoMethod *api_method;
137 MonoDebugMethodJitInfo *jit;
140 mgreg_t *reg_locations [MONO_MAX_IREGS];
142 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
143 * the frame can become invalid.
148 typedef struct _InvokeData InvokeData;
156 /* This is the context which needs to be restored after the invoke */
160 * If this is set, invoke this method with the arguments given by ARGS.
164 guint32 suspend_count;
167 InvokeData *last_invoke;
171 MonoThreadUnwindState context;
173 gpointer resume_event;
174 /* This is computed on demand when it is requested using the wire protocol */
175 /* It is freed up when the thread is resumed */
179 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
182 gboolean frames_up_to_date;
184 * Points to data about a pending invoke which needs to be executed after the thread
187 InvokeData *pending_invoke;
189 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
194 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
195 * within a finite amount of time.
199 * Set to TRUE if this thread is suspended in suspend_current ().
201 gboolean really_suspended;
202 /* Used to pass the context to the breakpoint/single step handler */
203 MonoContext handler_ctx;
204 /* Whenever thread_stop () was called for this thread */
207 /* Number of thread interruptions not yet processed */
208 gint32 interrupt_count;
210 /* Whenever to disable breakpoints (used during invokes) */
211 gboolean disable_breakpoints;
214 * Number of times this thread has been resumed using resume_thread ().
216 guint32 resume_count;
218 MonoInternalThread *thread;
221 * Information about the frame which transitioned to native code for running
224 StackFrameInfo async_last_frame;
227 * The context where the stack walk can be started for running threads.
229 MonoThreadUnwindState async_state;
232 * The context used for filter clauses
234 MonoThreadUnwindState filter_state;
237 * The callee address of the last mono_runtime_invoke call
239 gpointer invoke_addr;
241 gboolean abort_requested;
244 * The current mono_runtime_invoke invocation.
249 * The context where single stepping should resume while the thread is suspended because
250 * of an EXCEPTION event.
252 MonoContext catch_ctx;
254 gboolean has_catch_ctx;
257 * The context which needs to be restored after handling a single step/breakpoint
258 * event. This is the same as the ctx at step/breakpoint site, but includes changes
259 * to caller saved registers done by set_var ().
261 MonoContext restore_ctx;
266 void (*connect) (const char *address);
267 void (*close1) (void);
268 void (*close2) (void);
269 gboolean (*send) (void *buf, int len);
270 int (*recv) (void *buf, int len);
274 * Wire Protocol definitions
277 #define HEADER_LENGTH 11
279 #define MAJOR_VERSION 2
280 #define MINOR_VERSION 22
284 CMD_SET_OBJECT_REF = 9,
285 CMD_SET_STRING_REF = 10,
287 CMD_SET_ARRAY_REF = 13,
288 CMD_SET_EVENT_REQUEST = 15,
289 CMD_SET_STACK_FRAME = 16,
290 CMD_SET_APPDOMAIN = 20,
291 CMD_SET_ASSEMBLY = 21,
299 EVENT_KIND_VM_START = 0,
300 EVENT_KIND_VM_DEATH = 1,
301 EVENT_KIND_THREAD_START = 2,
302 EVENT_KIND_THREAD_DEATH = 3,
303 EVENT_KIND_APPDOMAIN_CREATE = 4,
304 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
305 EVENT_KIND_METHOD_ENTRY = 6,
306 EVENT_KIND_METHOD_EXIT = 7,
307 EVENT_KIND_ASSEMBLY_LOAD = 8,
308 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
309 EVENT_KIND_BREAKPOINT = 10,
310 EVENT_KIND_STEP = 11,
311 EVENT_KIND_TYPE_LOAD = 12,
312 EVENT_KIND_EXCEPTION = 13,
313 EVENT_KIND_KEEPALIVE = 14,
314 EVENT_KIND_USER_BREAK = 15,
315 EVENT_KIND_USER_LOG = 16
319 SUSPEND_POLICY_NONE = 0,
320 SUSPEND_POLICY_EVENT_THREAD = 1,
321 SUSPEND_POLICY_ALL = 2
326 ERR_INVALID_OBJECT = 20,
327 ERR_INVALID_FIELDID = 25,
328 ERR_INVALID_FRAMEID = 30,
329 ERR_NOT_IMPLEMENTED = 100,
330 ERR_NOT_SUSPENDED = 101,
331 ERR_INVALID_ARGUMENT = 102,
333 ERR_NO_INVOCATION = 104,
334 ERR_ABSENT_INFORMATION = 105,
335 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
336 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
341 MOD_KIND_THREAD_ONLY = 3,
342 MOD_KIND_LOCATION_ONLY = 7,
343 MOD_KIND_EXCEPTION_ONLY = 8,
345 MOD_KIND_ASSEMBLY_ONLY = 11,
346 MOD_KIND_SOURCE_FILE_ONLY = 12,
347 MOD_KIND_TYPE_NAME_ONLY = 13
362 STEP_FILTER_NONE = 0,
363 STEP_FILTER_STATIC_CTOR = 1,
364 STEP_FILTER_DEBUGGER_HIDDEN = 2
368 TOKEN_TYPE_STRING = 0,
370 TOKEN_TYPE_FIELD = 2,
371 TOKEN_TYPE_METHOD = 3,
372 TOKEN_TYPE_UNKNOWN = 4
376 VALUE_TYPE_ID_NULL = 0xf0,
377 VALUE_TYPE_ID_TYPE = 0xf1
381 FRAME_FLAG_DEBUGGER_INVOKE = 1,
382 FRAME_FLAG_NATIVE_TRANSITION = 2
386 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
387 INVOKE_FLAG_SINGLE_THREADED = 2
391 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
392 } BindingFlagsExtensions;
396 CMD_VM_ALL_THREADS = 2,
401 CMD_VM_INVOKE_METHOD = 7,
402 CMD_VM_SET_PROTOCOL_VERSION = 8,
403 CMD_VM_ABORT_INVOKE = 9,
404 CMD_VM_SET_KEEPALIVE = 10,
405 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
406 CMD_VM_GET_TYPES = 12,
407 CMD_VM_INVOKE_METHODS = 13
411 CMD_THREAD_GET_FRAME_INFO = 1,
412 CMD_THREAD_GET_NAME = 2,
413 CMD_THREAD_GET_STATE = 3,
414 CMD_THREAD_GET_INFO = 4,
415 CMD_THREAD_GET_ID = 5,
416 CMD_THREAD_GET_TID = 6
420 CMD_EVENT_REQUEST_SET = 1,
421 CMD_EVENT_REQUEST_CLEAR = 2,
422 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
430 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
431 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
432 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
433 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
434 CMD_APPDOMAIN_CREATE_STRING = 5,
435 CMD_APPDOMAIN_GET_CORLIB = 6,
436 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
440 CMD_ASSEMBLY_GET_LOCATION = 1,
441 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
442 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
443 CMD_ASSEMBLY_GET_OBJECT = 4,
444 CMD_ASSEMBLY_GET_TYPE = 5,
445 CMD_ASSEMBLY_GET_NAME = 6
449 CMD_MODULE_GET_INFO = 1,
453 CMD_METHOD_GET_NAME = 1,
454 CMD_METHOD_GET_DECLARING_TYPE = 2,
455 CMD_METHOD_GET_DEBUG_INFO = 3,
456 CMD_METHOD_GET_PARAM_INFO = 4,
457 CMD_METHOD_GET_LOCALS_INFO = 5,
458 CMD_METHOD_GET_INFO = 6,
459 CMD_METHOD_GET_BODY = 7,
460 CMD_METHOD_RESOLVE_TOKEN = 8,
461 CMD_METHOD_GET_CATTRS = 9,
465 CMD_TYPE_GET_INFO = 1,
466 CMD_TYPE_GET_METHODS = 2,
467 CMD_TYPE_GET_FIELDS = 3,
468 CMD_TYPE_GET_VALUES = 4,
469 CMD_TYPE_GET_OBJECT = 5,
470 CMD_TYPE_GET_SOURCE_FILES = 6,
471 CMD_TYPE_SET_VALUES = 7,
472 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
473 CMD_TYPE_GET_PROPERTIES = 9,
474 CMD_TYPE_GET_CATTRS = 10,
475 CMD_TYPE_GET_FIELD_CATTRS = 11,
476 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
477 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
478 CMD_TYPE_GET_VALUES_2 = 14,
479 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
480 CMD_TYPE_GET_INTERFACES = 16,
481 CMD_TYPE_GET_INTERFACE_MAP = 17,
485 CMD_STACK_FRAME_GET_VALUES = 1,
486 CMD_STACK_FRAME_GET_THIS = 2,
487 CMD_STACK_FRAME_SET_VALUES = 3
491 CMD_ARRAY_REF_GET_LENGTH = 1,
492 CMD_ARRAY_REF_GET_VALUES = 2,
493 CMD_ARRAY_REF_SET_VALUES = 3,
497 CMD_STRING_REF_GET_VALUE = 1,
498 CMD_STRING_REF_GET_LENGTH = 2,
499 CMD_STRING_REF_GET_CHARS = 3
503 CMD_OBJECT_REF_GET_TYPE = 1,
504 CMD_OBJECT_REF_GET_VALUES = 2,
505 CMD_OBJECT_REF_IS_COLLECTED = 3,
506 CMD_OBJECT_REF_GET_ADDRESS = 4,
507 CMD_OBJECT_REF_GET_DOMAIN = 5,
508 CMD_OBJECT_REF_SET_VALUES = 6,
509 CMD_OBJECT_REF_GET_INFO = 7,
515 int count; /* For kind == MOD_KIND_COUNT */
516 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
517 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
518 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
519 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
520 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
521 StepFilter filter; /* For kind == MOD_KIND_STEP */
523 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
532 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
536 * Describes a single step request.
540 MonoInternalThread *thread;
546 MonoMethod *last_method;
548 /* Whenever single stepping is performed using start/stop_single_stepping () */
550 /* The list of breakpoints used to implement step-over */
555 * Contains additional information for an event
558 /* For EVENT_KIND_EXCEPTION */
560 MonoContext catch_ctx;
562 /* For EVENT_KIND_USER_LOG */
564 char *category, *message;
565 /* For EVENT_KIND_TYPE_LOAD */
569 /* Dummy structure used for the profiler callbacks */
574 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
577 #define get_last_sock_error() WSAGetLastError()
578 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
579 #define MONO_EINTR WSAEINTR
581 #define get_last_sock_error() errno
582 #define MONO_EWOULDBLOCK EWOULDBLOCK
583 #define MONO_EINTR EINTR
586 #define CHECK_PROTOCOL_VERSION(major,minor) \
587 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
593 static AgentConfig agent_config;
596 * Whenever the agent is fully initialized.
597 * When using the onuncaught or onthrow options, only some parts of the agent are
598 * initialized on startup, and the full initialization which includes connection
599 * establishment and the startup of the agent thread is only done in response to
602 static gint32 inited;
604 #ifndef DISABLE_SOCKET_TRANSPORT
606 static int listen_fd;
609 static int packet_id = 0;
611 static int objref_id = 0;
613 static int event_request_id = 0;
615 static int frame_id = 0;
617 static GPtrArray *event_requests;
619 static MonoNativeTlsKey debugger_tls_id;
621 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
623 /* Maps MonoInternalThread -> DebuggerTlsData */
624 static MonoGHashTable *thread_to_tls;
626 /* Maps tid -> MonoInternalThread */
627 static MonoGHashTable *tid_to_thread;
629 /* Maps tid -> MonoThread (not MonoInternalThread) */
630 static MonoGHashTable *tid_to_thread_obj;
632 static gsize debugger_thread_id;
634 static HANDLE debugger_thread_handle;
636 static int log_level;
638 static gboolean embedding;
640 static FILE *log_file;
642 /* Assemblies whose assembly load event has no been sent yet */
643 static GPtrArray *pending_assembly_loads;
645 /* Whenever the debugger thread has exited */
646 static gboolean debugger_thread_exited;
648 /* Cond variable used to wait for debugger_thread_exited becoming true */
649 static mono_cond_t debugger_thread_exited_cond;
651 /* Mutex for the cond var above */
652 static mono_mutex_t debugger_thread_exited_mutex;
654 static DebuggerProfiler debugger_profiler;
656 /* The single step request instance */
657 static SingleStepReq *ss_req = NULL;
658 static gpointer ss_invoke_addr = NULL;
660 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
661 /* Number of single stepping operations in progress */
665 /* The protocol version of the client */
666 static int major_version, minor_version;
668 /* Whenever the variables above are set by the client */
669 static gboolean protocol_version_set;
671 /* A hash table containing all active domains */
672 static GHashTable *domains;
674 static void transport_init (void);
675 static void transport_connect (const char *address);
676 static gboolean transport_handshake (void);
677 static void register_transport (DebuggerTransport *trans);
679 static guint32 WINAPI debugger_thread (void *arg);
681 static void runtime_initialized (MonoProfiler *prof);
683 static void runtime_shutdown (MonoProfiler *prof);
685 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
687 static void thread_end (MonoProfiler *prof, uintptr_t tid);
689 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
691 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
693 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
695 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
697 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
699 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
701 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
703 static void emit_assembly_load (gpointer assembly, gpointer user_data);
705 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
707 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
709 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
711 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
713 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
715 static void start_single_stepping (void);
717 static void stop_single_stepping (void);
719 static void suspend_current (void);
721 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
723 static void clear_types_for_assembly (MonoAssembly *assembly);
725 static void clear_breakpoints_for_domain (MonoDomain *domain);
727 static void process_profiler_event (EventKind event, gpointer arg);
729 /* Submodule init/cleanup */
730 static void breakpoints_init (void);
731 static void breakpoints_cleanup (void);
733 static void objrefs_init (void);
734 static void objrefs_cleanup (void);
736 static void ids_init (void);
737 static void ids_cleanup (void);
739 static void suspend_init (void);
741 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
742 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
743 static void ss_destroy (SingleStepReq *req);
745 static void start_debugger_thread (void);
746 static void stop_debugger_thread (void);
748 static void finish_agent_init (gboolean on_startup);
750 static void process_profiler_event (EventKind event, gpointer arg);
752 static void invalidate_frames (DebuggerTlsData *tls);
754 #ifndef DISABLE_SOCKET_TRANSPORT
756 register_socket_transport (void);
760 parse_address (char *address, char **host, int *port)
762 char *pos = strchr (address, ':');
764 if (pos == NULL || pos == address)
767 *host = g_malloc (pos - address + 1);
768 strncpy (*host, address, pos - address);
769 (*host) [pos - address] = '\0';
771 *port = atoi (pos + 1);
779 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
780 fprintf (stderr, "Available options:\n");
781 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
782 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
783 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
784 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
785 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
786 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
787 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
788 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
789 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
793 parse_flag (const char *option, char *flag)
795 if (!strcmp (flag, "y"))
797 else if (!strcmp (flag, "n"))
800 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
807 mono_debugger_agent_parse_options (char *options)
814 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
815 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
819 extra = getenv ("MONO_SDB_ENV_OPTIONS");
821 options = g_strdup_printf ("%s,%s", options, extra);
823 agent_config.enabled = TRUE;
824 agent_config.suspend = TRUE;
825 agent_config.server = FALSE;
826 agent_config.defer = FALSE;
827 agent_config.address = NULL;
829 args = g_strsplit (options, ",", -1);
830 for (ptr = args; ptr && *ptr; ptr ++) {
833 if (strncmp (arg, "transport=", 10) == 0) {
834 agent_config.transport = g_strdup (arg + 10);
835 } else if (strncmp (arg, "address=", 8) == 0) {
836 agent_config.address = g_strdup (arg + 8);
837 } else if (strncmp (arg, "loglevel=", 9) == 0) {
838 agent_config.log_level = atoi (arg + 9);
839 } else if (strncmp (arg, "logfile=", 8) == 0) {
840 agent_config.log_file = g_strdup (arg + 8);
841 } else if (strncmp (arg, "suspend=", 8) == 0) {
842 agent_config.suspend = parse_flag ("suspend", arg + 8);
843 } else if (strncmp (arg, "server=", 7) == 0) {
844 agent_config.server = parse_flag ("server", arg + 7);
845 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
846 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
847 } else if (strncmp (arg, "onthrow=", 8) == 0) {
848 /* We support multiple onthrow= options */
849 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
850 } else if (strncmp (arg, "onthrow", 7) == 0) {
851 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
852 } else if (strncmp (arg, "help", 4) == 0) {
855 } else if (strncmp (arg, "timeout=", 8) == 0) {
856 agent_config.timeout = atoi (arg + 8);
857 } else if (strncmp (arg, "launch=", 7) == 0) {
858 agent_config.launch = g_strdup (arg + 7);
859 } else if (strncmp (arg, "embedding=", 10) == 0) {
860 agent_config.embedding = atoi (arg + 10) == 1;
861 } else if (strncmp (arg, "keepalive=", 10) == 0) {
862 agent_config.keepalive = atoi (arg + 10);
869 if (agent_config.server && !agent_config.suspend) {
870 /* Waiting for deferred attachment */
871 agent_config.defer = TRUE;
872 if (agent_config.address == NULL) {
873 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
877 //agent_config.log_level = 0;
879 if (agent_config.transport == NULL) {
880 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
884 if (agent_config.address == NULL && !agent_config.server) {
885 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
890 if (!strcmp (agent_config.transport, "dt_socket")) {
891 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
892 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
899 mono_debugger_agent_init (void)
901 if (!agent_config.enabled)
906 /* Need to know whenever a thread has acquired the loader mutex */
907 mono_loader_lock_track_ownership (TRUE);
909 event_requests = g_ptr_array_new ();
911 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
912 mono_cond_init (&debugger_thread_exited_cond, NULL);
914 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
915 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
916 mono_profiler_install_runtime_initialized (runtime_initialized);
917 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
918 mono_profiler_install_thread (thread_startup, thread_end);
919 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
920 mono_profiler_install_jit_end (jit_end);
921 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
923 mono_native_tls_alloc (&debugger_tls_id, NULL);
925 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
926 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
928 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
929 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
931 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
932 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
934 pending_assembly_loads = g_ptr_array_new ();
935 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
937 log_level = agent_config.log_level;
939 embedding = agent_config.embedding;
942 if (agent_config.log_file) {
943 log_file = fopen (agent_config.log_file, "w+");
945 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
957 mini_get_debug_options ()->gen_seq_points = TRUE;
959 * This is needed because currently we don't handle liveness info.
961 mini_get_debug_options ()->mdb_optimizations = TRUE;
963 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
964 /* This is needed because we can't set local variables in registers yet */
965 mono_disable_optimizations (MONO_OPT_LINEARS);
969 * The stack walk done from thread_interrupt () needs to be signal safe, but it
970 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
971 * safe (#3411). So load AOT info eagerly when the debugger is running as a
974 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
976 if (!agent_config.onuncaught && !agent_config.onthrow)
977 finish_agent_init (TRUE);
979 /* FIXME: Is this still needed ? */
980 #if defined(__MACH__)
981 mono_thread_info_disable_new_interrupt (TRUE);
988 * Finish the initialization of the agent. This involves connecting the transport
989 * and starting the agent thread. This is either done at startup, or
990 * in response to some event like an unhandled exception.
993 finish_agent_init (gboolean on_startup)
997 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1000 if (agent_config.launch) {
1003 // FIXME: Generated address
1004 // FIXME: Races with transport_connect ()
1006 argv [0] = agent_config.launch;
1007 argv [1] = agent_config.transport;
1008 argv [2] = agent_config.address;
1011 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1013 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1018 transport_connect (agent_config.address);
1021 /* Do some which is usually done after sending the VMStart () event */
1022 vm_start_event_sent = TRUE;
1023 start_debugger_thread ();
1028 mono_debugger_agent_cleanup (void)
1033 stop_debugger_thread ();
1035 breakpoints_cleanup ();
1039 mono_mutex_destroy (&debugger_thread_exited_mutex);
1040 mono_cond_destroy (&debugger_thread_exited_cond);
1047 #ifndef DISABLE_SOCKET_TRANSPORT
1052 * recv() + handle incomplete reads and EINTR
1055 socket_transport_recv (void *buf, int len)
1061 static gint32 last_keepalive;
1066 res = recv (fd, (char *) buf + total, len - total, flags);
1069 if (agent_config.keepalive) {
1070 gboolean need_keepalive = FALSE;
1071 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1072 need_keepalive = TRUE;
1073 } else if (res == -1) {
1074 /* This could happen if recv () is interrupted repeatedly */
1075 msecs = mono_msec_ticks ();
1076 if (msecs - last_keepalive >= agent_config.keepalive) {
1077 need_keepalive = TRUE;
1078 last_keepalive = msecs;
1081 if (need_keepalive) {
1082 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1086 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1091 #define HAVE_GETADDRINFO 1
1095 set_keepalive (void)
1100 if (!agent_config.keepalive || !conn_fd)
1103 tv.tv_sec = agent_config.keepalive / 1000;
1104 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1106 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1107 g_assert (result >= 0);
1111 socket_transport_accept (int socket_fd)
1113 conn_fd = accept (socket_fd, NULL, NULL);
1114 if (conn_fd == -1) {
1115 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1117 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1124 socket_transport_send (void *data, int len)
1129 res = send (conn_fd, data, len, 0);
1130 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1138 * socket_transport_connect:
1140 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1143 socket_transport_connect (const char *address)
1145 #ifdef HAVE_GETADDRINFO
1146 struct addrinfo hints;
1147 struct addrinfo *result, *rp;
1149 struct hostent *result;
1151 int sfd = -1, s, res;
1152 char port_string [128];
1156 if (agent_config.address) {
1157 res = parse_address (agent_config.address, &host, &port);
1158 g_assert (res == 0);
1168 sprintf (port_string, "%d", port);
1170 mono_network_init ();
1172 /* Obtain address(es) matching host/port */
1173 #ifdef HAVE_GETADDRINFO
1174 memset (&hints, 0, sizeof (struct addrinfo));
1175 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1176 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1178 hints.ai_protocol = 0; /* Any protocol */
1180 s = getaddrinfo (host, port_string, &hints, &result);
1182 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1186 /* The PS3 doesn't even have _r or hstrerror () */
1187 result = gethostbyname (host);
1189 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1194 if (agent_config.server) {
1195 #ifdef HAVE_GETADDRINFO
1196 /* Wait for a connection */
1198 struct sockaddr_in addr;
1201 /* No address, generate one */
1202 sfd = socket (AF_INET, SOCK_STREAM, 0);
1205 /* This will bind the socket to a random port */
1206 res = listen (sfd, 16);
1208 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1213 addrlen = sizeof (addr);
1214 memset (&addr, 0, sizeof (addr));
1215 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1216 g_assert (res == 0);
1218 host = (char*)"127.0.0.1";
1219 port = ntohs (addr.sin_port);
1221 /* Emit the address to stdout */
1222 /* FIXME: Should print another interface, not localhost */
1223 printf ("%s:%d\n", host, port);
1225 /* Listen on the provided address */
1226 for (rp = result; rp != NULL; rp = rp->ai_next) {
1229 sfd = socket (rp->ai_family, rp->ai_socktype,
1234 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1237 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1241 res = listen (sfd, 16);
1250 * this function is not present on win2000 which we still support, and the
1251 * workaround described here:
1252 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1253 * only works with MSVC.
1255 #ifdef HAVE_GETADDRINFO
1256 freeaddrinfo (result);
1261 if (agent_config.defer)
1264 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1266 if (agent_config.timeout) {
1271 tv.tv_usec = agent_config.timeout * 1000;
1273 FD_SET (sfd, &readfds);
1274 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1276 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1281 conn_fd = socket_transport_accept (sfd);
1285 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1288 #endif /* HAVE_GETADDRINFO */
1290 /* Connect to the specified address */
1291 #ifdef HAVE_GETADDRINFO
1292 /* FIXME: Respect the timeout */
1293 for (rp = result; rp != NULL; rp = rp->ai_next) {
1294 sfd = socket (rp->ai_family, rp->ai_socktype,
1299 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1300 break; /* Success */
1306 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1310 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1312 g_assert_not_reached ();
1313 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1315 g_assert_not_reached ();
1321 /* See the comment above */
1322 #ifdef HAVE_GETADDRINFO
1323 freeaddrinfo (result);
1328 disconnected = !transport_handshake ();
1334 socket_transport_close1 (void)
1336 /* This will interrupt the agent thread */
1337 /* Close the read part only so it can still send back replies */
1338 /* Also shut down the connection listener so that we can exit normally */
1340 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1341 shutdown (conn_fd, SD_BOTH);
1342 shutdown (listen_fd, SD_BOTH);
1343 closesocket (listen_fd);
1345 shutdown (conn_fd, SHUT_RD);
1346 shutdown (listen_fd, SHUT_RDWR);
1352 socket_transport_close2 (void)
1355 shutdown (conn_fd, SD_BOTH);
1357 shutdown (conn_fd, SHUT_RDWR);
1362 register_socket_transport (void)
1364 DebuggerTransport trans;
1366 trans.name = "dt_socket";
1367 trans.connect = socket_transport_connect;
1368 trans.close1 = socket_transport_close1;
1369 trans.close2 = socket_transport_close2;
1370 trans.send = socket_transport_send;
1371 trans.recv = socket_transport_recv;
1373 register_transport (&trans);
1376 #endif /* DISABLE_SOCKET_TRANSPORT */
1382 #define MAX_TRANSPORTS 16
1384 static DebuggerTransport *transport;
1386 static DebuggerTransport transports [MAX_TRANSPORTS];
1387 static int ntransports;
1390 register_transport (DebuggerTransport *trans)
1392 g_assert (ntransports < MAX_TRANSPORTS);
1394 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1399 transport_init (void)
1403 #ifndef DISABLE_SOCKET_TRANSPORT
1404 register_socket_transport ();
1407 for (i = 0; i < ntransports; ++i) {
1408 if (!strcmp (agent_config.transport, transports [i].name))
1411 if (i == ntransports) {
1412 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1413 for (i = 0; i < ntransports; ++i)
1414 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1415 fprintf (stderr, "\n");
1418 transport = &transports [i];
1422 transport_connect (const char *address)
1424 transport->connect (address);
1428 transport_close1 (void)
1430 transport->close1 ();
1434 transport_close2 (void)
1436 transport->close2 ();
1440 transport_send (void *buf, int len)
1442 return transport->send (buf, len);
1446 transport_recv (void *buf, int len)
1448 return transport->recv (buf, len);
1452 transport_handshake (void)
1454 char handshake_msg [128];
1458 /* Write handshake message */
1459 sprintf (handshake_msg, "DWP-Handshake");
1461 res = transport_send (handshake_msg, strlen (handshake_msg));
1462 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1463 g_assert (res != -1);
1466 res = transport_recv (buf, strlen (handshake_msg));
1467 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1468 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1473 * To support older clients, the client sends its protocol version after connecting
1474 * using a command. Until that is received, default to our protocol version.
1476 major_version = MAJOR_VERSION;
1477 minor_version = MINOR_VERSION;
1478 protocol_version_set = FALSE;
1480 #ifndef DISABLE_SOCKET_TRANSPORT
1481 // FIXME: Move this somewhere else
1483 * Set TCP_NODELAY on the socket so the client receives events/command
1484 * results immediately.
1488 int result = setsockopt (conn_fd,
1493 g_assert (result >= 0);
1503 stop_debugger_thread (void)
1508 transport_close1 ();
1511 * Wait for the thread to exit.
1513 * If we continue with the shutdown without waiting for it, then the client might
1514 * not receive an answer to its last command like a resume.
1515 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1518 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1519 if (GetCurrentThreadId () != debugger_thread_id) {
1521 mono_mutex_lock (&debugger_thread_exited_mutex);
1522 if (!debugger_thread_exited) {
1524 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1525 mono_mutex_unlock (&debugger_thread_exited_mutex);
1527 mono_mutex_lock (&debugger_thread_exited_mutex);
1530 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1533 mono_mutex_unlock (&debugger_thread_exited_mutex);
1534 } while (!debugger_thread_exited);
1537 transport_close2 ();
1541 start_debugger_thread (void)
1545 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1546 g_assert (debugger_thread_handle);
1550 * Functions to decode protocol data
1554 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1557 g_assert (*endbuf <= limit);
1562 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1565 g_assert (*endbuf <= limit);
1567 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1570 static inline gint64
1571 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1573 guint32 high = decode_int (buf, &buf, limit);
1574 guint32 low = decode_int (buf, &buf, limit);
1578 return ((((guint64)high) << 32) | ((guint64)low));
1582 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1584 return decode_int (buf, endbuf, limit);
1588 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1590 int len = decode_int (buf, &buf, limit);
1598 s = g_malloc (len + 1);
1601 memcpy (s, buf, len);
1610 * Functions to encode protocol data
1614 guint8 *buf, *p, *end;
1618 buffer_init (Buffer *buf, int size)
1620 buf->buf = g_malloc (size);
1622 buf->end = buf->buf + size;
1626 buffer_make_room (Buffer *buf, int size)
1628 if (buf->end - buf->p < size) {
1629 int new_size = buf->end - buf->buf + size + 32;
1630 guint8 *p = g_realloc (buf->buf, new_size);
1631 size = buf->p - buf->buf;
1634 buf->end = buf->buf + new_size;
1639 buffer_add_byte (Buffer *buf, guint8 val)
1641 buffer_make_room (buf, 1);
1647 buffer_add_short (Buffer *buf, guint32 val)
1649 buffer_make_room (buf, 2);
1650 buf->p [0] = (val >> 8) & 0xff;
1651 buf->p [1] = (val >> 0) & 0xff;
1656 buffer_add_int (Buffer *buf, guint32 val)
1658 buffer_make_room (buf, 4);
1659 buf->p [0] = (val >> 24) & 0xff;
1660 buf->p [1] = (val >> 16) & 0xff;
1661 buf->p [2] = (val >> 8) & 0xff;
1662 buf->p [3] = (val >> 0) & 0xff;
1667 buffer_add_long (Buffer *buf, guint64 l)
1669 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1670 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1674 buffer_add_id (Buffer *buf, int id)
1676 buffer_add_int (buf, (guint64)id);
1680 buffer_add_data (Buffer *buf, guint8 *data, int len)
1682 buffer_make_room (buf, len);
1683 memcpy (buf->p, data, len);
1688 buffer_add_string (Buffer *buf, const char *str)
1693 buffer_add_int (buf, 0);
1696 buffer_add_int (buf, len);
1697 buffer_add_data (buf, (guint8*)str, len);
1702 buffer_free (Buffer *buf)
1708 send_packet (int command_set, int command, Buffer *data)
1714 id = InterlockedIncrement (&packet_id);
1716 len = data->p - data->buf + 11;
1717 buffer_init (&buf, len);
1718 buffer_add_int (&buf, len);
1719 buffer_add_int (&buf, id);
1720 buffer_add_byte (&buf, 0); /* flags */
1721 buffer_add_byte (&buf, command_set);
1722 buffer_add_byte (&buf, command);
1723 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1725 res = transport_send (buf.buf, len);
1733 send_reply_packet (int id, int error, Buffer *data)
1739 len = data->p - data->buf + 11;
1740 buffer_init (&buf, len);
1741 buffer_add_int (&buf, len);
1742 buffer_add_int (&buf, id);
1743 buffer_add_byte (&buf, 0x80); /* flags */
1744 buffer_add_byte (&buf, (error >> 8) & 0xff);
1745 buffer_add_byte (&buf, error);
1746 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1748 res = transport_send (buf.buf, len);
1760 * Represents an object accessible by the debugger client.
1763 /* Unique id used in the wire protocol to refer to objects */
1766 * A weakref gc handle pointing to the object. The gc handle is used to
1767 * detect if the object was garbage collected.
1772 /* Maps objid -> ObjRef */
1773 static GHashTable *objrefs;
1776 free_objref (gpointer value)
1780 mono_gchandle_free (o->handle);
1788 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1792 objrefs_cleanup (void)
1794 g_hash_table_destroy (objrefs);
1798 static GHashTable *obj_to_objref;
1801 * Return an ObjRef for OBJ.
1804 get_objref (MonoObject *obj)
1807 GSList *reflist = NULL, *l;
1813 mono_loader_lock ();
1816 obj_to_objref = g_hash_table_new (NULL, NULL);
1818 /* FIXME: The tables can grow indefinitely */
1820 if (mono_gc_is_moving ()) {
1822 * Objects can move, so use a hash table mapping hash codes to lists of
1823 * ObjRef structures.
1825 hash = mono_object_hash (obj);
1827 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1828 for (l = reflist; l; l = l->next) {
1830 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1831 mono_loader_unlock ();
1836 /* Use a hash table with masked pointers to internalize object references */
1837 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1838 /* ref might refer to a different object with the same addr which was GCd */
1839 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1840 mono_loader_unlock ();
1845 ref = g_new0 (ObjRef, 1);
1846 ref->id = InterlockedIncrement (&objref_id);
1847 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1849 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1851 if (mono_gc_is_moving ()) {
1852 reflist = g_slist_append (reflist, ref);
1853 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1855 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1858 mono_loader_unlock ();
1864 get_objid (MonoObject *obj)
1866 return get_objref (obj)->id;
1870 * Set OBJ to the object identified by OBJID.
1871 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1875 get_object_allow_null (int objid, MonoObject **obj)
1885 return ERR_INVALID_OBJECT;
1887 mono_loader_lock ();
1889 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1892 *obj = mono_gchandle_get_target (ref->handle);
1893 mono_loader_unlock ();
1895 return ERR_INVALID_OBJECT;
1898 mono_loader_unlock ();
1899 return ERR_INVALID_OBJECT;
1904 get_object (int objid, MonoObject **obj)
1906 int err = get_object_allow_null (objid, obj);
1911 return ERR_INVALID_OBJECT;
1916 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1918 return decode_id (buf, endbuf, limit);
1922 buffer_add_objid (Buffer *buf, MonoObject *o)
1924 buffer_add_id (buf, get_objid (o));
1943 * Represents a runtime structure accessible to the debugger client
1946 /* Unique id used in the wire protocol */
1948 /* Domain of the runtime structure, NULL if the domain was unloaded */
1955 MonoAssembly *assembly;
1956 MonoClassField *field;
1958 MonoProperty *property;
1963 /* Maps runtime structure -> Id */
1964 GHashTable *val_to_id [ID_NUM];
1965 /* Classes whose class load event has been sent */
1966 GHashTable *loaded_classes;
1967 /* Maps MonoClass->GPtrArray of file names */
1968 GHashTable *source_files;
1969 /* Maps source file basename -> GSList of classes */
1970 GHashTable *source_file_to_class;
1971 /* Same with ignore-case */
1972 GHashTable *source_file_to_class_ignorecase;
1976 static GPtrArray *ids [ID_NUM];
1983 for (i = 0; i < ID_NUM; ++i)
1984 ids [i] = g_ptr_array_new ();
1992 for (i = 0; i < ID_NUM; ++i) {
1994 for (j = 0; j < ids [i]->len; ++j)
1995 g_free (g_ptr_array_index (ids [i], j));
1996 g_ptr_array_free (ids [i], TRUE);
2003 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2005 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2007 GHashTableIter iter;
2008 GPtrArray *file_names;
2013 for (i = 0; i < ID_NUM; ++i)
2014 if (info->val_to_id [i])
2015 g_hash_table_destroy (info->val_to_id [i]);
2016 g_hash_table_destroy (info->loaded_classes);
2018 g_hash_table_iter_init (&iter, info->source_files);
2019 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2020 for (i = 0; i < file_names->len; ++i)
2021 g_free (g_ptr_array_index (file_names, i));
2022 g_ptr_array_free (file_names, TRUE);
2025 g_hash_table_iter_init (&iter, info->source_file_to_class);
2026 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2031 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2032 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2040 domain_jit_info (domain)->agent_info = NULL;
2042 /* Clear ids referencing structures in the domain */
2043 for (i = 0; i < ID_NUM; ++i) {
2045 for (j = 0; j < ids [i]->len; ++j) {
2046 Id *id = g_ptr_array_index (ids [i], j);
2047 if (id->domain == domain)
2053 mono_loader_lock ();
2054 g_hash_table_remove (domains, domain);
2055 mono_loader_unlock ();
2058 static AgentDomainInfo*
2059 get_agent_domain_info (MonoDomain *domain)
2061 AgentDomainInfo *info = NULL;
2063 mono_domain_lock (domain);
2065 info = domain_jit_info (domain)->agent_info;
2067 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2068 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2069 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2070 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2071 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2074 mono_domain_unlock (domain);
2080 get_id (MonoDomain *domain, IdType type, gpointer val)
2083 AgentDomainInfo *info;
2088 mono_loader_lock ();
2090 mono_domain_lock (domain);
2092 info = get_agent_domain_info (domain);
2094 if (info->val_to_id [type] == NULL)
2095 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2097 id = g_hash_table_lookup (info->val_to_id [type], val);
2099 mono_domain_unlock (domain);
2100 mono_loader_unlock ();
2104 id = g_new0 (Id, 1);
2106 id->id = ids [type]->len + 1;
2107 id->domain = domain;
2110 g_hash_table_insert (info->val_to_id [type], val, id);
2112 mono_domain_unlock (domain);
2114 g_ptr_array_add (ids [type], id);
2116 mono_loader_unlock ();
2121 static inline gpointer
2122 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2126 int id = decode_id (buf, endbuf, limit);
2135 // FIXME: error handling
2136 mono_loader_lock ();
2137 g_assert (id > 0 && id <= ids [type]->len);
2139 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2140 mono_loader_unlock ();
2142 if (res->domain == NULL) {
2143 *err = ERR_UNLOADED;
2148 *domain = res->domain;
2150 return res->data.val;
2154 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2156 buffer_add_id (buf, get_id (domain, type, val));
2159 static inline MonoClass*
2160 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2162 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2165 static inline MonoAssembly*
2166 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2168 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2171 static inline MonoImage*
2172 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2174 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2177 static inline MonoMethod*
2178 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2180 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2183 static inline MonoClassField*
2184 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2186 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2189 static inline MonoDomain*
2190 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2192 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2195 static inline MonoProperty*
2196 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2198 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2202 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2204 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2208 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2210 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2214 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2216 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2220 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2222 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2226 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2228 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2232 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2234 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2238 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2240 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2243 static void invoke_method (void);
2250 * save_thread_context:
2252 * Set CTX as the current threads context which is used for computing stack traces.
2253 * This function is signal-safe.
2256 save_thread_context (MonoContext *ctx)
2258 DebuggerTlsData *tls;
2260 tls = mono_native_tls_get_value (debugger_tls_id);
2264 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2266 mono_thread_state_init_from_current (&tls->context);
2269 /* The number of times the runtime is suspended */
2270 static gint32 suspend_count;
2272 /* Number of threads suspended */
2274 * If this is equal to the size of thread_to_tls, the runtime is considered
2277 static gint32 threads_suspend_count;
2279 static mono_mutex_t suspend_mutex;
2281 /* Cond variable used to wait for suspend_count becoming 0 */
2282 static mono_cond_t suspend_cond;
2284 /* Semaphore used to wait for a thread becoming suspended */
2285 static MonoSemType suspend_sem;
2290 mono_mutex_init (&suspend_mutex, NULL);
2291 mono_cond_init (&suspend_cond, NULL);
2292 MONO_SEM_INIT (&suspend_sem, 0);
2297 StackFrameInfo last_frame;
2298 gboolean last_frame_set;
2301 } GetLastFrameUserData;
2304 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2306 GetLastFrameUserData *data = user_data;
2308 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2311 if (!data->last_frame_set) {
2312 /* Store the last frame */
2313 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2314 data->last_frame_set = TRUE;
2317 /* Store the context/lmf for the frame above the last frame */
2318 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2319 data->lmf = info->lmf;
2327 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2328 * INFO is set, process the thread described by INFO.
2329 * This should be signal safe.
2332 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2336 MonoNativeThreadId tid;
2339 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2340 * guarantee the signal handler will be called that many times. Instead of tracking
2341 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2342 * has been requested that hasn't been handled yet, otherwise we can have threads
2343 * refuse to die when VM_EXIT is called
2345 #if defined(__APPLE__)
2346 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2350 * We use interrupt_count to determine whenever this interrupt should be processed
2351 * by us or the normal interrupt processing code in the signal handler.
2352 * There is no race here with notify_thread (), since the signal is sent after
2353 * incrementing interrupt_count.
2355 if (tls->interrupt_count == 0)
2358 InterlockedDecrement (&tls->interrupt_count);
2362 ip = mono_arch_ip_from_context (sigctx);
2364 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2369 tid = mono_thread_info_get_tid (info);
2371 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2373 // FIXME: Races when the thread leaves managed code before hitting a single step
2377 /* Running managed code, will be suspended by the single step code */
2378 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2382 * Running native code, will be suspended when it returns to/enters
2383 * managed code. Treat it as already suspended.
2384 * This might interrupt the code in process_single_step_inner (), we use the
2385 * tls->suspending flag to avoid races when that happens.
2387 if (!tls->suspended && !tls->suspending) {
2389 GetLastFrameUserData data;
2391 // FIXME: printf is not signal safe, but this is only used during
2392 // debugger debugging
2394 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2395 //save_thread_context (&ctx);
2398 /* Already terminated */
2401 tls->context.valid = FALSE;
2404 * We are in a difficult position: we want to be able to provide stack
2405 * traces for this thread, but we can't use the current ctx+lmf, since
2406 * the thread is still running, so it might return to managed code,
2407 * making these invalid.
2408 * So we start a stack walk and save the first frame, along with the
2409 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2410 * suspended when it returns to managed code, so the parent's ctx should
2413 data.last_frame_set = FALSE;
2415 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2417 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2418 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2419 * since we are not in a JITted method.
2421 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2423 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2425 if (data.last_frame_set) {
2426 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2427 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2429 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2432 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2433 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2434 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2436 /* No managed frames */
2437 tls->async_state.valid = FALSE;
2439 mono_memory_barrier ();
2441 tls->suspended = TRUE;
2442 MONO_SEM_POST (&suspend_sem);
2449 * mono_debugger_agent_thread_interrupt:
2451 * Called by the abort signal handler.
2452 * Should be signal safe.
2455 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2457 DebuggerTlsData *tls;
2462 tls = mono_native_tls_get_value (debugger_tls_id);
2466 return thread_interrupt (tls, NULL, sigctx, ji);
2470 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2473 mono_debugger_agent_thread_interrupt (NULL, NULL);
2475 #endif /* HOST_WIN32 */
2478 * reset_native_thread_suspend_state:
2480 * Reset the suspended flag and state on native threads
2483 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2485 DebuggerTlsData *tls = value;
2487 if (!tls->really_suspended && tls->suspended) {
2488 tls->suspended = FALSE;
2490 * The thread might still be running if it was executing native code, so the state won't be invalided by
2491 * suspend_current ().
2493 tls->context.valid = FALSE;
2494 tls->async_state.valid = FALSE;
2495 invalidate_frames (tls);
2502 * Notify a thread that it needs to suspend.
2505 notify_thread (gpointer key, gpointer value, gpointer user_data)
2507 MonoInternalThread *thread = key;
2508 DebuggerTlsData *tls = value;
2509 gsize tid = thread->tid;
2512 if (GetCurrentThreadId () == tid || tls->terminated)
2515 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2518 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2519 * guarantee the signal handler will be called that many times. Instead of tracking
2520 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2521 * has been requested that hasn't been handled yet, otherwise we can have threads
2522 * refuse to die when VM_EXIT is called
2524 #if defined(__APPLE__)
2525 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2529 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2530 * of things like breaking waits etc. which we don't want.
2532 InterlockedIncrement (&tls->interrupt_count);
2535 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2537 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2539 if (mono_thread_info_new_interrupt_enabled ()) {
2540 MonoThreadInfo *info;
2543 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2546 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2548 thread_interrupt (tls, info, NULL, ji);
2550 mono_thread_info_resume (mono_thread_info_get_tid (info));
2552 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2555 * Attached thread which died without detaching.
2557 tls->terminated = TRUE;
2563 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2565 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2568 if (mono_loader_lock_is_owned_by_self ()) {
2570 * Shortcut for the check in suspend_current (). This speeds up processing
2571 * when executing long running code inside the loader lock, i.e. assembly load
2577 if (debugger_thread_id == GetCurrentThreadId ())
2580 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2581 if (suspend_count - tls->resume_count > 0)
2582 tls->suspending = TRUE;
2584 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2586 if (suspend_count - tls->resume_count == 0) {
2588 * We are executing a single threaded invoke but the single step for
2589 * suspending is still active.
2590 * FIXME: This slows down single threaded invokes.
2592 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2596 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2598 /* Can't suspend in these methods */
2599 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2602 save_thread_context (ctx);
2610 * Increase the suspend count of the VM. While the suspend count is greater
2611 * than 0, runtime threads are suspended at certain points during execution.
2616 mono_loader_lock ();
2618 mono_mutex_lock (&suspend_mutex);
2622 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2624 if (suspend_count == 1) {
2625 // FIXME: Is it safe to call this inside the lock ?
2626 start_single_stepping ();
2627 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2630 mono_mutex_unlock (&suspend_mutex);
2632 mono_loader_unlock ();
2638 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2646 g_assert (debugger_thread_id == GetCurrentThreadId ());
2648 mono_loader_lock ();
2650 mono_mutex_lock (&suspend_mutex);
2652 g_assert (suspend_count > 0);
2655 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2657 if (suspend_count == 0) {
2658 // FIXME: Is it safe to call this inside the lock ?
2659 stop_single_stepping ();
2660 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2663 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2664 err = mono_cond_broadcast (&suspend_cond);
2665 g_assert (err == 0);
2667 mono_mutex_unlock (&suspend_mutex);
2668 //g_assert (err == 0);
2670 mono_loader_unlock ();
2676 * Resume just one thread.
2679 resume_thread (MonoInternalThread *thread)
2682 DebuggerTlsData *tls;
2684 g_assert (debugger_thread_id == GetCurrentThreadId ());
2686 mono_loader_lock ();
2688 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2691 mono_mutex_lock (&suspend_mutex);
2693 g_assert (suspend_count > 0);
2695 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2697 tls->resume_count += suspend_count;
2700 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2701 * but only the one whose resume_count field is > 0 will be resumed.
2703 err = mono_cond_broadcast (&suspend_cond);
2704 g_assert (err == 0);
2706 mono_mutex_unlock (&suspend_mutex);
2707 //g_assert (err == 0);
2709 mono_loader_unlock ();
2713 invalidate_frames (DebuggerTlsData *tls)
2718 tls = mono_native_tls_get_value (debugger_tls_id);
2721 for (i = 0; i < tls->frame_count; ++i) {
2722 if (tls->frames [i]->jit)
2723 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2724 g_free (tls->frames [i]);
2726 g_free (tls->frames);
2727 tls->frame_count = 0;
2734 * Suspend the current thread until the runtime is resumed. If the thread has a
2735 * pending invoke, then the invoke is executed before this function returns.
2738 suspend_current (void)
2741 DebuggerTlsData *tls;
2743 g_assert (debugger_thread_id != GetCurrentThreadId ());
2745 if (mono_loader_lock_is_owned_by_self ()) {
2747 * If we own the loader mutex, can't suspend until we release it, since the
2748 * whole runtime can deadlock otherwise.
2753 tls = mono_native_tls_get_value (debugger_tls_id);
2756 mono_mutex_lock (&suspend_mutex);
2758 tls->suspending = FALSE;
2759 tls->really_suspended = TRUE;
2761 if (!tls->suspended) {
2762 tls->suspended = TRUE;
2763 MONO_SEM_POST (&suspend_sem);
2766 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2768 while (suspend_count - tls->resume_count > 0) {
2770 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2772 mono_mutex_unlock (&suspend_mutex);
2774 mono_mutex_lock (&suspend_mutex);
2780 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2781 g_assert (err == 0);
2785 tls->suspended = FALSE;
2786 tls->really_suspended = FALSE;
2788 threads_suspend_count --;
2790 mono_mutex_unlock (&suspend_mutex);
2792 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2794 if (tls->pending_invoke) {
2795 /* Save the original context */
2796 tls->pending_invoke->has_ctx = TRUE;
2797 tls->pending_invoke->ctx = tls->context.ctx;
2802 /* The frame info becomes invalid after a resume */
2803 tls->context.valid = FALSE;
2804 tls->async_state.valid = FALSE;
2805 invalidate_frames (tls);
2809 count_thread (gpointer key, gpointer value, gpointer user_data)
2811 DebuggerTlsData *tls = value;
2813 if (!tls->suspended && !tls->terminated)
2814 *(int*)user_data = *(int*)user_data + 1;
2818 count_threads_to_wait_for (void)
2822 mono_loader_lock ();
2823 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2824 mono_loader_unlock ();
2832 * Wait until the runtime is completely suspended.
2835 wait_for_suspend (void)
2837 int nthreads, nwait, err;
2838 gboolean waited = FALSE;
2840 // FIXME: Threads starting/stopping ?
2841 mono_loader_lock ();
2842 nthreads = mono_g_hash_table_size (thread_to_tls);
2843 mono_loader_unlock ();
2846 nwait = count_threads_to_wait_for ();
2848 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2849 err = MONO_SEM_WAIT (&suspend_sem);
2850 g_assert (err == 0);
2858 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2864 * Return whenever the runtime is suspended.
2869 return count_threads_to_wait_for () == 0;
2872 static MonoSeqPointInfo*
2873 get_seq_points (MonoDomain *domain, MonoMethod *method)
2875 MonoSeqPointInfo *seq_points;
2877 mono_domain_lock (domain);
2878 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2879 if (!seq_points && method->is_inflated) {
2880 /* generic sharing + aot */
2881 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2883 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2885 mono_domain_unlock (domain);
2890 static MonoSeqPointInfo*
2891 find_seq_points (MonoDomain *domain, MonoMethod *method)
2893 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2896 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2897 g_assert (seq_points);
2903 * find_next_seq_point_for_native_offset:
2905 * Find the first sequence point after NATIVE_OFFSET.
2908 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2910 MonoSeqPointInfo *seq_points;
2913 seq_points = find_seq_points (domain, method);
2917 for (i = 0; i < seq_points->len; ++i) {
2918 if (seq_points->seq_points [i].native_offset >= native_offset)
2919 return &seq_points->seq_points [i];
2926 * find_prev_seq_point_for_native_offset:
2928 * Find the first sequence point before NATIVE_OFFSET.
2931 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2933 MonoSeqPointInfo *seq_points;
2936 seq_points = find_seq_points (domain, method);
2940 for (i = seq_points->len - 1; i >= 0; --i) {
2941 if (seq_points->seq_points [i].native_offset <= native_offset)
2942 return &seq_points->seq_points [i];
2951 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2952 * should be the location of a sequence point.
2954 static G_GNUC_UNUSED SeqPoint*
2955 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2957 MonoSeqPointInfo *seq_points;
2962 seq_points = get_seq_points (domain, method);
2967 for (i = 0; i < seq_points->len; ++i) {
2968 if (seq_points->seq_points [i].il_offset == il_offset)
2969 return &seq_points->seq_points [i];
2976 DebuggerTlsData *tls;
2978 } ComputeFramesUserData;
2981 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2983 ComputeFramesUserData *ud = user_data;
2985 MonoMethod *method, *actual_method, *api_method;
2989 if (info->type != FRAME_TYPE_MANAGED) {
2990 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2991 /* Mark the last frame as an invoke frame */
2993 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2999 method = info->ji->method;
3001 method = info->method;
3002 actual_method = info->actual_method;
3003 api_method = method;
3008 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3011 if (info->il_offset == -1) {
3012 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3013 if (ud->frames == NULL) {
3014 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3016 info->il_offset = sp->il_offset;
3018 if (info->il_offset == -1)
3019 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3022 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));
3024 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3025 if (!CHECK_PROTOCOL_VERSION (2, 17))
3026 /* Older clients can't handle this flag */
3028 api_method = mono_marshal_method_from_wrapper (method);
3031 actual_method = api_method;
3032 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3035 frame = g_new0 (StackFrame, 1);
3036 frame->method = method;
3037 frame->actual_method = actual_method;
3038 frame->api_method = api_method;
3039 frame->il_offset = info->il_offset;
3040 frame->native_offset = info->native_offset;
3041 frame->flags = flags;
3042 frame->ji = info->ji;
3043 if (info->reg_locations)
3044 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3047 frame->has_ctx = TRUE;
3049 frame->domain = info->domain;
3051 ud->frames = g_slist_append (ud->frames, frame);
3057 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3059 ComputeFramesUserData *ud = user_data;
3062 * 'tls->filter_ctx' is the location of the throw site.
3064 * mono_walk_stack() will never actually hit the throw site, but unwind
3065 * directly from the filter to the call site; we abort stack unwinding here
3066 * once this happens and resume from the throw site.
3069 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3072 return process_frame (info, ctx, user_data);
3076 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3078 ComputeFramesUserData user_data;
3080 int i, findex, new_frame_count;
3081 StackFrame **new_frames, *f;
3082 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3084 // FIXME: Locking on tls
3085 if (tls->frames && tls->frames_up_to_date)
3088 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3090 user_data.tls = tls;
3091 user_data.frames = NULL;
3092 if (tls->terminated) {
3093 tls->frame_count = 0;
3095 } if (!tls->really_suspended && tls->async_state.valid) {
3096 /* Have to use the state saved by the signal handler */
3097 process_frame (&tls->async_last_frame, NULL, &user_data);
3098 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3099 } else if (tls->filter_state.valid) {
3101 * We are inside an exception filter.
3103 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3105 if (tls->context.valid)
3106 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3108 * After that, we resume unwinding from the location where the exception has been thrown.
3110 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3111 } else if (tls->context.valid) {
3112 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3115 tls->frame_count = 0;
3119 new_frame_count = g_slist_length (user_data.frames);
3120 new_frames = g_new0 (StackFrame*, new_frame_count);
3122 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3126 * Reuse the id for already existing stack frames, so invokes don't invalidate
3127 * the still valid stack frames.
3129 for (i = 0; i < tls->frame_count; ++i) {
3130 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3131 f->id = tls->frames [i]->id;
3136 if (i >= tls->frame_count)
3137 f->id = InterlockedIncrement (&frame_id);
3139 new_frames [findex ++] = f;
3142 g_slist_free (user_data.frames);
3144 invalidate_frames (tls);
3146 tls->frames = new_frames;
3147 tls->frame_count = new_frame_count;
3148 tls->frames_up_to_date = TRUE;
3152 * GHFunc to emit an appdomain creation event
3153 * @param key Don't care
3154 * @param value A loaded appdomain
3155 * @param user_data Don't care
3158 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3160 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3161 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3165 * GHFunc to emit a thread start event
3166 * @param key A thread id
3167 * @param value A thread object
3168 * @param user_data Don't care
3171 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3173 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3174 process_profiler_event (EVENT_KIND_THREAD_START, value);
3178 * GFunc to emit an assembly load event
3179 * @param value A loaded assembly
3180 * @param user_data Don't care
3183 emit_assembly_load (gpointer value, gpointer user_data)
3185 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3189 * GFunc to emit a type load event
3190 * @param value A loaded type
3191 * @param user_data Don't care
3194 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3196 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3200 strdup_tolower (char *s)
3205 for (p = s2; *p; ++p)
3215 * create_event_list:
3217 * Return a list of event request ids matching EVENT, starting from REQS, which
3218 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3220 * We return request ids, instead of requests, to simplify threading, since
3221 * requests could be deleted anytime when the loader lock is not held.
3222 * LOCKING: Assumes the loader lock is held.
3225 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3228 GSList *events = NULL;
3230 *suspend_policy = SUSPEND_POLICY_NONE;
3233 reqs = event_requests;
3238 for (i = 0; i < reqs->len; ++i) {
3239 EventRequest *req = g_ptr_array_index (reqs, i);
3240 if (req->event_kind == event) {
3241 gboolean filtered = FALSE;
3244 for (j = 0; j < req->nmodifiers; ++j) {
3245 Modifier *mod = &req->modifiers [j];
3247 if (mod->kind == MOD_KIND_COUNT) {
3249 if (mod->data.count > 0) {
3250 if (mod->data.count > 0) {
3252 if (mod->data.count == 0)
3256 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3257 if (mod->data.thread != mono_thread_internal_current ())
3259 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3260 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3262 if (ei->caught && !mod->caught)
3264 if (!ei->caught && !mod->uncaught)
3266 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3268 gboolean found = FALSE;
3269 MonoAssembly **assemblies = mod->data.assemblies;
3272 for (k = 0; assemblies [k]; ++k)
3273 if (assemblies [k] == ji->method->klass->image->assembly)
3278 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3279 gpointer iter = NULL;
3281 MonoDebugSourceInfo *sinfo;
3282 char *source_file, *s;
3283 gboolean found = FALSE;
3285 GPtrArray *source_file_list;
3287 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3288 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3291 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3292 for (i = 0; i < source_file_list->len; ++i) {
3293 sinfo = g_ptr_array_index (source_file_list, i);
3295 * Do a case-insesitive match by converting the file name to
3298 s = strdup_tolower (sinfo->source_file);
3299 if (g_hash_table_lookup (mod->data.source_files, s))
3303 g_ptr_array_free (source_file_list, TRUE);
3308 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3311 s = mono_type_full_name (&ei->klass->byval_arg);
3312 if (!g_hash_table_lookup (mod->data.type_names, s))
3315 } else if (mod->kind == MOD_KIND_STEP) {
3316 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3317 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3318 !strcmp (ji->method->name, ".cctor"))
3320 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3321 MonoCustomAttrInfo *ainfo;
3322 static MonoClass *klass;
3325 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3328 if (!ji->dbg_hidden_inited) {
3329 ainfo = mono_custom_attrs_from_method (ji->method);
3331 if (mono_custom_attrs_has_attr (ainfo, klass))
3332 ji->dbg_hidden = TRUE;
3333 mono_custom_attrs_free (ainfo);
3335 ji->dbg_hidden_inited = TRUE;
3344 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3345 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3350 /* Send a VM START/DEATH event by default */
3351 if (event == EVENT_KIND_VM_START)
3352 events = g_slist_append (events, GINT_TO_POINTER (0));
3353 if (event == EVENT_KIND_VM_DEATH)
3354 events = g_slist_append (events, GINT_TO_POINTER (0));
3359 static G_GNUC_UNUSED const char*
3360 event_to_string (EventKind event)
3363 case EVENT_KIND_VM_START: return "VM_START";
3364 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3365 case EVENT_KIND_THREAD_START: return "THREAD_START";
3366 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3367 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3368 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3369 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3370 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3371 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3372 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3373 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3374 case EVENT_KIND_STEP: return "STEP";
3375 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3376 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3377 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3378 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3379 case EVENT_KIND_USER_LOG: return "USER_LOG";
3381 g_assert_not_reached ();
3388 * Send an event to the client, suspending the vm if needed.
3389 * LOCKING: Since this can suspend the calling thread, no locks should be held
3391 * The EVENTS list is freed by this function.
3394 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3398 MonoDomain *domain = mono_domain_get ();
3399 MonoThread *thread = NULL;
3400 gboolean send_success = FALSE;
3405 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3409 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3410 // FIXME: We miss those events
3411 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3415 if (vm_death_event_sent) {
3416 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3420 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3421 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3426 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3430 if (event == EVENT_KIND_KEEPALIVE)
3431 suspend_policy = SUSPEND_POLICY_NONE;
3436 if (agent_config.defer) {
3437 /* Make sure the thread id is always set when doing deferred debugging */
3438 if (debugger_thread_id == GetCurrentThreadId ()) {
3439 /* Don't suspend on events from the debugger thread */
3440 suspend_policy = SUSPEND_POLICY_NONE;
3441 thread = mono_thread_get_main ();
3443 else thread = mono_thread_current ();
3445 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3446 // FIXME: Send these with a NULL thread, don't suspend the current thread
3451 nevents = g_slist_length (events);
3452 buffer_init (&buf, 128);
3453 buffer_add_byte (&buf, suspend_policy);
3454 buffer_add_int (&buf, nevents);
3456 for (l = events; l; l = l->next) {
3457 buffer_add_byte (&buf, event); // event kind
3458 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3463 thread = mono_thread_current ();
3465 if (event == EVENT_KIND_VM_START && arg != NULL)
3468 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3471 case EVENT_KIND_THREAD_START:
3472 case EVENT_KIND_THREAD_DEATH:
3474 case EVENT_KIND_APPDOMAIN_CREATE:
3475 case EVENT_KIND_APPDOMAIN_UNLOAD:
3476 buffer_add_domainid (&buf, arg);
3478 case EVENT_KIND_METHOD_ENTRY:
3479 case EVENT_KIND_METHOD_EXIT:
3480 buffer_add_methodid (&buf, domain, arg);
3482 case EVENT_KIND_ASSEMBLY_LOAD:
3483 case EVENT_KIND_ASSEMBLY_UNLOAD:
3484 buffer_add_assemblyid (&buf, domain, arg);
3486 case EVENT_KIND_TYPE_LOAD:
3487 buffer_add_typeid (&buf, domain, arg);
3489 case EVENT_KIND_BREAKPOINT:
3490 case EVENT_KIND_STEP:
3491 buffer_add_methodid (&buf, domain, arg);
3492 buffer_add_long (&buf, il_offset);
3494 case EVENT_KIND_VM_START:
3495 buffer_add_domainid (&buf, mono_get_root_domain ());
3497 case EVENT_KIND_VM_DEATH:
3499 case EVENT_KIND_EXCEPTION: {
3500 EventInfo *ei = arg;
3501 buffer_add_objid (&buf, ei->exc);
3504 case EVENT_KIND_USER_BREAK:
3506 case EVENT_KIND_USER_LOG: {
3507 EventInfo *ei = arg;
3508 buffer_add_int (&buf, ei->level);
3509 buffer_add_string (&buf, ei->category ? ei->category : "");
3510 buffer_add_string (&buf, ei->message ? ei->message : "");
3513 case EVENT_KIND_KEEPALIVE:
3514 suspend_policy = SUSPEND_POLICY_NONE;
3517 g_assert_not_reached ();
3521 if (event == EVENT_KIND_VM_START) {
3522 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3523 if (!agent_config.defer)
3524 start_debugger_thread ();
3527 if (event == EVENT_KIND_VM_DEATH) {
3528 vm_death_event_sent = TRUE;
3529 suspend_policy = SUSPEND_POLICY_NONE;
3532 if (mono_runtime_is_shutting_down ())
3533 suspend_policy = SUSPEND_POLICY_NONE;
3535 if (suspend_policy != SUSPEND_POLICY_NONE) {
3537 * Save the thread context and start suspending before sending the packet,
3538 * since we could be receiving the resume request before send_packet ()
3541 save_thread_context (ctx);
3545 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3549 g_slist_free (events);
3552 if (!send_success) {
3553 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3557 if (event == EVENT_KIND_VM_START) {
3558 vm_start_event_sent = TRUE;
3561 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3563 switch (suspend_policy) {
3564 case SUSPEND_POLICY_NONE:
3566 case SUSPEND_POLICY_ALL:
3569 case SUSPEND_POLICY_EVENT_THREAD:
3573 g_assert_not_reached ();
3578 process_profiler_event (EventKind event, gpointer arg)
3582 EventInfo ei, *ei_arg = NULL;
3584 if (event == EVENT_KIND_TYPE_LOAD) {
3589 mono_loader_lock ();
3590 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3591 mono_loader_unlock ();
3593 process_event (event, arg, 0, NULL, events, suspend_policy);
3597 runtime_initialized (MonoProfiler *prof)
3599 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3600 if (agent_config.defer)
3601 start_debugger_thread ();
3605 runtime_shutdown (MonoProfiler *prof)
3607 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3609 mono_debugger_agent_cleanup ();
3613 thread_startup (MonoProfiler *prof, uintptr_t tid)
3615 MonoInternalThread *thread = mono_thread_internal_current ();
3616 MonoInternalThread *old_thread;
3617 DebuggerTlsData *tls;
3619 if (tid == debugger_thread_id)
3622 g_assert (thread->tid == tid);
3624 mono_loader_lock ();
3625 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3626 mono_loader_unlock ();
3628 if (thread == old_thread) {
3630 * For some reason, thread_startup () might be called for the same thread
3631 * multiple times (attach ?).
3633 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3637 * thread_end () might not be called for some threads, and the tid could
3640 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3641 mono_loader_lock ();
3642 mono_g_hash_table_remove (thread_to_tls, old_thread);
3643 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3644 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3645 mono_loader_unlock ();
3649 tls = mono_native_tls_get_value (debugger_tls_id);
3651 // FIXME: Free this somewhere
3652 tls = g_new0 (DebuggerTlsData, 1);
3653 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3654 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3655 tls->thread = thread;
3656 mono_native_tls_set_value (debugger_tls_id, tls);
3658 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3660 mono_loader_lock ();
3661 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3662 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3663 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3664 mono_loader_unlock ();
3666 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3669 * suspend_vm () could have missed this thread, so wait for a resume.
3675 thread_end (MonoProfiler *prof, uintptr_t tid)
3677 MonoInternalThread *thread;
3678 DebuggerTlsData *tls = NULL;
3680 mono_loader_lock ();
3681 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3683 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3684 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3686 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3687 tls->terminated = TRUE;
3688 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3689 MONO_GC_UNREGISTER_ROOT (tls->thread);
3693 mono_loader_unlock ();
3695 /* We might be called for threads started before we registered the start callback */
3697 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3698 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3703 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3705 mono_loader_lock ();
3706 g_hash_table_insert (domains, domain, domain);
3707 mono_loader_unlock ();
3709 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3713 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3715 clear_breakpoints_for_domain (domain);
3717 mono_loader_lock ();
3718 /* Invalidate each thread's frame stack */
3719 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3720 mono_loader_unlock ();
3722 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3726 * invalidate_each_thread:
3728 * A GHFunc to invalidate frames.
3729 * value must be a DebuggerTlsData*
3732 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3734 invalidate_frames (value);
3738 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3740 /* Sent later in jit_end () */
3741 mono_loader_lock ();
3742 g_ptr_array_add (pending_assembly_loads, assembly);
3743 mono_loader_unlock ();
3747 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3749 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3751 clear_event_requests_for_assembly (assembly);
3752 clear_types_for_assembly (assembly);
3756 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3758 #if defined(HOST_WIN32) && !defined(__GNUC__)
3759 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3761 gpointer stackptr = __builtin_frame_address (1);
3763 MonoInternalThread *thread = mono_thread_internal_current ();
3764 DebuggerTlsData *tls;
3766 mono_loader_lock ();
3768 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3769 /* Could be the debugger thread with assembly/type load hooks */
3771 tls->invoke_addr = stackptr;
3773 mono_loader_unlock ();
3777 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3780 #if defined(HOST_WIN32) && !defined(__GNUC__)
3781 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3783 gpointer stackptr = __builtin_frame_address (1);
3786 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3790 * We need to stop single stepping when exiting a runtime invoke, since if it is
3791 * a step out, it may return to native code, and thus never end.
3793 mono_loader_lock ();
3794 ss_invoke_addr = NULL;
3796 for (i = 0; i < event_requests->len; ++i) {
3797 EventRequest *req = g_ptr_array_index (event_requests, i);
3799 if (req->event_kind == EVENT_KIND_STEP) {
3800 ss_destroy (req->info);
3801 g_ptr_array_remove_index_fast (event_requests, i);
3806 mono_loader_unlock ();
3810 send_type_load (MonoClass *klass)
3812 gboolean type_load = FALSE;
3813 MonoDomain *domain = mono_domain_get ();
3814 AgentDomainInfo *info = NULL;
3816 mono_loader_lock ();
3817 mono_domain_lock (domain);
3819 info = get_agent_domain_info (domain);
3821 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3823 g_hash_table_insert (info->loaded_classes, klass, klass);
3826 mono_domain_unlock (domain);
3827 mono_loader_unlock ();
3829 emit_type_load (klass, klass, NULL);
3833 * Emit load events for all types currently loaded in the domain.
3834 * Takes the loader and domain locks.
3835 * user_data is unused.
3838 send_types_for_domain (MonoDomain *domain, void *user_data)
3840 AgentDomainInfo *info = NULL;
3842 mono_loader_lock ();
3843 mono_domain_lock (domain);
3844 info = get_agent_domain_info (domain);
3846 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3847 mono_domain_unlock (domain);
3848 mono_loader_unlock ();
3852 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3855 * We emit type load events when the first method of the type is JITted,
3856 * since the class load profiler callbacks might be called with the
3857 * loader lock held. They could also occur in the debugger thread.
3858 * Same for assembly load events.
3861 MonoAssembly *assembly = NULL;
3863 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3864 mono_loader_lock ();
3865 if (pending_assembly_loads->len > 0) {
3866 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3867 g_ptr_array_remove_index (pending_assembly_loads, 0);
3869 mono_loader_unlock ();
3872 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3878 send_type_load (method->klass);
3881 add_pending_breakpoints (method, jinfo);
3885 * BREAKPOINTS/SINGLE STEPPING
3889 * Contains information about an inserted breakpoint.
3892 long il_offset, native_offset;
3897 } BreakpointInstance;
3900 * Contains generic information about a breakpoint.
3904 * The method where the breakpoint is placed. Can be NULL in which case it
3905 * is inserted into every method. This is used to implement method entry/
3906 * exit events. Can be a generic method definition, in which case the
3907 * breakpoint is inserted into every instance.
3913 * A list of BreakpointInstance structures describing where the breakpoint
3914 * was inserted. There could be more than one because of
3915 * generics/appdomains/method entry/exit.
3917 GPtrArray *children;
3920 /* List of breakpoints */
3921 static GPtrArray *breakpoints;
3922 /* Maps breakpoint locations to the number of breakpoints at that location */
3923 static GHashTable *bp_locs;
3926 breakpoints_init (void)
3928 breakpoints = g_ptr_array_new ();
3929 bp_locs = g_hash_table_new (NULL, NULL);
3933 * insert_breakpoint:
3935 * Insert the breakpoint described by BP into the method described by
3939 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3942 BreakpointInstance *inst;
3943 SeqPoint *sp = NULL;
3946 mono_error_init (error);
3948 for (i = 0; i < seq_points->len; ++i) {
3949 sp = &seq_points->seq_points [i];
3951 if (sp->il_offset == bp->il_offset)
3955 if (i == seq_points->len) {
3957 * The set of IL offsets with seq points doesn't completely match the
3958 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3960 for (i = 0; i < seq_points->len; ++i) {
3961 sp = &seq_points->seq_points [i];
3963 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3968 if (i == seq_points->len) {
3969 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);
3971 for (i = 0; i < seq_points->len; ++i)
3972 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
3975 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3984 inst = g_new0 (BreakpointInstance, 1);
3986 inst->native_offset = sp->native_offset;
3987 inst->ip = (guint8*)ji->code_start + sp->native_offset;
3989 inst->domain = domain;
3991 mono_loader_lock ();
3993 g_ptr_array_add (bp->children, inst);
3995 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3996 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3997 mono_loader_unlock ();
4000 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4001 mono_arch_set_breakpoint (ji, inst->ip);
4007 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4011 remove_breakpoint (BreakpointInstance *inst)
4013 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4015 MonoJitInfo *ji = inst->ji;
4016 guint8 *ip = inst->ip;
4018 mono_loader_lock ();
4019 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4020 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4021 mono_loader_unlock ();
4023 g_assert (count > 0);
4026 mono_arch_clear_breakpoint (ji, ip);
4033 static inline gboolean
4034 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4040 if (method == bp->method)
4042 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4045 if (bp->method->is_inflated && method->is_inflated) {
4046 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4047 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4049 /* Open generic methods should match closed generic methods of the same class */
4050 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4051 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4052 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4054 /* FIXME: Handle !mvar */
4055 if (t1->type != MONO_TYPE_MVAR)
4066 * add_pending_breakpoints:
4068 * Insert pending breakpoints into the newly JITted method METHOD.
4071 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4074 MonoSeqPointInfo *seq_points;
4080 domain = mono_domain_get ();
4082 mono_loader_lock ();
4084 for (i = 0; i < breakpoints->len; ++i) {
4085 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4086 gboolean found = FALSE;
4088 if (!bp_matches_method (bp, method))
4091 for (j = 0; j < bp->children->len; ++j) {
4092 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4099 mono_domain_lock (domain);
4100 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4101 if (!seq_points && ji->method->is_inflated)
4102 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4103 mono_domain_unlock (domain);
4105 /* Could be AOT code */
4107 g_assert (seq_points);
4109 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4113 mono_loader_unlock ();
4117 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4123 mono_error_init (error);
4125 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4127 /* Might be AOTed code */
4128 code = mono_aot_get_method (domain, method);
4130 ji = mono_jit_info_table_find (domain, code);
4135 insert_breakpoint (seq_points, domain, ji, bp, error);
4139 clear_breakpoint (MonoBreakpoint *bp);
4144 * Set a breakpoint at IL_OFFSET in METHOD.
4145 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4146 * METHOD can also be a generic method definition, in which case a breakpoint
4147 * is placed in all instances of the method.
4148 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4151 static MonoBreakpoint*
4152 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4155 GHashTableIter iter, iter2;
4158 MonoSeqPointInfo *seq_points;
4161 mono_error_init (error);
4164 // - suspend/resume the vm to prevent code patching problems
4165 // - multiple breakpoints on the same location
4166 // - dynamic methods
4169 bp = g_new0 (MonoBreakpoint, 1);
4170 bp->method = method;
4171 bp->il_offset = il_offset;
4173 bp->children = g_ptr_array_new ();
4175 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));
4177 mono_loader_lock ();
4179 g_hash_table_iter_init (&iter, domains);
4180 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4181 mono_domain_lock (domain);
4183 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4184 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4185 if (bp_matches_method (bp, m))
4186 set_bp_in_method (domain, m, seq_points, bp, error);
4189 mono_domain_unlock (domain);
4192 mono_loader_unlock ();
4194 mono_loader_lock ();
4195 g_ptr_array_add (breakpoints, bp);
4196 mono_loader_unlock ();
4198 if (error && !mono_error_ok (error)) {
4199 clear_breakpoint (bp);
4207 clear_breakpoint (MonoBreakpoint *bp)
4211 // FIXME: locking, races
4212 for (i = 0; i < bp->children->len; ++i) {
4213 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4215 remove_breakpoint (inst);
4220 mono_loader_lock ();
4221 g_ptr_array_remove (breakpoints, bp);
4222 mono_loader_unlock ();
4224 g_ptr_array_free (bp->children, TRUE);
4229 breakpoints_cleanup (void)
4233 mono_loader_lock ();
4235 while (i < event_requests->len) {
4236 EventRequest *req = g_ptr_array_index (event_requests, i);
4238 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4239 clear_breakpoint (req->info);
4240 g_ptr_array_remove_index_fast (event_requests, i);
4247 for (i = 0; i < breakpoints->len; ++i)
4248 g_free (g_ptr_array_index (breakpoints, i));
4250 g_ptr_array_free (breakpoints, TRUE);
4251 g_hash_table_destroy (bp_locs);
4256 mono_loader_unlock ();
4260 * clear_breakpoints_for_domain:
4262 * Clear breakpoint instances which reference DOMAIN.
4265 clear_breakpoints_for_domain (MonoDomain *domain)
4269 /* This could be called after shutdown */
4273 mono_loader_lock ();
4274 for (i = 0; i < breakpoints->len; ++i) {
4275 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4278 while (j < bp->children->len) {
4279 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4281 if (inst->domain == domain) {
4282 remove_breakpoint (inst);
4286 g_ptr_array_remove_index_fast (bp->children, j);
4292 mono_loader_unlock ();
4296 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4298 return bp->method && bp->method->klass->image->assembly == assembly;
4302 process_breakpoint_inner (DebuggerTlsData *tls)
4306 int i, j, suspend_policy;
4307 guint32 native_offset;
4309 BreakpointInstance *inst;
4310 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4311 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4312 EventKind kind = EVENT_KIND_BREAKPOINT;
4313 MonoContext *ctx = &tls->restore_ctx;
4314 MonoSeqPointInfo *info;
4317 // FIXME: Speed this up
4319 ip = MONO_CONTEXT_GET_IP (ctx);
4320 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4322 g_assert (ji->method);
4324 /* Compute the native offset of the breakpoint from the ip */
4325 native_offset = ip - (guint8*)ji->code_start;
4328 * Skip the instruction causing the breakpoint signal.
4330 mono_arch_skip_breakpoint (ctx, ji);
4332 if (ji->method->wrapper_type || tls->disable_breakpoints)
4335 bp_reqs = g_ptr_array_new ();
4336 ss_reqs = g_ptr_array_new ();
4337 ss_reqs_orig = g_ptr_array_new ();
4339 mono_loader_lock ();
4342 * The ip points to the instruction causing the breakpoint event, which is after
4343 * the offset recorded in the seq point map, so find the prev seq point before ip.
4345 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4347 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));
4350 for (i = 0; i < breakpoints->len; ++i) {
4351 bp = g_ptr_array_index (breakpoints, i);
4356 for (j = 0; j < bp->children->len; ++j) {
4357 inst = g_ptr_array_index (bp->children, j);
4358 if (inst->ji == ji && inst->sp == sp) {
4359 if (bp->req->event_kind == EVENT_KIND_STEP) {
4360 g_ptr_array_add (ss_reqs_orig, bp->req);
4362 g_ptr_array_add (bp_reqs, bp->req);
4367 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4368 /* Maybe a method entry/exit event */
4369 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4370 kind = EVENT_KIND_METHOD_ENTRY;
4371 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4372 kind = EVENT_KIND_METHOD_EXIT;
4375 /* Process single step requests */
4376 for (i = 0; i < ss_reqs_orig->len; ++i) {
4377 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4378 SingleStepReq *ss_req = req->info;
4379 gboolean hit = TRUE;
4381 if (ss_req->size == STEP_SIZE_LINE) {
4382 /* Have to check whenever a different source line was reached */
4383 MonoDebugMethodInfo *minfo;
4384 MonoDebugSourceLocation *loc = NULL;
4386 minfo = mono_debug_lookup_method (ji->method);
4389 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4391 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4392 /* Have to continue single stepping */
4393 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4398 ss_req->last_method = ji->method;
4399 ss_req->last_line = loc->row;
4400 mono_debug_free_source_location (loc);
4405 g_ptr_array_add (ss_reqs, req);
4407 /* Start single stepping again from the current sequence point */
4408 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4411 if (ss_reqs->len > 0)
4412 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4413 if (bp_reqs->len > 0)
4414 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4415 if (kind != EVENT_KIND_BREAKPOINT)
4416 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4418 mono_loader_unlock ();
4420 g_ptr_array_free (bp_reqs, TRUE);
4421 g_ptr_array_free (ss_reqs, TRUE);
4424 * FIXME: The first event will suspend, so the second will only be sent after the
4428 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4430 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4431 if (enter_leave_events)
4432 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4435 /* Process a breakpoint/single step event after resuming from a signal handler */
4437 process_signal_event (void (*func) (DebuggerTlsData*))
4439 DebuggerTlsData *tls;
4440 MonoContext orig_restore_ctx, ctx;
4441 static void (*restore_context) (void *);
4443 if (!restore_context)
4444 restore_context = mono_get_restore_context ();
4446 tls = mono_native_tls_get_value (debugger_tls_id);
4447 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4448 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4449 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4453 /* This is called when resuming from a signal handler, so it shouldn't return */
4454 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4455 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4456 restore_context (&ctx);
4457 g_assert_not_reached ();
4461 process_breakpoint (void)
4463 process_signal_event (process_breakpoint_inner);
4467 resume_from_signal_handler (void *sigctx, void *func)
4469 DebuggerTlsData *tls;
4472 /* Save the original context in TLS */
4473 // FIXME: This might not work on an altstack ?
4474 tls = mono_native_tls_get_value (debugger_tls_id);
4477 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4478 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4479 // clob:c could be added to op_seq_point.
4481 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4482 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4483 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4484 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4486 MONO_CONTEXT_SET_IP (&ctx, func);
4488 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4490 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4491 mono_ppc_set_func_into_sigctx (sigctx, func);
4496 mono_debugger_agent_breakpoint_hit (void *sigctx)
4499 * We are called from a signal handler, and running code there causes all kinds of
4500 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4501 * So set up the signal context to return to the real breakpoint handler function.
4503 resume_from_signal_handler (sigctx, process_breakpoint);
4507 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4509 if (frame->managed) {
4510 *(MonoContext*)data = *ctx;
4519 * Called by System.Diagnostics.Debugger:Break ().
4522 mono_debugger_agent_user_break (void)
4524 if (agent_config.enabled) {
4529 /* Obtain a context */
4530 MONO_CONTEXT_SET_IP (&ctx, NULL);
4531 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4532 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4534 mono_loader_lock ();
4535 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4536 mono_loader_unlock ();
4538 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4545 ss_depth_to_string (StepDepth depth)
4548 case STEP_DEPTH_OVER:
4550 case STEP_DEPTH_OUT:
4552 case STEP_DEPTH_INTO:
4555 g_assert_not_reached ();
4561 process_single_step_inner (DebuggerTlsData *tls)
4566 int il_offset, suspend_policy;
4569 MonoContext *ctx = &tls->restore_ctx;
4571 MonoSeqPointInfo *info;
4573 ip = MONO_CONTEXT_GET_IP (ctx);
4575 /* Skip the instruction causing the single step */
4576 mono_arch_skip_single_step (ctx);
4578 if (suspend_count > 0) {
4579 process_suspend (tls, ctx);
4584 // FIXME: A suspend race
4587 if (mono_thread_internal_current () != ss_req->thread)
4590 if (log_level > 0) {
4591 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4593 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));
4596 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4598 g_assert (ji->method);
4600 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4605 * Stopping in memset makes half-initialized vtypes visible.
4606 * Stopping in memcpy makes half-copied vtypes visible.
4608 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4612 * The ip points to the instruction causing the single step event, which is before
4613 * the offset recorded in the seq point map, so find the next seq point after ip.
4615 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4618 il_offset = sp->il_offset;
4620 // FIXME: No tests fail if this is disabled
4622 if (ss_req->size == STEP_SIZE_LINE) {
4626 /* Step until a different source line is reached */
4627 MonoDebugMethodInfo *minfo;
4629 minfo = mono_debug_lookup_method (ji->method);
4632 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4634 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4635 mono_debug_free_source_location (loc);
4640 * Step until we reach a location with line number info,
4641 * otherwise the client can't show a location.
4642 * This can happen for example with statics initialized inline
4643 * outside of a cctor.
4648 ss_req->last_method = ji->method;
4649 ss_req->last_line = loc->row;
4650 mono_debug_free_source_location (loc);
4656 /* Start single stepping again from the current sequence point */
4657 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4659 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4660 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4661 !strcmp (ji->method->name, ".cctor"))
4664 // FIXME: Has to lock earlier
4666 reqs = g_ptr_array_new ();
4668 mono_loader_lock ();
4670 g_ptr_array_add (reqs, ss_req->req);
4672 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4674 g_ptr_array_free (reqs, TRUE);
4676 mono_loader_unlock ();
4678 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4682 process_single_step (void)
4684 process_signal_event (process_single_step_inner);
4688 * mono_debugger_agent_single_step_event:
4690 * Called from a signal handler to handle a single step event.
4693 mono_debugger_agent_single_step_event (void *sigctx)
4695 /* Resume to process_single_step through the signal context */
4697 // FIXME: Since step out/over is implemented using step in, the step in case should
4698 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4701 if (GetCurrentThreadId () == debugger_thread_id) {
4703 * This could happen despite our best effors when the runtime calls
4704 * assembly/type resolve hooks.
4705 * FIXME: Breakpoints too.
4709 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4710 mono_arch_skip_single_step (&ctx);
4711 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4715 resume_from_signal_handler (sigctx, process_single_step);
4719 debugger_agent_single_step_from_context (MonoContext *ctx)
4721 DebuggerTlsData *tls;
4722 MonoContext orig_restore_ctx;
4724 tls = mono_native_tls_get_value (debugger_tls_id);
4727 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4728 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4729 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4731 process_single_step_inner (tls);
4733 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4734 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4738 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4740 DebuggerTlsData *tls;
4741 MonoContext orig_restore_ctx;
4743 tls = mono_native_tls_get_value (debugger_tls_id);
4745 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4746 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4748 process_breakpoint_inner (tls);
4750 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4751 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4755 * start_single_stepping:
4757 * Turn on single stepping. Can be called multiple times, for example,
4758 * by a single step event request + a suspend.
4761 start_single_stepping (void)
4763 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4764 int val = InterlockedIncrement (&ss_count);
4767 mono_arch_start_single_stepping ();
4769 if (ss_req != NULL && ss_invoke_addr == NULL) {
4770 DebuggerTlsData *tls;
4772 mono_loader_lock ();
4774 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4775 ss_invoke_addr = tls->invoke_addr;
4777 mono_loader_unlock ();
4780 g_assert_not_reached ();
4785 stop_single_stepping (void)
4787 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4788 int val = InterlockedDecrement (&ss_count);
4791 mono_arch_stop_single_stepping ();
4793 g_assert_not_reached ();
4800 * Stop the single stepping operation given by SS_REQ.
4803 ss_stop (SingleStepReq *ss_req)
4808 for (l = ss_req->bps; l; l = l->next) {
4809 clear_breakpoint (l->data);
4811 g_slist_free (ss_req->bps);
4815 if (ss_req->global) {
4816 stop_single_stepping ();
4817 ss_req->global = FALSE;
4824 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4825 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4826 * belong to the same thread as CTX.
4829 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4831 int i, j, frame_index;
4834 gboolean enable_global = FALSE;
4836 /* Stop the previous operation */
4840 * Implement single stepping using breakpoints if possible.
4842 if (step_to_catch) {
4843 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4844 ss_req->bps = g_slist_append (ss_req->bps, bp);
4848 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4849 /* Need parent frames */
4850 if (!tls->context.valid)
4851 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4852 compute_frame_info (tls->thread, tls);
4856 * Find the first sequence point in the current or in a previous frame which
4857 * is not the last in its method.
4859 if (ss_req->depth == STEP_DEPTH_OUT) {
4860 /* Ignore seq points in current method */
4861 while (frame_index < tls->frame_count) {
4862 StackFrame *frame = tls->frames [frame_index];
4864 method = frame->method;
4865 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4867 if (sp && sp->next_len != 0)
4870 // There could be method calls before the next seq point in the caller when using nested calls
4871 //enable_global = TRUE;
4873 while (sp && sp->next_len == 0) {
4875 if (frame_index < tls->frame_count) {
4876 StackFrame *frame = tls->frames [frame_index];
4878 method = frame->method;
4879 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4885 if (sp && sp->next_len > 0) {
4886 for (i = 0; i < sp->next_len; ++i) {
4887 next_sp = &info->seq_points [sp->next [i]];
4889 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4890 ss_req->bps = g_slist_append (ss_req->bps, bp);
4894 if (ss_req->depth == STEP_DEPTH_OVER) {
4895 /* Need to stop in catch clauses as well */
4896 for (i = 0; i < tls->frame_count; ++i) {
4897 StackFrame *frame = tls->frames [i];
4900 MonoJitInfo *jinfo = frame->ji;
4901 for (j = 0; j < jinfo->num_clauses; ++j) {
4902 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4904 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4906 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4907 ss_req->bps = g_slist_append (ss_req->bps, bp);
4915 if (ss_req->depth == STEP_DEPTH_INTO) {
4916 /* Enable global stepping so we stop at method entry too */
4917 enable_global = TRUE;
4921 * The ctx/frame info computed above will become invalid when we continue.
4923 tls->context.valid = FALSE;
4924 tls->async_state.valid = FALSE;
4925 invalidate_frames (tls);
4928 if (enable_global) {
4929 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4930 ss_req->global = TRUE;
4931 start_single_stepping ();
4932 } else if (!ss_req->bps) {
4933 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4934 ss_req->global = TRUE;
4935 start_single_stepping ();
4937 ss_req->global = FALSE;
4942 * Start single stepping of thread THREAD
4945 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4947 DebuggerTlsData *tls;
4948 MonoSeqPointInfo *info = NULL;
4949 SeqPoint *sp = NULL;
4950 MonoMethod *method = NULL;
4951 MonoDebugMethodInfo *minfo;
4952 gboolean step_to_catch = FALSE;
4954 if (suspend_count == 0)
4955 return ERR_NOT_SUSPENDED;
4957 wait_for_suspend ();
4959 // FIXME: Multiple requests
4961 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4962 return ERR_NOT_IMPLEMENTED;
4965 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4967 ss_req = g_new0 (SingleStepReq, 1);
4969 ss_req->thread = thread;
4970 ss_req->size = size;
4971 ss_req->depth = depth;
4974 mono_loader_lock ();
4975 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4976 mono_loader_unlock ();
4978 g_assert (tls->context.valid);
4979 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4981 if (tls->has_catch_ctx) {
4983 StackFrameInfo frame;
4984 MonoContext new_ctx;
4985 MonoLMF *lmf = NULL;
4988 * We are stopped at a throw site. Stepping should go to the catch site.
4991 /* Find the the jit info for the catch context */
4992 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4994 g_assert (frame.type == FRAME_TYPE_MANAGED);
4997 * Find the seq point corresponding to the landing site ip, which is the first seq
5000 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5003 method = frame.method;
5005 step_to_catch = TRUE;
5006 /* This make sure the seq point is not skipped by process_single_step () */
5007 ss_req->last_sp = NULL;
5010 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5013 /* Compute the initial line info */
5014 compute_frame_info (thread, tls);
5016 if (tls->frame_count) {
5017 frame = tls->frames [0];
5019 ss_req->last_method = frame->method;
5020 ss_req->last_line = -1;
5022 minfo = mono_debug_lookup_method (frame->method);
5023 if (minfo && frame->il_offset != -1) {
5024 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5027 ss_req->last_line = loc->row;
5034 if (!step_to_catch) {
5037 compute_frame_info (thread, tls);
5039 if (tls->frame_count) {
5040 frame = tls->frames [0];
5042 if (!method && frame->il_offset != -1) {
5043 /* FIXME: Sort the table and use a binary search */
5044 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5046 method = frame->method;
5051 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5057 ss_destroy (SingleStepReq *req)
5060 g_assert (ss_req == req);
5069 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5072 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5078 if (!agent_config.enabled)
5081 mono_loader_lock ();
5082 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5083 mono_loader_unlock ();
5086 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5087 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5089 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5091 g_free (ei.category);
5092 g_free (ei.message);
5096 mono_debugger_agent_debug_log_is_enabled (void)
5098 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5099 return agent_config.enabled;
5103 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5104 MonoContext *catch_ctx)
5110 DebuggerTlsData *tls = NULL;
5112 if (thread_to_tls != NULL) {
5113 MonoInternalThread *thread = mono_thread_internal_current ();
5115 mono_loader_lock ();
5116 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5117 mono_loader_unlock ();
5119 if (tls && tls->abort_requested)
5121 if (tls && tls->disable_breakpoints)
5125 memset (&ei, 0, sizeof (EventInfo));
5127 /* Just-In-Time debugging */
5129 if (agent_config.onuncaught && !inited) {
5130 finish_agent_init (FALSE);
5133 * Send an unsolicited EXCEPTION event with a dummy request id.
5135 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5136 ei.exc = (MonoObject*)exc;
5137 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5140 } else if (agent_config.onthrow && !inited) {
5142 gboolean found = FALSE;
5144 for (l = agent_config.onthrow; l; l = l->next) {
5145 char *ex_type = l->data;
5146 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5148 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5155 finish_agent_init (FALSE);
5158 * Send an unsolicited EXCEPTION event with a dummy request id.
5160 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5161 ei.exc = (MonoObject*)exc;
5162 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5170 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5172 ei.exc = (MonoObject*)exc;
5173 ei.caught = catch_ctx != NULL;
5175 mono_loader_lock ();
5176 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5177 mono_loader_unlock ();
5179 if (tls && catch_ctx) {
5180 tls->catch_ctx = *catch_ctx;
5181 tls->has_catch_ctx = TRUE;
5184 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5187 tls->has_catch_ctx = FALSE;
5191 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5193 DebuggerTlsData *tls;
5198 tls = mono_native_tls_get_value (debugger_tls_id);
5203 * We're about to invoke an exception filter during the first pass of exception handling.
5205 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5206 * 'orig_ctx' is the context where the exception has been thrown.
5209 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5211 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5212 * the call site (line 37) and then continue to Main(), but it would never
5213 * include the throw site (line 32).
5215 * Since exception filters are invoked during the first pass of exception handling,
5216 * the stack frames of the throw site are still intact, so we should include them
5219 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5221 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5222 * but report the location of the 'throw' to the user.
5226 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5230 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5232 DebuggerTlsData *tls;
5237 tls = mono_native_tls_get_value (debugger_tls_id);
5241 tls->filter_state.valid = FALSE;
5245 * buffer_add_value_full:
5247 * Add the encoding of the value at ADDR described by T to the buffer.
5248 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5252 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5258 g_assert (*(void**)addr);
5259 addr = *(void**)addr;
5264 case MONO_TYPE_BOOLEAN:
5267 case MONO_TYPE_CHAR:
5287 case MONO_TYPE_VOID:
5288 buffer_add_byte (buf, t->type);
5290 case MONO_TYPE_BOOLEAN:
5293 buffer_add_byte (buf, t->type);
5294 buffer_add_int (buf, *(gint8*)addr);
5296 case MONO_TYPE_CHAR:
5299 buffer_add_byte (buf, t->type);
5300 buffer_add_int (buf, *(gint16*)addr);
5305 buffer_add_byte (buf, t->type);
5306 buffer_add_int (buf, *(gint32*)addr);
5311 buffer_add_byte (buf, t->type);
5312 buffer_add_long (buf, *(gint64*)addr);
5316 /* Treat it as a vtype */
5318 case MONO_TYPE_PTR: {
5319 gssize val = *(gssize*)addr;
5321 buffer_add_byte (buf, t->type);
5322 buffer_add_long (buf, val);
5326 case MONO_TYPE_STRING:
5327 case MONO_TYPE_SZARRAY:
5328 case MONO_TYPE_OBJECT:
5329 case MONO_TYPE_CLASS:
5330 case MONO_TYPE_ARRAY:
5331 obj = *(MonoObject**)addr;
5334 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5336 if (obj->vtable->klass->valuetype) {
5337 t = &obj->vtable->klass->byval_arg;
5338 addr = mono_object_unbox (obj);
5340 } else if (obj->vtable->klass->rank) {
5341 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5342 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5343 buffer_add_byte (buf, MONO_TYPE_CLASS);
5345 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5347 buffer_add_objid (buf, obj);
5351 case MONO_TYPE_VALUETYPE: {
5355 MonoClass *klass = mono_class_from_mono_type (t);
5357 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5358 buffer_add_byte (buf, klass->enumtype);
5359 buffer_add_typeid (buf, domain, klass);
5363 while ((f = mono_class_get_fields (klass, &iter))) {
5364 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5366 if (mono_field_is_deleted (f))
5370 buffer_add_int (buf, nfields);
5373 while ((f = mono_class_get_fields (klass, &iter))) {
5374 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5376 if (mono_field_is_deleted (f))
5378 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5382 case MONO_TYPE_GENERICINST:
5383 if (mono_type_generic_inst_is_valuetype (t)) {
5395 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5397 buffer_add_value_full (buf, t, addr, domain, FALSE);
5401 obj_is_of_type (MonoObject *obj, MonoType *t)
5403 MonoClass *klass = obj->vtable->klass;
5404 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5405 if (klass == mono_defaults.transparent_proxy_class) {
5406 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5407 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5417 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5420 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5424 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5425 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5426 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5427 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5428 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5429 char *name = mono_type_full_name (t);
5430 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5432 return ERR_INVALID_ARGUMENT;
5436 case MONO_TYPE_BOOLEAN:
5437 *(guint8*)addr = decode_int (buf, &buf, limit);
5439 case MONO_TYPE_CHAR:
5440 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5443 *(gint8*)addr = decode_int (buf, &buf, limit);
5446 *(guint8*)addr = decode_int (buf, &buf, limit);
5449 *(gint16*)addr = decode_int (buf, &buf, limit);
5452 *(guint16*)addr = decode_int (buf, &buf, limit);
5455 *(gint32*)addr = decode_int (buf, &buf, limit);
5458 *(guint32*)addr = decode_int (buf, &buf, limit);
5461 *(gint64*)addr = decode_long (buf, &buf, limit);
5464 *(guint64*)addr = decode_long (buf, &buf, limit);
5467 *(guint32*)addr = decode_int (buf, &buf, limit);
5470 *(guint64*)addr = decode_long (buf, &buf, limit);
5473 /* We send these as I8, so we get them back as such */
5474 g_assert (type == MONO_TYPE_I8);
5475 *(gssize*)addr = decode_long (buf, &buf, limit);
5477 case MONO_TYPE_GENERICINST:
5478 if (MONO_TYPE_ISSTRUCT (t)) {
5479 /* The client sends these as a valuetype */
5487 /* We send these as vtypes, so we get them back as such */
5488 g_assert (type == MONO_TYPE_VALUETYPE);
5491 case MONO_TYPE_VALUETYPE: {
5492 gboolean is_enum = decode_byte (buf, &buf, limit);
5496 gpointer iter = NULL;
5499 /* Enums are sent as a normal vtype */
5501 return ERR_NOT_IMPLEMENTED;
5502 klass = decode_typeid (buf, &buf, limit, &d, &err);
5506 if (klass != mono_class_from_mono_type (t))
5507 return ERR_INVALID_ARGUMENT;
5509 nfields = decode_int (buf, &buf, limit);
5510 while ((f = mono_class_get_fields (klass, &iter))) {
5511 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5513 if (mono_field_is_deleted (f))
5515 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5520 g_assert (nfields == 0);
5525 if (MONO_TYPE_IS_REFERENCE (t)) {
5526 if (type == MONO_TYPE_OBJECT) {
5527 int objid = decode_objid (buf, &buf, limit);
5531 err = get_object (objid, (MonoObject**)&obj);
5536 if (!obj_is_of_type (obj, t)) {
5537 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5538 return ERR_INVALID_ARGUMENT;
5541 if (obj && obj->vtable->domain != domain)
5542 return ERR_INVALID_ARGUMENT;
5544 mono_gc_wbarrier_generic_store (addr, obj);
5545 } else if (type == VALUE_TYPE_ID_NULL) {
5546 *(MonoObject**)addr = NULL;
5548 return ERR_INVALID_ARGUMENT;
5562 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5565 int type = decode_byte (buf, &buf, limit);
5567 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5568 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5569 guint8 *nullable_buf;
5572 * First try decoding it as a Nullable`1
5574 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5579 * Then try decoding as a primitive value or null.
5581 if (targ->type == type) {
5582 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5583 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5585 g_free (nullable_buf);
5588 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5589 g_free (nullable_buf);
5592 } else if (type == VALUE_TYPE_ID_NULL) {
5593 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5599 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5603 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5610 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5611 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5614 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5615 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5617 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5619 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5620 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5621 addr += (gint32)var->offset;
5623 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5625 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5627 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5631 g_assert_not_reached ();
5636 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5642 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5643 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5645 if (MONO_TYPE_IS_REFERENCE (t))
5646 size = sizeof (gpointer);
5648 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5651 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5652 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5654 gboolean is_signed = FALSE;
5656 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5661 v = is_signed ? *(gint8*)val : *(guint8*)val;
5664 v = is_signed ? *(gint16*)val : *(guint16*)val;
5667 v = is_signed ? *(gint32*)val : *(guint32*)val;
5670 v = is_signed ? *(gint64*)val : *(guint64*)val;
5673 g_assert_not_reached ();
5679 /* Set value on the stack or in the return ctx */
5680 if (reg_locations [reg]) {
5681 /* Saved on the stack */
5682 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5683 *(reg_locations [reg]) = v;
5686 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5687 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5690 // FIXME: Move these to mono-context.h/c.
5691 mono_arch_context_set_int_reg (ctx, reg, v);
5693 // FIXME: Can't set registers, so we disable linears
5698 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5699 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5700 addr += (gint32)var->offset;
5702 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5705 addr = *(guint8**)addr;
5711 // FIXME: Write barriers
5712 mono_gc_memmove (addr, val, size);
5714 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5718 g_assert_not_reached ();
5723 clear_event_request (int req_id, int etype)
5727 mono_loader_lock ();
5728 for (i = 0; i < event_requests->len; ++i) {
5729 EventRequest *req = g_ptr_array_index (event_requests, i);
5731 if (req->id == req_id && req->event_kind == etype) {
5732 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5733 clear_breakpoint (req->info);
5734 if (req->event_kind == EVENT_KIND_STEP)
5735 ss_destroy (req->info);
5736 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5737 clear_breakpoint (req->info);
5738 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5739 clear_breakpoint (req->info);
5740 g_ptr_array_remove_index_fast (event_requests, i);
5745 mono_loader_unlock ();
5749 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5751 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5752 return breakpoint_matches_assembly (req->info, assembly);
5756 for (i = 0; i < req->nmodifiers; ++i) {
5757 Modifier *m = &req->modifiers [i];
5759 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5761 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5762 for (j = 0; m->data.assemblies [j]; ++j)
5763 if (m->data.assemblies [j] == assembly)
5773 * clear_event_requests_for_assembly:
5775 * Clear all events requests which reference ASSEMBLY.
5778 clear_event_requests_for_assembly (MonoAssembly *assembly)
5783 mono_loader_lock ();
5787 for (i = 0; i < event_requests->len; ++i) {
5788 EventRequest *req = g_ptr_array_index (event_requests, i);
5790 if (event_req_matches_assembly (req, assembly)) {
5791 clear_event_request (req->id, req->event_kind);
5797 mono_loader_unlock ();
5801 * type_comes_from_assembly:
5803 * GHRFunc that returns TRUE if klass comes from assembly
5806 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5808 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5812 * clear_types_for_assembly:
5814 * Clears types from loaded_classes for a given assembly
5817 clear_types_for_assembly (MonoAssembly *assembly)
5819 MonoDomain *domain = mono_domain_get ();
5820 AgentDomainInfo *info = NULL;
5822 mono_loader_lock ();
5823 info = get_agent_domain_info (domain);
5824 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5825 mono_loader_unlock ();
5829 add_thread (gpointer key, gpointer value, gpointer user_data)
5831 MonoInternalThread *thread = value;
5832 Buffer *buf = user_data;
5834 buffer_add_objid (buf, (MonoObject*)thread);
5838 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5840 guint8 *end = invoke->endp;
5843 MonoMethodSignature *sig;
5846 MonoObject *this, *res, *exc;
5849 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5852 MonoStopwatch watch;
5854 if (invoke->method) {
5856 * Invoke this method directly, currently only Environment.Exit () is supported.
5859 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>"));
5860 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5861 g_assert_not_reached ();
5864 m = decode_methodid (p, &p, end, &domain, &err);
5867 sig = mono_method_signature (m);
5869 if (m->klass->valuetype)
5870 this_buf = g_alloca (mono_class_instance_size (m->klass));
5872 this_buf = g_alloca (sizeof (MonoObject*));
5873 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5874 /* Should be null */
5875 int type = decode_byte (p, &p, end);
5876 if (type != VALUE_TYPE_ID_NULL)
5877 return ERR_INVALID_ARGUMENT;
5878 memset (this_buf, 0, mono_class_instance_size (m->klass));
5880 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5885 if (!m->klass->valuetype)
5886 this = *(MonoObject**)this_buf;
5890 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>"));
5892 if (this && this->vtable->domain != domain)
5895 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5896 if (!strcmp (m->name, ".ctor")) {
5897 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5898 return ERR_INVALID_ARGUMENT;
5900 this = mono_object_new (domain, m->klass);
5902 return ERR_INVALID_ARGUMENT;
5906 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
5907 return ERR_INVALID_ARGUMENT;
5909 nargs = decode_int (p, &p, end);
5910 if (nargs != sig->param_count)
5911 return ERR_INVALID_ARGUMENT;
5912 /* Use alloca to get gc tracking */
5913 arg_buf = g_alloca (nargs * sizeof (gpointer));
5914 memset (arg_buf, 0, nargs * sizeof (gpointer));
5915 args = g_alloca (nargs * sizeof (gpointer));
5916 for (i = 0; i < nargs; ++i) {
5917 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5918 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5922 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5925 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5926 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5929 args [i] = arg_buf [i];
5936 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5937 tls->disable_breakpoints = TRUE;
5939 tls->disable_breakpoints = FALSE;
5942 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5944 /* FIXME: Move this to arch specific code */
5945 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5946 if (invoke->has_ctx) {
5949 lmf_addr = mono_get_lmf_addr ();
5952 memset (&ext, 0, sizeof (ext));
5954 ext.lmf.previous_lmf = *(lmf_addr);
5955 /* Mark that this is a MonoLMFExt */
5956 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5957 ext.lmf.rsp = (gssize)&ext;
5958 #elif defined(TARGET_X86)
5959 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5960 /* Mark that this is a MonoLMFExt */
5961 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5962 ext.lmf.ebp = (gssize)&ext;
5963 #elif defined(TARGET_ARM)
5964 ext.lmf.previous_lmf = *(lmf_addr);
5965 /* Mark that this is a MonoLMFExt */
5966 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5967 ext.lmf.sp = (gssize)&ext;
5968 #elif defined(TARGET_POWERPC)
5969 ext.lmf.previous_lmf = *(lmf_addr);
5970 /* Mark that this is a MonoLMFExt */
5971 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5972 ext.lmf.ebp = (gssize)&ext;
5973 #elif defined(TARGET_S390X)
5974 ext.lmf.previous_lmf = *(lmf_addr);
5975 /* Mark that this is a MonoLMFExt */
5976 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5977 ext.lmf.ebp = (gssize)&ext;
5978 #elif defined(TARGET_MIPS)
5979 ext.lmf.previous_lmf = *(lmf_addr);
5980 /* Mark that this is a MonoLMFExt */
5981 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5982 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5984 g_assert_not_reached ();
5987 ext.debugger_invoke = TRUE;
5988 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5990 mono_set_lmf ((MonoLMF*)&ext);
5994 mono_stopwatch_start (&watch);
5995 if (m->klass->valuetype)
5996 res = mono_runtime_invoke (m, this_buf, args, &exc);
5998 res = mono_runtime_invoke (m, this, args, &exc);
5999 mono_stopwatch_stop (&watch);
6000 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)));
6002 buffer_add_byte (buf, 0);
6003 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6005 buffer_add_byte (buf, 1);
6006 if (sig->ret->type == MONO_TYPE_VOID) {
6007 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6008 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6011 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6012 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6013 buffer_add_value (buf, sig->ret, &res, domain);
6014 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6015 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6016 MonoClass *k = mono_class_from_mono_type (sig->ret);
6017 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6019 g_assert (nullable_buf);
6020 mono_nullable_init (nullable_buf, res, k);
6021 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6024 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6031 tls->disable_breakpoints = FALSE;
6033 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6034 if (invoke->has_ctx)
6035 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6039 // FIXME: byref arguments
6047 * Invoke the method given by tls->pending_invoke in the current thread.
6050 invoke_method (void)
6052 DebuggerTlsData *tls;
6057 static void (*restore_context) (void *);
6058 MonoContext restore_ctx;
6061 if (!restore_context)
6062 restore_context = mono_get_restore_context ();
6064 tls = mono_native_tls_get_value (debugger_tls_id);
6068 * Store the `InvokeData *' in `tls->invoke' until we're done with
6069 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6072 mono_loader_lock ();
6074 invoke = tls->pending_invoke;
6076 tls->pending_invoke = NULL;
6078 invoke->last_invoke = tls->invoke;
6079 tls->invoke = invoke;
6081 mono_loader_unlock ();
6083 tls->frames_up_to_date = FALSE;
6089 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6090 buffer_init (&buf, 128);
6093 /* Fail the other invokes as well */
6095 err = do_invoke_method (tls, &buf, invoke, p, &p);
6098 /* Start suspending before sending the reply */
6099 if (mindex == invoke->nmethods - 1) {
6100 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6101 for (i = 0; i < invoke->suspend_count; ++i)
6106 send_reply_packet (id, err, &buf);
6111 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6113 if (invoke->has_ctx)
6114 save_thread_context (&restore_ctx);
6116 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6117 g_assert (tls->resume_count);
6118 tls->resume_count -= invoke->suspend_count;
6121 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6124 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6126 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6127 * after the mono_runtime_invoke() already returned, but it doesn't matter
6128 * because we reset the abort here.
6131 mono_loader_lock ();
6133 if (tls->abort_requested)
6134 mono_thread_internal_reset_abort (tls->thread);
6136 tls->invoke = tls->invoke->last_invoke;
6137 tls->abort_requested = FALSE;
6139 mono_loader_unlock ();
6148 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6150 MonoThread *thread = value;
6151 DebuggerTlsData *tls;
6154 mono_loader_lock ();
6155 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6157 res = tls->really_suspended;
6158 mono_loader_unlock ();
6164 get_source_files_for_type (MonoClass *klass)
6166 gpointer iter = NULL;
6168 MonoDebugSourceInfo *sinfo;
6172 files = g_ptr_array_new ();
6174 while ((method = mono_class_get_methods (klass, &iter))) {
6175 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6176 GPtrArray *source_file_list;
6179 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6180 for (j = 0; j < source_file_list->len; ++j) {
6181 sinfo = g_ptr_array_index (source_file_list, j);
6182 for (i = 0; i < files->len; ++i)
6183 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6185 if (i == files->len)
6186 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6188 g_ptr_array_free (source_file_list, TRUE);
6196 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6199 case CMD_VM_VERSION: {
6200 char *build_info, *version;
6202 build_info = mono_get_runtime_build_info ();
6203 version = g_strdup_printf ("mono %s", build_info);
6205 buffer_add_string (buf, version); /* vm version */
6206 buffer_add_int (buf, MAJOR_VERSION);
6207 buffer_add_int (buf, MINOR_VERSION);
6208 g_free (build_info);
6212 case CMD_VM_SET_PROTOCOL_VERSION: {
6213 major_version = decode_int (p, &p, end);
6214 minor_version = decode_int (p, &p, end);
6215 protocol_version_set = TRUE;
6216 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6219 case CMD_VM_ALL_THREADS: {
6221 mono_loader_lock ();
6222 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6223 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6224 mono_loader_unlock ();
6227 case CMD_VM_SUSPEND:
6229 wait_for_suspend ();
6232 if (suspend_count == 0)
6233 return ERR_NOT_SUSPENDED;
6236 case CMD_VM_DISPOSE:
6237 /* Clear all event requests */
6238 mono_loader_lock ();
6239 while (event_requests->len > 0) {
6240 EventRequest *req = g_ptr_array_index (event_requests, 0);
6242 clear_event_request (req->id, req->event_kind);
6244 mono_loader_unlock ();
6246 while (suspend_count > 0)
6248 disconnected = TRUE;
6249 vm_start_event_sent = FALSE;
6252 MonoInternalThread *thread;
6253 DebuggerTlsData *tls;
6254 MonoClass *env_class;
6255 MonoMethod *exit_method = NULL;
6259 exit_code = decode_int (p, &p, end);
6261 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6263 /* Have to send a reply before exiting */
6264 send_reply_packet (id, 0, buf);
6266 /* Clear all event requests */
6267 mono_loader_lock ();
6268 while (event_requests->len > 0) {
6269 EventRequest *req = g_ptr_array_index (event_requests, 0);
6271 clear_event_request (req->id, req->event_kind);
6273 mono_loader_unlock ();
6276 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6277 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6278 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6279 * better than doing the shutdown ourselves, since it avoids various races.
6283 wait_for_suspend ();
6285 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6287 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6289 mono_loader_lock ();
6290 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6291 mono_loader_unlock ();
6293 if (thread && exit_method) {
6294 mono_loader_lock ();
6295 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6296 mono_loader_unlock ();
6298 args = g_new0 (gpointer, 1);
6299 args [0] = g_malloc (sizeof (int));
6300 *(int*)(args [0]) = exit_code;
6302 tls->pending_invoke = g_new0 (InvokeData, 1);
6303 tls->pending_invoke->method = exit_method;
6304 tls->pending_invoke->args = args;
6305 tls->pending_invoke->nmethods = 1;
6307 while (suspend_count > 0)
6311 * No thread found, do it ourselves.
6312 * FIXME: This can race with normal shutdown etc.
6314 while (suspend_count > 0)
6317 mono_runtime_set_shutting_down ();
6319 mono_threads_set_shutting_down ();
6321 /* Suspend all managed threads since the runtime is going away */
6322 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6323 mono_thread_suspend_all_other_threads ();
6324 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6325 mono_runtime_quit ();
6326 transport_close2 ();
6327 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6333 case CMD_VM_INVOKE_METHOD:
6334 case CMD_VM_INVOKE_METHODS: {
6335 int objid = decode_objid (p, &p, end);
6337 DebuggerTlsData *tls;
6338 int i, count, err, flags, nmethods;
6340 err = get_object (objid, (MonoObject**)&thread);
6344 flags = decode_int (p, &p, end);
6346 if (command == CMD_VM_INVOKE_METHODS)
6347 nmethods = decode_int (p, &p, end);
6351 // Wait for suspending if it already started
6353 wait_for_suspend ();
6354 if (!is_suspended ())
6355 return ERR_NOT_SUSPENDED;
6357 mono_loader_lock ();
6358 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6359 mono_loader_unlock ();
6362 if (!tls->really_suspended)
6363 /* The thread is still running native code, can't do invokes */
6364 return ERR_NOT_SUSPENDED;
6367 * Store the invoke data into tls, the thread will execute it after it is
6370 if (tls->pending_invoke)
6371 return ERR_NOT_SUSPENDED;
6372 tls->pending_invoke = g_new0 (InvokeData, 1);
6373 tls->pending_invoke->id = id;
6374 tls->pending_invoke->flags = flags;
6375 tls->pending_invoke->p = g_malloc (end - p);
6376 memcpy (tls->pending_invoke->p, p, end - p);
6377 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6378 tls->pending_invoke->suspend_count = suspend_count;
6379 tls->pending_invoke->nmethods = nmethods;
6381 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6382 resume_thread (THREAD_TO_INTERNAL (thread));
6385 count = suspend_count;
6386 for (i = 0; i < count; ++i)
6391 case CMD_VM_ABORT_INVOKE: {
6392 int objid = decode_objid (p, &p, end);
6394 DebuggerTlsData *tls;
6397 err = get_object (objid, (MonoObject**)&thread);
6401 invoke_id = decode_int (p, &p, end);
6403 mono_loader_lock ();
6404 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6407 if (tls->abort_requested) {
6408 mono_loader_unlock ();
6413 * Check whether we're still inside the mono_runtime_invoke() and that it's
6414 * actually the correct invocation.
6416 * Careful, we do not stop the thread that's doing the invocation, so we can't
6417 * inspect its stack. However, invoke_method() also acquires the loader lock
6418 * when it's done, so we're safe here.
6422 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6423 mono_loader_unlock ();
6424 return ERR_NO_INVOCATION;
6427 tls->abort_requested = TRUE;
6429 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6430 mono_loader_unlock ();
6434 case CMD_VM_SET_KEEPALIVE: {
6435 int timeout = decode_int (p, &p, end);
6436 agent_config.keepalive = timeout;
6438 #ifndef DISABLE_SOCKET_TRANSPORT
6445 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6446 GHashTableIter iter, kiter;
6451 char *fname, *basename;
6452 gboolean ignore_case;
6453 GSList *class_list, *l;
6454 GPtrArray *res_classes, *res_domains;
6456 fname = decode_string (p, &p, end);
6457 ignore_case = decode_byte (p, &p, end);
6459 basename = g_path_get_basename (fname);
6461 res_classes = g_ptr_array_new ();
6462 res_domains = g_ptr_array_new ();
6464 mono_loader_lock ();
6465 g_hash_table_iter_init (&iter, domains);
6466 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6467 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6469 /* Update 'source_file_to_class' cache */
6470 g_hash_table_iter_init (&kiter, info->loaded_classes);
6471 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6472 if (!g_hash_table_lookup (info->source_files, klass)) {
6473 files = get_source_files_for_type (klass);
6474 g_hash_table_insert (info->source_files, klass, files);
6476 for (i = 0; i < files->len; ++i) {
6477 char *s = g_ptr_array_index (files, i);
6478 char *s2 = g_path_get_basename (s);
6481 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6483 class_list = g_slist_prepend (class_list, klass);
6484 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6486 class_list = g_slist_prepend (class_list, klass);
6487 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6490 /* The _ignorecase hash contains the lowercase path */
6491 s3 = strdup_tolower (s2);
6492 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6494 class_list = g_slist_prepend (class_list, klass);
6495 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6497 class_list = g_slist_prepend (class_list, klass);
6498 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6510 s = strdup_tolower (basename);
6511 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6514 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6517 for (l = class_list; l; l = l->next) {
6520 g_ptr_array_add (res_classes, klass);
6521 g_ptr_array_add (res_domains, domain);
6524 mono_loader_unlock ();
6529 buffer_add_int (buf, res_classes->len);
6530 for (i = 0; i < res_classes->len; ++i)
6531 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6532 g_ptr_array_free (res_classes, TRUE);
6533 g_ptr_array_free (res_domains, TRUE);
6536 case CMD_VM_GET_TYPES: {
6537 GHashTableIter iter;
6541 gboolean ignore_case;
6542 GPtrArray *res_classes, *res_domains;
6543 MonoTypeNameParse info;
6545 name = decode_string (p, &p, end);
6546 ignore_case = decode_byte (p, &p, end);
6548 if (!mono_reflection_parse_type (name, &info)) {
6550 mono_reflection_free_type_info (&info);
6551 return ERR_INVALID_ARGUMENT;
6554 res_classes = g_ptr_array_new ();
6555 res_domains = g_ptr_array_new ();
6557 mono_loader_lock ();
6558 g_hash_table_iter_init (&iter, domains);
6559 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6561 gboolean type_resolve;
6565 mono_domain_assemblies_lock (domain);
6566 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6570 type_resolve = TRUE;
6571 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6573 g_ptr_array_add (res_classes, mono_type_get_class (t));
6574 g_ptr_array_add (res_domains, domain);
6578 mono_domain_assemblies_unlock (domain);
6580 mono_loader_unlock ();
6583 mono_reflection_free_type_info (&info);
6585 buffer_add_int (buf, res_classes->len);
6586 for (i = 0; i < res_classes->len; ++i)
6587 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6588 g_ptr_array_free (res_classes, TRUE);
6589 g_ptr_array_free (res_domains, TRUE);
6594 return ERR_NOT_IMPLEMENTED;
6601 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6607 case CMD_EVENT_REQUEST_SET: {
6609 int i, event_kind, suspend_policy, nmodifiers, mod;
6612 MonoThread *step_thread;
6613 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6617 event_kind = decode_byte (p, &p, end);
6618 suspend_policy = decode_byte (p, &p, end);
6619 nmodifiers = decode_byte (p, &p, end);
6621 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6622 req->id = InterlockedIncrement (&event_request_id);
6623 req->event_kind = event_kind;
6624 req->suspend_policy = suspend_policy;
6625 req->nmodifiers = nmodifiers;
6628 for (i = 0; i < nmodifiers; ++i) {
6629 mod = decode_byte (p, &p, end);
6631 req->modifiers [i].kind = mod;
6632 if (mod == MOD_KIND_COUNT) {
6633 req->modifiers [i].data.count = decode_int (p, &p, end);
6634 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6635 method = decode_methodid (p, &p, end, &domain, &err);
6638 location = decode_long (p, &p, end);
6639 } else if (mod == MOD_KIND_STEP) {
6640 step_thread_id = decode_id (p, &p, end);
6641 size = decode_int (p, &p, end);
6642 depth = decode_int (p, &p, end);
6643 if (CHECK_PROTOCOL_VERSION (2, 16))
6644 filter = decode_int (p, &p, end);
6645 req->modifiers [i].data.filter = filter;
6646 } else if (mod == MOD_KIND_THREAD_ONLY) {
6647 int id = decode_id (p, &p, end);
6649 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6654 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6655 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6659 req->modifiers [i].caught = decode_byte (p, &p, end);
6660 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6661 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" : ""));
6663 req->modifiers [i].data.exc_class = exc_class;
6665 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6667 return ERR_INVALID_ARGUMENT;
6670 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6671 int n = decode_int (p, &p, end);
6674 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6675 for (j = 0; j < n; ++j) {
6676 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6678 g_free (req->modifiers [i].data.assemblies);
6682 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6683 int n = decode_int (p, &p, end);
6686 modifier = &req->modifiers [i];
6687 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6688 for (j = 0; j < n; ++j) {
6689 char *s = decode_string (p, &p, end);
6693 s2 = strdup_tolower (s);
6694 g_hash_table_insert (modifier->data.source_files, s2, s2);
6698 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6699 int n = decode_int (p, &p, end);
6702 modifier = &req->modifiers [i];
6703 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6704 for (j = 0; j < n; ++j) {
6705 char *s = decode_string (p, &p, end);
6708 g_hash_table_insert (modifier->data.type_names, s, s);
6712 return ERR_NOT_IMPLEMENTED;
6716 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6719 req->info = set_breakpoint (method, location, req, &error);
6720 if (!mono_error_ok (&error)) {
6722 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6723 mono_error_cleanup (&error);
6724 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6726 } else if (req->event_kind == EVENT_KIND_STEP) {
6727 g_assert (step_thread_id);
6729 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6735 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6740 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6741 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6742 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6743 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6744 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6745 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6747 if (req->nmodifiers) {
6749 return ERR_NOT_IMPLEMENTED;
6753 mono_loader_lock ();
6754 g_ptr_array_add (event_requests, req);
6756 if (agent_config.defer) {
6757 /* Transmit cached data to the client on receipt of the event request */
6758 switch (req->event_kind) {
6759 case EVENT_KIND_APPDOMAIN_CREATE:
6760 /* Emit load events for currently loaded domains */
6761 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6763 case EVENT_KIND_ASSEMBLY_LOAD:
6764 /* Emit load events for currently loaded assemblies */
6765 mono_assembly_foreach (emit_assembly_load, NULL);
6767 case EVENT_KIND_THREAD_START:
6768 /* Emit start events for currently started threads */
6769 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6771 case EVENT_KIND_TYPE_LOAD:
6772 /* Emit type load events for currently loaded types */
6773 mono_domain_foreach (send_types_for_domain, NULL);
6779 mono_loader_unlock ();
6781 buffer_add_int (buf, req->id);
6784 case CMD_EVENT_REQUEST_CLEAR: {
6785 int etype = decode_byte (p, &p, end);
6786 int req_id = decode_int (p, &p, end);
6788 // FIXME: Make a faster mapping from req_id to request
6789 mono_loader_lock ();
6790 clear_event_request (req_id, etype);
6791 mono_loader_unlock ();
6794 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6797 mono_loader_lock ();
6799 while (i < event_requests->len) {
6800 EventRequest *req = g_ptr_array_index (event_requests, i);
6802 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6803 clear_breakpoint (req->info);
6805 g_ptr_array_remove_index_fast (event_requests, i);
6811 mono_loader_unlock ();
6815 return ERR_NOT_IMPLEMENTED;
6822 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6828 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6829 buffer_add_domainid (buf, mono_get_root_domain ());
6832 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6833 domain = decode_domainid (p, &p, end, NULL, &err);
6836 buffer_add_string (buf, domain->friendly_name);
6839 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6844 domain = decode_domainid (p, &p, end, NULL, &err);
6847 mono_loader_lock ();
6849 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6852 buffer_add_int (buf, count);
6853 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6855 buffer_add_assemblyid (buf, domain, ass);
6857 mono_loader_unlock ();
6860 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6861 domain = decode_domainid (p, &p, end, NULL, &err);
6865 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6868 case CMD_APPDOMAIN_GET_CORLIB: {
6869 domain = decode_domainid (p, &p, end, NULL, &err);
6873 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6876 case CMD_APPDOMAIN_CREATE_STRING: {
6880 domain = decode_domainid (p, &p, end, NULL, &err);
6883 s = decode_string (p, &p, end);
6885 o = mono_string_new (domain, s);
6886 buffer_add_objid (buf, (MonoObject*)o);
6889 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6891 MonoDomain *domain2;
6894 domain = decode_domainid (p, &p, end, NULL, &err);
6897 klass = decode_typeid (p, &p, end, &domain2, &err);
6902 g_assert (domain == domain2);
6904 o = mono_object_new (domain, klass);
6906 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6910 buffer_add_objid (buf, o);
6914 return ERR_NOT_IMPLEMENTED;
6921 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6927 ass = decode_assemblyid (p, &p, end, &domain, &err);
6932 case CMD_ASSEMBLY_GET_LOCATION: {
6933 buffer_add_string (buf, mono_image_get_filename (ass->image));
6936 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6940 if (ass->image->dynamic) {
6941 buffer_add_id (buf, 0);
6943 token = mono_image_get_entry_point (ass->image);
6945 buffer_add_id (buf, 0);
6947 m = mono_get_method (ass->image, token, NULL);
6948 buffer_add_methodid (buf, domain, m);
6953 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6954 buffer_add_moduleid (buf, domain, ass->image);
6957 case CMD_ASSEMBLY_GET_OBJECT: {
6958 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
6959 buffer_add_objid (buf, o);
6962 case CMD_ASSEMBLY_GET_TYPE: {
6963 char *s = decode_string (p, &p, end);
6964 gboolean ignorecase = decode_byte (p, &p, end);
6965 MonoTypeNameParse info;
6967 gboolean type_resolve, res;
6968 MonoDomain *d = mono_domain_get ();
6970 /* This is needed to be able to find referenced assemblies */
6971 res = mono_domain_set (domain, FALSE);
6974 if (!mono_reflection_parse_type (s, &info)) {
6977 if (info.assembly.name)
6979 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6981 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6982 mono_reflection_free_type_info (&info);
6985 mono_domain_set (d, TRUE);
6989 case CMD_ASSEMBLY_GET_NAME: {
6991 MonoAssembly *mass = ass;
6993 name = g_strdup_printf (
6994 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6996 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6997 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6998 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6999 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7001 buffer_add_string (buf, name);
7006 return ERR_NOT_IMPLEMENTED;
7013 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7019 case CMD_MODULE_GET_INFO: {
7020 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7023 basename = g_path_get_basename (image->name);
7024 buffer_add_string (buf, basename); // name
7025 buffer_add_string (buf, image->module_name); // scopename
7026 buffer_add_string (buf, image->name); // fqname
7027 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7028 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7033 return ERR_NOT_IMPLEMENTED;
7040 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7042 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7043 /* Special case these so the client doesn't have to handle Type objects */
7045 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7046 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7047 } else if (MONO_TYPE_IS_REFERENCE (t))
7048 buffer_add_value (buf, t, &val, domain);
7050 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7054 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7060 buffer_add_int (buf, 0);
7064 for (i = 0; i < cinfo->num_attrs; ++i) {
7065 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7068 buffer_add_int (buf, nattrs);
7070 for (i = 0; i < cinfo->num_attrs; ++i) {
7071 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7072 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7073 MonoArray *typed_args, *named_args;
7075 CattrNamedArg *arginfo;
7077 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7079 buffer_add_methodid (buf, domain, attr->ctor);
7083 buffer_add_int (buf, mono_array_length (typed_args));
7084 for (j = 0; j < mono_array_length (typed_args); ++j) {
7085 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7087 t = mono_method_signature (attr->ctor)->params [j];
7089 buffer_add_cattr_arg (buf, t, domain, val);
7092 buffer_add_int (buf, 0);
7097 buffer_add_int (buf, mono_array_length (named_args));
7099 for (j = 0; j < mono_array_length (named_args); ++j) {
7100 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7102 if (arginfo [j].prop) {
7103 buffer_add_byte (buf, 0x54);
7104 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7105 } else if (arginfo [j].field) {
7106 buffer_add_byte (buf, 0x53);
7107 buffer_add_fieldid (buf, domain, arginfo [j].field);
7109 g_assert_not_reached ();
7112 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7115 buffer_add_int (buf, 0);
7121 /* FIXME: Code duplication with icall.c */
7123 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7128 mono_class_setup_interfaces (klass, error);
7129 if (!mono_error_ok (error))
7132 for (i = 0; i < klass->interface_count; i++) {
7133 ic = klass->interfaces [i];
7134 g_hash_table_insert (ifaces, ic, ic);
7136 collect_interfaces (ic, ifaces, error);
7137 if (!mono_error_ok (error))
7143 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7153 case CMD_TYPE_GET_INFO: {
7154 buffer_add_string (buf, klass->name_space);
7155 buffer_add_string (buf, klass->name);
7157 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7158 buffer_add_string (buf, name);
7160 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7161 buffer_add_moduleid (buf, domain, klass->image);
7162 buffer_add_typeid (buf, domain, klass->parent);
7163 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7164 buffer_add_typeid (buf, domain, klass->element_class);
7166 buffer_add_id (buf, 0);
7167 buffer_add_int (buf, klass->type_token);
7168 buffer_add_byte (buf, klass->rank);
7169 buffer_add_int (buf, klass->flags);
7171 type = &klass->byval_arg;
7172 // FIXME: Can't decide whenever a class represents a byref type
7175 if (type->type == MONO_TYPE_PTR)
7177 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7179 if (type->type == MONO_TYPE_VALUETYPE)
7181 if (klass->enumtype)
7183 if (klass->generic_container)
7185 if (klass->generic_container || klass->generic_class)
7187 buffer_add_byte (buf, b);
7190 while ((nested = mono_class_get_nested_types (klass, &iter)))
7192 buffer_add_int (buf, nnested);
7194 while ((nested = mono_class_get_nested_types (klass, &iter)))
7195 buffer_add_typeid (buf, domain, nested);
7196 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7197 if (klass->generic_container)
7198 buffer_add_typeid (buf, domain, klass);
7199 else if (klass->generic_class)
7200 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7202 buffer_add_id (buf, 0);
7204 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7207 if (klass->generic_class) {
7208 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7210 count = inst->type_argc;
7211 buffer_add_int (buf, count);
7212 for (i = 0; i < count; i++)
7213 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7214 } else if (klass->generic_container) {
7215 MonoGenericContainer *container = klass->generic_container;
7218 count = container->type_argc;
7219 buffer_add_int (buf, count);
7220 for (i = 0; i < count; i++) {
7221 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7222 buffer_add_typeid (buf, domain, pklass);
7225 buffer_add_int (buf, 0);
7230 case CMD_TYPE_GET_METHODS: {
7233 gpointer iter = NULL;
7236 mono_class_setup_methods (klass);
7238 nmethods = mono_class_num_methods (klass);
7240 buffer_add_int (buf, nmethods);
7242 while ((m = mono_class_get_methods (klass, &iter))) {
7243 buffer_add_methodid (buf, domain, m);
7246 g_assert (i == nmethods);
7249 case CMD_TYPE_GET_FIELDS: {
7252 gpointer iter = NULL;
7255 nfields = mono_class_num_fields (klass);
7257 buffer_add_int (buf, nfields);
7259 while ((f = mono_class_get_fields (klass, &iter))) {
7260 buffer_add_fieldid (buf, domain, f);
7261 buffer_add_string (buf, f->name);
7262 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7263 buffer_add_int (buf, f->type->attrs);
7266 g_assert (i == nfields);
7269 case CMD_TYPE_GET_PROPERTIES: {
7272 gpointer iter = NULL;
7275 nprops = mono_class_num_properties (klass);
7277 buffer_add_int (buf, nprops);
7279 while ((p = mono_class_get_properties (klass, &iter))) {
7280 buffer_add_propertyid (buf, domain, p);
7281 buffer_add_string (buf, p->name);
7282 buffer_add_methodid (buf, domain, p->get);
7283 buffer_add_methodid (buf, domain, p->set);
7284 buffer_add_int (buf, p->attrs);
7287 g_assert (i == nprops);
7290 case CMD_TYPE_GET_CATTRS: {
7291 MonoClass *attr_klass;
7292 MonoCustomAttrInfo *cinfo;
7294 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7295 /* attr_klass can be NULL */
7299 cinfo = mono_custom_attrs_from_class (klass);
7301 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7304 case CMD_TYPE_GET_FIELD_CATTRS: {
7305 MonoClass *attr_klass;
7306 MonoCustomAttrInfo *cinfo;
7307 MonoClassField *field;
7309 field = decode_fieldid (p, &p, end, NULL, &err);
7312 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7316 cinfo = mono_custom_attrs_from_field (klass, field);
7318 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7321 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7322 MonoClass *attr_klass;
7323 MonoCustomAttrInfo *cinfo;
7326 prop = decode_propertyid (p, &p, end, NULL, &err);
7329 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7333 cinfo = mono_custom_attrs_from_property (klass, prop);
7335 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7338 case CMD_TYPE_GET_VALUES:
7339 case CMD_TYPE_GET_VALUES_2: {
7346 MonoThread *thread_obj;
7347 MonoInternalThread *thread = NULL;
7348 guint32 special_static_type;
7350 if (command == CMD_TYPE_GET_VALUES_2) {
7351 int objid = decode_objid (p, &p, end);
7354 err = get_object (objid, (MonoObject**)&thread_obj);
7358 thread = THREAD_TO_INTERNAL (thread_obj);
7361 len = decode_int (p, &p, end);
7362 for (i = 0; i < len; ++i) {
7363 f = decode_fieldid (p, &p, end, NULL, &err);
7367 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7368 return ERR_INVALID_FIELDID;
7369 special_static_type = mono_class_field_get_special_static_type (f);
7370 if (special_static_type != SPECIAL_STATIC_NONE) {
7371 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7372 return ERR_INVALID_FIELDID;
7375 /* Check that the field belongs to the object */
7377 for (k = klass; k; k = k->parent) {
7378 if (k == f->parent) {
7384 return ERR_INVALID_FIELDID;
7386 vtable = mono_class_vtable (domain, f->parent);
7387 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7388 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7389 buffer_add_value (buf, f->type, val, domain);
7394 case CMD_TYPE_SET_VALUES: {
7402 len = decode_int (p, &p, end);
7403 for (i = 0; i < len; ++i) {
7404 f = decode_fieldid (p, &p, end, NULL, &err);
7408 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7409 return ERR_INVALID_FIELDID;
7410 if (mono_class_field_is_special_static (f))
7411 return ERR_INVALID_FIELDID;
7413 /* Check that the field belongs to the object */
7415 for (k = klass; k; k = k->parent) {
7416 if (k == f->parent) {
7422 return ERR_INVALID_FIELDID;
7424 // FIXME: Check for literal/const
7426 vtable = mono_class_vtable (domain, f->parent);
7427 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7428 err = decode_value (f->type, domain, val, p, &p, end);
7433 if (MONO_TYPE_IS_REFERENCE (f->type))
7434 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7436 mono_field_static_set_value (vtable, f, val);
7441 case CMD_TYPE_GET_OBJECT: {
7442 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7443 buffer_add_objid (buf, o);
7446 case CMD_TYPE_GET_SOURCE_FILES:
7447 case CMD_TYPE_GET_SOURCE_FILES_2: {
7448 char *source_file, *base;
7452 files = get_source_files_for_type (klass);
7454 buffer_add_int (buf, files->len);
7455 for (i = 0; i < files->len; ++i) {
7456 source_file = g_ptr_array_index (files, i);
7457 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7458 buffer_add_string (buf, source_file);
7460 base = g_path_get_basename (source_file);
7461 buffer_add_string (buf, base);
7464 g_free (source_file);
7466 g_ptr_array_free (files, TRUE);
7469 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7470 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7474 if (mono_class_is_assignable_from (klass, oklass))
7475 buffer_add_byte (buf, 1);
7477 buffer_add_byte (buf, 0);
7480 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7481 char *name = decode_string (p, &p, end);
7482 int i, flags = decode_int (p, &p, end);
7483 MonoException *ex = NULL;
7484 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7487 return ERR_LOADER_ERROR;
7488 buffer_add_int (buf, array->len);
7489 for (i = 0; i < array->len; ++i) {
7490 MonoMethod *method = g_ptr_array_index (array, i);
7491 buffer_add_methodid (buf, domain, method);
7494 g_ptr_array_free (array, TRUE);
7498 case CMD_TYPE_GET_INTERFACES: {
7500 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7502 MonoClass *tclass, *iface;
7503 GHashTableIter iter;
7507 for (parent = tclass; parent; parent = parent->parent) {
7508 mono_class_setup_interfaces (parent, &error);
7509 if (!mono_error_ok (&error))
7510 return ERR_LOADER_ERROR;
7511 collect_interfaces (parent, iface_hash, &error);
7512 if (!mono_error_ok (&error))
7513 return ERR_LOADER_ERROR;
7516 buffer_add_int (buf, g_hash_table_size (iface_hash));
7518 g_hash_table_iter_init (&iter, iface_hash);
7519 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7520 buffer_add_typeid (buf, domain, iface);
7521 g_hash_table_destroy (iface_hash);
7524 case CMD_TYPE_GET_INTERFACE_MAP: {
7525 int tindex, ioffset;
7526 gboolean variance_used;
7528 int len, nmethods, i;
7532 len = decode_int (p, &p, end);
7533 mono_class_setup_vtable (klass);
7535 for (tindex = 0; tindex < len; ++tindex) {
7536 iclass = decode_typeid (p, &p, end, NULL, &err);
7540 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7542 return ERR_INVALID_ARGUMENT;
7544 nmethods = mono_class_num_methods (iclass);
7545 buffer_add_int (buf, nmethods);
7548 while ((method = mono_class_get_methods (iclass, &iter))) {
7549 buffer_add_methodid (buf, domain, method);
7551 for (i = 0; i < nmethods; ++i)
7552 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7557 return ERR_NOT_IMPLEMENTED;
7564 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7567 MonoDomain *old_domain;
7571 klass = decode_typeid (p, &p, end, &domain, &err);
7575 old_domain = mono_domain_get ();
7577 mono_domain_set (domain, TRUE);
7579 err = type_commands_internal (command, klass, domain, p, end, buf);
7581 mono_domain_set (old_domain, TRUE);
7587 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7589 MonoMethodHeader *header;
7593 case CMD_METHOD_GET_NAME: {
7594 buffer_add_string (buf, method->name);
7597 case CMD_METHOD_GET_DECLARING_TYPE: {
7598 buffer_add_typeid (buf, domain, method->klass);
7601 case CMD_METHOD_GET_DEBUG_INFO: {
7602 MonoDebugMethodInfo *minfo;
7604 int i, j, n_il_offsets;
7607 int *column_numbers;
7609 GPtrArray *source_file_list;
7611 header = mono_method_get_header (method);
7613 buffer_add_int (buf, 0);
7614 buffer_add_string (buf, "");
7615 buffer_add_int (buf, 0);
7619 minfo = mono_debug_lookup_method (method);
7621 buffer_add_int (buf, header->code_size);
7622 buffer_add_string (buf, "");
7623 buffer_add_int (buf, 0);
7624 mono_metadata_free_mh (header);
7628 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7629 buffer_add_int (buf, header->code_size);
7630 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7631 buffer_add_int (buf, source_file_list->len);
7632 for (i = 0; i < source_file_list->len; ++i) {
7633 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7634 buffer_add_string (buf, sinfo->source_file);
7635 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7636 for (j = 0; j < 16; ++j)
7637 buffer_add_byte (buf, sinfo->hash [j]);
7641 buffer_add_string (buf, source_file);
7643 buffer_add_int (buf, n_il_offsets);
7644 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7645 for (i = 0; i < n_il_offsets; ++i) {
7646 const char *srcfile = "";
7648 if (source_files [i] != -1) {
7649 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7650 srcfile = sinfo->source_file;
7652 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7653 buffer_add_int (buf, il_offsets [i]);
7654 buffer_add_int (buf, line_numbers [i]);
7655 if (CHECK_PROTOCOL_VERSION (2, 13))
7656 buffer_add_int (buf, source_files [i]);
7657 if (CHECK_PROTOCOL_VERSION (2, 19))
7658 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7660 g_free (source_file);
7661 g_free (il_offsets);
7662 g_free (line_numbers);
7663 g_free (source_files);
7664 g_ptr_array_free (source_file_list, TRUE);
7665 mono_metadata_free_mh (header);
7668 case CMD_METHOD_GET_PARAM_INFO: {
7669 MonoMethodSignature *sig = mono_method_signature (method);
7673 /* FIXME: mono_class_from_mono_type () and byrefs */
7675 /* FIXME: Use a smaller encoding */
7676 buffer_add_int (buf, sig->call_convention);
7677 buffer_add_int (buf, sig->param_count);
7678 buffer_add_int (buf, sig->generic_param_count);
7679 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7680 for (i = 0; i < sig->param_count; ++i) {
7682 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7685 /* Emit parameter names */
7686 names = g_new (char *, sig->param_count);
7687 mono_method_get_param_names (method, (const char **) names);
7688 for (i = 0; i < sig->param_count; ++i)
7689 buffer_add_string (buf, names [i]);
7694 case CMD_METHOD_GET_LOCALS_INFO: {
7695 int i, j, num_locals;
7696 MonoDebugLocalsInfo *locals;
7698 header = mono_method_get_header (method);
7700 return ERR_INVALID_ARGUMENT;
7702 buffer_add_int (buf, header->num_locals);
7705 for (i = 0; i < header->num_locals; ++i)
7706 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7709 locals = mono_debug_lookup_locals (method);
7711 num_locals = locals->num_locals;
7714 for (i = 0; i < header->num_locals; ++i) {
7715 for (j = 0; j < num_locals; ++j)
7716 if (locals->locals [j].index == i)
7719 buffer_add_string (buf, locals->locals [j].name);
7721 buffer_add_string (buf, "");
7725 for (i = 0; i < header->num_locals; ++i) {
7726 for (j = 0; j < num_locals; ++j)
7727 if (locals->locals [j].index == i)
7729 if (j < num_locals && locals->locals [j].block) {
7730 buffer_add_int (buf, locals->locals [j].block->start_offset);
7731 buffer_add_int (buf, locals->locals [j].block->end_offset);
7733 buffer_add_int (buf, 0);
7734 buffer_add_int (buf, header->code_size);
7737 mono_metadata_free_mh (header);
7740 mono_debug_symfile_free_locals (locals);
7744 case CMD_METHOD_GET_INFO:
7745 buffer_add_int (buf, method->flags);
7746 buffer_add_int (buf, method->iflags);
7747 buffer_add_int (buf, method->token);
7748 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7750 if (method->is_generic)
7752 if (mono_method_signature (method)->generic_param_count)
7754 buffer_add_byte (buf, attrs);
7755 if (method->is_generic || method->is_inflated) {
7758 if (method->is_generic) {
7761 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7763 result = imethod->declaring;
7764 if (imethod->context.class_inst) {
7765 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7766 /*Generic methods gets the context of the GTD.*/
7767 if (mono_class_get_context (klass))
7768 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7772 buffer_add_methodid (buf, domain, result);
7774 buffer_add_id (buf, 0);
7776 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7777 if (mono_method_signature (method)->generic_param_count) {
7780 if (method->is_inflated) {
7781 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7783 count = inst->type_argc;
7784 buffer_add_int (buf, count);
7786 for (i = 0; i < count; i++)
7787 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7789 buffer_add_int (buf, 0);
7791 } else if (method->is_generic) {
7792 MonoGenericContainer *container = mono_method_get_generic_container (method);
7794 count = mono_method_signature (method)->generic_param_count;
7795 buffer_add_int (buf, count);
7796 for (i = 0; i < count; i++) {
7797 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7798 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7799 buffer_add_typeid (buf, domain, pklass);
7802 buffer_add_int (buf, 0);
7805 buffer_add_int (buf, 0);
7810 case CMD_METHOD_GET_BODY: {
7813 header = mono_method_get_header (method);
7815 buffer_add_int (buf, 0);
7817 if (CHECK_PROTOCOL_VERSION (2, 18))
7818 buffer_add_int (buf, 0);
7820 buffer_add_int (buf, header->code_size);
7821 for (i = 0; i < header->code_size; ++i)
7822 buffer_add_byte (buf, header->code [i]);
7824 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7825 buffer_add_int (buf, header->num_clauses);
7826 for (i = 0; i < header->num_clauses; ++i) {
7827 MonoExceptionClause *clause = &header->clauses [i];
7829 buffer_add_int (buf, clause->flags);
7830 buffer_add_int (buf, clause->try_offset);
7831 buffer_add_int (buf, clause->try_len);
7832 buffer_add_int (buf, clause->handler_offset);
7833 buffer_add_int (buf, clause->handler_len);
7834 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7835 buffer_add_typeid (buf, domain, clause->data.catch_class);
7836 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7837 buffer_add_int (buf, clause->data.filter_offset);
7841 mono_metadata_free_mh (header);
7846 case CMD_METHOD_RESOLVE_TOKEN: {
7847 guint32 token = decode_int (p, &p, end);
7850 switch (mono_metadata_token_code (token)) {
7851 case MONO_TOKEN_STRING: {
7855 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7858 s2 = mono_string_to_utf8 (s);
7860 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7861 buffer_add_string (buf, s2);
7867 MonoClass *handle_class;
7869 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7870 val = mono_method_get_wrapper_data (method, token);
7871 handle_class = mono_method_get_wrapper_data (method, token + 1);
7873 if (handle_class == NULL) {
7874 // Can't figure out the token type
7875 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7879 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7883 if (handle_class == mono_defaults.typehandle_class) {
7884 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7885 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7886 buffer_add_typeid (buf, domain, (MonoClass *) val);
7888 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7889 } else if (handle_class == mono_defaults.fieldhandle_class) {
7890 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7891 buffer_add_fieldid (buf, domain, val);
7892 } else if (handle_class == mono_defaults.methodhandle_class) {
7893 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7894 buffer_add_methodid (buf, domain, val);
7895 } else if (handle_class == mono_defaults.string_class) {
7898 s = mono_string_to_utf8 (val);
7899 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7900 buffer_add_string (buf, s);
7903 g_assert_not_reached ();
7910 case CMD_METHOD_GET_CATTRS: {
7911 MonoClass *attr_klass;
7912 MonoCustomAttrInfo *cinfo;
7914 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7915 /* attr_klass can be NULL */
7919 cinfo = mono_custom_attrs_from_method (method);
7921 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
7925 return ERR_NOT_IMPLEMENTED;
7932 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7935 MonoDomain *old_domain;
7939 method = decode_methodid (p, &p, end, &domain, &err);
7943 old_domain = mono_domain_get ();
7945 mono_domain_set (domain, TRUE);
7947 err = method_commands_internal (command, method, domain, p, end, buf);
7949 mono_domain_set (old_domain, TRUE);
7955 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7957 int objid = decode_objid (p, &p, end);
7959 MonoThread *thread_obj;
7960 MonoInternalThread *thread;
7962 err = get_object (objid, (MonoObject**)&thread_obj);
7966 thread = THREAD_TO_INTERNAL (thread_obj);
7969 case CMD_THREAD_GET_NAME: {
7971 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7974 buffer_add_int (buf, 0);
7979 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7981 buffer_add_int (buf, len);
7982 buffer_add_data (buf, (guint8*)name, len);
7987 case CMD_THREAD_GET_FRAME_INFO: {
7988 DebuggerTlsData *tls;
7989 int i, start_frame, length;
7991 // Wait for suspending if it already started
7992 // FIXME: Races with suspend_count
7993 while (!is_suspended ()) {
7995 wait_for_suspend ();
7999 wait_for_suspend ();
8000 if (!is_suspended ())
8001 return ERR_NOT_SUSPENDED;
8004 start_frame = decode_int (p, &p, end);
8005 length = decode_int (p, &p, end);
8007 if (start_frame != 0 || length != -1)
8008 return ERR_NOT_IMPLEMENTED;
8010 mono_loader_lock ();
8011 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8012 mono_loader_unlock ();
8015 compute_frame_info (thread, tls);
8017 buffer_add_int (buf, tls->frame_count);
8018 for (i = 0; i < tls->frame_count; ++i) {
8019 buffer_add_int (buf, tls->frames [i]->id);
8020 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8021 buffer_add_int (buf, tls->frames [i]->il_offset);
8023 * Instead of passing the frame type directly to the client, we associate
8024 * it with the previous frame using a set of flags. This avoids lots of
8025 * conditional code in the client, since a frame whose type isn't
8026 * FRAME_TYPE_MANAGED has no method, location, etc.
8028 buffer_add_byte (buf, tls->frames [i]->flags);
8033 case CMD_THREAD_GET_STATE:
8034 buffer_add_int (buf, thread->state);
8036 case CMD_THREAD_GET_INFO:
8037 buffer_add_byte (buf, thread->threadpool_thread);
8039 case CMD_THREAD_GET_ID:
8040 buffer_add_long (buf, (guint64)(gsize)thread);
8042 case CMD_THREAD_GET_TID:
8043 buffer_add_long (buf, (guint64)thread->tid);
8046 return ERR_NOT_IMPLEMENTED;
8053 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8057 MonoThread *thread_obj;
8058 MonoInternalThread *thread;
8059 int pos, i, len, frame_idx;
8060 DebuggerTlsData *tls;
8062 MonoDebugMethodJitInfo *jit;
8063 MonoDebugVarInfo *var;
8064 MonoMethodSignature *sig;
8066 MonoMethodHeader *header;
8068 objid = decode_objid (p, &p, end);
8069 err = get_object (objid, (MonoObject**)&thread_obj);
8073 thread = THREAD_TO_INTERNAL (thread_obj);
8075 id = decode_id (p, &p, end);
8077 mono_loader_lock ();
8078 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8079 mono_loader_unlock ();
8082 for (i = 0; i < tls->frame_count; ++i) {
8083 if (tls->frames [i]->id == id)
8086 if (i == tls->frame_count)
8087 return ERR_INVALID_FRAMEID;
8090 frame = tls->frames [frame_idx];
8092 if (!frame->has_ctx)
8094 return ERR_INVALID_FRAMEID;
8097 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8098 if (!frame->jit && frame->api_method->is_inflated)
8099 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8103 /* This could happen for aot images with no jit debug info */
8104 s = mono_method_full_name (frame->api_method, TRUE);
8105 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8107 return ERR_ABSENT_INFORMATION;
8112 sig = mono_method_signature (frame->actual_method);
8114 if (!get_seq_points (frame->domain, frame->actual_method))
8116 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8118 return ERR_ABSENT_INFORMATION;
8121 case CMD_STACK_FRAME_GET_VALUES: {
8122 len = decode_int (p, &p, end);
8123 header = mono_method_get_header (frame->actual_method);
8125 for (i = 0; i < len; ++i) {
8126 pos = decode_int (p, &p, end);
8131 g_assert (pos >= 0 && pos < jit->num_params);
8133 var = &jit->params [pos];
8135 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8137 g_assert (pos >= 0 && pos < jit->num_locals);
8139 var = &jit->locals [pos];
8141 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8144 mono_metadata_free_mh (header);
8147 case CMD_STACK_FRAME_GET_THIS: {
8148 if (frame->api_method->klass->valuetype) {
8149 if (!sig->hasthis) {
8150 MonoObject *p = NULL;
8151 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8153 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8156 if (!sig->hasthis) {
8157 MonoObject *p = NULL;
8158 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8160 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8165 case CMD_STACK_FRAME_SET_VALUES: {
8168 MonoDebugVarInfo *var;
8170 len = decode_int (p, &p, end);
8171 header = mono_method_get_header (frame->actual_method);
8173 for (i = 0; i < len; ++i) {
8174 pos = decode_int (p, &p, end);
8179 g_assert (pos >= 0 && pos < jit->num_params);
8181 t = sig->params [pos];
8182 var = &jit->params [pos];
8184 g_assert (pos >= 0 && pos < jit->num_locals);
8186 t = header->locals [pos];
8187 var = &jit->locals [pos];
8190 if (MONO_TYPE_IS_REFERENCE (t))
8191 val_buf = g_alloca (sizeof (MonoObject*));
8193 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8194 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8198 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8200 mono_metadata_free_mh (header);
8204 return ERR_NOT_IMPLEMENTED;
8211 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8214 int objid, err, index, len, i, esize;
8217 objid = decode_objid (p, &p, end);
8218 err = get_object (objid, (MonoObject**)&arr);
8223 case CMD_ARRAY_REF_GET_LENGTH:
8224 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8226 buffer_add_int (buf, arr->max_length);
8227 buffer_add_int (buf, 0);
8229 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8230 buffer_add_int (buf, arr->bounds [i].length);
8231 buffer_add_int (buf, arr->bounds [i].lower_bound);
8235 case CMD_ARRAY_REF_GET_VALUES:
8236 index = decode_int (p, &p, end);
8237 len = decode_int (p, &p, end);
8239 g_assert (index >= 0 && len >= 0);
8240 // Reordered to avoid integer overflow
8241 g_assert (!(index > arr->max_length - len));
8243 esize = mono_array_element_size (arr->obj.vtable->klass);
8244 for (i = index; i < index + len; ++i) {
8245 elem = (gpointer*)((char*)arr->vector + (i * esize));
8246 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8249 case CMD_ARRAY_REF_SET_VALUES:
8250 index = decode_int (p, &p, end);
8251 len = decode_int (p, &p, end);
8253 g_assert (index >= 0 && len >= 0);
8254 // Reordered to avoid integer overflow
8255 g_assert (!(index > arr->max_length - len));
8257 esize = mono_array_element_size (arr->obj.vtable->klass);
8258 for (i = index; i < index + len; ++i) {
8259 elem = (gpointer*)((char*)arr->vector + (i * esize));
8261 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8265 return ERR_NOT_IMPLEMENTED;
8272 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8277 int i, index, length;
8280 objid = decode_objid (p, &p, end);
8281 err = get_object (objid, (MonoObject**)&str);
8286 case CMD_STRING_REF_GET_VALUE:
8287 s = mono_string_to_utf8 (str);
8288 buffer_add_string (buf, s);
8291 case CMD_STRING_REF_GET_LENGTH:
8292 buffer_add_long (buf, mono_string_length (str));
8294 case CMD_STRING_REF_GET_CHARS:
8295 index = decode_long (p, &p, end);
8296 length = decode_long (p, &p, end);
8297 if (index > mono_string_length (str) - length)
8298 return ERR_INVALID_ARGUMENT;
8299 c = mono_string_chars (str) + index;
8300 for (i = 0; i < length; ++i)
8301 buffer_add_short (buf, c [i]);
8304 return ERR_NOT_IMPLEMENTED;
8311 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8320 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8321 objid = decode_objid (p, &p, end);
8322 err = get_object (objid, &obj);
8324 buffer_add_int (buf, 1);
8326 buffer_add_int (buf, 0);
8330 objid = decode_objid (p, &p, end);
8331 err = get_object (objid, &obj);
8336 case CMD_OBJECT_REF_GET_TYPE:
8337 /* This handles transparent proxies too */
8338 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8340 case CMD_OBJECT_REF_GET_VALUES:
8341 len = decode_int (p, &p, end);
8343 for (i = 0; i < len; ++i) {
8344 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8348 /* Check that the field belongs to the object */
8350 for (k = obj->vtable->klass; k; k = k->parent) {
8351 if (k == f->parent) {
8357 return ERR_INVALID_FIELDID;
8359 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8363 if (mono_class_field_is_special_static (f))
8364 return ERR_INVALID_FIELDID;
8366 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8367 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8368 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8369 mono_field_static_get_value (vtable, f, val);
8370 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8373 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8377 case CMD_OBJECT_REF_SET_VALUES:
8378 len = decode_int (p, &p, end);
8380 for (i = 0; i < len; ++i) {
8381 f = decode_fieldid (p, &p, end, NULL, &err);
8385 /* Check that the field belongs to the object */
8387 for (k = obj->vtable->klass; k; k = k->parent) {
8388 if (k == f->parent) {
8394 return ERR_INVALID_FIELDID;
8396 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8400 if (mono_class_field_is_special_static (f))
8401 return ERR_INVALID_FIELDID;
8403 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8404 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8406 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8407 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8412 mono_field_static_set_value (vtable, f, val);
8415 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8421 case CMD_OBJECT_REF_GET_ADDRESS:
8422 buffer_add_long (buf, (gssize)obj);
8424 case CMD_OBJECT_REF_GET_DOMAIN:
8425 buffer_add_domainid (buf, obj->vtable->domain);
8427 case CMD_OBJECT_REF_GET_INFO:
8428 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8429 buffer_add_domainid (buf, obj->vtable->domain);
8432 return ERR_NOT_IMPLEMENTED;
8439 command_set_to_string (CommandSet command_set)
8441 switch (command_set) {
8444 case CMD_SET_OBJECT_REF:
8445 return "OBJECT_REF";
8446 case CMD_SET_STRING_REF:
8447 return "STRING_REF";
8448 case CMD_SET_THREAD:
8450 case CMD_SET_ARRAY_REF:
8452 case CMD_SET_EVENT_REQUEST:
8453 return "EVENT_REQUEST";
8454 case CMD_SET_STACK_FRAME:
8455 return "STACK_FRAME";
8456 case CMD_SET_APPDOMAIN:
8458 case CMD_SET_ASSEMBLY:
8460 case CMD_SET_METHOD:
8464 case CMD_SET_MODULE:
8474 cmd_to_string (CommandSet set, int command)
8479 case CMD_VM_VERSION:
8481 case CMD_VM_ALL_THREADS:
8482 return "ALL_THREADS";
8483 case CMD_VM_SUSPEND:
8489 case CMD_VM_DISPOSE:
8491 case CMD_VM_INVOKE_METHOD:
8492 return "INVOKE_METHOD";
8493 case CMD_VM_SET_PROTOCOL_VERSION:
8494 return "SET_PROTOCOL_VERSION";
8495 case CMD_VM_ABORT_INVOKE:
8496 return "ABORT_INVOKE";
8497 case CMD_VM_SET_KEEPALIVE:
8498 return "SET_KEEPALIVE";
8511 wait_for_attach (void)
8513 #ifndef DISABLE_SOCKET_TRANSPORT
8514 if (listen_fd == -1) {
8515 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8519 /* Block and wait for client connection */
8520 conn_fd = socket_transport_accept (listen_fd);
8521 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8522 if (conn_fd == -1) {
8523 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8527 g_assert_not_reached ();
8531 disconnected = !transport_handshake ();
8533 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8543 * This thread handles communication with the debugger client using a JDWP
8546 static guint32 WINAPI
8547 debugger_thread (void *arg)
8549 int res, len, id, flags, command_set = 0, command = 0;
8550 guint8 header [HEADER_LENGTH];
8551 guint8 *data, *p, *end;
8555 gboolean attach_failed = FALSE;
8557 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8559 debugger_thread_id = GetCurrentThreadId ();
8561 mono_jit_thread_attach (mono_get_root_domain ());
8563 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8565 mono_set_is_debugger_attached (TRUE);
8567 if (agent_config.defer) {
8568 if (!wait_for_attach ()) {
8569 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8570 attach_failed = TRUE; // Don't abort process when we can't listen
8572 /* Send start event to client */
8573 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8577 while (!attach_failed) {
8578 res = transport_recv (header, HEADER_LENGTH);
8580 /* This will break if the socket is closed during shutdown too */
8581 if (res != HEADER_LENGTH)
8585 end = header + HEADER_LENGTH;
8587 len = decode_int (p, &p, end);
8588 id = decode_int (p, &p, end);
8589 flags = decode_byte (p, &p, end);
8590 command_set = decode_byte (p, &p, end);
8591 command = decode_byte (p, &p, end);
8593 g_assert (flags == 0);
8596 const char *cmd_str;
8599 cmd_str = cmd_to_string (command_set, command);
8601 sprintf (cmd_num, "%d", command);
8605 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8608 data = g_malloc (len - HEADER_LENGTH);
8609 if (len - HEADER_LENGTH > 0)
8611 res = transport_recv (data, len - HEADER_LENGTH);
8612 if (res != len - HEADER_LENGTH)
8617 end = data + (len - HEADER_LENGTH);
8619 buffer_init (&buf, 128);
8624 /* Process the request */
8625 switch (command_set) {
8627 err = vm_commands (command, id, p, end, &buf);
8628 if (!err && command == CMD_VM_INVOKE_METHOD)
8629 /* Sent after the invoke is complete */
8632 case CMD_SET_EVENT_REQUEST:
8633 err = event_commands (command, p, end, &buf);
8635 case CMD_SET_APPDOMAIN:
8636 err = domain_commands (command, p, end, &buf);
8638 case CMD_SET_ASSEMBLY:
8639 err = assembly_commands (command, p, end, &buf);
8641 case CMD_SET_MODULE:
8642 err = module_commands (command, p, end, &buf);
8645 err = type_commands (command, p, end, &buf);
8647 case CMD_SET_METHOD:
8648 err = method_commands (command, p, end, &buf);
8650 case CMD_SET_THREAD:
8651 err = thread_commands (command, p, end, &buf);
8653 case CMD_SET_STACK_FRAME:
8654 err = frame_commands (command, p, end, &buf);
8656 case CMD_SET_ARRAY_REF:
8657 err = array_commands (command, p, end, &buf);
8659 case CMD_SET_STRING_REF:
8660 err = string_commands (command, p, end, &buf);
8662 case CMD_SET_OBJECT_REF:
8663 err = object_commands (command, p, end, &buf);
8666 err = ERR_NOT_IMPLEMENTED;
8670 send_reply_packet (id, err, &buf);
8675 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8679 mono_set_is_debugger_attached (FALSE);
8681 mono_mutex_lock (&debugger_thread_exited_mutex);
8682 debugger_thread_exited = TRUE;
8683 mono_cond_signal (&debugger_thread_exited_cond);
8684 mono_mutex_unlock (&debugger_thread_exited_mutex);
8686 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8688 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8689 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8690 start_debugger_thread ();
8696 #else /* DISABLE_DEBUGGER_AGENT */
8699 mono_debugger_agent_parse_options (char *options)
8701 g_error ("This runtime is configured with the debugger agent disabled.");
8705 mono_debugger_agent_init (void)
8710 mono_debugger_agent_breakpoint_hit (void *sigctx)
8715 mono_debugger_agent_single_step_event (void *sigctx)
8720 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8725 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8731 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8732 MonoContext *catch_ctx)
8737 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8742 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8747 mono_debugger_agent_user_break (void)
8753 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8758 mono_debugger_agent_debug_log_is_enabled (void)