2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
43 #ifdef HAVE_UCONTEXT_H
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
62 #ifdef PLATFORM_ANDROID
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/utils/mono-semaphore.h>
76 #include <mono/utils/mono-error-internals.h>
77 #include <mono/utils/mono-stack-unwinding.h>
78 #include <mono/utils/mono-time.h>
79 #include <mono/utils/mono-threads.h>
80 #include "debugger-agent.h"
83 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
84 #define DISABLE_DEBUGGER_AGENT 1
87 #ifdef DISABLE_SOFT_DEBUG
88 #define DISABLE_DEBUGGER_AGENT 1
91 #ifndef DISABLE_DEBUGGER_AGENT
93 #include <mono/io-layer/mono-mutex.h>
95 /* Definitions to make backporting to 2.6 easier */
96 //#define MonoInternalThread MonoThread
97 //#define mono_thread_internal_current mono_thread_current
98 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
120 guint32 il_offset, native_offset;
124 * If method is gshared, this is the actual instance, otherwise this is equal to
127 MonoMethod *actual_method;
129 * This is the method which is visible to debugger clients. Same as method,
130 * except for native-to-managed wrappers.
132 MonoMethod *api_method;
134 MonoDebugMethodJitInfo *jit;
137 mgreg_t *reg_locations [MONO_MAX_IREGS];
139 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
140 * the frame can become invalid.
145 typedef struct _InvokeData InvokeData;
153 /* This is the context which needs to be restored after the invoke */
157 * If this is set, invoke this method with the arguments given by ARGS.
161 guint32 suspend_count;
164 InvokeData *last_invoke;
168 MonoThreadUnwindState context;
170 /* This is computed on demand when it is requested using the wire protocol */
171 /* It is freed up when the thread is resumed */
175 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
178 gboolean frames_up_to_date;
180 * Points to data about a pending invoke which needs to be executed after the thread
183 InvokeData *pending_invoke;
185 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
190 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
191 * within a finite amount of time.
195 * Set to TRUE if this thread is suspended in suspend_current ().
197 gboolean really_suspended;
198 /* Used to pass the context to the breakpoint/single step handler */
199 MonoContext handler_ctx;
200 /* Whenever thread_stop () was called for this thread */
203 /* Number of thread interruptions not yet processed */
204 gint32 interrupt_count;
206 /* Whenever to disable breakpoints (used during invokes) */
207 gboolean disable_breakpoints;
210 * Number of times this thread has been resumed using resume_thread ().
212 guint32 resume_count;
214 MonoInternalThread *thread;
217 * Information about the frame which transitioned to native code for running
220 StackFrameInfo async_last_frame;
223 * The context where the stack walk can be started for running threads.
225 MonoThreadUnwindState async_state;
228 * The context used for filter clauses
230 MonoThreadUnwindState filter_state;
233 * The callee address of the last mono_runtime_invoke call
235 gpointer invoke_addr;
237 gboolean abort_requested;
240 * The current mono_runtime_invoke invocation.
245 * The context where single stepping should resume while the thread is suspended because
246 * of an EXCEPTION event.
248 MonoContext catch_ctx;
250 gboolean has_catch_ctx;
253 * The context which needs to be restored after handling a single step/breakpoint
254 * event. This is the same as the ctx at step/breakpoint site, but includes changes
255 * to caller saved registers done by set_var ().
257 MonoContext restore_ctx;
262 void (*connect) (const char *address);
263 void (*close1) (void);
264 void (*close2) (void);
265 gboolean (*send) (void *buf, int len);
266 int (*recv) (void *buf, int len);
270 * Wire Protocol definitions
273 #define HEADER_LENGTH 11
275 #define MAJOR_VERSION 2
276 #define MINOR_VERSION 22
280 CMD_SET_OBJECT_REF = 9,
281 CMD_SET_STRING_REF = 10,
283 CMD_SET_ARRAY_REF = 13,
284 CMD_SET_EVENT_REQUEST = 15,
285 CMD_SET_STACK_FRAME = 16,
286 CMD_SET_APPDOMAIN = 20,
287 CMD_SET_ASSEMBLY = 21,
295 EVENT_KIND_VM_START = 0,
296 EVENT_KIND_VM_DEATH = 1,
297 EVENT_KIND_THREAD_START = 2,
298 EVENT_KIND_THREAD_DEATH = 3,
299 EVENT_KIND_APPDOMAIN_CREATE = 4,
300 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
301 EVENT_KIND_METHOD_ENTRY = 6,
302 EVENT_KIND_METHOD_EXIT = 7,
303 EVENT_KIND_ASSEMBLY_LOAD = 8,
304 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
305 EVENT_KIND_BREAKPOINT = 10,
306 EVENT_KIND_STEP = 11,
307 EVENT_KIND_TYPE_LOAD = 12,
308 EVENT_KIND_EXCEPTION = 13,
309 EVENT_KIND_KEEPALIVE = 14,
310 EVENT_KIND_USER_BREAK = 15,
311 EVENT_KIND_USER_LOG = 16
315 SUSPEND_POLICY_NONE = 0,
316 SUSPEND_POLICY_EVENT_THREAD = 1,
317 SUSPEND_POLICY_ALL = 2
322 ERR_INVALID_OBJECT = 20,
323 ERR_INVALID_FIELDID = 25,
324 ERR_INVALID_FRAMEID = 30,
325 ERR_NOT_IMPLEMENTED = 100,
326 ERR_NOT_SUSPENDED = 101,
327 ERR_INVALID_ARGUMENT = 102,
329 ERR_NO_INVOCATION = 104,
330 ERR_ABSENT_INFORMATION = 105,
331 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
332 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
337 MOD_KIND_THREAD_ONLY = 3,
338 MOD_KIND_LOCATION_ONLY = 7,
339 MOD_KIND_EXCEPTION_ONLY = 8,
341 MOD_KIND_ASSEMBLY_ONLY = 11,
342 MOD_KIND_SOURCE_FILE_ONLY = 12,
343 MOD_KIND_TYPE_NAME_ONLY = 13
358 STEP_FILTER_NONE = 0,
359 STEP_FILTER_STATIC_CTOR = 1,
360 STEP_FILTER_DEBUGGER_HIDDEN = 2
364 TOKEN_TYPE_STRING = 0,
366 TOKEN_TYPE_FIELD = 2,
367 TOKEN_TYPE_METHOD = 3,
368 TOKEN_TYPE_UNKNOWN = 4
372 VALUE_TYPE_ID_NULL = 0xf0,
373 VALUE_TYPE_ID_TYPE = 0xf1
377 FRAME_FLAG_DEBUGGER_INVOKE = 1,
378 FRAME_FLAG_NATIVE_TRANSITION = 2
382 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
383 INVOKE_FLAG_SINGLE_THREADED = 2
387 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
388 } BindingFlagsExtensions;
392 CMD_VM_ALL_THREADS = 2,
397 CMD_VM_INVOKE_METHOD = 7,
398 CMD_VM_SET_PROTOCOL_VERSION = 8,
399 CMD_VM_ABORT_INVOKE = 9,
400 CMD_VM_SET_KEEPALIVE = 10,
401 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
402 CMD_VM_GET_TYPES = 12,
403 CMD_VM_INVOKE_METHODS = 13
407 CMD_THREAD_GET_FRAME_INFO = 1,
408 CMD_THREAD_GET_NAME = 2,
409 CMD_THREAD_GET_STATE = 3,
410 CMD_THREAD_GET_INFO = 4,
411 CMD_THREAD_GET_ID = 5,
412 CMD_THREAD_GET_TID = 6
416 CMD_EVENT_REQUEST_SET = 1,
417 CMD_EVENT_REQUEST_CLEAR = 2,
418 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
426 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
427 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
428 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
429 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
430 CMD_APPDOMAIN_CREATE_STRING = 5,
431 CMD_APPDOMAIN_GET_CORLIB = 6,
432 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
436 CMD_ASSEMBLY_GET_LOCATION = 1,
437 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
438 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
439 CMD_ASSEMBLY_GET_OBJECT = 4,
440 CMD_ASSEMBLY_GET_TYPE = 5,
441 CMD_ASSEMBLY_GET_NAME = 6
445 CMD_MODULE_GET_INFO = 1,
449 CMD_METHOD_GET_NAME = 1,
450 CMD_METHOD_GET_DECLARING_TYPE = 2,
451 CMD_METHOD_GET_DEBUG_INFO = 3,
452 CMD_METHOD_GET_PARAM_INFO = 4,
453 CMD_METHOD_GET_LOCALS_INFO = 5,
454 CMD_METHOD_GET_INFO = 6,
455 CMD_METHOD_GET_BODY = 7,
456 CMD_METHOD_RESOLVE_TOKEN = 8,
457 CMD_METHOD_GET_CATTRS = 9,
461 CMD_TYPE_GET_INFO = 1,
462 CMD_TYPE_GET_METHODS = 2,
463 CMD_TYPE_GET_FIELDS = 3,
464 CMD_TYPE_GET_VALUES = 4,
465 CMD_TYPE_GET_OBJECT = 5,
466 CMD_TYPE_GET_SOURCE_FILES = 6,
467 CMD_TYPE_SET_VALUES = 7,
468 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
469 CMD_TYPE_GET_PROPERTIES = 9,
470 CMD_TYPE_GET_CATTRS = 10,
471 CMD_TYPE_GET_FIELD_CATTRS = 11,
472 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
473 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
474 CMD_TYPE_GET_VALUES_2 = 14,
475 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
476 CMD_TYPE_GET_INTERFACES = 16,
477 CMD_TYPE_GET_INTERFACE_MAP = 17,
481 CMD_STACK_FRAME_GET_VALUES = 1,
482 CMD_STACK_FRAME_GET_THIS = 2,
483 CMD_STACK_FRAME_SET_VALUES = 3
487 CMD_ARRAY_REF_GET_LENGTH = 1,
488 CMD_ARRAY_REF_GET_VALUES = 2,
489 CMD_ARRAY_REF_SET_VALUES = 3,
493 CMD_STRING_REF_GET_VALUE = 1,
494 CMD_STRING_REF_GET_LENGTH = 2,
495 CMD_STRING_REF_GET_CHARS = 3
499 CMD_OBJECT_REF_GET_TYPE = 1,
500 CMD_OBJECT_REF_GET_VALUES = 2,
501 CMD_OBJECT_REF_IS_COLLECTED = 3,
502 CMD_OBJECT_REF_GET_ADDRESS = 4,
503 CMD_OBJECT_REF_GET_DOMAIN = 5,
504 CMD_OBJECT_REF_SET_VALUES = 6,
505 CMD_OBJECT_REF_GET_INFO = 7,
511 int count; /* For kind == MOD_KIND_COUNT */
512 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
513 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
514 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
515 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
516 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
517 StepFilter filter; /* For kind == MOD_KIND_STEP */
519 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
528 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
532 * Describes a single step request.
536 MonoInternalThread *thread;
542 MonoMethod *last_method;
544 /* Whenever single stepping is performed using start/stop_single_stepping () */
546 /* The list of breakpoints used to implement step-over */
551 * Contains additional information for an event
554 /* For EVENT_KIND_EXCEPTION */
556 MonoContext catch_ctx;
558 /* For EVENT_KIND_USER_LOG */
560 char *category, *message;
561 /* For EVENT_KIND_TYPE_LOAD */
565 /* Dummy structure used for the profiler callbacks */
570 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
573 #define get_last_sock_error() WSAGetLastError()
574 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
575 #define MONO_EINTR WSAEINTR
577 #define get_last_sock_error() errno
578 #define MONO_EWOULDBLOCK EWOULDBLOCK
579 #define MONO_EINTR EINTR
582 #define CHECK_PROTOCOL_VERSION(major,minor) \
583 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
589 static AgentConfig agent_config;
592 * Whenever the agent is fully initialized.
593 * When using the onuncaught or onthrow options, only some parts of the agent are
594 * initialized on startup, and the full initialization which includes connection
595 * establishment and the startup of the agent thread is only done in response to
598 static gint32 inited;
600 #ifndef DISABLE_SOCKET_TRANSPORT
602 static int listen_fd;
605 static int packet_id = 0;
607 static int objref_id = 0;
609 static int event_request_id = 0;
611 static int frame_id = 0;
613 static GPtrArray *event_requests;
615 static MonoNativeTlsKey debugger_tls_id;
617 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
619 /* Maps MonoInternalThread -> DebuggerTlsData */
620 static MonoGHashTable *thread_to_tls;
622 /* Maps tid -> MonoInternalThread */
623 static MonoGHashTable *tid_to_thread;
625 /* Maps tid -> MonoThread (not MonoInternalThread) */
626 static MonoGHashTable *tid_to_thread_obj;
628 static gsize debugger_thread_id;
630 static HANDLE debugger_thread_handle;
632 static int log_level;
634 static gboolean embedding;
636 static FILE *log_file;
638 /* Assemblies whose assembly load event has no been sent yet */
639 static GPtrArray *pending_assembly_loads;
641 /* Whenever the debugger thread has exited */
642 static gboolean debugger_thread_exited;
644 /* Cond variable used to wait for debugger_thread_exited becoming true */
645 static mono_cond_t debugger_thread_exited_cond;
647 /* Mutex for the cond var above */
648 static mono_mutex_t debugger_thread_exited_mutex;
650 static DebuggerProfiler debugger_profiler;
652 /* The single step request instance */
653 static SingleStepReq *ss_req = NULL;
654 static gpointer ss_invoke_addr = NULL;
656 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
657 /* Number of single stepping operations in progress */
661 /* The protocol version of the client */
662 static int major_version, minor_version;
664 /* Whenever the variables above are set by the client */
665 static gboolean protocol_version_set;
667 /* A hash table containing all active domains */
668 static GHashTable *domains;
670 static void transport_init (void);
671 static void transport_connect (const char *address);
672 static gboolean transport_handshake (void);
673 static void register_transport (DebuggerTransport *trans);
675 static guint32 WINAPI debugger_thread (void *arg);
677 static void runtime_initialized (MonoProfiler *prof);
679 static void runtime_shutdown (MonoProfiler *prof);
681 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
683 static void thread_end (MonoProfiler *prof, uintptr_t tid);
685 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
687 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
689 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
691 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
693 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
695 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
697 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
699 static void emit_assembly_load (gpointer assembly, gpointer user_data);
701 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
703 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
705 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
707 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
709 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
711 static void start_single_stepping (void);
713 static void stop_single_stepping (void);
715 static void suspend_current (void);
717 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
719 static void clear_types_for_assembly (MonoAssembly *assembly);
721 static void clear_breakpoints_for_domain (MonoDomain *domain);
723 static void process_profiler_event (EventKind event, gpointer arg);
725 /* Submodule init/cleanup */
726 static void breakpoints_init (void);
727 static void breakpoints_cleanup (void);
729 static void objrefs_init (void);
730 static void objrefs_cleanup (void);
732 static void ids_init (void);
733 static void ids_cleanup (void);
735 static void suspend_init (void);
737 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
738 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
739 static void ss_destroy (SingleStepReq *req);
741 static void start_debugger_thread (void);
742 static void stop_debugger_thread (void);
744 static void finish_agent_init (gboolean on_startup);
746 static void process_profiler_event (EventKind event, gpointer arg);
748 static void invalidate_frames (DebuggerTlsData *tls);
750 #ifndef DISABLE_SOCKET_TRANSPORT
752 register_socket_transport (void);
756 parse_address (char *address, char **host, int *port)
758 char *pos = strchr (address, ':');
760 if (pos == NULL || pos == address)
763 *host = g_malloc (pos - address + 1);
764 strncpy (*host, address, pos - address);
765 (*host) [pos - address] = '\0';
767 *port = atoi (pos + 1);
775 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
776 fprintf (stderr, "Available options:\n");
777 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
778 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
779 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
780 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
781 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
782 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
783 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
784 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
785 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
789 parse_flag (const char *option, char *flag)
791 if (!strcmp (flag, "y"))
793 else if (!strcmp (flag, "n"))
796 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
803 mono_debugger_agent_parse_options (char *options)
810 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
811 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
815 extra = getenv ("MONO_SDB_ENV_OPTIONS");
817 options = g_strdup_printf ("%s,%s", options, extra);
819 agent_config.enabled = TRUE;
820 agent_config.suspend = TRUE;
821 agent_config.server = FALSE;
822 agent_config.defer = FALSE;
823 agent_config.address = NULL;
825 args = g_strsplit (options, ",", -1);
826 for (ptr = args; ptr && *ptr; ptr ++) {
829 if (strncmp (arg, "transport=", 10) == 0) {
830 agent_config.transport = g_strdup (arg + 10);
831 } else if (strncmp (arg, "address=", 8) == 0) {
832 agent_config.address = g_strdup (arg + 8);
833 } else if (strncmp (arg, "loglevel=", 9) == 0) {
834 agent_config.log_level = atoi (arg + 9);
835 } else if (strncmp (arg, "logfile=", 8) == 0) {
836 agent_config.log_file = g_strdup (arg + 8);
837 } else if (strncmp (arg, "suspend=", 8) == 0) {
838 agent_config.suspend = parse_flag ("suspend", arg + 8);
839 } else if (strncmp (arg, "server=", 7) == 0) {
840 agent_config.server = parse_flag ("server", arg + 7);
841 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
842 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
843 } else if (strncmp (arg, "onthrow=", 8) == 0) {
844 /* We support multiple onthrow= options */
845 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
846 } else if (strncmp (arg, "onthrow", 7) == 0) {
847 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
848 } else if (strncmp (arg, "help", 4) == 0) {
851 } else if (strncmp (arg, "timeout=", 8) == 0) {
852 agent_config.timeout = atoi (arg + 8);
853 } else if (strncmp (arg, "launch=", 7) == 0) {
854 agent_config.launch = g_strdup (arg + 7);
855 } else if (strncmp (arg, "embedding=", 10) == 0) {
856 agent_config.embedding = atoi (arg + 10) == 1;
857 } else if (strncmp (arg, "keepalive=", 10) == 0) {
858 agent_config.keepalive = atoi (arg + 10);
865 if (agent_config.server && !agent_config.suspend) {
866 /* Waiting for deferred attachment */
867 agent_config.defer = TRUE;
868 if (agent_config.address == NULL) {
869 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
873 //agent_config.log_level = 0;
875 if (agent_config.transport == NULL) {
876 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
880 if (agent_config.address == NULL && !agent_config.server) {
881 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
886 if (!strcmp (agent_config.transport, "dt_socket")) {
887 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
888 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
895 mono_debugger_agent_init (void)
897 if (!agent_config.enabled)
902 /* Need to know whenever a thread has acquired the loader mutex */
903 mono_loader_lock_track_ownership (TRUE);
905 event_requests = g_ptr_array_new ();
907 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
908 mono_cond_init (&debugger_thread_exited_cond, NULL);
910 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
911 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
912 mono_profiler_install_runtime_initialized (runtime_initialized);
913 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
914 mono_profiler_install_thread (thread_startup, thread_end);
915 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
916 mono_profiler_install_jit_end (jit_end);
917 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
919 mono_native_tls_alloc (&debugger_tls_id, NULL);
921 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
922 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
924 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
925 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
927 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
928 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
930 pending_assembly_loads = g_ptr_array_new ();
931 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
933 log_level = agent_config.log_level;
935 embedding = agent_config.embedding;
938 if (agent_config.log_file) {
939 log_file = fopen (agent_config.log_file, "w+");
941 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
953 mini_get_debug_options ()->gen_seq_points = TRUE;
955 * This is needed because currently we don't handle liveness info.
957 mini_get_debug_options ()->mdb_optimizations = TRUE;
959 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
960 /* This is needed because we can't set local variables in registers yet */
961 mono_disable_optimizations (MONO_OPT_LINEARS);
965 * The stack walk done from thread_interrupt () needs to be signal safe, but it
966 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
967 * safe (#3411). So load AOT info eagerly when the debugger is running as a
970 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
972 if (!agent_config.onuncaught && !agent_config.onthrow)
973 finish_agent_init (TRUE);
979 * Finish the initialization of the agent. This involves connecting the transport
980 * and starting the agent thread. This is either done at startup, or
981 * in response to some event like an unhandled exception.
984 finish_agent_init (gboolean on_startup)
988 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
991 if (agent_config.launch) {
994 // FIXME: Generated address
995 // FIXME: Races with transport_connect ()
997 argv [0] = agent_config.launch;
998 argv [1] = agent_config.transport;
999 argv [2] = agent_config.address;
1002 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1004 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1009 transport_connect (agent_config.address);
1012 /* Do some which is usually done after sending the VMStart () event */
1013 vm_start_event_sent = TRUE;
1014 start_debugger_thread ();
1019 mono_debugger_agent_cleanup (void)
1024 stop_debugger_thread ();
1026 breakpoints_cleanup ();
1030 mono_mutex_destroy (&debugger_thread_exited_mutex);
1031 mono_cond_destroy (&debugger_thread_exited_cond);
1038 #ifndef DISABLE_SOCKET_TRANSPORT
1043 * recv() + handle incomplete reads and EINTR
1046 socket_transport_recv (void *buf, int len)
1052 static gint32 last_keepalive;
1057 res = recv (fd, (char *) buf + total, len - total, flags);
1060 if (agent_config.keepalive) {
1061 gboolean need_keepalive = FALSE;
1062 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1063 need_keepalive = TRUE;
1064 } else if (res == -1) {
1065 /* This could happen if recv () is interrupted repeatedly */
1066 msecs = mono_msec_ticks ();
1067 if (msecs - last_keepalive >= agent_config.keepalive) {
1068 need_keepalive = TRUE;
1069 last_keepalive = msecs;
1072 if (need_keepalive) {
1073 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1077 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1082 #define HAVE_GETADDRINFO 1
1086 set_keepalive (void)
1091 if (!agent_config.keepalive || !conn_fd)
1094 tv.tv_sec = agent_config.keepalive / 1000;
1095 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1097 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1098 g_assert (result >= 0);
1102 socket_transport_accept (int socket_fd)
1104 conn_fd = accept (socket_fd, NULL, NULL);
1105 if (conn_fd == -1) {
1106 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1108 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1115 socket_transport_send (void *data, int len)
1120 res = send (conn_fd, data, len, 0);
1121 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1129 * socket_transport_connect:
1131 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1134 socket_transport_connect (const char *address)
1136 #ifdef HAVE_GETADDRINFO
1137 struct addrinfo hints;
1138 struct addrinfo *result, *rp;
1140 struct hostent *result;
1142 int sfd = -1, s, res;
1143 char port_string [128];
1147 if (agent_config.address) {
1148 res = parse_address (agent_config.address, &host, &port);
1149 g_assert (res == 0);
1159 sprintf (port_string, "%d", port);
1161 mono_network_init ();
1163 /* Obtain address(es) matching host/port */
1164 #ifdef HAVE_GETADDRINFO
1165 memset (&hints, 0, sizeof (struct addrinfo));
1166 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1167 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1169 hints.ai_protocol = 0; /* Any protocol */
1171 s = getaddrinfo (host, port_string, &hints, &result);
1173 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1177 /* The PS3 doesn't even have _r or hstrerror () */
1178 result = gethostbyname (host);
1180 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1185 if (agent_config.server) {
1186 #ifdef HAVE_GETADDRINFO
1187 /* Wait for a connection */
1189 struct sockaddr_in addr;
1192 /* No address, generate one */
1193 sfd = socket (AF_INET, SOCK_STREAM, 0);
1196 /* This will bind the socket to a random port */
1197 res = listen (sfd, 16);
1199 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1204 addrlen = sizeof (addr);
1205 memset (&addr, 0, sizeof (addr));
1206 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1207 g_assert (res == 0);
1209 host = (char*)"127.0.0.1";
1210 port = ntohs (addr.sin_port);
1212 /* Emit the address to stdout */
1213 /* FIXME: Should print another interface, not localhost */
1214 printf ("%s:%d\n", host, port);
1216 /* Listen on the provided address */
1217 for (rp = result; rp != NULL; rp = rp->ai_next) {
1220 sfd = socket (rp->ai_family, rp->ai_socktype,
1225 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1228 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1232 res = listen (sfd, 16);
1241 * this function is not present on win2000 which we still support, and the
1242 * workaround described here:
1243 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1244 * only works with MSVC.
1246 #ifdef HAVE_GETADDRINFO
1247 freeaddrinfo (result);
1252 if (agent_config.defer)
1255 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1257 if (agent_config.timeout) {
1262 tv.tv_usec = agent_config.timeout * 1000;
1264 FD_SET (sfd, &readfds);
1265 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1267 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1272 conn_fd = socket_transport_accept (sfd);
1276 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1279 #endif /* HAVE_GETADDRINFO */
1281 /* Connect to the specified address */
1282 #ifdef HAVE_GETADDRINFO
1283 /* FIXME: Respect the timeout */
1284 for (rp = result; rp != NULL; rp = rp->ai_next) {
1285 sfd = socket (rp->ai_family, rp->ai_socktype,
1290 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1291 break; /* Success */
1297 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1301 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1303 g_assert_not_reached ();
1304 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1306 g_assert_not_reached ();
1312 /* See the comment above */
1313 #ifdef HAVE_GETADDRINFO
1314 freeaddrinfo (result);
1319 if (!transport_handshake ())
1324 socket_transport_close1 (void)
1326 /* This will interrupt the agent thread */
1327 /* Close the read part only so it can still send back replies */
1328 /* Also shut down the connection listener so that we can exit normally */
1330 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1331 shutdown (conn_fd, SD_BOTH);
1332 shutdown (listen_fd, SD_BOTH);
1333 closesocket (listen_fd);
1335 shutdown (conn_fd, SHUT_RD);
1336 shutdown (listen_fd, SHUT_RDWR);
1342 socket_transport_close2 (void)
1345 shutdown (conn_fd, SD_BOTH);
1347 shutdown (conn_fd, SHUT_RDWR);
1352 register_socket_transport (void)
1354 DebuggerTransport trans;
1356 trans.name = "dt_socket";
1357 trans.connect = socket_transport_connect;
1358 trans.close1 = socket_transport_close1;
1359 trans.close2 = socket_transport_close2;
1360 trans.send = socket_transport_send;
1361 trans.recv = socket_transport_recv;
1363 register_transport (&trans);
1366 #endif /* DISABLE_SOCKET_TRANSPORT */
1372 #define MAX_TRANSPORTS 16
1374 static DebuggerTransport *transport;
1376 static DebuggerTransport transports [MAX_TRANSPORTS];
1377 static int ntransports;
1380 register_transport (DebuggerTransport *trans)
1382 g_assert (ntransports < MAX_TRANSPORTS);
1384 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1389 transport_init (void)
1393 #ifndef DISABLE_SOCKET_TRANSPORT
1394 register_socket_transport ();
1397 for (i = 0; i < ntransports; ++i) {
1398 if (!strcmp (agent_config.transport, transports [i].name))
1401 if (i == ntransports) {
1402 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1403 for (i = 0; i < ntransports; ++i)
1404 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1405 fprintf (stderr, "\n");
1408 transport = &transports [i];
1412 transport_connect (const char *address)
1414 transport->connect (address);
1418 transport_close1 (void)
1420 transport->close1 ();
1424 transport_close2 (void)
1426 transport->close2 ();
1430 transport_send (void *buf, int len)
1432 return transport->send (buf, len);
1436 transport_recv (void *buf, int len)
1438 return transport->recv (buf, len);
1442 transport_handshake (void)
1444 char handshake_msg [128];
1448 disconnected = TRUE;
1450 /* Write handshake message */
1451 sprintf (handshake_msg, "DWP-Handshake");
1453 res = transport_send (handshake_msg, strlen (handshake_msg));
1454 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1455 g_assert (res != -1);
1458 res = transport_recv (buf, strlen (handshake_msg));
1459 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1460 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1465 * To support older clients, the client sends its protocol version after connecting
1466 * using a command. Until that is received, default to our protocol version.
1468 major_version = MAJOR_VERSION;
1469 minor_version = MINOR_VERSION;
1470 protocol_version_set = FALSE;
1472 #ifndef DISABLE_SOCKET_TRANSPORT
1473 // FIXME: Move this somewhere else
1475 * Set TCP_NODELAY on the socket so the client receives events/command
1476 * results immediately.
1480 int result = setsockopt (conn_fd,
1485 g_assert (result >= 0);
1491 disconnected = FALSE;
1496 stop_debugger_thread (void)
1501 transport_close1 ();
1504 * Wait for the thread to exit.
1506 * If we continue with the shutdown without waiting for it, then the client might
1507 * not receive an answer to its last command like a resume.
1508 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1511 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1512 if (GetCurrentThreadId () != debugger_thread_id) {
1514 mono_mutex_lock (&debugger_thread_exited_mutex);
1515 if (!debugger_thread_exited) {
1517 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1518 mono_mutex_unlock (&debugger_thread_exited_mutex);
1520 mono_mutex_lock (&debugger_thread_exited_mutex);
1523 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1526 mono_mutex_unlock (&debugger_thread_exited_mutex);
1527 } while (!debugger_thread_exited);
1530 transport_close2 ();
1534 start_debugger_thread (void)
1538 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1539 g_assert (debugger_thread_handle);
1543 * Functions to decode protocol data
1547 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1550 g_assert (*endbuf <= limit);
1555 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1558 g_assert (*endbuf <= limit);
1560 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1563 static inline gint64
1564 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1566 guint32 high = decode_int (buf, &buf, limit);
1567 guint32 low = decode_int (buf, &buf, limit);
1571 return ((((guint64)high) << 32) | ((guint64)low));
1575 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1577 return decode_int (buf, endbuf, limit);
1581 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1583 int len = decode_int (buf, &buf, limit);
1591 s = g_malloc (len + 1);
1594 memcpy (s, buf, len);
1603 * Functions to encode protocol data
1607 guint8 *buf, *p, *end;
1611 buffer_init (Buffer *buf, int size)
1613 buf->buf = g_malloc (size);
1615 buf->end = buf->buf + size;
1619 buffer_make_room (Buffer *buf, int size)
1621 if (buf->end - buf->p < size) {
1622 int new_size = buf->end - buf->buf + size + 32;
1623 guint8 *p = g_realloc (buf->buf, new_size);
1624 size = buf->p - buf->buf;
1627 buf->end = buf->buf + new_size;
1632 buffer_add_byte (Buffer *buf, guint8 val)
1634 buffer_make_room (buf, 1);
1640 buffer_add_short (Buffer *buf, guint32 val)
1642 buffer_make_room (buf, 2);
1643 buf->p [0] = (val >> 8) & 0xff;
1644 buf->p [1] = (val >> 0) & 0xff;
1649 buffer_add_int (Buffer *buf, guint32 val)
1651 buffer_make_room (buf, 4);
1652 buf->p [0] = (val >> 24) & 0xff;
1653 buf->p [1] = (val >> 16) & 0xff;
1654 buf->p [2] = (val >> 8) & 0xff;
1655 buf->p [3] = (val >> 0) & 0xff;
1660 buffer_add_long (Buffer *buf, guint64 l)
1662 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1663 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1667 buffer_add_id (Buffer *buf, int id)
1669 buffer_add_int (buf, (guint64)id);
1673 buffer_add_data (Buffer *buf, guint8 *data, int len)
1675 buffer_make_room (buf, len);
1676 memcpy (buf->p, data, len);
1681 buffer_add_string (Buffer *buf, const char *str)
1686 buffer_add_int (buf, 0);
1689 buffer_add_int (buf, len);
1690 buffer_add_data (buf, (guint8*)str, len);
1695 buffer_free (Buffer *buf)
1701 send_packet (int command_set, int command, Buffer *data)
1707 id = InterlockedIncrement (&packet_id);
1709 len = data->p - data->buf + 11;
1710 buffer_init (&buf, len);
1711 buffer_add_int (&buf, len);
1712 buffer_add_int (&buf, id);
1713 buffer_add_byte (&buf, 0); /* flags */
1714 buffer_add_byte (&buf, command_set);
1715 buffer_add_byte (&buf, command);
1716 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1718 res = transport_send (buf.buf, len);
1726 send_reply_packet (int id, int error, Buffer *data)
1732 len = data->p - data->buf + 11;
1733 buffer_init (&buf, len);
1734 buffer_add_int (&buf, len);
1735 buffer_add_int (&buf, id);
1736 buffer_add_byte (&buf, 0x80); /* flags */
1737 buffer_add_byte (&buf, (error >> 8) & 0xff);
1738 buffer_add_byte (&buf, error);
1739 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1741 res = transport_send (buf.buf, len);
1753 * Represents an object accessible by the debugger client.
1756 /* Unique id used in the wire protocol to refer to objects */
1759 * A weakref gc handle pointing to the object. The gc handle is used to
1760 * detect if the object was garbage collected.
1765 /* Maps objid -> ObjRef */
1766 static GHashTable *objrefs;
1769 free_objref (gpointer value)
1773 mono_gchandle_free (o->handle);
1781 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1785 objrefs_cleanup (void)
1787 g_hash_table_destroy (objrefs);
1791 static GHashTable *obj_to_objref;
1794 * Return an ObjRef for OBJ.
1797 get_objref (MonoObject *obj)
1800 GSList *reflist = NULL, *l;
1806 mono_loader_lock ();
1809 obj_to_objref = g_hash_table_new (NULL, NULL);
1811 /* FIXME: The tables can grow indefinitely */
1813 if (mono_gc_is_moving ()) {
1815 * Objects can move, so use a hash table mapping hash codes to lists of
1816 * ObjRef structures.
1818 hash = mono_object_hash (obj);
1820 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1821 for (l = reflist; l; l = l->next) {
1823 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1824 mono_loader_unlock ();
1829 /* Use a hash table with masked pointers to internalize object references */
1830 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1831 /* ref might refer to a different object with the same addr which was GCd */
1832 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1833 mono_loader_unlock ();
1838 ref = g_new0 (ObjRef, 1);
1839 ref->id = InterlockedIncrement (&objref_id);
1840 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1842 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1844 if (mono_gc_is_moving ()) {
1845 reflist = g_slist_append (reflist, ref);
1846 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1848 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1851 mono_loader_unlock ();
1857 get_objid (MonoObject *obj)
1859 return get_objref (obj)->id;
1863 * Set OBJ to the object identified by OBJID.
1864 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1868 get_object_allow_null (int objid, MonoObject **obj)
1878 return ERR_INVALID_OBJECT;
1880 mono_loader_lock ();
1882 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1885 *obj = mono_gchandle_get_target (ref->handle);
1886 mono_loader_unlock ();
1888 return ERR_INVALID_OBJECT;
1891 mono_loader_unlock ();
1892 return ERR_INVALID_OBJECT;
1897 get_object (int objid, MonoObject **obj)
1899 int err = get_object_allow_null (objid, obj);
1904 return ERR_INVALID_OBJECT;
1909 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1911 return decode_id (buf, endbuf, limit);
1915 buffer_add_objid (Buffer *buf, MonoObject *o)
1917 buffer_add_id (buf, get_objid (o));
1936 * Represents a runtime structure accessible to the debugger client
1939 /* Unique id used in the wire protocol */
1941 /* Domain of the runtime structure, NULL if the domain was unloaded */
1948 MonoAssembly *assembly;
1949 MonoClassField *field;
1951 MonoProperty *property;
1956 /* Maps runtime structure -> Id */
1957 GHashTable *val_to_id [ID_NUM];
1958 /* Classes whose class load event has been sent */
1959 GHashTable *loaded_classes;
1960 /* Maps MonoClass->GPtrArray of file names */
1961 GHashTable *source_files;
1962 /* Maps source file basename -> GSList of classes */
1963 GHashTable *source_file_to_class;
1964 /* Same with ignore-case */
1965 GHashTable *source_file_to_class_ignorecase;
1969 static GPtrArray *ids [ID_NUM];
1976 for (i = 0; i < ID_NUM; ++i)
1977 ids [i] = g_ptr_array_new ();
1985 for (i = 0; i < ID_NUM; ++i) {
1987 for (j = 0; j < ids [i]->len; ++j)
1988 g_free (g_ptr_array_index (ids [i], j));
1989 g_ptr_array_free (ids [i], TRUE);
1996 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1998 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2000 GHashTableIter iter;
2001 GPtrArray *file_names;
2006 for (i = 0; i < ID_NUM; ++i)
2007 if (info->val_to_id [i])
2008 g_hash_table_destroy (info->val_to_id [i]);
2009 g_hash_table_destroy (info->loaded_classes);
2011 g_hash_table_iter_init (&iter, info->source_files);
2012 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2013 for (i = 0; i < file_names->len; ++i)
2014 g_free (g_ptr_array_index (file_names, i));
2015 g_ptr_array_free (file_names, TRUE);
2018 g_hash_table_iter_init (&iter, info->source_file_to_class);
2019 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2024 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2025 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2033 domain_jit_info (domain)->agent_info = NULL;
2035 /* Clear ids referencing structures in the domain */
2036 for (i = 0; i < ID_NUM; ++i) {
2038 for (j = 0; j < ids [i]->len; ++j) {
2039 Id *id = g_ptr_array_index (ids [i], j);
2040 if (id->domain == domain)
2046 mono_loader_lock ();
2047 g_hash_table_remove (domains, domain);
2048 mono_loader_unlock ();
2051 static AgentDomainInfo*
2052 get_agent_domain_info (MonoDomain *domain)
2054 AgentDomainInfo *info = NULL;
2056 mono_domain_lock (domain);
2058 info = domain_jit_info (domain)->agent_info;
2060 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2061 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2062 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2063 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2064 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2067 mono_domain_unlock (domain);
2073 get_id (MonoDomain *domain, IdType type, gpointer val)
2076 AgentDomainInfo *info;
2081 mono_loader_lock ();
2083 mono_domain_lock (domain);
2085 info = get_agent_domain_info (domain);
2087 if (info->val_to_id [type] == NULL)
2088 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2090 id = g_hash_table_lookup (info->val_to_id [type], val);
2092 mono_domain_unlock (domain);
2093 mono_loader_unlock ();
2097 id = g_new0 (Id, 1);
2099 id->id = ids [type]->len + 1;
2100 id->domain = domain;
2103 g_hash_table_insert (info->val_to_id [type], val, id);
2105 mono_domain_unlock (domain);
2107 g_ptr_array_add (ids [type], id);
2109 mono_loader_unlock ();
2114 static inline gpointer
2115 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2119 int id = decode_id (buf, endbuf, limit);
2128 // FIXME: error handling
2129 mono_loader_lock ();
2130 g_assert (id > 0 && id <= ids [type]->len);
2132 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2133 mono_loader_unlock ();
2135 if (res->domain == NULL) {
2136 *err = ERR_UNLOADED;
2141 *domain = res->domain;
2143 return res->data.val;
2147 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2149 buffer_add_id (buf, get_id (domain, type, val));
2152 static inline MonoClass*
2153 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2155 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2158 static inline MonoAssembly*
2159 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2161 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2164 static inline MonoImage*
2165 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2167 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2170 static inline MonoMethod*
2171 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2173 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2176 static inline MonoClassField*
2177 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2179 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2182 static inline MonoDomain*
2183 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2185 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2188 static inline MonoProperty*
2189 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2191 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2195 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2197 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2201 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2203 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2207 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2209 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2213 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2215 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2219 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2221 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2225 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2227 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2231 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2233 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2236 static void invoke_method (void);
2243 * save_thread_context:
2245 * Set CTX as the current threads context which is used for computing stack traces.
2246 * This function is signal-safe.
2249 save_thread_context (MonoContext *ctx)
2251 DebuggerTlsData *tls;
2253 tls = mono_native_tls_get_value (debugger_tls_id);
2257 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2259 mono_thread_state_init_from_current (&tls->context);
2262 /* The number of times the runtime is suspended */
2263 static gint32 suspend_count;
2265 /* Number of threads suspended */
2267 * If this is equal to the size of thread_to_tls, the runtime is considered
2270 static gint32 threads_suspend_count;
2272 static mono_mutex_t suspend_mutex;
2274 /* Cond variable used to wait for suspend_count becoming 0 */
2275 static mono_cond_t suspend_cond;
2277 /* Semaphore used to wait for a thread becoming suspended */
2278 static MonoSemType suspend_sem;
2283 mono_mutex_init (&suspend_mutex, NULL);
2284 mono_cond_init (&suspend_cond, NULL);
2285 MONO_SEM_INIT (&suspend_sem, 0);
2290 StackFrameInfo last_frame;
2291 gboolean last_frame_set;
2294 } GetLastFrameUserData;
2297 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2299 GetLastFrameUserData *data = user_data;
2301 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2304 if (!data->last_frame_set) {
2305 /* Store the last frame */
2306 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2307 data->last_frame_set = TRUE;
2310 /* Store the context/lmf for the frame above the last frame */
2311 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2312 data->lmf = info->lmf;
2320 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2321 * INFO is set, process the thread described by INFO.
2322 * This should be signal safe.
2325 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2329 MonoNativeThreadId tid;
2332 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2333 * guarantee the signal handler will be called that many times. Instead of tracking
2334 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2335 * has been requested that hasn't been handled yet, otherwise we can have threads
2336 * refuse to die when VM_EXIT is called
2338 #if defined(__APPLE__)
2339 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2343 * We use interrupt_count to determine whenever this interrupt should be processed
2344 * by us or the normal interrupt processing code in the signal handler.
2345 * There is no race here with notify_thread (), since the signal is sent after
2346 * incrementing interrupt_count.
2348 if (tls->interrupt_count == 0)
2351 InterlockedDecrement (&tls->interrupt_count);
2355 ip = mono_arch_ip_from_context (sigctx);
2357 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2362 tid = mono_thread_info_get_tid (info);
2364 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2366 // FIXME: Races when the thread leaves managed code before hitting a single step
2370 /* Running managed code, will be suspended by the single step code */
2371 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2375 * Running native code, will be suspended when it returns to/enters
2376 * managed code. Treat it as already suspended.
2377 * This might interrupt the code in process_single_step_inner (), we use the
2378 * tls->suspending flag to avoid races when that happens.
2380 if (!tls->suspended && !tls->suspending) {
2382 GetLastFrameUserData data;
2384 // FIXME: printf is not signal safe, but this is only used during
2385 // debugger debugging
2387 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2388 //save_thread_context (&ctx);
2391 /* Already terminated */
2394 tls->context.valid = FALSE;
2397 * We are in a difficult position: we want to be able to provide stack
2398 * traces for this thread, but we can't use the current ctx+lmf, since
2399 * the thread is still running, so it might return to managed code,
2400 * making these invalid.
2401 * So we start a stack walk and save the first frame, along with the
2402 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2403 * suspended when it returns to managed code, so the parent's ctx should
2406 data.last_frame_set = FALSE;
2408 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2410 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2411 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2412 * since we are not in a JITted method.
2414 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2416 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2418 if (data.last_frame_set) {
2419 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2420 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2422 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2425 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2426 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2427 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2429 /* No managed frames */
2430 tls->async_state.valid = FALSE;
2432 mono_memory_barrier ();
2434 tls->suspended = TRUE;
2435 MONO_SEM_POST (&suspend_sem);
2442 * mono_debugger_agent_thread_interrupt:
2444 * Called by the abort signal handler.
2445 * Should be signal safe.
2448 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2450 DebuggerTlsData *tls;
2455 tls = mono_native_tls_get_value (debugger_tls_id);
2457 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2461 return thread_interrupt (tls, NULL, sigctx, ji);
2465 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2468 mono_debugger_agent_thread_interrupt (NULL, NULL);
2470 #endif /* HOST_WIN32 */
2473 * reset_native_thread_suspend_state:
2475 * Reset the suspended flag and state on native threads
2478 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2480 DebuggerTlsData *tls = value;
2482 if (!tls->really_suspended && tls->suspended) {
2483 tls->suspended = FALSE;
2485 * The thread might still be running if it was executing native code, so the state won't be invalided by
2486 * suspend_current ().
2488 tls->context.valid = FALSE;
2489 tls->async_state.valid = FALSE;
2490 invalidate_frames (tls);
2497 * Notify a thread that it needs to suspend.
2500 notify_thread (gpointer key, gpointer value, gpointer user_data)
2502 MonoInternalThread *thread = key;
2503 DebuggerTlsData *tls = value;
2504 gsize tid = thread->tid;
2507 if (GetCurrentThreadId () == tid || tls->terminated)
2510 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2513 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2514 * guarantee the signal handler will be called that many times. Instead of tracking
2515 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2516 * has been requested that hasn't been handled yet, otherwise we can have threads
2517 * refuse to die when VM_EXIT is called
2519 #if defined(__APPLE__)
2520 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2524 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2525 * of things like breaking waits etc. which we don't want.
2527 InterlockedIncrement (&tls->interrupt_count);
2530 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2532 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2534 if (mono_thread_info_new_interrupt_enabled ()) {
2535 MonoThreadInfo *info;
2538 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2541 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2543 thread_interrupt (tls, info, NULL, ji);
2545 mono_thread_info_resume (mono_thread_info_get_tid (info));
2547 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2549 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2551 * Attached thread which died without detaching.
2553 tls->terminated = TRUE;
2560 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2562 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2565 if (mono_loader_lock_is_owned_by_self ()) {
2567 * Shortcut for the check in suspend_current (). This speeds up processing
2568 * when executing long running code inside the loader lock, i.e. assembly load
2574 if (debugger_thread_id == GetCurrentThreadId ())
2577 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2578 if (suspend_count - tls->resume_count > 0)
2579 tls->suspending = TRUE;
2581 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2583 if (suspend_count - tls->resume_count == 0) {
2585 * We are executing a single threaded invoke but the single step for
2586 * suspending is still active.
2587 * FIXME: This slows down single threaded invokes.
2589 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2593 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2595 /* Can't suspend in these methods */
2596 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2599 save_thread_context (ctx);
2607 * Increase the suspend count of the VM. While the suspend count is greater
2608 * than 0, runtime threads are suspended at certain points during execution.
2613 mono_loader_lock ();
2615 mono_mutex_lock (&suspend_mutex);
2619 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2621 if (suspend_count == 1) {
2622 // FIXME: Is it safe to call this inside the lock ?
2623 start_single_stepping ();
2624 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2627 mono_mutex_unlock (&suspend_mutex);
2629 mono_loader_unlock ();
2635 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2643 g_assert (debugger_thread_id == GetCurrentThreadId ());
2645 mono_loader_lock ();
2647 mono_mutex_lock (&suspend_mutex);
2649 g_assert (suspend_count > 0);
2652 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2654 if (suspend_count == 0) {
2655 // FIXME: Is it safe to call this inside the lock ?
2656 stop_single_stepping ();
2657 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2660 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2661 err = mono_cond_broadcast (&suspend_cond);
2662 g_assert (err == 0);
2664 mono_mutex_unlock (&suspend_mutex);
2665 //g_assert (err == 0);
2667 mono_loader_unlock ();
2673 * Resume just one thread.
2676 resume_thread (MonoInternalThread *thread)
2679 DebuggerTlsData *tls;
2681 g_assert (debugger_thread_id == GetCurrentThreadId ());
2683 mono_loader_lock ();
2685 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2688 mono_mutex_lock (&suspend_mutex);
2690 g_assert (suspend_count > 0);
2692 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2694 tls->resume_count += suspend_count;
2697 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2698 * but only the one whose resume_count field is > 0 will be resumed.
2700 err = mono_cond_broadcast (&suspend_cond);
2701 g_assert (err == 0);
2703 mono_mutex_unlock (&suspend_mutex);
2704 //g_assert (err == 0);
2706 mono_loader_unlock ();
2710 invalidate_frames (DebuggerTlsData *tls)
2715 tls = mono_native_tls_get_value (debugger_tls_id);
2718 for (i = 0; i < tls->frame_count; ++i) {
2719 if (tls->frames [i]->jit)
2720 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2721 g_free (tls->frames [i]);
2723 g_free (tls->frames);
2724 tls->frame_count = 0;
2731 * Suspend the current thread until the runtime is resumed. If the thread has a
2732 * pending invoke, then the invoke is executed before this function returns.
2735 suspend_current (void)
2738 DebuggerTlsData *tls;
2740 g_assert (debugger_thread_id != GetCurrentThreadId ());
2742 if (mono_loader_lock_is_owned_by_self ()) {
2744 * If we own the loader mutex, can't suspend until we release it, since the
2745 * whole runtime can deadlock otherwise.
2750 tls = mono_native_tls_get_value (debugger_tls_id);
2753 mono_mutex_lock (&suspend_mutex);
2755 tls->suspending = FALSE;
2756 tls->really_suspended = TRUE;
2758 if (!tls->suspended) {
2759 tls->suspended = TRUE;
2760 MONO_SEM_POST (&suspend_sem);
2763 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2765 while (suspend_count - tls->resume_count > 0) {
2767 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2769 mono_mutex_unlock (&suspend_mutex);
2771 mono_mutex_lock (&suspend_mutex);
2777 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2778 g_assert (err == 0);
2782 tls->suspended = FALSE;
2783 tls->really_suspended = FALSE;
2785 threads_suspend_count --;
2787 mono_mutex_unlock (&suspend_mutex);
2789 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2791 if (tls->pending_invoke) {
2792 /* Save the original context */
2793 tls->pending_invoke->has_ctx = TRUE;
2794 tls->pending_invoke->ctx = tls->context.ctx;
2799 /* The frame info becomes invalid after a resume */
2800 tls->context.valid = FALSE;
2801 tls->async_state.valid = FALSE;
2802 invalidate_frames (tls);
2806 count_thread (gpointer key, gpointer value, gpointer user_data)
2808 DebuggerTlsData *tls = value;
2810 if (!tls->suspended && !tls->terminated)
2811 *(int*)user_data = *(int*)user_data + 1;
2815 count_threads_to_wait_for (void)
2819 mono_loader_lock ();
2820 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2821 mono_loader_unlock ();
2829 * Wait until the runtime is completely suspended.
2832 wait_for_suspend (void)
2834 int nthreads, nwait, err;
2835 gboolean waited = FALSE;
2837 // FIXME: Threads starting/stopping ?
2838 mono_loader_lock ();
2839 nthreads = mono_g_hash_table_size (thread_to_tls);
2840 mono_loader_unlock ();
2843 nwait = count_threads_to_wait_for ();
2845 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2846 err = MONO_SEM_WAIT (&suspend_sem);
2847 g_assert (err == 0);
2855 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2861 * Return whenever the runtime is suspended.
2866 return count_threads_to_wait_for () == 0;
2869 static MonoSeqPointInfo*
2870 get_seq_points (MonoDomain *domain, MonoMethod *method)
2872 MonoSeqPointInfo *seq_points;
2874 mono_domain_lock (domain);
2875 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2876 if (!seq_points && method->is_inflated) {
2877 /* generic sharing + aot */
2878 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2880 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2882 mono_domain_unlock (domain);
2887 static MonoSeqPointInfo*
2888 find_seq_points (MonoDomain *domain, MonoMethod *method)
2890 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2893 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2894 g_assert (seq_points);
2900 * find_next_seq_point_for_native_offset:
2902 * Find the first sequence point after NATIVE_OFFSET.
2905 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2907 MonoSeqPointInfo *seq_points;
2910 seq_points = find_seq_points (domain, method);
2914 for (i = 0; i < seq_points->len; ++i) {
2915 if (seq_points->seq_points [i].native_offset >= native_offset)
2916 return &seq_points->seq_points [i];
2923 * find_prev_seq_point_for_native_offset:
2925 * Find the first sequence point before NATIVE_OFFSET.
2928 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2930 MonoSeqPointInfo *seq_points;
2933 seq_points = find_seq_points (domain, method);
2937 for (i = seq_points->len - 1; i >= 0; --i) {
2938 if (seq_points->seq_points [i].native_offset <= native_offset)
2939 return &seq_points->seq_points [i];
2948 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2949 * should be the location of a sequence point.
2951 static G_GNUC_UNUSED SeqPoint*
2952 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2954 MonoSeqPointInfo *seq_points;
2959 seq_points = get_seq_points (domain, method);
2964 for (i = 0; i < seq_points->len; ++i) {
2965 if (seq_points->seq_points [i].il_offset == il_offset)
2966 return &seq_points->seq_points [i];
2973 DebuggerTlsData *tls;
2975 } ComputeFramesUserData;
2978 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2980 ComputeFramesUserData *ud = user_data;
2982 MonoMethod *method, *actual_method, *api_method;
2986 if (info->type != FRAME_TYPE_MANAGED) {
2987 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2988 /* Mark the last frame as an invoke frame */
2990 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2996 method = info->ji->method;
2998 method = info->method;
2999 actual_method = info->actual_method;
3000 api_method = method;
3005 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3008 if (info->il_offset == -1) {
3009 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3010 if (ud->frames == NULL) {
3011 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3013 info->il_offset = sp->il_offset;
3015 if (info->il_offset == -1)
3016 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3019 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));
3021 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3022 if (!CHECK_PROTOCOL_VERSION (2, 17))
3023 /* Older clients can't handle this flag */
3025 api_method = mono_marshal_method_from_wrapper (method);
3028 actual_method = api_method;
3029 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3032 frame = g_new0 (StackFrame, 1);
3033 frame->method = method;
3034 frame->actual_method = actual_method;
3035 frame->api_method = api_method;
3036 frame->il_offset = info->il_offset;
3037 frame->native_offset = info->native_offset;
3038 frame->flags = flags;
3039 frame->ji = info->ji;
3040 if (info->reg_locations)
3041 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3044 frame->has_ctx = TRUE;
3046 frame->domain = info->domain;
3048 ud->frames = g_slist_append (ud->frames, frame);
3054 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3056 ComputeFramesUserData *ud = user_data;
3059 * 'tls->filter_ctx' is the location of the throw site.
3061 * mono_walk_stack() will never actually hit the throw site, but unwind
3062 * directly from the filter to the call site; we abort stack unwinding here
3063 * once this happens and resume from the throw site.
3066 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3069 return process_frame (info, ctx, user_data);
3073 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3075 ComputeFramesUserData user_data;
3077 int i, findex, new_frame_count;
3078 StackFrame **new_frames, *f;
3079 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3081 // FIXME: Locking on tls
3082 if (tls->frames && tls->frames_up_to_date)
3085 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3087 user_data.tls = tls;
3088 user_data.frames = NULL;
3089 if (tls->terminated) {
3090 tls->frame_count = 0;
3092 } if (!tls->really_suspended && tls->async_state.valid) {
3093 /* Have to use the state saved by the signal handler */
3094 process_frame (&tls->async_last_frame, NULL, &user_data);
3095 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3096 } else if (tls->filter_state.valid) {
3098 * We are inside an exception filter.
3100 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3102 if (tls->context.valid)
3103 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3105 * After that, we resume unwinding from the location where the exception has been thrown.
3107 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3108 } else if (tls->context.valid) {
3109 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3112 tls->frame_count = 0;
3116 new_frame_count = g_slist_length (user_data.frames);
3117 new_frames = g_new0 (StackFrame*, new_frame_count);
3119 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3123 * Reuse the id for already existing stack frames, so invokes don't invalidate
3124 * the still valid stack frames.
3126 for (i = 0; i < tls->frame_count; ++i) {
3127 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3128 f->id = tls->frames [i]->id;
3133 if (i >= tls->frame_count)
3134 f->id = InterlockedIncrement (&frame_id);
3136 new_frames [findex ++] = f;
3139 g_slist_free (user_data.frames);
3141 invalidate_frames (tls);
3143 tls->frames = new_frames;
3144 tls->frame_count = new_frame_count;
3145 tls->frames_up_to_date = TRUE;
3149 * GHFunc to emit an appdomain creation event
3150 * @param key Don't care
3151 * @param value A loaded appdomain
3152 * @param user_data Don't care
3155 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3157 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3158 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3162 * GHFunc to emit a thread start event
3163 * @param key A thread id
3164 * @param value A thread object
3165 * @param user_data Don't care
3168 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3170 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3171 process_profiler_event (EVENT_KIND_THREAD_START, value);
3175 * GFunc to emit an assembly load event
3176 * @param value A loaded assembly
3177 * @param user_data Don't care
3180 emit_assembly_load (gpointer value, gpointer user_data)
3182 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3186 * GFunc to emit a type load event
3187 * @param value A loaded type
3188 * @param user_data Don't care
3191 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3193 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3197 strdup_tolower (char *s)
3202 for (p = s2; *p; ++p)
3212 * create_event_list:
3214 * Return a list of event request ids matching EVENT, starting from REQS, which
3215 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3217 * We return request ids, instead of requests, to simplify threading, since
3218 * requests could be deleted anytime when the loader lock is not held.
3219 * LOCKING: Assumes the loader lock is held.
3222 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3225 GSList *events = NULL;
3227 *suspend_policy = SUSPEND_POLICY_NONE;
3230 reqs = event_requests;
3235 for (i = 0; i < reqs->len; ++i) {
3236 EventRequest *req = g_ptr_array_index (reqs, i);
3237 if (req->event_kind == event) {
3238 gboolean filtered = FALSE;
3241 for (j = 0; j < req->nmodifiers; ++j) {
3242 Modifier *mod = &req->modifiers [j];
3244 if (mod->kind == MOD_KIND_COUNT) {
3246 if (mod->data.count > 0) {
3247 if (mod->data.count > 0) {
3249 if (mod->data.count == 0)
3253 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3254 if (mod->data.thread != mono_thread_internal_current ())
3256 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3257 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3259 if (ei->caught && !mod->caught)
3261 if (!ei->caught && !mod->uncaught)
3263 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3265 gboolean found = FALSE;
3266 MonoAssembly **assemblies = mod->data.assemblies;
3269 for (k = 0; assemblies [k]; ++k)
3270 if (assemblies [k] == ji->method->klass->image->assembly)
3275 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3276 gpointer iter = NULL;
3278 MonoDebugSourceInfo *sinfo;
3279 char *source_file, *s;
3280 gboolean found = FALSE;
3282 GPtrArray *source_file_list;
3284 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3285 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3288 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3289 for (i = 0; i < source_file_list->len; ++i) {
3290 sinfo = g_ptr_array_index (source_file_list, i);
3292 * Do a case-insesitive match by converting the file name to
3295 s = strdup_tolower (sinfo->source_file);
3296 if (g_hash_table_lookup (mod->data.source_files, s))
3300 g_ptr_array_free (source_file_list, TRUE);
3305 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3308 s = mono_type_full_name (&ei->klass->byval_arg);
3309 if (!g_hash_table_lookup (mod->data.type_names, s))
3312 } else if (mod->kind == MOD_KIND_STEP) {
3313 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3314 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3315 !strcmp (ji->method->name, ".cctor"))
3317 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3318 MonoCustomAttrInfo *ainfo;
3319 static MonoClass *klass;
3322 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3325 if (!ji->dbg_hidden_inited) {
3326 ainfo = mono_custom_attrs_from_method (ji->method);
3328 if (mono_custom_attrs_has_attr (ainfo, klass))
3329 ji->dbg_hidden = TRUE;
3330 mono_custom_attrs_free (ainfo);
3332 ji->dbg_hidden_inited = TRUE;
3341 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3342 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3347 /* Send a VM START/DEATH event by default */
3348 if (event == EVENT_KIND_VM_START)
3349 events = g_slist_append (events, GINT_TO_POINTER (0));
3350 if (event == EVENT_KIND_VM_DEATH)
3351 events = g_slist_append (events, GINT_TO_POINTER (0));
3356 static G_GNUC_UNUSED const char*
3357 event_to_string (EventKind event)
3360 case EVENT_KIND_VM_START: return "VM_START";
3361 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3362 case EVENT_KIND_THREAD_START: return "THREAD_START";
3363 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3364 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3365 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3366 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3367 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3368 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3369 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3370 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3371 case EVENT_KIND_STEP: return "STEP";
3372 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3373 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3374 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3375 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3376 case EVENT_KIND_USER_LOG: return "USER_LOG";
3378 g_assert_not_reached ();
3385 * Send an event to the client, suspending the vm if needed.
3386 * LOCKING: Since this can suspend the calling thread, no locks should be held
3388 * The EVENTS list is freed by this function.
3391 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3395 MonoDomain *domain = mono_domain_get ();
3396 MonoThread *thread = NULL;
3397 gboolean send_success = FALSE;
3402 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3406 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3407 // FIXME: We miss those events
3408 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3412 if (vm_death_event_sent) {
3413 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3417 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3418 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3423 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3427 if (event == EVENT_KIND_KEEPALIVE)
3428 suspend_policy = SUSPEND_POLICY_NONE;
3433 if (agent_config.defer) {
3434 /* Make sure the thread id is always set when doing deferred debugging */
3435 if (debugger_thread_id == GetCurrentThreadId ()) {
3436 /* Don't suspend on events from the debugger thread */
3437 suspend_policy = SUSPEND_POLICY_NONE;
3438 thread = mono_thread_get_main ();
3440 else thread = mono_thread_current ();
3442 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3443 // FIXME: Send these with a NULL thread, don't suspend the current thread
3448 nevents = g_slist_length (events);
3449 buffer_init (&buf, 128);
3450 buffer_add_byte (&buf, suspend_policy);
3451 buffer_add_int (&buf, nevents);
3453 for (l = events; l; l = l->next) {
3454 buffer_add_byte (&buf, event); // event kind
3455 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3460 thread = mono_thread_current ();
3462 if (event == EVENT_KIND_VM_START && arg != NULL)
3465 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3468 case EVENT_KIND_THREAD_START:
3469 case EVENT_KIND_THREAD_DEATH:
3471 case EVENT_KIND_APPDOMAIN_CREATE:
3472 case EVENT_KIND_APPDOMAIN_UNLOAD:
3473 buffer_add_domainid (&buf, arg);
3475 case EVENT_KIND_METHOD_ENTRY:
3476 case EVENT_KIND_METHOD_EXIT:
3477 buffer_add_methodid (&buf, domain, arg);
3479 case EVENT_KIND_ASSEMBLY_LOAD:
3480 case EVENT_KIND_ASSEMBLY_UNLOAD:
3481 buffer_add_assemblyid (&buf, domain, arg);
3483 case EVENT_KIND_TYPE_LOAD:
3484 buffer_add_typeid (&buf, domain, arg);
3486 case EVENT_KIND_BREAKPOINT:
3487 case EVENT_KIND_STEP:
3488 buffer_add_methodid (&buf, domain, arg);
3489 buffer_add_long (&buf, il_offset);
3491 case EVENT_KIND_VM_START:
3492 buffer_add_domainid (&buf, mono_get_root_domain ());
3494 case EVENT_KIND_VM_DEATH:
3496 case EVENT_KIND_EXCEPTION: {
3497 EventInfo *ei = arg;
3498 buffer_add_objid (&buf, ei->exc);
3501 case EVENT_KIND_USER_BREAK:
3503 case EVENT_KIND_USER_LOG: {
3504 EventInfo *ei = arg;
3505 buffer_add_int (&buf, ei->level);
3506 buffer_add_string (&buf, ei->category ? ei->category : "");
3507 buffer_add_string (&buf, ei->message ? ei->message : "");
3510 case EVENT_KIND_KEEPALIVE:
3511 suspend_policy = SUSPEND_POLICY_NONE;
3514 g_assert_not_reached ();
3518 if (event == EVENT_KIND_VM_START) {
3519 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3520 if (!agent_config.defer)
3521 start_debugger_thread ();
3524 if (event == EVENT_KIND_VM_DEATH) {
3525 vm_death_event_sent = TRUE;
3526 suspend_policy = SUSPEND_POLICY_NONE;
3529 if (mono_runtime_is_shutting_down ())
3530 suspend_policy = SUSPEND_POLICY_NONE;
3532 if (suspend_policy != SUSPEND_POLICY_NONE) {
3534 * Save the thread context and start suspending before sending the packet,
3535 * since we could be receiving the resume request before send_packet ()
3538 save_thread_context (ctx);
3542 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3546 g_slist_free (events);
3549 if (!send_success) {
3550 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3554 if (event == EVENT_KIND_VM_START) {
3555 vm_start_event_sent = TRUE;
3558 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3560 switch (suspend_policy) {
3561 case SUSPEND_POLICY_NONE:
3563 case SUSPEND_POLICY_ALL:
3566 case SUSPEND_POLICY_EVENT_THREAD:
3570 g_assert_not_reached ();
3575 process_profiler_event (EventKind event, gpointer arg)
3579 EventInfo ei, *ei_arg = NULL;
3581 if (event == EVENT_KIND_TYPE_LOAD) {
3586 mono_loader_lock ();
3587 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3588 mono_loader_unlock ();
3590 process_event (event, arg, 0, NULL, events, suspend_policy);
3594 runtime_initialized (MonoProfiler *prof)
3596 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3597 if (agent_config.defer)
3598 start_debugger_thread ();
3602 runtime_shutdown (MonoProfiler *prof)
3604 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3606 mono_debugger_agent_cleanup ();
3610 thread_startup (MonoProfiler *prof, uintptr_t tid)
3612 MonoInternalThread *thread = mono_thread_internal_current ();
3613 MonoInternalThread *old_thread;
3614 DebuggerTlsData *tls;
3616 if (tid == debugger_thread_id)
3619 g_assert (thread->tid == tid);
3621 mono_loader_lock ();
3622 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3623 mono_loader_unlock ();
3625 if (thread == old_thread) {
3627 * For some reason, thread_startup () might be called for the same thread
3628 * multiple times (attach ?).
3630 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3634 * thread_end () might not be called for some threads, and the tid could
3637 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3638 mono_loader_lock ();
3639 mono_g_hash_table_remove (thread_to_tls, old_thread);
3640 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3641 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3642 mono_loader_unlock ();
3646 tls = mono_native_tls_get_value (debugger_tls_id);
3648 // FIXME: Free this somewhere
3649 tls = g_new0 (DebuggerTlsData, 1);
3650 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3651 tls->thread = thread;
3652 mono_native_tls_set_value (debugger_tls_id, tls);
3654 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3656 mono_loader_lock ();
3657 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3658 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3659 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3660 mono_loader_unlock ();
3662 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3665 * suspend_vm () could have missed this thread, so wait for a resume.
3671 thread_end (MonoProfiler *prof, uintptr_t tid)
3673 MonoInternalThread *thread;
3674 DebuggerTlsData *tls = NULL;
3676 mono_loader_lock ();
3677 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3679 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3680 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3682 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3683 tls->terminated = TRUE;
3684 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3685 MONO_GC_UNREGISTER_ROOT (tls->thread);
3689 mono_loader_unlock ();
3691 /* We might be called for threads started before we registered the start callback */
3693 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3694 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3699 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3701 mono_loader_lock ();
3702 g_hash_table_insert (domains, domain, domain);
3703 mono_loader_unlock ();
3705 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3709 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3711 clear_breakpoints_for_domain (domain);
3713 mono_loader_lock ();
3714 /* Invalidate each thread's frame stack */
3715 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3716 mono_loader_unlock ();
3718 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3722 * invalidate_each_thread:
3724 * A GHFunc to invalidate frames.
3725 * value must be a DebuggerTlsData*
3728 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3730 invalidate_frames (value);
3734 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3736 /* Sent later in jit_end () */
3737 mono_loader_lock ();
3738 g_ptr_array_add (pending_assembly_loads, assembly);
3739 mono_loader_unlock ();
3743 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3745 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3747 clear_event_requests_for_assembly (assembly);
3748 clear_types_for_assembly (assembly);
3752 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3754 #if defined(HOST_WIN32) && !defined(__GNUC__)
3755 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3757 gpointer stackptr = __builtin_frame_address (1);
3759 MonoInternalThread *thread = mono_thread_internal_current ();
3760 DebuggerTlsData *tls;
3762 mono_loader_lock ();
3764 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3765 /* Could be the debugger thread with assembly/type load hooks */
3767 tls->invoke_addr = stackptr;
3769 mono_loader_unlock ();
3773 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3776 #if defined(HOST_WIN32) && !defined(__GNUC__)
3777 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3779 gpointer stackptr = __builtin_frame_address (1);
3782 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3786 * We need to stop single stepping when exiting a runtime invoke, since if it is
3787 * a step out, it may return to native code, and thus never end.
3789 mono_loader_lock ();
3790 ss_invoke_addr = NULL;
3792 for (i = 0; i < event_requests->len; ++i) {
3793 EventRequest *req = g_ptr_array_index (event_requests, i);
3795 if (req->event_kind == EVENT_KIND_STEP) {
3796 ss_destroy (req->info);
3797 g_ptr_array_remove_index_fast (event_requests, i);
3802 mono_loader_unlock ();
3806 send_type_load (MonoClass *klass)
3808 gboolean type_load = FALSE;
3809 MonoDomain *domain = mono_domain_get ();
3810 AgentDomainInfo *info = NULL;
3812 mono_loader_lock ();
3813 mono_domain_lock (domain);
3815 info = get_agent_domain_info (domain);
3817 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3819 g_hash_table_insert (info->loaded_classes, klass, klass);
3822 mono_domain_unlock (domain);
3823 mono_loader_unlock ();
3825 emit_type_load (klass, klass, NULL);
3829 * Emit load events for all types currently loaded in the domain.
3830 * Takes the loader and domain locks.
3831 * user_data is unused.
3834 send_types_for_domain (MonoDomain *domain, void *user_data)
3836 AgentDomainInfo *info = NULL;
3838 mono_loader_lock ();
3839 mono_domain_lock (domain);
3840 info = get_agent_domain_info (domain);
3842 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3843 mono_domain_unlock (domain);
3844 mono_loader_unlock ();
3848 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3851 * We emit type load events when the first method of the type is JITted,
3852 * since the class load profiler callbacks might be called with the
3853 * loader lock held. They could also occur in the debugger thread.
3854 * Same for assembly load events.
3857 MonoAssembly *assembly = NULL;
3859 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3860 mono_loader_lock ();
3861 if (pending_assembly_loads->len > 0) {
3862 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3863 g_ptr_array_remove_index (pending_assembly_loads, 0);
3865 mono_loader_unlock ();
3868 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3874 send_type_load (method->klass);
3877 add_pending_breakpoints (method, jinfo);
3881 * BREAKPOINTS/SINGLE STEPPING
3885 * Contains information about an inserted breakpoint.
3888 long il_offset, native_offset;
3893 } BreakpointInstance;
3896 * Contains generic information about a breakpoint.
3900 * The method where the breakpoint is placed. Can be NULL in which case it
3901 * is inserted into every method. This is used to implement method entry/
3902 * exit events. Can be a generic method definition, in which case the
3903 * breakpoint is inserted into every instance.
3909 * A list of BreakpointInstance structures describing where the breakpoint
3910 * was inserted. There could be more than one because of
3911 * generics/appdomains/method entry/exit.
3913 GPtrArray *children;
3916 /* List of breakpoints */
3917 static GPtrArray *breakpoints;
3918 /* Maps breakpoint locations to the number of breakpoints at that location */
3919 static GHashTable *bp_locs;
3922 breakpoints_init (void)
3924 breakpoints = g_ptr_array_new ();
3925 bp_locs = g_hash_table_new (NULL, NULL);
3929 * insert_breakpoint:
3931 * Insert the breakpoint described by BP into the method described by
3935 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3938 BreakpointInstance *inst;
3939 SeqPoint *sp = NULL;
3942 mono_error_init (error);
3944 for (i = 0; i < seq_points->len; ++i) {
3945 sp = &seq_points->seq_points [i];
3947 if (sp->il_offset == bp->il_offset)
3951 if (i == seq_points->len) {
3953 * The set of IL offsets with seq points doesn't completely match the
3954 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3956 for (i = 0; i < seq_points->len; ++i) {
3957 sp = &seq_points->seq_points [i];
3959 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3964 if (i == seq_points->len) {
3965 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);
3967 for (i = 0; i < seq_points->len; ++i)
3968 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
3971 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3980 inst = g_new0 (BreakpointInstance, 1);
3982 inst->native_offset = sp->native_offset;
3983 inst->ip = (guint8*)ji->code_start + sp->native_offset;
3985 inst->domain = domain;
3987 mono_loader_lock ();
3989 g_ptr_array_add (bp->children, inst);
3991 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3992 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3993 mono_loader_unlock ();
3996 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3997 mono_arch_set_breakpoint (ji, inst->ip);
4003 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4007 remove_breakpoint (BreakpointInstance *inst)
4009 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4011 MonoJitInfo *ji = inst->ji;
4012 guint8 *ip = inst->ip;
4014 mono_loader_lock ();
4015 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4016 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4017 mono_loader_unlock ();
4019 g_assert (count > 0);
4022 mono_arch_clear_breakpoint (ji, ip);
4029 static inline gboolean
4030 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4036 if (method == bp->method)
4038 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4041 if (bp->method->is_inflated && method->is_inflated) {
4042 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4043 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4045 /* Open generic methods should match closed generic methods of the same class */
4046 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4047 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4048 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4050 /* FIXME: Handle !mvar */
4051 if (t1->type != MONO_TYPE_MVAR)
4062 * add_pending_breakpoints:
4064 * Insert pending breakpoints into the newly JITted method METHOD.
4067 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4070 MonoSeqPointInfo *seq_points;
4076 domain = mono_domain_get ();
4078 mono_loader_lock ();
4080 for (i = 0; i < breakpoints->len; ++i) {
4081 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4082 gboolean found = FALSE;
4084 if (!bp_matches_method (bp, method))
4087 for (j = 0; j < bp->children->len; ++j) {
4088 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4095 mono_domain_lock (domain);
4096 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4097 if (!seq_points && ji->method->is_inflated)
4098 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4099 mono_domain_unlock (domain);
4101 /* Could be AOT code */
4103 g_assert (seq_points);
4105 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4109 mono_loader_unlock ();
4113 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4119 mono_error_init (error);
4121 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4123 /* Might be AOTed code */
4124 code = mono_aot_get_method (domain, method);
4126 ji = mono_jit_info_table_find (domain, code);
4131 insert_breakpoint (seq_points, domain, ji, bp, error);
4135 clear_breakpoint (MonoBreakpoint *bp);
4140 * Set a breakpoint at IL_OFFSET in METHOD.
4141 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4142 * METHOD can also be a generic method definition, in which case a breakpoint
4143 * is placed in all instances of the method.
4144 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4147 static MonoBreakpoint*
4148 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4151 GHashTableIter iter, iter2;
4154 MonoSeqPointInfo *seq_points;
4157 mono_error_init (error);
4160 // - suspend/resume the vm to prevent code patching problems
4161 // - multiple breakpoints on the same location
4162 // - dynamic methods
4165 bp = g_new0 (MonoBreakpoint, 1);
4166 bp->method = method;
4167 bp->il_offset = il_offset;
4169 bp->children = g_ptr_array_new ();
4171 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));
4173 mono_loader_lock ();
4175 g_hash_table_iter_init (&iter, domains);
4176 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4177 mono_domain_lock (domain);
4179 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4180 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4181 if (bp_matches_method (bp, m))
4182 set_bp_in_method (domain, m, seq_points, bp, error);
4185 mono_domain_unlock (domain);
4188 mono_loader_unlock ();
4190 mono_loader_lock ();
4191 g_ptr_array_add (breakpoints, bp);
4192 mono_loader_unlock ();
4194 if (error && !mono_error_ok (error)) {
4195 clear_breakpoint (bp);
4203 clear_breakpoint (MonoBreakpoint *bp)
4207 // FIXME: locking, races
4208 for (i = 0; i < bp->children->len; ++i) {
4209 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4211 remove_breakpoint (inst);
4216 mono_loader_lock ();
4217 g_ptr_array_remove (breakpoints, bp);
4218 mono_loader_unlock ();
4220 g_ptr_array_free (bp->children, TRUE);
4225 breakpoints_cleanup (void)
4229 mono_loader_lock ();
4231 while (i < event_requests->len) {
4232 EventRequest *req = g_ptr_array_index (event_requests, i);
4234 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4235 clear_breakpoint (req->info);
4236 g_ptr_array_remove_index_fast (event_requests, i);
4243 for (i = 0; i < breakpoints->len; ++i)
4244 g_free (g_ptr_array_index (breakpoints, i));
4246 g_ptr_array_free (breakpoints, TRUE);
4247 g_hash_table_destroy (bp_locs);
4252 mono_loader_unlock ();
4256 * clear_breakpoints_for_domain:
4258 * Clear breakpoint instances which reference DOMAIN.
4261 clear_breakpoints_for_domain (MonoDomain *domain)
4265 /* This could be called after shutdown */
4269 mono_loader_lock ();
4270 for (i = 0; i < breakpoints->len; ++i) {
4271 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4274 while (j < bp->children->len) {
4275 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4277 if (inst->domain == domain) {
4278 remove_breakpoint (inst);
4282 g_ptr_array_remove_index_fast (bp->children, j);
4288 mono_loader_unlock ();
4292 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4294 return bp->method && bp->method->klass->image->assembly == assembly;
4298 process_breakpoint_inner (DebuggerTlsData *tls)
4302 int i, j, suspend_policy;
4303 guint32 native_offset;
4305 BreakpointInstance *inst;
4306 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4307 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4308 EventKind kind = EVENT_KIND_BREAKPOINT;
4309 MonoContext *ctx = &tls->restore_ctx;
4310 MonoSeqPointInfo *info;
4313 // FIXME: Speed this up
4315 ip = MONO_CONTEXT_GET_IP (ctx);
4316 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4318 g_assert (ji->method);
4320 /* Compute the native offset of the breakpoint from the ip */
4321 native_offset = ip - (guint8*)ji->code_start;
4324 * Skip the instruction causing the breakpoint signal.
4326 mono_arch_skip_breakpoint (ctx, ji);
4328 if (ji->method->wrapper_type || tls->disable_breakpoints)
4331 bp_reqs = g_ptr_array_new ();
4332 ss_reqs = g_ptr_array_new ();
4333 ss_reqs_orig = g_ptr_array_new ();
4335 mono_loader_lock ();
4338 * The ip points to the instruction causing the breakpoint event, which is after
4339 * the offset recorded in the seq point map, so find the prev seq point before ip.
4341 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4343 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));
4346 for (i = 0; i < breakpoints->len; ++i) {
4347 bp = g_ptr_array_index (breakpoints, i);
4352 for (j = 0; j < bp->children->len; ++j) {
4353 inst = g_ptr_array_index (bp->children, j);
4354 if (inst->ji == ji && inst->sp == sp) {
4355 if (bp->req->event_kind == EVENT_KIND_STEP) {
4356 g_ptr_array_add (ss_reqs_orig, bp->req);
4358 g_ptr_array_add (bp_reqs, bp->req);
4363 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4364 /* Maybe a method entry/exit event */
4365 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4366 kind = EVENT_KIND_METHOD_ENTRY;
4367 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4368 kind = EVENT_KIND_METHOD_EXIT;
4371 /* Process single step requests */
4372 for (i = 0; i < ss_reqs_orig->len; ++i) {
4373 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4374 SingleStepReq *ss_req = req->info;
4375 gboolean hit = TRUE;
4377 if (ss_req->size == STEP_SIZE_LINE) {
4378 /* Have to check whenever a different source line was reached */
4379 MonoDebugMethodInfo *minfo;
4380 MonoDebugSourceLocation *loc = NULL;
4382 minfo = mono_debug_lookup_method (ji->method);
4385 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4387 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4388 /* Have to continue single stepping */
4389 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4394 ss_req->last_method = ji->method;
4395 ss_req->last_line = loc->row;
4396 mono_debug_free_source_location (loc);
4401 g_ptr_array_add (ss_reqs, req);
4403 /* Start single stepping again from the current sequence point */
4404 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4407 if (ss_reqs->len > 0)
4408 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4409 if (bp_reqs->len > 0)
4410 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4411 if (kind != EVENT_KIND_BREAKPOINT)
4412 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4414 mono_loader_unlock ();
4416 g_ptr_array_free (bp_reqs, TRUE);
4417 g_ptr_array_free (ss_reqs, TRUE);
4420 * FIXME: The first event will suspend, so the second will only be sent after the
4424 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4426 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4427 if (enter_leave_events)
4428 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4431 /* Process a breakpoint/single step event after resuming from a signal handler */
4433 process_signal_event (void (*func) (DebuggerTlsData*))
4435 DebuggerTlsData *tls;
4436 MonoContext orig_restore_ctx, ctx;
4437 static void (*restore_context) (void *);
4439 if (!restore_context)
4440 restore_context = mono_get_restore_context ();
4442 tls = mono_native_tls_get_value (debugger_tls_id);
4443 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4444 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4445 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4449 /* This is called when resuming from a signal handler, so it shouldn't return */
4450 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4451 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4452 restore_context (&ctx);
4453 g_assert_not_reached ();
4457 process_breakpoint (void)
4459 process_signal_event (process_breakpoint_inner);
4463 resume_from_signal_handler (void *sigctx, void *func)
4465 DebuggerTlsData *tls;
4468 /* Save the original context in TLS */
4469 // FIXME: This might not work on an altstack ?
4470 tls = mono_native_tls_get_value (debugger_tls_id);
4473 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4474 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4475 // clob:c could be added to op_seq_point.
4477 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4478 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4479 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4480 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4482 MONO_CONTEXT_SET_IP (&ctx, func);
4484 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4486 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4487 mono_ppc_set_func_into_sigctx (sigctx, func);
4492 mono_debugger_agent_breakpoint_hit (void *sigctx)
4495 * We are called from a signal handler, and running code there causes all kinds of
4496 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4497 * So set up the signal context to return to the real breakpoint handler function.
4499 resume_from_signal_handler (sigctx, process_breakpoint);
4503 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4505 if (frame->managed) {
4506 *(MonoContext*)data = *ctx;
4515 * Called by System.Diagnostics.Debugger:Break ().
4518 mono_debugger_agent_user_break (void)
4520 if (agent_config.enabled) {
4525 /* Obtain a context */
4526 MONO_CONTEXT_SET_IP (&ctx, NULL);
4527 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4528 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4530 mono_loader_lock ();
4531 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4532 mono_loader_unlock ();
4534 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4541 ss_depth_to_string (StepDepth depth)
4544 case STEP_DEPTH_OVER:
4546 case STEP_DEPTH_OUT:
4548 case STEP_DEPTH_INTO:
4551 g_assert_not_reached ();
4557 process_single_step_inner (DebuggerTlsData *tls)
4562 int il_offset, suspend_policy;
4565 MonoContext *ctx = &tls->restore_ctx;
4567 MonoSeqPointInfo *info;
4569 ip = MONO_CONTEXT_GET_IP (ctx);
4571 /* Skip the instruction causing the single step */
4572 mono_arch_skip_single_step (ctx);
4574 if (suspend_count > 0) {
4575 process_suspend (tls, ctx);
4580 // FIXME: A suspend race
4583 if (mono_thread_internal_current () != ss_req->thread)
4586 if (log_level > 0) {
4587 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4589 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));
4592 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4594 g_assert (ji->method);
4596 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4601 * Stopping in memset makes half-initialized vtypes visible.
4602 * Stopping in memcpy makes half-copied vtypes visible.
4604 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4608 * The ip points to the instruction causing the single step event, which is before
4609 * the offset recorded in the seq point map, so find the next seq point after ip.
4611 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4614 il_offset = sp->il_offset;
4616 // FIXME: No tests fail if this is disabled
4618 if (ss_req->size == STEP_SIZE_LINE) {
4622 /* Step until a different source line is reached */
4623 MonoDebugMethodInfo *minfo;
4625 minfo = mono_debug_lookup_method (ji->method);
4628 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4630 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4631 mono_debug_free_source_location (loc);
4636 * Step until we reach a location with line number info,
4637 * otherwise the client can't show a location.
4638 * This can happen for example with statics initialized inline
4639 * outside of a cctor.
4644 ss_req->last_method = ji->method;
4645 ss_req->last_line = loc->row;
4646 mono_debug_free_source_location (loc);
4652 /* Start single stepping again from the current sequence point */
4653 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4655 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4656 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4657 !strcmp (ji->method->name, ".cctor"))
4660 // FIXME: Has to lock earlier
4662 reqs = g_ptr_array_new ();
4664 mono_loader_lock ();
4666 g_ptr_array_add (reqs, ss_req->req);
4668 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4670 g_ptr_array_free (reqs, TRUE);
4672 mono_loader_unlock ();
4674 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4678 process_single_step (void)
4680 process_signal_event (process_single_step_inner);
4684 * mono_debugger_agent_single_step_event:
4686 * Called from a signal handler to handle a single step event.
4689 mono_debugger_agent_single_step_event (void *sigctx)
4691 /* Resume to process_single_step through the signal context */
4693 // FIXME: Since step out/over is implemented using step in, the step in case should
4694 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4697 if (GetCurrentThreadId () == debugger_thread_id) {
4699 * This could happen despite our best effors when the runtime calls
4700 * assembly/type resolve hooks.
4701 * FIXME: Breakpoints too.
4705 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4706 mono_arch_skip_single_step (&ctx);
4707 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4711 resume_from_signal_handler (sigctx, process_single_step);
4715 debugger_agent_single_step_from_context (MonoContext *ctx)
4717 DebuggerTlsData *tls;
4718 MonoContext orig_restore_ctx;
4720 tls = mono_native_tls_get_value (debugger_tls_id);
4723 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4724 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4725 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4727 process_single_step_inner (tls);
4729 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4730 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4734 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4736 DebuggerTlsData *tls;
4737 MonoContext orig_restore_ctx;
4739 tls = mono_native_tls_get_value (debugger_tls_id);
4741 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4742 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4744 process_breakpoint_inner (tls);
4746 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4747 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4751 * start_single_stepping:
4753 * Turn on single stepping. Can be called multiple times, for example,
4754 * by a single step event request + a suspend.
4757 start_single_stepping (void)
4759 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4760 int val = InterlockedIncrement (&ss_count);
4763 mono_arch_start_single_stepping ();
4765 if (ss_req != NULL && ss_invoke_addr == NULL) {
4766 DebuggerTlsData *tls;
4768 mono_loader_lock ();
4770 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4771 ss_invoke_addr = tls->invoke_addr;
4773 mono_loader_unlock ();
4776 g_assert_not_reached ();
4781 stop_single_stepping (void)
4783 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4784 int val = InterlockedDecrement (&ss_count);
4787 mono_arch_stop_single_stepping ();
4789 g_assert_not_reached ();
4796 * Stop the single stepping operation given by SS_REQ.
4799 ss_stop (SingleStepReq *ss_req)
4804 for (l = ss_req->bps; l; l = l->next) {
4805 clear_breakpoint (l->data);
4807 g_slist_free (ss_req->bps);
4811 if (ss_req->global) {
4812 stop_single_stepping ();
4813 ss_req->global = FALSE;
4820 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4821 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4822 * belong to the same thread as CTX.
4825 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4827 int i, j, frame_index;
4830 gboolean enable_global = FALSE;
4832 /* Stop the previous operation */
4836 * Implement single stepping using breakpoints if possible.
4838 if (step_to_catch) {
4839 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4840 ss_req->bps = g_slist_append (ss_req->bps, bp);
4844 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4845 /* Need parent frames */
4846 if (!tls->context.valid)
4847 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4848 compute_frame_info (tls->thread, tls);
4852 * Find the first sequence point in the current or in a previous frame which
4853 * is not the last in its method.
4855 if (ss_req->depth == STEP_DEPTH_OUT) {
4856 /* Ignore seq points in current method */
4857 while (frame_index < tls->frame_count) {
4858 StackFrame *frame = tls->frames [frame_index];
4860 method = frame->method;
4861 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4863 if (sp && sp->next_len != 0)
4866 // There could be method calls before the next seq point in the caller when using nested calls
4867 //enable_global = TRUE;
4869 while (sp && sp->next_len == 0) {
4871 if (frame_index < tls->frame_count) {
4872 StackFrame *frame = tls->frames [frame_index];
4874 method = frame->method;
4875 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4881 if (sp && sp->next_len > 0) {
4882 for (i = 0; i < sp->next_len; ++i) {
4883 next_sp = &info->seq_points [sp->next [i]];
4885 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4886 ss_req->bps = g_slist_append (ss_req->bps, bp);
4890 if (ss_req->depth == STEP_DEPTH_OVER) {
4891 /* Need to stop in catch clauses as well */
4892 for (i = 0; i < tls->frame_count; ++i) {
4893 StackFrame *frame = tls->frames [i];
4896 MonoJitInfo *jinfo = frame->ji;
4897 for (j = 0; j < jinfo->num_clauses; ++j) {
4898 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4900 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4902 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4903 ss_req->bps = g_slist_append (ss_req->bps, bp);
4911 if (ss_req->depth == STEP_DEPTH_INTO) {
4912 /* Enable global stepping so we stop at method entry too */
4913 enable_global = TRUE;
4917 * The ctx/frame info computed above will become invalid when we continue.
4919 tls->context.valid = FALSE;
4920 tls->async_state.valid = FALSE;
4921 invalidate_frames (tls);
4924 if (enable_global) {
4925 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4926 ss_req->global = TRUE;
4927 start_single_stepping ();
4928 } else if (!ss_req->bps) {
4929 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4930 ss_req->global = TRUE;
4931 start_single_stepping ();
4933 ss_req->global = FALSE;
4938 * Start single stepping of thread THREAD
4941 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4943 DebuggerTlsData *tls;
4944 MonoSeqPointInfo *info = NULL;
4945 SeqPoint *sp = NULL;
4946 MonoMethod *method = NULL;
4947 MonoDebugMethodInfo *minfo;
4948 gboolean step_to_catch = FALSE;
4950 if (suspend_count == 0)
4951 return ERR_NOT_SUSPENDED;
4953 wait_for_suspend ();
4955 // FIXME: Multiple requests
4957 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4958 return ERR_NOT_IMPLEMENTED;
4961 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4963 ss_req = g_new0 (SingleStepReq, 1);
4965 ss_req->thread = thread;
4966 ss_req->size = size;
4967 ss_req->depth = depth;
4970 mono_loader_lock ();
4971 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4972 mono_loader_unlock ();
4974 g_assert (tls->context.valid);
4975 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4977 if (tls->has_catch_ctx) {
4979 StackFrameInfo frame;
4980 MonoContext new_ctx;
4981 MonoLMF *lmf = NULL;
4984 * We are stopped at a throw site. Stepping should go to the catch site.
4987 /* Find the the jit info for the catch context */
4988 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4990 g_assert (frame.type == FRAME_TYPE_MANAGED);
4993 * Find the seq point corresponding to the landing site ip, which is the first seq
4996 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4999 method = frame.method;
5001 step_to_catch = TRUE;
5002 /* This make sure the seq point is not skipped by process_single_step () */
5003 ss_req->last_sp = NULL;
5006 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5009 /* Compute the initial line info */
5010 compute_frame_info (thread, tls);
5012 if (tls->frame_count) {
5013 frame = tls->frames [0];
5015 ss_req->last_method = frame->method;
5016 ss_req->last_line = -1;
5018 minfo = mono_debug_lookup_method (frame->method);
5019 if (minfo && frame->il_offset != -1) {
5020 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5023 ss_req->last_line = loc->row;
5030 if (!step_to_catch) {
5033 compute_frame_info (thread, tls);
5035 if (tls->frame_count) {
5036 frame = tls->frames [0];
5038 if (!method && frame->il_offset != -1) {
5039 /* FIXME: Sort the table and use a binary search */
5040 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5042 method = frame->method;
5047 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5053 ss_destroy (SingleStepReq *req)
5056 g_assert (ss_req == req);
5065 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5068 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5074 if (!agent_config.enabled)
5077 mono_loader_lock ();
5078 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5079 mono_loader_unlock ();
5082 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5083 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5085 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5087 g_free (ei.category);
5088 g_free (ei.message);
5092 mono_debugger_agent_debug_log_is_enabled (void)
5094 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5095 return agent_config.enabled;
5099 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5100 MonoContext *catch_ctx)
5106 DebuggerTlsData *tls = NULL;
5108 if (thread_to_tls != NULL) {
5109 MonoInternalThread *thread = mono_thread_internal_current ();
5111 mono_loader_lock ();
5112 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5113 mono_loader_unlock ();
5115 if (tls && tls->abort_requested)
5117 if (tls && tls->disable_breakpoints)
5121 memset (&ei, 0, sizeof (EventInfo));
5123 /* Just-In-Time debugging */
5125 if (agent_config.onuncaught && !inited) {
5126 finish_agent_init (FALSE);
5129 * Send an unsolicited EXCEPTION event with a dummy request id.
5131 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5132 ei.exc = (MonoObject*)exc;
5133 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5136 } else if (agent_config.onthrow && !inited) {
5138 gboolean found = FALSE;
5140 for (l = agent_config.onthrow; l; l = l->next) {
5141 char *ex_type = l->data;
5142 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5144 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5151 finish_agent_init (FALSE);
5154 * Send an unsolicited EXCEPTION event with a dummy request id.
5156 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5157 ei.exc = (MonoObject*)exc;
5158 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5166 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5168 ei.exc = (MonoObject*)exc;
5169 ei.caught = catch_ctx != NULL;
5171 mono_loader_lock ();
5172 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5173 mono_loader_unlock ();
5175 if (tls && catch_ctx) {
5176 tls->catch_ctx = *catch_ctx;
5177 tls->has_catch_ctx = TRUE;
5180 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5183 tls->has_catch_ctx = FALSE;
5187 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5189 DebuggerTlsData *tls;
5194 tls = mono_native_tls_get_value (debugger_tls_id);
5199 * We're about to invoke an exception filter during the first pass of exception handling.
5201 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5202 * 'orig_ctx' is the context where the exception has been thrown.
5205 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5207 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5208 * the call site (line 37) and then continue to Main(), but it would never
5209 * include the throw site (line 32).
5211 * Since exception filters are invoked during the first pass of exception handling,
5212 * the stack frames of the throw site are still intact, so we should include them
5215 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5217 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5218 * but report the location of the 'throw' to the user.
5222 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5226 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5228 DebuggerTlsData *tls;
5233 tls = mono_native_tls_get_value (debugger_tls_id);
5237 tls->filter_state.valid = FALSE;
5241 * buffer_add_value_full:
5243 * Add the encoding of the value at ADDR described by T to the buffer.
5244 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5248 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5254 g_assert (*(void**)addr);
5255 addr = *(void**)addr;
5260 case MONO_TYPE_BOOLEAN:
5263 case MONO_TYPE_CHAR:
5283 case MONO_TYPE_VOID:
5284 buffer_add_byte (buf, t->type);
5286 case MONO_TYPE_BOOLEAN:
5289 buffer_add_byte (buf, t->type);
5290 buffer_add_int (buf, *(gint8*)addr);
5292 case MONO_TYPE_CHAR:
5295 buffer_add_byte (buf, t->type);
5296 buffer_add_int (buf, *(gint16*)addr);
5301 buffer_add_byte (buf, t->type);
5302 buffer_add_int (buf, *(gint32*)addr);
5307 buffer_add_byte (buf, t->type);
5308 buffer_add_long (buf, *(gint64*)addr);
5312 /* Treat it as a vtype */
5314 case MONO_TYPE_PTR: {
5315 gssize val = *(gssize*)addr;
5317 buffer_add_byte (buf, t->type);
5318 buffer_add_long (buf, val);
5322 case MONO_TYPE_STRING:
5323 case MONO_TYPE_SZARRAY:
5324 case MONO_TYPE_OBJECT:
5325 case MONO_TYPE_CLASS:
5326 case MONO_TYPE_ARRAY:
5327 obj = *(MonoObject**)addr;
5330 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5332 if (obj->vtable->klass->valuetype) {
5333 t = &obj->vtable->klass->byval_arg;
5334 addr = mono_object_unbox (obj);
5336 } else if (obj->vtable->klass->rank) {
5337 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5338 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5339 buffer_add_byte (buf, MONO_TYPE_CLASS);
5341 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5343 buffer_add_objid (buf, obj);
5347 case MONO_TYPE_VALUETYPE: {
5351 MonoClass *klass = mono_class_from_mono_type (t);
5353 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5354 buffer_add_byte (buf, klass->enumtype);
5355 buffer_add_typeid (buf, domain, klass);
5359 while ((f = mono_class_get_fields (klass, &iter))) {
5360 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5362 if (mono_field_is_deleted (f))
5366 buffer_add_int (buf, nfields);
5369 while ((f = mono_class_get_fields (klass, &iter))) {
5370 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5372 if (mono_field_is_deleted (f))
5374 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5378 case MONO_TYPE_GENERICINST:
5379 if (mono_type_generic_inst_is_valuetype (t)) {
5391 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5393 buffer_add_value_full (buf, t, addr, domain, FALSE);
5397 obj_is_of_type (MonoObject *obj, MonoType *t)
5399 MonoClass *klass = obj->vtable->klass;
5400 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5401 if (klass == mono_defaults.transparent_proxy_class) {
5402 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5403 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5413 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5416 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5420 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5421 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5422 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5423 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5424 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5425 char *name = mono_type_full_name (t);
5426 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5428 return ERR_INVALID_ARGUMENT;
5432 case MONO_TYPE_BOOLEAN:
5433 *(guint8*)addr = decode_int (buf, &buf, limit);
5435 case MONO_TYPE_CHAR:
5436 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5439 *(gint8*)addr = decode_int (buf, &buf, limit);
5442 *(guint8*)addr = decode_int (buf, &buf, limit);
5445 *(gint16*)addr = decode_int (buf, &buf, limit);
5448 *(guint16*)addr = decode_int (buf, &buf, limit);
5451 *(gint32*)addr = decode_int (buf, &buf, limit);
5454 *(guint32*)addr = decode_int (buf, &buf, limit);
5457 *(gint64*)addr = decode_long (buf, &buf, limit);
5460 *(guint64*)addr = decode_long (buf, &buf, limit);
5463 *(guint32*)addr = decode_int (buf, &buf, limit);
5466 *(guint64*)addr = decode_long (buf, &buf, limit);
5469 /* We send these as I8, so we get them back as such */
5470 g_assert (type == MONO_TYPE_I8);
5471 *(gssize*)addr = decode_long (buf, &buf, limit);
5473 case MONO_TYPE_GENERICINST:
5474 if (MONO_TYPE_ISSTRUCT (t)) {
5475 /* The client sends these as a valuetype */
5483 /* We send these as vtypes, so we get them back as such */
5484 g_assert (type == MONO_TYPE_VALUETYPE);
5487 case MONO_TYPE_VALUETYPE: {
5488 gboolean is_enum = decode_byte (buf, &buf, limit);
5492 gpointer iter = NULL;
5495 /* Enums are sent as a normal vtype */
5497 return ERR_NOT_IMPLEMENTED;
5498 klass = decode_typeid (buf, &buf, limit, &d, &err);
5502 if (klass != mono_class_from_mono_type (t))
5503 return ERR_INVALID_ARGUMENT;
5505 nfields = decode_int (buf, &buf, limit);
5506 while ((f = mono_class_get_fields (klass, &iter))) {
5507 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5509 if (mono_field_is_deleted (f))
5511 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5516 g_assert (nfields == 0);
5521 if (MONO_TYPE_IS_REFERENCE (t)) {
5522 if (type == MONO_TYPE_OBJECT) {
5523 int objid = decode_objid (buf, &buf, limit);
5527 err = get_object (objid, (MonoObject**)&obj);
5532 if (!obj_is_of_type (obj, t)) {
5533 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5534 return ERR_INVALID_ARGUMENT;
5537 if (obj && obj->vtable->domain != domain)
5538 return ERR_INVALID_ARGUMENT;
5540 mono_gc_wbarrier_generic_store (addr, obj);
5541 } else if (type == VALUE_TYPE_ID_NULL) {
5542 *(MonoObject**)addr = NULL;
5544 return ERR_INVALID_ARGUMENT;
5558 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5561 int type = decode_byte (buf, &buf, limit);
5563 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5564 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5565 guint8 *nullable_buf;
5568 * First try decoding it as a Nullable`1
5570 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5575 * Then try decoding as a primitive value or null.
5577 if (targ->type == type) {
5578 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5579 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5581 g_free (nullable_buf);
5584 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5585 g_free (nullable_buf);
5588 } else if (type == VALUE_TYPE_ID_NULL) {
5589 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5595 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5599 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5606 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5607 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5610 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5611 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5613 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5615 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5616 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5617 addr += (gint32)var->offset;
5619 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5621 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5623 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5627 g_assert_not_reached ();
5632 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5638 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5639 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5641 if (MONO_TYPE_IS_REFERENCE (t))
5642 size = sizeof (gpointer);
5644 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5647 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5648 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5650 gboolean is_signed = FALSE;
5652 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5657 v = is_signed ? *(gint8*)val : *(guint8*)val;
5660 v = is_signed ? *(gint16*)val : *(guint16*)val;
5663 v = is_signed ? *(gint32*)val : *(guint32*)val;
5666 v = is_signed ? *(gint64*)val : *(guint64*)val;
5669 g_assert_not_reached ();
5675 /* Set value on the stack or in the return ctx */
5676 if (reg_locations [reg]) {
5677 /* Saved on the stack */
5678 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5679 *(reg_locations [reg]) = v;
5682 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5683 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5686 // FIXME: Move these to mono-context.h/c.
5687 mono_arch_context_set_int_reg (ctx, reg, v);
5689 // FIXME: Can't set registers, so we disable linears
5694 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5695 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5696 addr += (gint32)var->offset;
5698 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5701 addr = *(guint8**)addr;
5707 // FIXME: Write barriers
5708 mono_gc_memmove (addr, val, size);
5710 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5714 g_assert_not_reached ();
5719 clear_event_request (int req_id, int etype)
5723 mono_loader_lock ();
5724 for (i = 0; i < event_requests->len; ++i) {
5725 EventRequest *req = g_ptr_array_index (event_requests, i);
5727 if (req->id == req_id && req->event_kind == etype) {
5728 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5729 clear_breakpoint (req->info);
5730 if (req->event_kind == EVENT_KIND_STEP)
5731 ss_destroy (req->info);
5732 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5733 clear_breakpoint (req->info);
5734 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5735 clear_breakpoint (req->info);
5736 g_ptr_array_remove_index_fast (event_requests, i);
5741 mono_loader_unlock ();
5745 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5747 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5748 return breakpoint_matches_assembly (req->info, assembly);
5752 for (i = 0; i < req->nmodifiers; ++i) {
5753 Modifier *m = &req->modifiers [i];
5755 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5757 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5758 for (j = 0; m->data.assemblies [j]; ++j)
5759 if (m->data.assemblies [j] == assembly)
5769 * clear_event_requests_for_assembly:
5771 * Clear all events requests which reference ASSEMBLY.
5774 clear_event_requests_for_assembly (MonoAssembly *assembly)
5779 mono_loader_lock ();
5783 for (i = 0; i < event_requests->len; ++i) {
5784 EventRequest *req = g_ptr_array_index (event_requests, i);
5786 if (event_req_matches_assembly (req, assembly)) {
5787 clear_event_request (req->id, req->event_kind);
5793 mono_loader_unlock ();
5797 * type_comes_from_assembly:
5799 * GHRFunc that returns TRUE if klass comes from assembly
5802 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5804 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5808 * clear_types_for_assembly:
5810 * Clears types from loaded_classes for a given assembly
5813 clear_types_for_assembly (MonoAssembly *assembly)
5815 MonoDomain *domain = mono_domain_get ();
5816 AgentDomainInfo *info = NULL;
5818 mono_loader_lock ();
5819 info = get_agent_domain_info (domain);
5820 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5821 mono_loader_unlock ();
5825 add_thread (gpointer key, gpointer value, gpointer user_data)
5827 MonoInternalThread *thread = value;
5828 Buffer *buf = user_data;
5830 buffer_add_objid (buf, (MonoObject*)thread);
5834 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5836 guint8 *end = invoke->endp;
5839 MonoMethodSignature *sig;
5842 MonoObject *this, *res, *exc;
5845 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5848 MonoStopwatch watch;
5850 if (invoke->method) {
5852 * Invoke this method directly, currently only Environment.Exit () is supported.
5855 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>"));
5856 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5857 g_assert_not_reached ();
5860 m = decode_methodid (p, &p, end, &domain, &err);
5863 sig = mono_method_signature (m);
5865 if (m->klass->valuetype)
5866 this_buf = g_alloca (mono_class_instance_size (m->klass));
5868 this_buf = g_alloca (sizeof (MonoObject*));
5869 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5870 /* Should be null */
5871 int type = decode_byte (p, &p, end);
5872 if (type != VALUE_TYPE_ID_NULL)
5873 return ERR_INVALID_ARGUMENT;
5874 memset (this_buf, 0, mono_class_instance_size (m->klass));
5876 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5881 if (!m->klass->valuetype)
5882 this = *(MonoObject**)this_buf;
5886 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>"));
5888 if (this && this->vtable->domain != domain)
5891 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5892 if (!strcmp (m->name, ".ctor")) {
5893 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5894 return ERR_INVALID_ARGUMENT;
5896 this = mono_object_new (domain, m->klass);
5898 return ERR_INVALID_ARGUMENT;
5902 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
5903 return ERR_INVALID_ARGUMENT;
5905 nargs = decode_int (p, &p, end);
5906 if (nargs != sig->param_count)
5907 return ERR_INVALID_ARGUMENT;
5908 /* Use alloca to get gc tracking */
5909 arg_buf = g_alloca (nargs * sizeof (gpointer));
5910 memset (arg_buf, 0, nargs * sizeof (gpointer));
5911 args = g_alloca (nargs * sizeof (gpointer));
5912 for (i = 0; i < nargs; ++i) {
5913 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5914 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5918 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5921 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5922 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5925 args [i] = arg_buf [i];
5932 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5933 tls->disable_breakpoints = TRUE;
5935 tls->disable_breakpoints = FALSE;
5938 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5940 /* FIXME: Move this to arch specific code */
5941 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5942 if (invoke->has_ctx) {
5945 lmf_addr = mono_get_lmf_addr ();
5948 memset (&ext, 0, sizeof (ext));
5950 ext.lmf.previous_lmf = *(lmf_addr);
5951 /* Mark that this is a MonoLMFExt */
5952 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5953 ext.lmf.rsp = (gssize)&ext;
5954 #elif defined(TARGET_X86)
5955 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5956 /* Mark that this is a MonoLMFExt */
5957 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5958 ext.lmf.ebp = (gssize)&ext;
5959 #elif defined(TARGET_ARM)
5960 ext.lmf.previous_lmf = *(lmf_addr);
5961 /* Mark that this is a MonoLMFExt */
5962 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5963 ext.lmf.sp = (gssize)&ext;
5964 #elif defined(TARGET_POWERPC)
5965 ext.lmf.previous_lmf = *(lmf_addr);
5966 /* Mark that this is a MonoLMFExt */
5967 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5968 ext.lmf.ebp = (gssize)&ext;
5969 #elif defined(TARGET_S390X)
5970 ext.lmf.previous_lmf = *(lmf_addr);
5971 /* Mark that this is a MonoLMFExt */
5972 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5973 ext.lmf.ebp = (gssize)&ext;
5974 #elif defined(TARGET_MIPS)
5975 ext.lmf.previous_lmf = *(lmf_addr);
5976 /* Mark that this is a MonoLMFExt */
5977 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5978 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5980 g_assert_not_reached ();
5983 ext.debugger_invoke = TRUE;
5984 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5986 mono_set_lmf ((MonoLMF*)&ext);
5990 mono_stopwatch_start (&watch);
5991 if (m->klass->valuetype)
5992 res = mono_runtime_invoke (m, this_buf, args, &exc);
5994 res = mono_runtime_invoke (m, this, args, &exc);
5995 mono_stopwatch_stop (&watch);
5996 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)));
5998 buffer_add_byte (buf, 0);
5999 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6001 buffer_add_byte (buf, 1);
6002 if (sig->ret->type == MONO_TYPE_VOID) {
6003 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6004 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6007 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6008 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6009 buffer_add_value (buf, sig->ret, &res, domain);
6010 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6011 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6012 MonoClass *k = mono_class_from_mono_type (sig->ret);
6013 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6015 g_assert (nullable_buf);
6016 mono_nullable_init (nullable_buf, res, k);
6017 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6020 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6027 tls->disable_breakpoints = FALSE;
6029 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6030 if (invoke->has_ctx)
6031 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6035 // FIXME: byref arguments
6043 * Invoke the method given by tls->pending_invoke in the current thread.
6046 invoke_method (void)
6048 DebuggerTlsData *tls;
6053 static void (*restore_context) (void *);
6054 MonoContext restore_ctx;
6057 if (!restore_context)
6058 restore_context = mono_get_restore_context ();
6060 tls = mono_native_tls_get_value (debugger_tls_id);
6064 * Store the `InvokeData *' in `tls->invoke' until we're done with
6065 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6068 mono_loader_lock ();
6070 invoke = tls->pending_invoke;
6072 tls->pending_invoke = NULL;
6074 invoke->last_invoke = tls->invoke;
6075 tls->invoke = invoke;
6077 mono_loader_unlock ();
6079 tls->frames_up_to_date = FALSE;
6085 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6086 buffer_init (&buf, 128);
6089 /* Fail the other invokes as well */
6091 err = do_invoke_method (tls, &buf, invoke, p, &p);
6094 /* Start suspending before sending the reply */
6095 if (mindex == invoke->nmethods - 1) {
6096 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6097 for (i = 0; i < invoke->suspend_count; ++i)
6102 send_reply_packet (id, err, &buf);
6107 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6109 if (invoke->has_ctx)
6110 save_thread_context (&restore_ctx);
6112 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6113 g_assert (tls->resume_count);
6114 tls->resume_count -= invoke->suspend_count;
6117 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6120 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6122 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6123 * after the mono_runtime_invoke() already returned, but it doesn't matter
6124 * because we reset the abort here.
6127 mono_loader_lock ();
6129 if (tls->abort_requested)
6130 mono_thread_internal_reset_abort (tls->thread);
6132 tls->invoke = tls->invoke->last_invoke;
6133 tls->abort_requested = FALSE;
6135 mono_loader_unlock ();
6144 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6146 MonoThread *thread = value;
6147 DebuggerTlsData *tls;
6150 mono_loader_lock ();
6151 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6153 res = tls->really_suspended;
6154 mono_loader_unlock ();
6160 get_source_files_for_type (MonoClass *klass)
6162 gpointer iter = NULL;
6164 MonoDebugSourceInfo *sinfo;
6168 files = g_ptr_array_new ();
6170 while ((method = mono_class_get_methods (klass, &iter))) {
6171 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6172 GPtrArray *source_file_list;
6175 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6176 for (j = 0; j < source_file_list->len; ++j) {
6177 sinfo = g_ptr_array_index (source_file_list, j);
6178 for (i = 0; i < files->len; ++i)
6179 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6181 if (i == files->len)
6182 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6184 g_ptr_array_free (source_file_list, TRUE);
6192 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6195 case CMD_VM_VERSION: {
6196 char *build_info, *version;
6198 build_info = mono_get_runtime_build_info ();
6199 version = g_strdup_printf ("mono %s", build_info);
6201 buffer_add_string (buf, version); /* vm version */
6202 buffer_add_int (buf, MAJOR_VERSION);
6203 buffer_add_int (buf, MINOR_VERSION);
6204 g_free (build_info);
6208 case CMD_VM_SET_PROTOCOL_VERSION: {
6209 major_version = decode_int (p, &p, end);
6210 minor_version = decode_int (p, &p, end);
6211 protocol_version_set = TRUE;
6212 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6215 case CMD_VM_ALL_THREADS: {
6217 mono_loader_lock ();
6218 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6219 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6220 mono_loader_unlock ();
6223 case CMD_VM_SUSPEND:
6225 wait_for_suspend ();
6228 if (suspend_count == 0)
6229 return ERR_NOT_SUSPENDED;
6232 case CMD_VM_DISPOSE:
6233 /* Clear all event requests */
6234 mono_loader_lock ();
6235 while (event_requests->len > 0) {
6236 EventRequest *req = g_ptr_array_index (event_requests, 0);
6238 clear_event_request (req->id, req->event_kind);
6240 mono_loader_unlock ();
6242 while (suspend_count > 0)
6244 disconnected = TRUE;
6245 vm_start_event_sent = FALSE;
6248 MonoInternalThread *thread;
6249 DebuggerTlsData *tls;
6250 MonoClass *env_class;
6251 MonoMethod *exit_method = NULL;
6255 exit_code = decode_int (p, &p, end);
6257 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6259 /* Have to send a reply before exiting */
6260 send_reply_packet (id, 0, buf);
6262 /* Clear all event requests */
6263 mono_loader_lock ();
6264 while (event_requests->len > 0) {
6265 EventRequest *req = g_ptr_array_index (event_requests, 0);
6267 clear_event_request (req->id, req->event_kind);
6269 mono_loader_unlock ();
6272 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6273 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6274 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6275 * better than doing the shutdown ourselves, since it avoids various races.
6279 wait_for_suspend ();
6281 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6283 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6285 mono_loader_lock ();
6286 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6287 mono_loader_unlock ();
6289 if (thread && exit_method) {
6290 mono_loader_lock ();
6291 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6292 mono_loader_unlock ();
6294 args = g_new0 (gpointer, 1);
6295 args [0] = g_malloc (sizeof (int));
6296 *(int*)(args [0]) = exit_code;
6298 tls->pending_invoke = g_new0 (InvokeData, 1);
6299 tls->pending_invoke->method = exit_method;
6300 tls->pending_invoke->args = args;
6301 tls->pending_invoke->nmethods = 1;
6303 while (suspend_count > 0)
6307 * No thread found, do it ourselves.
6308 * FIXME: This can race with normal shutdown etc.
6310 while (suspend_count > 0)
6313 mono_runtime_set_shutting_down ();
6315 mono_threads_set_shutting_down ();
6317 /* Suspend all managed threads since the runtime is going away */
6318 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6319 mono_thread_suspend_all_other_threads ();
6320 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6321 mono_runtime_quit ();
6322 transport_close2 ();
6323 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6329 case CMD_VM_INVOKE_METHOD:
6330 case CMD_VM_INVOKE_METHODS: {
6331 int objid = decode_objid (p, &p, end);
6333 DebuggerTlsData *tls;
6334 int i, count, err, flags, nmethods;
6336 err = get_object (objid, (MonoObject**)&thread);
6340 flags = decode_int (p, &p, end);
6342 if (command == CMD_VM_INVOKE_METHODS)
6343 nmethods = decode_int (p, &p, end);
6347 // Wait for suspending if it already started
6349 wait_for_suspend ();
6350 if (!is_suspended ())
6351 return ERR_NOT_SUSPENDED;
6353 mono_loader_lock ();
6354 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6355 mono_loader_unlock ();
6358 if (!tls->really_suspended)
6359 /* The thread is still running native code, can't do invokes */
6360 return ERR_NOT_SUSPENDED;
6363 * Store the invoke data into tls, the thread will execute it after it is
6366 if (tls->pending_invoke)
6367 return ERR_NOT_SUSPENDED;
6368 tls->pending_invoke = g_new0 (InvokeData, 1);
6369 tls->pending_invoke->id = id;
6370 tls->pending_invoke->flags = flags;
6371 tls->pending_invoke->p = g_malloc (end - p);
6372 memcpy (tls->pending_invoke->p, p, end - p);
6373 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6374 tls->pending_invoke->suspend_count = suspend_count;
6375 tls->pending_invoke->nmethods = nmethods;
6377 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6378 resume_thread (THREAD_TO_INTERNAL (thread));
6381 count = suspend_count;
6382 for (i = 0; i < count; ++i)
6387 case CMD_VM_ABORT_INVOKE: {
6388 int objid = decode_objid (p, &p, end);
6390 DebuggerTlsData *tls;
6393 err = get_object (objid, (MonoObject**)&thread);
6397 invoke_id = decode_int (p, &p, end);
6399 mono_loader_lock ();
6400 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6403 if (tls->abort_requested) {
6404 mono_loader_unlock ();
6409 * Check whether we're still inside the mono_runtime_invoke() and that it's
6410 * actually the correct invocation.
6412 * Careful, we do not stop the thread that's doing the invocation, so we can't
6413 * inspect its stack. However, invoke_method() also acquires the loader lock
6414 * when it's done, so we're safe here.
6418 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6419 mono_loader_unlock ();
6420 return ERR_NO_INVOCATION;
6423 tls->abort_requested = TRUE;
6425 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6426 mono_loader_unlock ();
6430 case CMD_VM_SET_KEEPALIVE: {
6431 int timeout = decode_int (p, &p, end);
6432 agent_config.keepalive = timeout;
6434 #ifndef DISABLE_SOCKET_TRANSPORT
6441 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6442 GHashTableIter iter, kiter;
6447 char *fname, *basename;
6448 gboolean ignore_case;
6449 GSList *class_list, *l;
6450 GPtrArray *res_classes, *res_domains;
6452 fname = decode_string (p, &p, end);
6453 ignore_case = decode_byte (p, &p, end);
6455 basename = g_path_get_basename (fname);
6457 res_classes = g_ptr_array_new ();
6458 res_domains = g_ptr_array_new ();
6460 mono_loader_lock ();
6461 g_hash_table_iter_init (&iter, domains);
6462 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6463 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6465 /* Update 'source_file_to_class' cache */
6466 g_hash_table_iter_init (&kiter, info->loaded_classes);
6467 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6468 if (!g_hash_table_lookup (info->source_files, klass)) {
6469 files = get_source_files_for_type (klass);
6470 g_hash_table_insert (info->source_files, klass, files);
6472 for (i = 0; i < files->len; ++i) {
6473 char *s = g_ptr_array_index (files, i);
6474 char *s2 = g_path_get_basename (s);
6477 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6479 class_list = g_slist_prepend (class_list, klass);
6480 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6482 class_list = g_slist_prepend (class_list, klass);
6483 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6486 /* The _ignorecase hash contains the lowercase path */
6487 s3 = strdup_tolower (s2);
6488 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6490 class_list = g_slist_prepend (class_list, klass);
6491 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6493 class_list = g_slist_prepend (class_list, klass);
6494 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6506 s = strdup_tolower (basename);
6507 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6510 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6513 for (l = class_list; l; l = l->next) {
6516 g_ptr_array_add (res_classes, klass);
6517 g_ptr_array_add (res_domains, domain);
6520 mono_loader_unlock ();
6525 buffer_add_int (buf, res_classes->len);
6526 for (i = 0; i < res_classes->len; ++i)
6527 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6528 g_ptr_array_free (res_classes, TRUE);
6529 g_ptr_array_free (res_domains, TRUE);
6532 case CMD_VM_GET_TYPES: {
6533 GHashTableIter iter;
6537 gboolean ignore_case;
6538 GPtrArray *res_classes, *res_domains;
6539 MonoTypeNameParse info;
6541 name = decode_string (p, &p, end);
6542 ignore_case = decode_byte (p, &p, end);
6544 if (!mono_reflection_parse_type (name, &info)) {
6546 mono_reflection_free_type_info (&info);
6547 return ERR_INVALID_ARGUMENT;
6550 res_classes = g_ptr_array_new ();
6551 res_domains = g_ptr_array_new ();
6553 mono_loader_lock ();
6554 g_hash_table_iter_init (&iter, domains);
6555 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6557 gboolean type_resolve;
6561 mono_domain_assemblies_lock (domain);
6562 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6566 type_resolve = TRUE;
6567 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6569 g_ptr_array_add (res_classes, mono_type_get_class (t));
6570 g_ptr_array_add (res_domains, domain);
6574 mono_domain_assemblies_unlock (domain);
6576 mono_loader_unlock ();
6579 mono_reflection_free_type_info (&info);
6581 buffer_add_int (buf, res_classes->len);
6582 for (i = 0; i < res_classes->len; ++i)
6583 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6584 g_ptr_array_free (res_classes, TRUE);
6585 g_ptr_array_free (res_domains, TRUE);
6590 return ERR_NOT_IMPLEMENTED;
6597 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6603 case CMD_EVENT_REQUEST_SET: {
6605 int i, event_kind, suspend_policy, nmodifiers, mod;
6608 MonoThread *step_thread;
6609 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6613 event_kind = decode_byte (p, &p, end);
6614 suspend_policy = decode_byte (p, &p, end);
6615 nmodifiers = decode_byte (p, &p, end);
6617 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6618 req->id = InterlockedIncrement (&event_request_id);
6619 req->event_kind = event_kind;
6620 req->suspend_policy = suspend_policy;
6621 req->nmodifiers = nmodifiers;
6624 for (i = 0; i < nmodifiers; ++i) {
6625 mod = decode_byte (p, &p, end);
6627 req->modifiers [i].kind = mod;
6628 if (mod == MOD_KIND_COUNT) {
6629 req->modifiers [i].data.count = decode_int (p, &p, end);
6630 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6631 method = decode_methodid (p, &p, end, &domain, &err);
6634 location = decode_long (p, &p, end);
6635 } else if (mod == MOD_KIND_STEP) {
6636 step_thread_id = decode_id (p, &p, end);
6637 size = decode_int (p, &p, end);
6638 depth = decode_int (p, &p, end);
6639 if (CHECK_PROTOCOL_VERSION (2, 16))
6640 filter = decode_int (p, &p, end);
6641 req->modifiers [i].data.filter = filter;
6642 } else if (mod == MOD_KIND_THREAD_ONLY) {
6643 int id = decode_id (p, &p, end);
6645 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6650 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6651 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6655 req->modifiers [i].caught = decode_byte (p, &p, end);
6656 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6657 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" : ""));
6659 req->modifiers [i].data.exc_class = exc_class;
6661 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6663 return ERR_INVALID_ARGUMENT;
6666 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6667 int n = decode_int (p, &p, end);
6670 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6671 for (j = 0; j < n; ++j) {
6672 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6674 g_free (req->modifiers [i].data.assemblies);
6678 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6679 int n = decode_int (p, &p, end);
6682 modifier = &req->modifiers [i];
6683 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6684 for (j = 0; j < n; ++j) {
6685 char *s = decode_string (p, &p, end);
6689 s2 = strdup_tolower (s);
6690 g_hash_table_insert (modifier->data.source_files, s2, s2);
6694 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6695 int n = decode_int (p, &p, end);
6698 modifier = &req->modifiers [i];
6699 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6700 for (j = 0; j < n; ++j) {
6701 char *s = decode_string (p, &p, end);
6704 g_hash_table_insert (modifier->data.type_names, s, s);
6708 return ERR_NOT_IMPLEMENTED;
6712 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6715 req->info = set_breakpoint (method, location, req, &error);
6716 if (!mono_error_ok (&error)) {
6718 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6719 mono_error_cleanup (&error);
6720 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6722 } else if (req->event_kind == EVENT_KIND_STEP) {
6723 g_assert (step_thread_id);
6725 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6731 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6736 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6737 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6738 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6739 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6740 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6741 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6743 if (req->nmodifiers) {
6745 return ERR_NOT_IMPLEMENTED;
6749 mono_loader_lock ();
6750 g_ptr_array_add (event_requests, req);
6752 if (agent_config.defer) {
6753 /* Transmit cached data to the client on receipt of the event request */
6754 switch (req->event_kind) {
6755 case EVENT_KIND_APPDOMAIN_CREATE:
6756 /* Emit load events for currently loaded domains */
6757 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6759 case EVENT_KIND_ASSEMBLY_LOAD:
6760 /* Emit load events for currently loaded assemblies */
6761 mono_assembly_foreach (emit_assembly_load, NULL);
6763 case EVENT_KIND_THREAD_START:
6764 /* Emit start events for currently started threads */
6765 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6767 case EVENT_KIND_TYPE_LOAD:
6768 /* Emit type load events for currently loaded types */
6769 mono_domain_foreach (send_types_for_domain, NULL);
6775 mono_loader_unlock ();
6777 buffer_add_int (buf, req->id);
6780 case CMD_EVENT_REQUEST_CLEAR: {
6781 int etype = decode_byte (p, &p, end);
6782 int req_id = decode_int (p, &p, end);
6784 // FIXME: Make a faster mapping from req_id to request
6785 mono_loader_lock ();
6786 clear_event_request (req_id, etype);
6787 mono_loader_unlock ();
6790 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6793 mono_loader_lock ();
6795 while (i < event_requests->len) {
6796 EventRequest *req = g_ptr_array_index (event_requests, i);
6798 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6799 clear_breakpoint (req->info);
6801 g_ptr_array_remove_index_fast (event_requests, i);
6807 mono_loader_unlock ();
6811 return ERR_NOT_IMPLEMENTED;
6818 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6824 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6825 buffer_add_domainid (buf, mono_get_root_domain ());
6828 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6829 domain = decode_domainid (p, &p, end, NULL, &err);
6832 buffer_add_string (buf, domain->friendly_name);
6835 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6840 domain = decode_domainid (p, &p, end, NULL, &err);
6843 mono_loader_lock ();
6845 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6848 buffer_add_int (buf, count);
6849 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6851 buffer_add_assemblyid (buf, domain, ass);
6853 mono_loader_unlock ();
6856 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6857 domain = decode_domainid (p, &p, end, NULL, &err);
6861 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6864 case CMD_APPDOMAIN_GET_CORLIB: {
6865 domain = decode_domainid (p, &p, end, NULL, &err);
6869 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6872 case CMD_APPDOMAIN_CREATE_STRING: {
6876 domain = decode_domainid (p, &p, end, NULL, &err);
6879 s = decode_string (p, &p, end);
6881 o = mono_string_new (domain, s);
6882 buffer_add_objid (buf, (MonoObject*)o);
6885 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6887 MonoDomain *domain2;
6890 domain = decode_domainid (p, &p, end, NULL, &err);
6893 klass = decode_typeid (p, &p, end, &domain2, &err);
6898 g_assert (domain == domain2);
6900 o = mono_object_new (domain, klass);
6902 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6906 buffer_add_objid (buf, o);
6910 return ERR_NOT_IMPLEMENTED;
6917 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6923 ass = decode_assemblyid (p, &p, end, &domain, &err);
6928 case CMD_ASSEMBLY_GET_LOCATION: {
6929 buffer_add_string (buf, mono_image_get_filename (ass->image));
6932 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6936 if (ass->image->dynamic) {
6937 buffer_add_id (buf, 0);
6939 token = mono_image_get_entry_point (ass->image);
6941 buffer_add_id (buf, 0);
6943 m = mono_get_method (ass->image, token, NULL);
6944 buffer_add_methodid (buf, domain, m);
6949 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6950 buffer_add_moduleid (buf, domain, ass->image);
6953 case CMD_ASSEMBLY_GET_OBJECT: {
6954 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
6955 buffer_add_objid (buf, o);
6958 case CMD_ASSEMBLY_GET_TYPE: {
6959 char *s = decode_string (p, &p, end);
6960 gboolean ignorecase = decode_byte (p, &p, end);
6961 MonoTypeNameParse info;
6963 gboolean type_resolve, res;
6964 MonoDomain *d = mono_domain_get ();
6966 /* This is needed to be able to find referenced assemblies */
6967 res = mono_domain_set (domain, FALSE);
6970 if (!mono_reflection_parse_type (s, &info)) {
6973 if (info.assembly.name)
6975 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6977 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6978 mono_reflection_free_type_info (&info);
6981 mono_domain_set (d, TRUE);
6985 case CMD_ASSEMBLY_GET_NAME: {
6987 MonoAssembly *mass = ass;
6989 name = g_strdup_printf (
6990 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6992 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6993 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6994 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6995 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6997 buffer_add_string (buf, name);
7002 return ERR_NOT_IMPLEMENTED;
7009 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7015 case CMD_MODULE_GET_INFO: {
7016 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7019 basename = g_path_get_basename (image->name);
7020 buffer_add_string (buf, basename); // name
7021 buffer_add_string (buf, image->module_name); // scopename
7022 buffer_add_string (buf, image->name); // fqname
7023 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7024 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7029 return ERR_NOT_IMPLEMENTED;
7036 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7038 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7039 /* Special case these so the client doesn't have to handle Type objects */
7041 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7042 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7043 } else if (MONO_TYPE_IS_REFERENCE (t))
7044 buffer_add_value (buf, t, &val, domain);
7046 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7050 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7056 buffer_add_int (buf, 0);
7060 for (i = 0; i < cinfo->num_attrs; ++i) {
7061 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7064 buffer_add_int (buf, nattrs);
7066 for (i = 0; i < cinfo->num_attrs; ++i) {
7067 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7068 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7069 MonoArray *typed_args, *named_args;
7071 CattrNamedArg *arginfo;
7073 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7075 buffer_add_methodid (buf, domain, attr->ctor);
7079 buffer_add_int (buf, mono_array_length (typed_args));
7080 for (j = 0; j < mono_array_length (typed_args); ++j) {
7081 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7083 t = mono_method_signature (attr->ctor)->params [j];
7085 buffer_add_cattr_arg (buf, t, domain, val);
7088 buffer_add_int (buf, 0);
7093 buffer_add_int (buf, mono_array_length (named_args));
7095 for (j = 0; j < mono_array_length (named_args); ++j) {
7096 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7098 if (arginfo [j].prop) {
7099 buffer_add_byte (buf, 0x54);
7100 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7101 } else if (arginfo [j].field) {
7102 buffer_add_byte (buf, 0x53);
7103 buffer_add_fieldid (buf, domain, arginfo [j].field);
7105 g_assert_not_reached ();
7108 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7111 buffer_add_int (buf, 0);
7117 /* FIXME: Code duplication with icall.c */
7119 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7124 mono_class_setup_interfaces (klass, error);
7125 if (!mono_error_ok (error))
7128 for (i = 0; i < klass->interface_count; i++) {
7129 ic = klass->interfaces [i];
7130 g_hash_table_insert (ifaces, ic, ic);
7132 collect_interfaces (ic, ifaces, error);
7133 if (!mono_error_ok (error))
7139 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7149 case CMD_TYPE_GET_INFO: {
7150 buffer_add_string (buf, klass->name_space);
7151 buffer_add_string (buf, klass->name);
7153 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7154 buffer_add_string (buf, name);
7156 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7157 buffer_add_moduleid (buf, domain, klass->image);
7158 buffer_add_typeid (buf, domain, klass->parent);
7159 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7160 buffer_add_typeid (buf, domain, klass->element_class);
7162 buffer_add_id (buf, 0);
7163 buffer_add_int (buf, klass->type_token);
7164 buffer_add_byte (buf, klass->rank);
7165 buffer_add_int (buf, klass->flags);
7167 type = &klass->byval_arg;
7168 // FIXME: Can't decide whenever a class represents a byref type
7171 if (type->type == MONO_TYPE_PTR)
7173 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7175 if (type->type == MONO_TYPE_VALUETYPE)
7177 if (klass->enumtype)
7179 if (klass->generic_container)
7181 if (klass->generic_container || klass->generic_class)
7183 buffer_add_byte (buf, b);
7186 while ((nested = mono_class_get_nested_types (klass, &iter)))
7188 buffer_add_int (buf, nnested);
7190 while ((nested = mono_class_get_nested_types (klass, &iter)))
7191 buffer_add_typeid (buf, domain, nested);
7192 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7193 if (klass->generic_container)
7194 buffer_add_typeid (buf, domain, klass);
7195 else if (klass->generic_class)
7196 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7198 buffer_add_id (buf, 0);
7200 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7203 if (klass->generic_class) {
7204 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7206 count = inst->type_argc;
7207 buffer_add_int (buf, count);
7208 for (i = 0; i < count; i++)
7209 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7210 } else if (klass->generic_container) {
7211 MonoGenericContainer *container = klass->generic_container;
7214 count = container->type_argc;
7215 buffer_add_int (buf, count);
7216 for (i = 0; i < count; i++) {
7217 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7218 buffer_add_typeid (buf, domain, pklass);
7221 buffer_add_int (buf, 0);
7226 case CMD_TYPE_GET_METHODS: {
7229 gpointer iter = NULL;
7232 mono_class_setup_methods (klass);
7234 nmethods = mono_class_num_methods (klass);
7236 buffer_add_int (buf, nmethods);
7238 while ((m = mono_class_get_methods (klass, &iter))) {
7239 buffer_add_methodid (buf, domain, m);
7242 g_assert (i == nmethods);
7245 case CMD_TYPE_GET_FIELDS: {
7248 gpointer iter = NULL;
7251 nfields = mono_class_num_fields (klass);
7253 buffer_add_int (buf, nfields);
7255 while ((f = mono_class_get_fields (klass, &iter))) {
7256 buffer_add_fieldid (buf, domain, f);
7257 buffer_add_string (buf, f->name);
7258 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7259 buffer_add_int (buf, f->type->attrs);
7262 g_assert (i == nfields);
7265 case CMD_TYPE_GET_PROPERTIES: {
7268 gpointer iter = NULL;
7271 nprops = mono_class_num_properties (klass);
7273 buffer_add_int (buf, nprops);
7275 while ((p = mono_class_get_properties (klass, &iter))) {
7276 buffer_add_propertyid (buf, domain, p);
7277 buffer_add_string (buf, p->name);
7278 buffer_add_methodid (buf, domain, p->get);
7279 buffer_add_methodid (buf, domain, p->set);
7280 buffer_add_int (buf, p->attrs);
7283 g_assert (i == nprops);
7286 case CMD_TYPE_GET_CATTRS: {
7287 MonoClass *attr_klass;
7288 MonoCustomAttrInfo *cinfo;
7290 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7291 /* attr_klass can be NULL */
7295 cinfo = mono_custom_attrs_from_class (klass);
7297 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7300 case CMD_TYPE_GET_FIELD_CATTRS: {
7301 MonoClass *attr_klass;
7302 MonoCustomAttrInfo *cinfo;
7303 MonoClassField *field;
7305 field = decode_fieldid (p, &p, end, NULL, &err);
7308 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7312 cinfo = mono_custom_attrs_from_field (klass, field);
7314 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7317 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7318 MonoClass *attr_klass;
7319 MonoCustomAttrInfo *cinfo;
7322 prop = decode_propertyid (p, &p, end, NULL, &err);
7325 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7329 cinfo = mono_custom_attrs_from_property (klass, prop);
7331 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7334 case CMD_TYPE_GET_VALUES:
7335 case CMD_TYPE_GET_VALUES_2: {
7342 MonoThread *thread_obj;
7343 MonoInternalThread *thread = NULL;
7344 guint32 special_static_type;
7346 if (command == CMD_TYPE_GET_VALUES_2) {
7347 int objid = decode_objid (p, &p, end);
7350 err = get_object (objid, (MonoObject**)&thread_obj);
7354 thread = THREAD_TO_INTERNAL (thread_obj);
7357 len = decode_int (p, &p, end);
7358 for (i = 0; i < len; ++i) {
7359 f = decode_fieldid (p, &p, end, NULL, &err);
7363 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7364 return ERR_INVALID_FIELDID;
7365 special_static_type = mono_class_field_get_special_static_type (f);
7366 if (special_static_type != SPECIAL_STATIC_NONE) {
7367 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7368 return ERR_INVALID_FIELDID;
7371 /* Check that the field belongs to the object */
7373 for (k = klass; k; k = k->parent) {
7374 if (k == f->parent) {
7380 return ERR_INVALID_FIELDID;
7382 vtable = mono_class_vtable (domain, f->parent);
7383 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7384 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7385 buffer_add_value (buf, f->type, val, domain);
7390 case CMD_TYPE_SET_VALUES: {
7398 len = decode_int (p, &p, end);
7399 for (i = 0; i < len; ++i) {
7400 f = decode_fieldid (p, &p, end, NULL, &err);
7404 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7405 return ERR_INVALID_FIELDID;
7406 if (mono_class_field_is_special_static (f))
7407 return ERR_INVALID_FIELDID;
7409 /* Check that the field belongs to the object */
7411 for (k = klass; k; k = k->parent) {
7412 if (k == f->parent) {
7418 return ERR_INVALID_FIELDID;
7420 // FIXME: Check for literal/const
7422 vtable = mono_class_vtable (domain, f->parent);
7423 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7424 err = decode_value (f->type, domain, val, p, &p, end);
7429 if (MONO_TYPE_IS_REFERENCE (f->type))
7430 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7432 mono_field_static_set_value (vtable, f, val);
7437 case CMD_TYPE_GET_OBJECT: {
7438 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7439 buffer_add_objid (buf, o);
7442 case CMD_TYPE_GET_SOURCE_FILES:
7443 case CMD_TYPE_GET_SOURCE_FILES_2: {
7444 char *source_file, *base;
7448 files = get_source_files_for_type (klass);
7450 buffer_add_int (buf, files->len);
7451 for (i = 0; i < files->len; ++i) {
7452 source_file = g_ptr_array_index (files, i);
7453 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7454 buffer_add_string (buf, source_file);
7456 base = g_path_get_basename (source_file);
7457 buffer_add_string (buf, base);
7460 g_free (source_file);
7462 g_ptr_array_free (files, TRUE);
7465 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7466 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7470 if (mono_class_is_assignable_from (klass, oklass))
7471 buffer_add_byte (buf, 1);
7473 buffer_add_byte (buf, 0);
7476 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7477 char *name = decode_string (p, &p, end);
7478 int i, flags = decode_int (p, &p, end);
7479 MonoException *ex = NULL;
7480 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7483 return ERR_LOADER_ERROR;
7484 buffer_add_int (buf, array->len);
7485 for (i = 0; i < array->len; ++i) {
7486 MonoMethod *method = g_ptr_array_index (array, i);
7487 buffer_add_methodid (buf, domain, method);
7490 g_ptr_array_free (array, TRUE);
7494 case CMD_TYPE_GET_INTERFACES: {
7496 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7498 MonoClass *tclass, *iface;
7499 GHashTableIter iter;
7503 for (parent = tclass; parent; parent = parent->parent) {
7504 mono_class_setup_interfaces (parent, &error);
7505 if (!mono_error_ok (&error))
7506 return ERR_LOADER_ERROR;
7507 collect_interfaces (parent, iface_hash, &error);
7508 if (!mono_error_ok (&error))
7509 return ERR_LOADER_ERROR;
7512 buffer_add_int (buf, g_hash_table_size (iface_hash));
7514 g_hash_table_iter_init (&iter, iface_hash);
7515 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7516 buffer_add_typeid (buf, domain, iface);
7517 g_hash_table_destroy (iface_hash);
7520 case CMD_TYPE_GET_INTERFACE_MAP: {
7521 int tindex, ioffset;
7522 gboolean variance_used;
7524 int len, nmethods, i;
7528 len = decode_int (p, &p, end);
7529 mono_class_setup_vtable (klass);
7531 for (tindex = 0; tindex < len; ++tindex) {
7532 iclass = decode_typeid (p, &p, end, NULL, &err);
7536 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7538 return ERR_INVALID_ARGUMENT;
7540 nmethods = mono_class_num_methods (iclass);
7541 buffer_add_int (buf, nmethods);
7544 while ((method = mono_class_get_methods (iclass, &iter))) {
7545 buffer_add_methodid (buf, domain, method);
7547 for (i = 0; i < nmethods; ++i)
7548 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7553 return ERR_NOT_IMPLEMENTED;
7560 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7563 MonoDomain *old_domain;
7567 klass = decode_typeid (p, &p, end, &domain, &err);
7571 old_domain = mono_domain_get ();
7573 mono_domain_set (domain, TRUE);
7575 err = type_commands_internal (command, klass, domain, p, end, buf);
7577 mono_domain_set (old_domain, TRUE);
7583 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7585 MonoMethodHeader *header;
7589 case CMD_METHOD_GET_NAME: {
7590 buffer_add_string (buf, method->name);
7593 case CMD_METHOD_GET_DECLARING_TYPE: {
7594 buffer_add_typeid (buf, domain, method->klass);
7597 case CMD_METHOD_GET_DEBUG_INFO: {
7598 MonoDebugMethodInfo *minfo;
7600 int i, j, n_il_offsets;
7603 int *column_numbers;
7605 GPtrArray *source_file_list;
7607 header = mono_method_get_header (method);
7609 buffer_add_int (buf, 0);
7610 buffer_add_string (buf, "");
7611 buffer_add_int (buf, 0);
7615 minfo = mono_debug_lookup_method (method);
7617 buffer_add_int (buf, header->code_size);
7618 buffer_add_string (buf, "");
7619 buffer_add_int (buf, 0);
7620 mono_metadata_free_mh (header);
7624 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7625 buffer_add_int (buf, header->code_size);
7626 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7627 buffer_add_int (buf, source_file_list->len);
7628 for (i = 0; i < source_file_list->len; ++i) {
7629 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7630 buffer_add_string (buf, sinfo->source_file);
7631 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7632 for (j = 0; j < 16; ++j)
7633 buffer_add_byte (buf, sinfo->hash [j]);
7637 buffer_add_string (buf, source_file);
7639 buffer_add_int (buf, n_il_offsets);
7640 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7641 for (i = 0; i < n_il_offsets; ++i) {
7642 const char *srcfile = "";
7644 if (source_files [i] != -1) {
7645 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7646 srcfile = sinfo->source_file;
7648 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7649 buffer_add_int (buf, il_offsets [i]);
7650 buffer_add_int (buf, line_numbers [i]);
7651 if (CHECK_PROTOCOL_VERSION (2, 13))
7652 buffer_add_int (buf, source_files [i]);
7653 if (CHECK_PROTOCOL_VERSION (2, 19))
7654 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7656 g_free (source_file);
7657 g_free (il_offsets);
7658 g_free (line_numbers);
7659 g_free (source_files);
7660 g_ptr_array_free (source_file_list, TRUE);
7661 mono_metadata_free_mh (header);
7664 case CMD_METHOD_GET_PARAM_INFO: {
7665 MonoMethodSignature *sig = mono_method_signature (method);
7669 /* FIXME: mono_class_from_mono_type () and byrefs */
7671 /* FIXME: Use a smaller encoding */
7672 buffer_add_int (buf, sig->call_convention);
7673 buffer_add_int (buf, sig->param_count);
7674 buffer_add_int (buf, sig->generic_param_count);
7675 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7676 for (i = 0; i < sig->param_count; ++i) {
7678 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7681 /* Emit parameter names */
7682 names = g_new (char *, sig->param_count);
7683 mono_method_get_param_names (method, (const char **) names);
7684 for (i = 0; i < sig->param_count; ++i)
7685 buffer_add_string (buf, names [i]);
7690 case CMD_METHOD_GET_LOCALS_INFO: {
7691 int i, j, num_locals;
7692 MonoDebugLocalsInfo *locals;
7694 header = mono_method_get_header (method);
7696 return ERR_INVALID_ARGUMENT;
7698 buffer_add_int (buf, header->num_locals);
7701 for (i = 0; i < header->num_locals; ++i)
7702 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7705 locals = mono_debug_lookup_locals (method);
7707 num_locals = locals->num_locals;
7710 for (i = 0; i < header->num_locals; ++i) {
7711 for (j = 0; j < num_locals; ++j)
7712 if (locals->locals [j].index == i)
7715 buffer_add_string (buf, locals->locals [j].name);
7717 buffer_add_string (buf, "");
7721 for (i = 0; i < header->num_locals; ++i) {
7722 for (j = 0; j < num_locals; ++j)
7723 if (locals->locals [j].index == i)
7725 if (j < num_locals && locals->locals [j].block) {
7726 buffer_add_int (buf, locals->locals [j].block->start_offset);
7727 buffer_add_int (buf, locals->locals [j].block->end_offset);
7729 buffer_add_int (buf, 0);
7730 buffer_add_int (buf, header->code_size);
7733 mono_metadata_free_mh (header);
7736 mono_debug_symfile_free_locals (locals);
7740 case CMD_METHOD_GET_INFO:
7741 buffer_add_int (buf, method->flags);
7742 buffer_add_int (buf, method->iflags);
7743 buffer_add_int (buf, method->token);
7744 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7746 if (method->is_generic)
7748 if (mono_method_signature (method)->generic_param_count)
7750 buffer_add_byte (buf, attrs);
7751 if (method->is_generic || method->is_inflated) {
7754 if (method->is_generic) {
7757 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7759 result = imethod->declaring;
7760 if (imethod->context.class_inst) {
7761 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7762 /*Generic methods gets the context of the GTD.*/
7763 if (mono_class_get_context (klass))
7764 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7768 buffer_add_methodid (buf, domain, result);
7770 buffer_add_id (buf, 0);
7772 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7773 if (mono_method_signature (method)->generic_param_count) {
7776 if (method->is_inflated) {
7777 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7779 count = inst->type_argc;
7780 buffer_add_int (buf, count);
7782 for (i = 0; i < count; i++)
7783 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7785 buffer_add_int (buf, 0);
7787 } else if (method->is_generic) {
7788 MonoGenericContainer *container = mono_method_get_generic_container (method);
7790 count = mono_method_signature (method)->generic_param_count;
7791 buffer_add_int (buf, count);
7792 for (i = 0; i < count; i++) {
7793 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7794 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7795 buffer_add_typeid (buf, domain, pklass);
7798 buffer_add_int (buf, 0);
7801 buffer_add_int (buf, 0);
7806 case CMD_METHOD_GET_BODY: {
7809 header = mono_method_get_header (method);
7811 buffer_add_int (buf, 0);
7813 if (CHECK_PROTOCOL_VERSION (2, 18))
7814 buffer_add_int (buf, 0);
7816 buffer_add_int (buf, header->code_size);
7817 for (i = 0; i < header->code_size; ++i)
7818 buffer_add_byte (buf, header->code [i]);
7820 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7821 buffer_add_int (buf, header->num_clauses);
7822 for (i = 0; i < header->num_clauses; ++i) {
7823 MonoExceptionClause *clause = &header->clauses [i];
7825 buffer_add_int (buf, clause->flags);
7826 buffer_add_int (buf, clause->try_offset);
7827 buffer_add_int (buf, clause->try_len);
7828 buffer_add_int (buf, clause->handler_offset);
7829 buffer_add_int (buf, clause->handler_len);
7830 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7831 buffer_add_typeid (buf, domain, clause->data.catch_class);
7832 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7833 buffer_add_int (buf, clause->data.filter_offset);
7837 mono_metadata_free_mh (header);
7842 case CMD_METHOD_RESOLVE_TOKEN: {
7843 guint32 token = decode_int (p, &p, end);
7846 switch (mono_metadata_token_code (token)) {
7847 case MONO_TOKEN_STRING: {
7851 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7854 s2 = mono_string_to_utf8 (s);
7856 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7857 buffer_add_string (buf, s2);
7863 MonoClass *handle_class;
7865 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7866 val = mono_method_get_wrapper_data (method, token);
7867 handle_class = mono_method_get_wrapper_data (method, token + 1);
7869 if (handle_class == NULL) {
7870 // Can't figure out the token type
7871 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7875 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7879 if (handle_class == mono_defaults.typehandle_class) {
7880 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7881 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7882 buffer_add_typeid (buf, domain, (MonoClass *) val);
7884 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7885 } else if (handle_class == mono_defaults.fieldhandle_class) {
7886 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7887 buffer_add_fieldid (buf, domain, val);
7888 } else if (handle_class == mono_defaults.methodhandle_class) {
7889 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7890 buffer_add_methodid (buf, domain, val);
7891 } else if (handle_class == mono_defaults.string_class) {
7894 s = mono_string_to_utf8 (val);
7895 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7896 buffer_add_string (buf, s);
7899 g_assert_not_reached ();
7906 case CMD_METHOD_GET_CATTRS: {
7907 MonoClass *attr_klass;
7908 MonoCustomAttrInfo *cinfo;
7910 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7911 /* attr_klass can be NULL */
7915 cinfo = mono_custom_attrs_from_method (method);
7917 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
7921 return ERR_NOT_IMPLEMENTED;
7928 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7931 MonoDomain *old_domain;
7935 method = decode_methodid (p, &p, end, &domain, &err);
7939 old_domain = mono_domain_get ();
7941 mono_domain_set (domain, TRUE);
7943 err = method_commands_internal (command, method, domain, p, end, buf);
7945 mono_domain_set (old_domain, TRUE);
7951 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7953 int objid = decode_objid (p, &p, end);
7955 MonoThread *thread_obj;
7956 MonoInternalThread *thread;
7958 err = get_object (objid, (MonoObject**)&thread_obj);
7962 thread = THREAD_TO_INTERNAL (thread_obj);
7965 case CMD_THREAD_GET_NAME: {
7967 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7970 buffer_add_int (buf, 0);
7975 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7977 buffer_add_int (buf, len);
7978 buffer_add_data (buf, (guint8*)name, len);
7983 case CMD_THREAD_GET_FRAME_INFO: {
7984 DebuggerTlsData *tls;
7985 int i, start_frame, length;
7987 // Wait for suspending if it already started
7988 // FIXME: Races with suspend_count
7989 while (!is_suspended ()) {
7991 wait_for_suspend ();
7995 wait_for_suspend ();
7996 if (!is_suspended ())
7997 return ERR_NOT_SUSPENDED;
8000 start_frame = decode_int (p, &p, end);
8001 length = decode_int (p, &p, end);
8003 if (start_frame != 0 || length != -1)
8004 return ERR_NOT_IMPLEMENTED;
8006 mono_loader_lock ();
8007 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8008 mono_loader_unlock ();
8011 compute_frame_info (thread, tls);
8013 buffer_add_int (buf, tls->frame_count);
8014 for (i = 0; i < tls->frame_count; ++i) {
8015 buffer_add_int (buf, tls->frames [i]->id);
8016 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8017 buffer_add_int (buf, tls->frames [i]->il_offset);
8019 * Instead of passing the frame type directly to the client, we associate
8020 * it with the previous frame using a set of flags. This avoids lots of
8021 * conditional code in the client, since a frame whose type isn't
8022 * FRAME_TYPE_MANAGED has no method, location, etc.
8024 buffer_add_byte (buf, tls->frames [i]->flags);
8029 case CMD_THREAD_GET_STATE:
8030 buffer_add_int (buf, thread->state);
8032 case CMD_THREAD_GET_INFO:
8033 buffer_add_byte (buf, thread->threadpool_thread);
8035 case CMD_THREAD_GET_ID:
8036 buffer_add_long (buf, (guint64)(gsize)thread);
8038 case CMD_THREAD_GET_TID:
8039 buffer_add_long (buf, (guint64)thread->tid);
8042 return ERR_NOT_IMPLEMENTED;
8049 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8053 MonoThread *thread_obj;
8054 MonoInternalThread *thread;
8055 int pos, i, len, frame_idx;
8056 DebuggerTlsData *tls;
8058 MonoDebugMethodJitInfo *jit;
8059 MonoDebugVarInfo *var;
8060 MonoMethodSignature *sig;
8062 MonoMethodHeader *header;
8064 objid = decode_objid (p, &p, end);
8065 err = get_object (objid, (MonoObject**)&thread_obj);
8069 thread = THREAD_TO_INTERNAL (thread_obj);
8071 id = decode_id (p, &p, end);
8073 mono_loader_lock ();
8074 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8075 mono_loader_unlock ();
8078 for (i = 0; i < tls->frame_count; ++i) {
8079 if (tls->frames [i]->id == id)
8082 if (i == tls->frame_count)
8083 return ERR_INVALID_FRAMEID;
8086 frame = tls->frames [frame_idx];
8088 if (!frame->has_ctx)
8090 return ERR_INVALID_FRAMEID;
8093 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8094 if (!frame->jit && frame->api_method->is_inflated)
8095 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8099 /* This could happen for aot images with no jit debug info */
8100 s = mono_method_full_name (frame->api_method, TRUE);
8101 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8103 return ERR_ABSENT_INFORMATION;
8108 sig = mono_method_signature (frame->actual_method);
8110 if (!get_seq_points (frame->domain, frame->actual_method))
8112 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8114 return ERR_ABSENT_INFORMATION;
8117 case CMD_STACK_FRAME_GET_VALUES: {
8118 len = decode_int (p, &p, end);
8119 header = mono_method_get_header (frame->actual_method);
8121 for (i = 0; i < len; ++i) {
8122 pos = decode_int (p, &p, end);
8127 g_assert (pos >= 0 && pos < jit->num_params);
8129 var = &jit->params [pos];
8131 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8133 g_assert (pos >= 0 && pos < jit->num_locals);
8135 var = &jit->locals [pos];
8137 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8140 mono_metadata_free_mh (header);
8143 case CMD_STACK_FRAME_GET_THIS: {
8144 if (frame->api_method->klass->valuetype) {
8145 if (!sig->hasthis) {
8146 MonoObject *p = NULL;
8147 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8149 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8152 if (!sig->hasthis) {
8153 MonoObject *p = NULL;
8154 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8156 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8161 case CMD_STACK_FRAME_SET_VALUES: {
8164 MonoDebugVarInfo *var;
8166 len = decode_int (p, &p, end);
8167 header = mono_method_get_header (frame->actual_method);
8169 for (i = 0; i < len; ++i) {
8170 pos = decode_int (p, &p, end);
8175 g_assert (pos >= 0 && pos < jit->num_params);
8177 t = sig->params [pos];
8178 var = &jit->params [pos];
8180 g_assert (pos >= 0 && pos < jit->num_locals);
8182 t = header->locals [pos];
8183 var = &jit->locals [pos];
8186 if (MONO_TYPE_IS_REFERENCE (t))
8187 val_buf = g_alloca (sizeof (MonoObject*));
8189 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8190 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8194 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8196 mono_metadata_free_mh (header);
8200 return ERR_NOT_IMPLEMENTED;
8207 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8210 int objid, err, index, len, i, esize;
8213 objid = decode_objid (p, &p, end);
8214 err = get_object (objid, (MonoObject**)&arr);
8219 case CMD_ARRAY_REF_GET_LENGTH:
8220 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8222 buffer_add_int (buf, arr->max_length);
8223 buffer_add_int (buf, 0);
8225 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8226 buffer_add_int (buf, arr->bounds [i].length);
8227 buffer_add_int (buf, arr->bounds [i].lower_bound);
8231 case CMD_ARRAY_REF_GET_VALUES:
8232 index = decode_int (p, &p, end);
8233 len = decode_int (p, &p, end);
8235 g_assert (index >= 0 && len >= 0);
8236 // Reordered to avoid integer overflow
8237 g_assert (!(index > arr->max_length - len));
8239 esize = mono_array_element_size (arr->obj.vtable->klass);
8240 for (i = index; i < index + len; ++i) {
8241 elem = (gpointer*)((char*)arr->vector + (i * esize));
8242 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8245 case CMD_ARRAY_REF_SET_VALUES:
8246 index = decode_int (p, &p, end);
8247 len = decode_int (p, &p, end);
8249 g_assert (index >= 0 && len >= 0);
8250 // Reordered to avoid integer overflow
8251 g_assert (!(index > arr->max_length - len));
8253 esize = mono_array_element_size (arr->obj.vtable->klass);
8254 for (i = index; i < index + len; ++i) {
8255 elem = (gpointer*)((char*)arr->vector + (i * esize));
8257 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8261 return ERR_NOT_IMPLEMENTED;
8268 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8273 int i, index, length;
8276 objid = decode_objid (p, &p, end);
8277 err = get_object (objid, (MonoObject**)&str);
8282 case CMD_STRING_REF_GET_VALUE:
8283 s = mono_string_to_utf8 (str);
8284 buffer_add_string (buf, s);
8287 case CMD_STRING_REF_GET_LENGTH:
8288 buffer_add_long (buf, mono_string_length (str));
8290 case CMD_STRING_REF_GET_CHARS:
8291 index = decode_long (p, &p, end);
8292 length = decode_long (p, &p, end);
8293 if (index > mono_string_length (str) - length)
8294 return ERR_INVALID_ARGUMENT;
8295 c = mono_string_chars (str) + index;
8296 for (i = 0; i < length; ++i)
8297 buffer_add_short (buf, c [i]);
8300 return ERR_NOT_IMPLEMENTED;
8307 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8316 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8317 objid = decode_objid (p, &p, end);
8318 err = get_object (objid, &obj);
8320 buffer_add_int (buf, 1);
8322 buffer_add_int (buf, 0);
8326 objid = decode_objid (p, &p, end);
8327 err = get_object (objid, &obj);
8332 case CMD_OBJECT_REF_GET_TYPE:
8333 /* This handles transparent proxies too */
8334 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8336 case CMD_OBJECT_REF_GET_VALUES:
8337 len = decode_int (p, &p, end);
8339 for (i = 0; i < len; ++i) {
8340 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8344 /* Check that the field belongs to the object */
8346 for (k = obj->vtable->klass; k; k = k->parent) {
8347 if (k == f->parent) {
8353 return ERR_INVALID_FIELDID;
8355 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8359 if (mono_class_field_is_special_static (f))
8360 return ERR_INVALID_FIELDID;
8362 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8363 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8364 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8365 mono_field_static_get_value (vtable, f, val);
8366 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8369 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8373 case CMD_OBJECT_REF_SET_VALUES:
8374 len = decode_int (p, &p, end);
8376 for (i = 0; i < len; ++i) {
8377 f = decode_fieldid (p, &p, end, NULL, &err);
8381 /* Check that the field belongs to the object */
8383 for (k = obj->vtable->klass; k; k = k->parent) {
8384 if (k == f->parent) {
8390 return ERR_INVALID_FIELDID;
8392 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8396 if (mono_class_field_is_special_static (f))
8397 return ERR_INVALID_FIELDID;
8399 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8400 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8402 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8403 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8408 mono_field_static_set_value (vtable, f, val);
8411 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8417 case CMD_OBJECT_REF_GET_ADDRESS:
8418 buffer_add_long (buf, (gssize)obj);
8420 case CMD_OBJECT_REF_GET_DOMAIN:
8421 buffer_add_domainid (buf, obj->vtable->domain);
8423 case CMD_OBJECT_REF_GET_INFO:
8424 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8425 buffer_add_domainid (buf, obj->vtable->domain);
8428 return ERR_NOT_IMPLEMENTED;
8435 command_set_to_string (CommandSet command_set)
8437 switch (command_set) {
8440 case CMD_SET_OBJECT_REF:
8441 return "OBJECT_REF";
8442 case CMD_SET_STRING_REF:
8443 return "STRING_REF";
8444 case CMD_SET_THREAD:
8446 case CMD_SET_ARRAY_REF:
8448 case CMD_SET_EVENT_REQUEST:
8449 return "EVENT_REQUEST";
8450 case CMD_SET_STACK_FRAME:
8451 return "STACK_FRAME";
8452 case CMD_SET_APPDOMAIN:
8454 case CMD_SET_ASSEMBLY:
8456 case CMD_SET_METHOD:
8460 case CMD_SET_MODULE:
8470 cmd_to_string (CommandSet set, int command)
8475 case CMD_VM_VERSION:
8477 case CMD_VM_ALL_THREADS:
8478 return "ALL_THREADS";
8479 case CMD_VM_SUSPEND:
8485 case CMD_VM_DISPOSE:
8487 case CMD_VM_INVOKE_METHOD:
8488 return "INVOKE_METHOD";
8489 case CMD_VM_SET_PROTOCOL_VERSION:
8490 return "SET_PROTOCOL_VERSION";
8491 case CMD_VM_ABORT_INVOKE:
8492 return "ABORT_INVOKE";
8493 case CMD_VM_SET_KEEPALIVE:
8494 return "SET_KEEPALIVE";
8507 wait_for_attach (void)
8509 #ifndef DISABLE_SOCKET_TRANSPORT
8510 if (listen_fd == -1) {
8511 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8515 /* Block and wait for client connection */
8516 conn_fd = socket_transport_accept (listen_fd);
8517 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8518 if (conn_fd == -1) {
8519 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8523 g_assert_not_reached ();
8527 disconnected = !transport_handshake ();
8529 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8539 * This thread handles communication with the debugger client using a JDWP
8542 static guint32 WINAPI
8543 debugger_thread (void *arg)
8545 int res, len, id, flags, command_set = 0, command = 0;
8546 guint8 header [HEADER_LENGTH];
8547 guint8 *data, *p, *end;
8551 gboolean attach_failed = FALSE;
8553 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8555 debugger_thread_id = GetCurrentThreadId ();
8557 mono_jit_thread_attach (mono_get_root_domain ());
8559 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8561 mono_set_is_debugger_attached (TRUE);
8563 if (agent_config.defer) {
8564 if (!wait_for_attach ()) {
8565 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8566 attach_failed = TRUE; // Don't abort process when we can't listen
8568 /* Send start event to client */
8569 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8573 while (!attach_failed) {
8574 res = transport_recv (header, HEADER_LENGTH);
8576 /* This will break if the socket is closed during shutdown too */
8577 if (res != HEADER_LENGTH)
8581 end = header + HEADER_LENGTH;
8583 len = decode_int (p, &p, end);
8584 id = decode_int (p, &p, end);
8585 flags = decode_byte (p, &p, end);
8586 command_set = decode_byte (p, &p, end);
8587 command = decode_byte (p, &p, end);
8589 g_assert (flags == 0);
8592 const char *cmd_str;
8595 cmd_str = cmd_to_string (command_set, command);
8597 sprintf (cmd_num, "%d", command);
8601 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8604 data = g_malloc (len - HEADER_LENGTH);
8605 if (len - HEADER_LENGTH > 0)
8607 res = transport_recv (data, len - HEADER_LENGTH);
8608 if (res != len - HEADER_LENGTH)
8613 end = data + (len - HEADER_LENGTH);
8615 buffer_init (&buf, 128);
8620 /* Process the request */
8621 switch (command_set) {
8623 err = vm_commands (command, id, p, end, &buf);
8624 if (!err && command == CMD_VM_INVOKE_METHOD)
8625 /* Sent after the invoke is complete */
8628 case CMD_SET_EVENT_REQUEST:
8629 err = event_commands (command, p, end, &buf);
8631 case CMD_SET_APPDOMAIN:
8632 err = domain_commands (command, p, end, &buf);
8634 case CMD_SET_ASSEMBLY:
8635 err = assembly_commands (command, p, end, &buf);
8637 case CMD_SET_MODULE:
8638 err = module_commands (command, p, end, &buf);
8641 err = type_commands (command, p, end, &buf);
8643 case CMD_SET_METHOD:
8644 err = method_commands (command, p, end, &buf);
8646 case CMD_SET_THREAD:
8647 err = thread_commands (command, p, end, &buf);
8649 case CMD_SET_STACK_FRAME:
8650 err = frame_commands (command, p, end, &buf);
8652 case CMD_SET_ARRAY_REF:
8653 err = array_commands (command, p, end, &buf);
8655 case CMD_SET_STRING_REF:
8656 err = string_commands (command, p, end, &buf);
8658 case CMD_SET_OBJECT_REF:
8659 err = object_commands (command, p, end, &buf);
8662 err = ERR_NOT_IMPLEMENTED;
8666 send_reply_packet (id, err, &buf);
8671 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8675 mono_set_is_debugger_attached (FALSE);
8677 mono_mutex_lock (&debugger_thread_exited_mutex);
8678 debugger_thread_exited = TRUE;
8679 mono_cond_signal (&debugger_thread_exited_cond);
8680 mono_mutex_unlock (&debugger_thread_exited_mutex);
8682 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8684 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8685 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8686 start_debugger_thread ();
8692 #else /* DISABLE_DEBUGGER_AGENT */
8695 mono_debugger_agent_parse_options (char *options)
8697 g_error ("This runtime is configured with the debugger agent disabled.");
8701 mono_debugger_agent_init (void)
8706 mono_debugger_agent_breakpoint_hit (void *sigctx)
8711 mono_debugger_agent_single_step_event (void *sigctx)
8716 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8721 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8727 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8728 MonoContext *catch_ctx)
8733 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8738 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8743 mono_debugger_agent_user_break (void)
8749 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8754 mono_debugger_agent_debug_log_is_enabled (void)