2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
43 #ifdef HAVE_UCONTEXT_H
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
62 #ifdef PLATFORM_ANDROID
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/utils/mono-semaphore.h>
76 #include <mono/utils/mono-error-internals.h>
77 #include <mono/utils/mono-stack-unwinding.h>
78 #include <mono/utils/mono-time.h>
79 #include "debugger-agent.h"
82 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
83 #define DISABLE_DEBUGGER_AGENT 1
86 #ifdef DISABLE_SOFT_DEBUG
87 #define DISABLE_DEBUGGER_AGENT 1
91 #include <mono/utils/mono-threads.h>
94 #ifndef DISABLE_DEBUGGER_AGENT
96 #include <mono/io-layer/mono-mutex.h>
98 /* Definitions to make backporting to 2.6 easier */
99 //#define MonoInternalThread MonoThread
100 //#define mono_thread_internal_current mono_thread_current
101 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
123 guint32 il_offset, native_offset;
127 * If method is gshared, this is the actual instance, otherwise this is equal to
130 MonoMethod *actual_method;
132 * This is the method which is visible to debugger clients. Same as method,
133 * except for native-to-managed wrappers.
135 MonoMethod *api_method;
137 MonoDebugMethodJitInfo *jit;
140 mgreg_t *reg_locations [MONO_MAX_IREGS];
142 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
143 * the frame can become invalid.
148 typedef struct _InvokeData InvokeData;
156 /* This is the context which needs to be restored after the invoke */
160 * If this is set, invoke this method with the arguments given by ARGS.
164 guint32 suspend_count;
166 InvokeData *last_invoke;
170 MonoThreadUnwindState context;
172 gpointer resume_event;
173 /* This is computed on demand when it is requested using the wire protocol */
174 /* It is freed up when the thread is resumed */
178 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
181 gboolean frames_up_to_date;
183 * Points to data about a pending invoke which needs to be executed after the thread
186 InvokeData *pending_invoke;
188 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
193 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
194 * within a finite amount of time.
198 * Set to TRUE if this thread is suspended in suspend_current ().
200 gboolean really_suspended;
201 /* Used to pass the context to the breakpoint/single step handler */
202 MonoContext handler_ctx;
203 /* Whenever thread_stop () was called for this thread */
206 /* Number of thread interruptions not yet processed */
207 gint32 interrupt_count;
209 /* Whenever to disable breakpoints (used during invokes) */
210 gboolean disable_breakpoints;
213 * Number of times this thread has been resumed using resume_thread ().
215 guint32 resume_count;
217 MonoInternalThread *thread;
220 * Information about the frame which transitioned to native code for running
223 StackFrameInfo async_last_frame;
226 * The context where the stack walk can be started for running threads.
228 MonoThreadUnwindState async_state;
231 * The context used for filter clauses
233 MonoThreadUnwindState filter_state;
236 * The callee address of the last mono_runtime_invoke call
238 gpointer invoke_addr;
240 gboolean abort_requested;
243 * The current mono_runtime_invoke invocation.
248 * The context where single stepping should resume while the thread is suspended because
249 * of an EXCEPTION event.
251 MonoContext catch_ctx;
253 gboolean has_catch_ctx;
256 * The context which needs to be restored after handling a single step/breakpoint
257 * event. This is the same as the ctx at step/breakpoint site, but includes changes
258 * to caller saved registers done by set_var ().
260 MonoContext restore_ctx;
265 void (*connect) (const char *address);
266 void (*close1) (void);
267 void (*close2) (void);
268 gboolean (*send) (void *buf, int len);
269 int (*recv) (void *buf, int len);
273 * Wire Protocol definitions
276 #define HEADER_LENGTH 11
278 #define MAJOR_VERSION 2
279 #define MINOR_VERSION 19
283 CMD_SET_OBJECT_REF = 9,
284 CMD_SET_STRING_REF = 10,
286 CMD_SET_ARRAY_REF = 13,
287 CMD_SET_EVENT_REQUEST = 15,
288 CMD_SET_STACK_FRAME = 16,
289 CMD_SET_APPDOMAIN = 20,
290 CMD_SET_ASSEMBLY = 21,
298 EVENT_KIND_VM_START = 0,
299 EVENT_KIND_VM_DEATH = 1,
300 EVENT_KIND_THREAD_START = 2,
301 EVENT_KIND_THREAD_DEATH = 3,
302 EVENT_KIND_APPDOMAIN_CREATE = 4,
303 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
304 EVENT_KIND_METHOD_ENTRY = 6,
305 EVENT_KIND_METHOD_EXIT = 7,
306 EVENT_KIND_ASSEMBLY_LOAD = 8,
307 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
308 EVENT_KIND_BREAKPOINT = 10,
309 EVENT_KIND_STEP = 11,
310 EVENT_KIND_TYPE_LOAD = 12,
311 EVENT_KIND_EXCEPTION = 13,
312 EVENT_KIND_KEEPALIVE = 14,
313 EVENT_KIND_USER_BREAK = 15,
314 EVENT_KIND_USER_LOG = 16
318 SUSPEND_POLICY_NONE = 0,
319 SUSPEND_POLICY_EVENT_THREAD = 1,
320 SUSPEND_POLICY_ALL = 2
325 ERR_INVALID_OBJECT = 20,
326 ERR_INVALID_FIELDID = 25,
327 ERR_INVALID_FRAMEID = 30,
328 ERR_NOT_IMPLEMENTED = 100,
329 ERR_NOT_SUSPENDED = 101,
330 ERR_INVALID_ARGUMENT = 102,
332 ERR_NO_INVOCATION = 104,
333 ERR_ABSENT_INFORMATION = 105,
334 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
335 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
340 MOD_KIND_THREAD_ONLY = 3,
341 MOD_KIND_LOCATION_ONLY = 7,
342 MOD_KIND_EXCEPTION_ONLY = 8,
344 MOD_KIND_ASSEMBLY_ONLY = 11,
345 MOD_KIND_SOURCE_FILE_ONLY = 12,
346 MOD_KIND_TYPE_NAME_ONLY = 13
361 STEP_FILTER_NONE = 0,
362 STEP_FILTER_STATIC_CTOR = 1
366 TOKEN_TYPE_STRING = 0,
368 TOKEN_TYPE_FIELD = 2,
369 TOKEN_TYPE_METHOD = 3,
370 TOKEN_TYPE_UNKNOWN = 4
374 VALUE_TYPE_ID_NULL = 0xf0,
375 VALUE_TYPE_ID_TYPE = 0xf1
379 FRAME_FLAG_DEBUGGER_INVOKE = 1,
380 FRAME_FLAG_NATIVE_TRANSITION = 2
384 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
385 INVOKE_FLAG_SINGLE_THREADED = 2
389 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
390 } BindingFlagsExtensions;
394 CMD_VM_ALL_THREADS = 2,
399 CMD_VM_INVOKE_METHOD = 7,
400 CMD_VM_SET_PROTOCOL_VERSION = 8,
401 CMD_VM_ABORT_INVOKE = 9,
402 CMD_VM_SET_KEEPALIVE = 10,
403 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
404 CMD_VM_GET_TYPES = 12
408 CMD_THREAD_GET_FRAME_INFO = 1,
409 CMD_THREAD_GET_NAME = 2,
410 CMD_THREAD_GET_STATE = 3,
411 CMD_THREAD_GET_INFO = 4,
412 CMD_THREAD_GET_ID = 5,
413 CMD_THREAD_GET_TID = 6
417 CMD_EVENT_REQUEST_SET = 1,
418 CMD_EVENT_REQUEST_CLEAR = 2,
419 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
427 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
428 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
429 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
430 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
431 CMD_APPDOMAIN_CREATE_STRING = 5,
432 CMD_APPDOMAIN_GET_CORLIB = 6,
433 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
437 CMD_ASSEMBLY_GET_LOCATION = 1,
438 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
439 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
440 CMD_ASSEMBLY_GET_OBJECT = 4,
441 CMD_ASSEMBLY_GET_TYPE = 5,
442 CMD_ASSEMBLY_GET_NAME = 6
446 CMD_MODULE_GET_INFO = 1,
450 CMD_METHOD_GET_NAME = 1,
451 CMD_METHOD_GET_DECLARING_TYPE = 2,
452 CMD_METHOD_GET_DEBUG_INFO = 3,
453 CMD_METHOD_GET_PARAM_INFO = 4,
454 CMD_METHOD_GET_LOCALS_INFO = 5,
455 CMD_METHOD_GET_INFO = 6,
456 CMD_METHOD_GET_BODY = 7,
457 CMD_METHOD_RESOLVE_TOKEN = 8,
461 CMD_TYPE_GET_INFO = 1,
462 CMD_TYPE_GET_METHODS = 2,
463 CMD_TYPE_GET_FIELDS = 3,
464 CMD_TYPE_GET_VALUES = 4,
465 CMD_TYPE_GET_OBJECT = 5,
466 CMD_TYPE_GET_SOURCE_FILES = 6,
467 CMD_TYPE_SET_VALUES = 7,
468 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
469 CMD_TYPE_GET_PROPERTIES = 9,
470 CMD_TYPE_GET_CATTRS = 10,
471 CMD_TYPE_GET_FIELD_CATTRS = 11,
472 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
473 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
474 CMD_TYPE_GET_VALUES_2 = 14,
475 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
476 CMD_TYPE_GET_INTERFACES = 16,
477 CMD_TYPE_GET_INTERFACE_MAP = 17,
481 CMD_STACK_FRAME_GET_VALUES = 1,
482 CMD_STACK_FRAME_GET_THIS = 2,
483 CMD_STACK_FRAME_SET_VALUES = 3
487 CMD_ARRAY_REF_GET_LENGTH = 1,
488 CMD_ARRAY_REF_GET_VALUES = 2,
489 CMD_ARRAY_REF_SET_VALUES = 3,
493 CMD_STRING_REF_GET_VALUE = 1,
494 CMD_STRING_REF_GET_LENGTH = 2,
495 CMD_STRING_REF_GET_CHARS = 3
499 CMD_OBJECT_REF_GET_TYPE = 1,
500 CMD_OBJECT_REF_GET_VALUES = 2,
501 CMD_OBJECT_REF_IS_COLLECTED = 3,
502 CMD_OBJECT_REF_GET_ADDRESS = 4,
503 CMD_OBJECT_REF_GET_DOMAIN = 5,
504 CMD_OBJECT_REF_SET_VALUES = 6,
505 CMD_OBJECT_REF_GET_INFO = 7,
511 int count; /* For kind == MOD_KIND_COUNT */
512 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
513 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
514 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
515 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
516 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
517 StepFilter filter; /* For kind == MOD_KIND_STEP */
519 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
528 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
532 * Describes a single step request.
536 MonoInternalThread *thread;
542 MonoMethod *last_method;
544 /* Whenever single stepping is performed using start/stop_single_stepping () */
546 /* The list of breakpoints used to implement step-over */
551 * Contains additional information for an event
554 /* For EVENT_KIND_EXCEPTION */
556 MonoContext catch_ctx;
558 /* For EVENT_KIND_USER_LOG */
560 char *category, *message;
561 /* For EVENT_KIND_TYPE_LOAD */
565 /* Dummy structure used for the profiler callbacks */
570 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
573 #define get_last_sock_error() WSAGetLastError()
574 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
575 #define MONO_EINTR WSAEINTR
577 #define get_last_sock_error() errno
578 #define MONO_EWOULDBLOCK EWOULDBLOCK
579 #define MONO_EINTR EINTR
582 #define CHECK_PROTOCOL_VERSION(major,minor) \
583 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
589 static AgentConfig agent_config;
592 * Whenever the agent is fully initialized.
593 * When using the onuncaught or onthrow options, only some parts of the agent are
594 * initialized on startup, and the full initialization which includes connection
595 * establishment and the startup of the agent thread is only done in response to
598 static gint32 inited;
600 #ifndef DISABLE_SOCKET_TRANSPORT
602 static int listen_fd;
605 static int packet_id = 0;
607 static int objref_id = 0;
609 static int event_request_id = 0;
611 static int frame_id = 0;
613 static GPtrArray *event_requests;
615 static MonoNativeTlsKey debugger_tls_id;
617 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
619 /* Maps MonoInternalThread -> DebuggerTlsData */
620 static MonoGHashTable *thread_to_tls;
622 /* Maps tid -> MonoInternalThread */
623 static MonoGHashTable *tid_to_thread;
625 /* Maps tid -> MonoThread (not MonoInternalThread) */
626 static MonoGHashTable *tid_to_thread_obj;
628 static gsize debugger_thread_id;
630 static HANDLE debugger_thread_handle;
632 static int log_level;
634 static gboolean embedding;
636 static FILE *log_file;
638 /* Assemblies whose assembly load event has no been sent yet */
639 static GPtrArray *pending_assembly_loads;
641 /* Whenever the debugger thread has exited */
642 static gboolean debugger_thread_exited;
644 /* Cond variable used to wait for debugger_thread_exited becoming true */
645 static mono_cond_t debugger_thread_exited_cond;
647 /* Mutex for the cond var above */
648 static mono_mutex_t debugger_thread_exited_mutex;
650 static DebuggerProfiler debugger_profiler;
652 /* The single step request instance */
653 static SingleStepReq *ss_req = NULL;
654 static gpointer ss_invoke_addr = NULL;
656 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
657 /* Number of single stepping operations in progress */
661 /* The protocol version of the client */
662 static int major_version, minor_version;
664 /* Whenever the variables above are set by the client */
665 static gboolean protocol_version_set;
667 /* A hash table containing all active domains */
668 static GHashTable *domains;
670 static void transport_init (void);
671 static void transport_connect (const char *address);
672 static gboolean transport_handshake (void);
673 static void register_transport (DebuggerTransport *trans);
675 static guint32 WINAPI debugger_thread (void *arg);
677 static void runtime_initialized (MonoProfiler *prof);
679 static void runtime_shutdown (MonoProfiler *prof);
681 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
683 static void thread_end (MonoProfiler *prof, uintptr_t tid);
685 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
687 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
689 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
691 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
693 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
695 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
697 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
699 static void emit_assembly_load (gpointer assembly, gpointer user_data);
701 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
703 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
705 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
707 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
709 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
711 static void start_single_stepping (void);
713 static void stop_single_stepping (void);
715 static void suspend_current (void);
717 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
719 static void clear_types_for_assembly (MonoAssembly *assembly);
721 static void clear_breakpoints_for_domain (MonoDomain *domain);
723 static void process_profiler_event (EventKind event, gpointer arg);
725 /* Submodule init/cleanup */
726 static void breakpoints_init (void);
727 static void breakpoints_cleanup (void);
729 static void objrefs_init (void);
730 static void objrefs_cleanup (void);
732 static void ids_init (void);
733 static void ids_cleanup (void);
735 static void suspend_init (void);
737 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
738 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
739 static void ss_destroy (SingleStepReq *req);
741 static void start_debugger_thread (void);
742 static void stop_debugger_thread (void);
744 static void finish_agent_init (gboolean on_startup);
746 static void process_profiler_event (EventKind event, gpointer arg);
748 static void invalidate_frames (DebuggerTlsData *tls);
750 #ifndef DISABLE_SOCKET_TRANSPORT
752 register_socket_transport (void);
756 parse_address (char *address, char **host, int *port)
758 char *pos = strchr (address, ':');
760 if (pos == NULL || pos == address)
763 *host = g_malloc (pos - address + 1);
764 strncpy (*host, address, pos - address);
765 (*host) [pos - address] = '\0';
767 *port = atoi (pos + 1);
775 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
776 fprintf (stderr, "Available options:\n");
777 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
778 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
779 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
780 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
781 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
782 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
783 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
784 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
785 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
789 parse_flag (const char *option, char *flag)
791 if (!strcmp (flag, "y"))
793 else if (!strcmp (flag, "n"))
796 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
803 mono_debugger_agent_parse_options (char *options)
810 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
811 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
815 extra = getenv ("MONO_SDB_ENV_OPTIONS");
817 options = g_strdup_printf ("%s,%s", options, extra);
819 agent_config.enabled = TRUE;
820 agent_config.suspend = TRUE;
821 agent_config.server = FALSE;
822 agent_config.defer = FALSE;
823 agent_config.address = NULL;
825 args = g_strsplit (options, ",", -1);
826 for (ptr = args; ptr && *ptr; ptr ++) {
829 if (strncmp (arg, "transport=", 10) == 0) {
830 agent_config.transport = g_strdup (arg + 10);
831 } else if (strncmp (arg, "address=", 8) == 0) {
832 agent_config.address = g_strdup (arg + 8);
833 } else if (strncmp (arg, "loglevel=", 9) == 0) {
834 agent_config.log_level = atoi (arg + 9);
835 } else if (strncmp (arg, "logfile=", 8) == 0) {
836 agent_config.log_file = g_strdup (arg + 8);
837 } else if (strncmp (arg, "suspend=", 8) == 0) {
838 agent_config.suspend = parse_flag ("suspend", arg + 8);
839 } else if (strncmp (arg, "server=", 7) == 0) {
840 agent_config.server = parse_flag ("server", arg + 7);
841 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
842 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
843 } else if (strncmp (arg, "onthrow=", 8) == 0) {
844 /* We support multiple onthrow= options */
845 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
846 } else if (strncmp (arg, "onthrow", 7) == 0) {
847 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
848 } else if (strncmp (arg, "help", 4) == 0) {
851 } else if (strncmp (arg, "timeout=", 8) == 0) {
852 agent_config.timeout = atoi (arg + 8);
853 } else if (strncmp (arg, "launch=", 7) == 0) {
854 agent_config.launch = g_strdup (arg + 7);
855 } else if (strncmp (arg, "embedding=", 10) == 0) {
856 agent_config.embedding = atoi (arg + 10) == 1;
857 } else if (strncmp (arg, "keepalive=", 10) == 0) {
858 agent_config.keepalive = atoi (arg + 10);
865 if (agent_config.server && !agent_config.suspend) {
866 /* Waiting for deferred attachment */
867 agent_config.defer = TRUE;
868 if (agent_config.address == NULL) {
869 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
873 //agent_config.log_level = 0;
875 if (agent_config.transport == NULL) {
876 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
880 if (agent_config.address == NULL && !agent_config.server) {
881 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
886 if (!strcmp (agent_config.transport, "dt_socket")) {
887 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
888 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
895 mono_debugger_agent_init (void)
897 if (!agent_config.enabled)
902 /* Need to know whenever a thread has acquired the loader mutex */
903 mono_loader_lock_track_ownership (TRUE);
905 event_requests = g_ptr_array_new ();
907 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
908 mono_cond_init (&debugger_thread_exited_cond, NULL);
910 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
911 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
912 mono_profiler_install_runtime_initialized (runtime_initialized);
913 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
914 mono_profiler_install_thread (thread_startup, thread_end);
915 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
916 mono_profiler_install_jit_end (jit_end);
917 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
919 mono_native_tls_alloc (&debugger_tls_id, NULL);
921 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
922 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
924 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
925 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
927 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
928 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
930 pending_assembly_loads = g_ptr_array_new ();
931 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
933 log_level = agent_config.log_level;
935 embedding = agent_config.embedding;
938 if (agent_config.log_file) {
939 log_file = fopen (agent_config.log_file, "w+");
941 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
953 mini_get_debug_options ()->gen_seq_points = TRUE;
955 * This is needed because currently we don't handle liveness info.
957 mini_get_debug_options ()->mdb_optimizations = TRUE;
959 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
960 /* This is needed because we can't set local variables in registers yet */
961 mono_disable_optimizations (MONO_OPT_LINEARS);
965 * The stack walk done from thread_interrupt () needs to be signal safe, but it
966 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
967 * safe (#3411). So load AOT info eagerly when the debugger is running as a
970 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
972 if (!agent_config.onuncaught && !agent_config.onthrow)
973 finish_agent_init (TRUE);
975 /* FIXME: Is this still needed ? */
976 #if defined(__MACH__)
977 mono_thread_info_disable_new_interrupt (TRUE);
984 * Finish the initialization of the agent. This involves connecting the transport
985 * and starting the agent thread. This is either done at startup, or
986 * in response to some event like an unhandled exception.
989 finish_agent_init (gboolean on_startup)
993 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
996 if (agent_config.launch) {
999 // FIXME: Generated address
1000 // FIXME: Races with transport_connect ()
1002 argv [0] = agent_config.launch;
1003 argv [1] = agent_config.transport;
1004 argv [2] = agent_config.address;
1007 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1009 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1014 transport_connect (agent_config.address);
1017 /* Do some which is usually done after sending the VMStart () event */
1018 vm_start_event_sent = TRUE;
1019 start_debugger_thread ();
1024 mono_debugger_agent_cleanup (void)
1029 stop_debugger_thread ();
1031 breakpoints_cleanup ();
1035 mono_mutex_destroy (&debugger_thread_exited_mutex);
1036 mono_cond_destroy (&debugger_thread_exited_cond);
1043 #ifndef DISABLE_SOCKET_TRANSPORT
1048 * recv() + handle incomplete reads and EINTR
1051 socket_transport_recv (void *buf, int len)
1057 static gint32 last_keepalive;
1062 res = recv (fd, (char *) buf + total, len - total, flags);
1065 if (agent_config.keepalive) {
1066 gboolean need_keepalive = FALSE;
1067 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1068 need_keepalive = TRUE;
1069 } else if (res == -1) {
1070 /* This could happen if recv () is interrupted repeatedly */
1071 msecs = mono_msec_ticks ();
1072 if (msecs - last_keepalive >= agent_config.keepalive) {
1073 need_keepalive = TRUE;
1074 last_keepalive = msecs;
1077 if (need_keepalive) {
1078 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1082 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1087 #define HAVE_GETADDRINFO 1
1091 set_keepalive (void)
1096 if (!agent_config.keepalive)
1099 tv.tv_sec = agent_config.keepalive / 1000;
1100 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1102 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1103 g_assert (result >= 0);
1107 socket_transport_accept (int socket_fd)
1109 conn_fd = accept (socket_fd, NULL, NULL);
1110 if (conn_fd == -1) {
1111 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1113 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1120 socket_transport_send (void *data, int len)
1125 res = send (conn_fd, data, len, 0);
1126 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1134 * socket_transport_connect:
1136 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1139 socket_transport_connect (const char *address)
1141 #ifdef HAVE_GETADDRINFO
1142 struct addrinfo hints;
1143 struct addrinfo *result, *rp;
1145 struct hostent *result;
1147 int sfd = -1, s, res;
1148 char port_string [128];
1152 if (agent_config.address) {
1153 res = parse_address (agent_config.address, &host, &port);
1154 g_assert (res == 0);
1164 sprintf (port_string, "%d", port);
1166 mono_network_init ();
1168 /* Obtain address(es) matching host/port */
1169 #ifdef HAVE_GETADDRINFO
1170 memset (&hints, 0, sizeof (struct addrinfo));
1171 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1172 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1174 hints.ai_protocol = 0; /* Any protocol */
1176 s = getaddrinfo (host, port_string, &hints, &result);
1178 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1182 /* The PS3 doesn't even have _r or hstrerror () */
1183 result = gethostbyname (host);
1185 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1190 if (agent_config.server) {
1191 #ifdef HAVE_GETADDRINFO
1192 /* Wait for a connection */
1194 struct sockaddr_in addr;
1197 /* No address, generate one */
1198 sfd = socket (AF_INET, SOCK_STREAM, 0);
1201 /* This will bind the socket to a random port */
1202 res = listen (sfd, 16);
1204 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1209 addrlen = sizeof (addr);
1210 memset (&addr, 0, sizeof (addr));
1211 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1212 g_assert (res == 0);
1214 host = (char*)"127.0.0.1";
1215 port = ntohs (addr.sin_port);
1217 /* Emit the address to stdout */
1218 /* FIXME: Should print another interface, not localhost */
1219 printf ("%s:%d\n", host, port);
1221 /* Listen on the provided address */
1222 for (rp = result; rp != NULL; rp = rp->ai_next) {
1225 sfd = socket (rp->ai_family, rp->ai_socktype,
1230 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1233 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1237 res = listen (sfd, 16);
1246 * this function is not present on win2000 which we still support, and the
1247 * workaround described here:
1248 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1249 * only works with MSVC.
1251 #ifdef HAVE_GETADDRINFO
1252 freeaddrinfo (result);
1257 if (agent_config.defer)
1260 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1262 if (agent_config.timeout) {
1267 tv.tv_usec = agent_config.timeout * 1000;
1269 FD_SET (sfd, &readfds);
1270 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1272 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1277 conn_fd = socket_transport_accept (sfd);
1281 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1284 #endif /* HAVE_GETADDRINFO */
1286 /* Connect to the specified address */
1287 #ifdef HAVE_GETADDRINFO
1288 /* FIXME: Respect the timeout */
1289 for (rp = result; rp != NULL; rp = rp->ai_next) {
1290 sfd = socket (rp->ai_family, rp->ai_socktype,
1295 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1296 break; /* Success */
1302 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1306 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1308 g_assert_not_reached ();
1309 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1311 g_assert_not_reached ();
1317 /* See the comment above */
1318 #ifdef HAVE_GETADDRINFO
1319 freeaddrinfo (result);
1324 disconnected = !transport_handshake ();
1330 socket_transport_close1 (void)
1332 /* This will interrupt the agent thread */
1333 /* Close the read part only so it can still send back replies */
1334 /* Also shut down the connection listener so that we can exit normally */
1336 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1337 shutdown (conn_fd, SD_BOTH);
1338 shutdown (listen_fd, SD_BOTH);
1339 closesocket (listen_fd);
1341 shutdown (conn_fd, SHUT_RD);
1342 shutdown (listen_fd, SHUT_RDWR);
1348 socket_transport_close2 (void)
1351 shutdown (conn_fd, SD_BOTH);
1353 shutdown (conn_fd, SHUT_RDWR);
1358 register_socket_transport (void)
1360 DebuggerTransport trans;
1362 trans.name = "dt_socket";
1363 trans.connect = socket_transport_connect;
1364 trans.close1 = socket_transport_close1;
1365 trans.close2 = socket_transport_close2;
1366 trans.send = socket_transport_send;
1367 trans.recv = socket_transport_recv;
1369 register_transport (&trans);
1372 #endif /* DISABLE_SOCKET_TRANSPORT */
1378 #define MAX_TRANSPORTS 16
1380 static DebuggerTransport *transport;
1382 static DebuggerTransport transports [MAX_TRANSPORTS];
1383 static int ntransports;
1386 register_transport (DebuggerTransport *trans)
1388 g_assert (ntransports < MAX_TRANSPORTS);
1390 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1395 transport_init (void)
1399 #ifndef DISABLE_SOCKET_TRANSPORT
1400 register_socket_transport ();
1403 for (i = 0; i < ntransports; ++i) {
1404 if (!strcmp (agent_config.transport, transports [i].name))
1407 if (i == ntransports) {
1408 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1409 for (i = 0; i < ntransports; ++i)
1410 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1411 fprintf (stderr, "\n");
1414 transport = &transports [i];
1418 transport_connect (const char *address)
1420 transport->connect (address);
1424 transport_close1 (void)
1426 transport->close1 ();
1430 transport_close2 (void)
1432 transport->close2 ();
1436 transport_send (void *buf, int len)
1438 return transport->send (buf, len);
1442 transport_recv (void *buf, int len)
1444 return transport->recv (buf, len);
1448 transport_handshake (void)
1450 char handshake_msg [128];
1454 /* Write handshake message */
1455 sprintf (handshake_msg, "DWP-Handshake");
1457 res = transport_send (handshake_msg, strlen (handshake_msg));
1458 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1459 g_assert (res != -1);
1462 res = transport_recv (buf, strlen (handshake_msg));
1463 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1464 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1469 * To support older clients, the client sends its protocol version after connecting
1470 * using a command. Until that is received, default to our protocol version.
1472 major_version = MAJOR_VERSION;
1473 minor_version = MINOR_VERSION;
1474 protocol_version_set = FALSE;
1476 #ifndef DISABLE_SOCKET_TRANSPORT
1477 // FIXME: Move this somewhere else
1479 * Set TCP_NODELAY on the socket so the client receives events/command
1480 * results immediately.
1484 int result = setsockopt (conn_fd,
1489 g_assert (result >= 0);
1499 stop_debugger_thread (void)
1504 transport_close1 ();
1507 * Wait for the thread to exit.
1509 * If we continue with the shutdown without waiting for it, then the client might
1510 * not receive an answer to its last command like a resume.
1511 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1514 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1515 if (GetCurrentThreadId () != debugger_thread_id) {
1517 mono_mutex_lock (&debugger_thread_exited_mutex);
1518 if (!debugger_thread_exited) {
1520 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1521 mono_mutex_unlock (&debugger_thread_exited_mutex);
1523 mono_mutex_lock (&debugger_thread_exited_mutex);
1526 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1529 mono_mutex_unlock (&debugger_thread_exited_mutex);
1530 } while (!debugger_thread_exited);
1533 transport_close2 ();
1537 start_debugger_thread (void)
1541 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1542 g_assert (debugger_thread_handle);
1546 * Functions to decode protocol data
1550 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1553 g_assert (*endbuf <= limit);
1558 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1561 g_assert (*endbuf <= limit);
1563 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1566 static inline gint64
1567 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1569 guint32 high = decode_int (buf, &buf, limit);
1570 guint32 low = decode_int (buf, &buf, limit);
1574 return ((((guint64)high) << 32) | ((guint64)low));
1578 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1580 return decode_int (buf, endbuf, limit);
1584 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1586 int len = decode_int (buf, &buf, limit);
1594 s = g_malloc (len + 1);
1597 memcpy (s, buf, len);
1606 * Functions to encode protocol data
1610 guint8 *buf, *p, *end;
1614 buffer_init (Buffer *buf, int size)
1616 buf->buf = g_malloc (size);
1618 buf->end = buf->buf + size;
1622 buffer_make_room (Buffer *buf, int size)
1624 if (buf->end - buf->p < size) {
1625 int new_size = buf->end - buf->buf + size + 32;
1626 guint8 *p = g_realloc (buf->buf, new_size);
1627 size = buf->p - buf->buf;
1630 buf->end = buf->buf + new_size;
1635 buffer_add_byte (Buffer *buf, guint8 val)
1637 buffer_make_room (buf, 1);
1643 buffer_add_short (Buffer *buf, guint32 val)
1645 buffer_make_room (buf, 2);
1646 buf->p [0] = (val >> 8) & 0xff;
1647 buf->p [1] = (val >> 0) & 0xff;
1652 buffer_add_int (Buffer *buf, guint32 val)
1654 buffer_make_room (buf, 4);
1655 buf->p [0] = (val >> 24) & 0xff;
1656 buf->p [1] = (val >> 16) & 0xff;
1657 buf->p [2] = (val >> 8) & 0xff;
1658 buf->p [3] = (val >> 0) & 0xff;
1663 buffer_add_long (Buffer *buf, guint64 l)
1665 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1666 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1670 buffer_add_id (Buffer *buf, int id)
1672 buffer_add_int (buf, (guint64)id);
1676 buffer_add_data (Buffer *buf, guint8 *data, int len)
1678 buffer_make_room (buf, len);
1679 memcpy (buf->p, data, len);
1684 buffer_add_string (Buffer *buf, const char *str)
1689 buffer_add_int (buf, 0);
1692 buffer_add_int (buf, len);
1693 buffer_add_data (buf, (guint8*)str, len);
1698 buffer_free (Buffer *buf)
1704 send_packet (int command_set, int command, Buffer *data)
1710 id = InterlockedIncrement (&packet_id);
1712 len = data->p - data->buf + 11;
1713 buffer_init (&buf, len);
1714 buffer_add_int (&buf, len);
1715 buffer_add_int (&buf, id);
1716 buffer_add_byte (&buf, 0); /* flags */
1717 buffer_add_byte (&buf, command_set);
1718 buffer_add_byte (&buf, command);
1719 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1721 res = transport_send (buf.buf, len);
1729 send_reply_packet (int id, int error, Buffer *data)
1735 len = data->p - data->buf + 11;
1736 buffer_init (&buf, len);
1737 buffer_add_int (&buf, len);
1738 buffer_add_int (&buf, id);
1739 buffer_add_byte (&buf, 0x80); /* flags */
1740 buffer_add_byte (&buf, (error >> 8) & 0xff);
1741 buffer_add_byte (&buf, error);
1742 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1744 res = transport_send (buf.buf, len);
1756 * Represents an object accessible by the debugger client.
1759 /* Unique id used in the wire protocol to refer to objects */
1762 * A weakref gc handle pointing to the object. The gc handle is used to
1763 * detect if the object was garbage collected.
1768 /* Maps objid -> ObjRef */
1769 static GHashTable *objrefs;
1772 free_objref (gpointer value)
1776 mono_gchandle_free (o->handle);
1784 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1788 objrefs_cleanup (void)
1790 g_hash_table_destroy (objrefs);
1794 static GHashTable *obj_to_objref;
1797 * Return an ObjRef for OBJ.
1800 get_objref (MonoObject *obj)
1803 GSList *reflist = NULL, *l;
1809 mono_loader_lock ();
1812 obj_to_objref = g_hash_table_new (NULL, NULL);
1814 /* FIXME: The tables can grow indefinitely */
1816 if (mono_gc_is_moving ()) {
1818 * Objects can move, so use a hash table mapping hash codes to lists of
1819 * ObjRef structures.
1821 hash = mono_object_hash (obj);
1823 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1824 for (l = reflist; l; l = l->next) {
1826 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1827 mono_loader_unlock ();
1832 /* Use a hash table with masked pointers to internalize object references */
1833 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1834 /* ref might refer to a different object with the same addr which was GCd */
1835 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1836 mono_loader_unlock ();
1841 ref = g_new0 (ObjRef, 1);
1842 ref->id = InterlockedIncrement (&objref_id);
1843 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1845 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1847 if (mono_gc_is_moving ()) {
1848 reflist = g_slist_append (reflist, ref);
1849 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1851 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1854 mono_loader_unlock ();
1860 get_objid (MonoObject *obj)
1862 return get_objref (obj)->id;
1866 * Set OBJ to the object identified by OBJID.
1867 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1871 get_object_allow_null (int objid, MonoObject **obj)
1881 return ERR_INVALID_OBJECT;
1883 mono_loader_lock ();
1885 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1888 *obj = mono_gchandle_get_target (ref->handle);
1889 mono_loader_unlock ();
1891 return ERR_INVALID_OBJECT;
1894 mono_loader_unlock ();
1895 return ERR_INVALID_OBJECT;
1900 get_object (int objid, MonoObject **obj)
1902 int err = get_object_allow_null (objid, obj);
1907 return ERR_INVALID_OBJECT;
1912 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1914 return decode_id (buf, endbuf, limit);
1918 buffer_add_objid (Buffer *buf, MonoObject *o)
1920 buffer_add_id (buf, get_objid (o));
1939 * Represents a runtime structure accessible to the debugger client
1942 /* Unique id used in the wire protocol */
1944 /* Domain of the runtime structure, NULL if the domain was unloaded */
1951 MonoAssembly *assembly;
1952 MonoClassField *field;
1954 MonoProperty *property;
1959 /* Maps runtime structure -> Id */
1960 GHashTable *val_to_id [ID_NUM];
1961 /* Classes whose class load event has been sent */
1962 GHashTable *loaded_classes;
1963 /* Maps MonoClass->GPtrArray of file names */
1964 GHashTable *source_files;
1965 /* Maps source file basename -> GSList of classes */
1966 GHashTable *source_file_to_class;
1967 /* Same with ignore-case */
1968 GHashTable *source_file_to_class_ignorecase;
1972 static GPtrArray *ids [ID_NUM];
1979 for (i = 0; i < ID_NUM; ++i)
1980 ids [i] = g_ptr_array_new ();
1988 for (i = 0; i < ID_NUM; ++i) {
1990 for (j = 0; j < ids [i]->len; ++j)
1991 g_free (g_ptr_array_index (ids [i], j));
1992 g_ptr_array_free (ids [i], TRUE);
1999 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2001 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2003 GHashTableIter iter;
2004 GPtrArray *file_names;
2009 for (i = 0; i < ID_NUM; ++i)
2010 if (info->val_to_id [i])
2011 g_hash_table_destroy (info->val_to_id [i]);
2012 g_hash_table_destroy (info->loaded_classes);
2014 g_hash_table_iter_init (&iter, info->source_files);
2015 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2016 for (i = 0; i < file_names->len; ++i)
2017 g_free (g_ptr_array_index (file_names, i));
2018 g_ptr_array_free (file_names, TRUE);
2021 g_hash_table_iter_init (&iter, info->source_file_to_class);
2022 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2027 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2028 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2036 domain_jit_info (domain)->agent_info = NULL;
2038 /* Clear ids referencing structures in the domain */
2039 for (i = 0; i < ID_NUM; ++i) {
2041 for (j = 0; j < ids [i]->len; ++j) {
2042 Id *id = g_ptr_array_index (ids [i], j);
2043 if (id->domain == domain)
2049 mono_loader_lock ();
2050 g_hash_table_remove (domains, domain);
2051 mono_loader_unlock ();
2054 static AgentDomainInfo*
2055 get_agent_domain_info (MonoDomain *domain)
2057 AgentDomainInfo *info = NULL;
2059 mono_domain_lock (domain);
2061 info = domain_jit_info (domain)->agent_info;
2063 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2064 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2065 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2066 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2067 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2070 mono_domain_unlock (domain);
2076 get_id (MonoDomain *domain, IdType type, gpointer val)
2079 AgentDomainInfo *info;
2084 mono_loader_lock ();
2086 mono_domain_lock (domain);
2088 info = get_agent_domain_info (domain);
2090 if (info->val_to_id [type] == NULL)
2091 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2093 id = g_hash_table_lookup (info->val_to_id [type], val);
2095 mono_domain_unlock (domain);
2096 mono_loader_unlock ();
2100 id = g_new0 (Id, 1);
2102 id->id = ids [type]->len + 1;
2103 id->domain = domain;
2106 g_hash_table_insert (info->val_to_id [type], val, id);
2108 mono_domain_unlock (domain);
2110 g_ptr_array_add (ids [type], id);
2112 mono_loader_unlock ();
2117 static inline gpointer
2118 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2122 int id = decode_id (buf, endbuf, limit);
2131 // FIXME: error handling
2132 mono_loader_lock ();
2133 g_assert (id > 0 && id <= ids [type]->len);
2135 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2136 mono_loader_unlock ();
2138 if (res->domain == NULL) {
2139 *err = ERR_UNLOADED;
2144 *domain = res->domain;
2146 return res->data.val;
2150 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2152 buffer_add_id (buf, get_id (domain, type, val));
2155 static inline MonoClass*
2156 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2158 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2161 static inline MonoAssembly*
2162 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2164 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2167 static inline MonoImage*
2168 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2170 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2173 static inline MonoMethod*
2174 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2176 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2179 static inline MonoClassField*
2180 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2182 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2185 static inline MonoDomain*
2186 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2188 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2191 static inline MonoProperty*
2192 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2194 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2198 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2200 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2204 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2206 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2210 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2212 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2216 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2218 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2222 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2224 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2228 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2230 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2234 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2236 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2239 static void invoke_method (void);
2246 * save_thread_context:
2248 * Set CTX as the current threads context which is used for computing stack traces.
2249 * This function is signal-safe.
2252 save_thread_context (MonoContext *ctx)
2254 DebuggerTlsData *tls;
2256 tls = mono_native_tls_get_value (debugger_tls_id);
2260 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2262 mono_thread_state_init_from_current (&tls->context);
2265 /* The number of times the runtime is suspended */
2266 static gint32 suspend_count;
2268 /* Number of threads suspended */
2270 * If this is equal to the size of thread_to_tls, the runtime is considered
2273 static gint32 threads_suspend_count;
2275 static mono_mutex_t suspend_mutex;
2277 /* Cond variable used to wait for suspend_count becoming 0 */
2278 static mono_cond_t suspend_cond;
2280 /* Semaphore used to wait for a thread becoming suspended */
2281 static MonoSemType suspend_sem;
2286 mono_mutex_init (&suspend_mutex, NULL);
2287 mono_cond_init (&suspend_cond, NULL);
2288 MONO_SEM_INIT (&suspend_sem, 0);
2293 StackFrameInfo last_frame;
2294 gboolean last_frame_set;
2297 } GetLastFrameUserData;
2300 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2302 GetLastFrameUserData *data = user_data;
2304 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2307 if (!data->last_frame_set) {
2308 /* Store the last frame */
2309 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2310 data->last_frame_set = TRUE;
2313 /* Store the context/lmf for the frame above the last frame */
2314 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2315 data->lmf = info->lmf;
2323 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2324 * INFO is set, process the thread described by INFO.
2325 * This should be signal safe.
2328 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2332 MonoNativeThreadId tid;
2335 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2336 * guarantee the signal handler will be called that many times. Instead of tracking
2337 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2338 * has been requested that hasn't been handled yet, otherwise we can have threads
2339 * refuse to die when VM_EXIT is called
2341 #if defined(__APPLE__)
2342 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2346 * We use interrupt_count to determine whenever this interrupt should be processed
2347 * by us or the normal interrupt processing code in the signal handler.
2348 * There is no race here with notify_thread (), since the signal is sent after
2349 * incrementing interrupt_count.
2351 if (tls->interrupt_count == 0)
2354 InterlockedDecrement (&tls->interrupt_count);
2358 ip = mono_arch_ip_from_context (sigctx);
2360 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2365 tid = mono_thread_info_get_tid (info);
2367 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2369 // FIXME: Races when the thread leaves managed code before hitting a single step
2373 /* Running managed code, will be suspended by the single step code */
2374 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2378 * Running native code, will be suspended when it returns to/enters
2379 * managed code. Treat it as already suspended.
2380 * This might interrupt the code in process_single_step_inner (), we use the
2381 * tls->suspending flag to avoid races when that happens.
2383 if (!tls->suspended && !tls->suspending) {
2385 GetLastFrameUserData data;
2387 // FIXME: printf is not signal safe, but this is only used during
2388 // debugger debugging
2390 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2391 //save_thread_context (&ctx);
2394 /* Already terminated */
2397 tls->context.valid = FALSE;
2400 * We are in a difficult position: we want to be able to provide stack
2401 * traces for this thread, but we can't use the current ctx+lmf, since
2402 * the thread is still running, so it might return to managed code,
2403 * making these invalid.
2404 * So we start a stack walk and save the first frame, along with the
2405 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2406 * suspended when it returns to managed code, so the parent's ctx should
2409 data.last_frame_set = FALSE;
2411 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2413 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2414 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2415 * since we are not in a JITted method.
2417 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2419 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2421 if (data.last_frame_set) {
2422 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2423 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2425 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2428 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2429 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2430 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2432 /* No managed frames */
2433 tls->async_state.valid = FALSE;
2435 mono_memory_barrier ();
2437 tls->suspended = TRUE;
2438 MONO_SEM_POST (&suspend_sem);
2445 * mono_debugger_agent_thread_interrupt:
2447 * Called by the abort signal handler.
2448 * Should be signal safe.
2451 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2453 DebuggerTlsData *tls;
2458 tls = mono_native_tls_get_value (debugger_tls_id);
2462 return thread_interrupt (tls, NULL, sigctx, ji);
2466 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2469 mono_debugger_agent_thread_interrupt (NULL, NULL);
2471 #endif /* HOST_WIN32 */
2474 * reset_native_thread_suspend_state:
2476 * Reset the suspended flag and state on native threads
2479 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2481 DebuggerTlsData *tls = value;
2483 if (!tls->really_suspended && tls->suspended) {
2484 tls->suspended = FALSE;
2486 * The thread might still be running if it was executing native code, so the state won't be invalided by
2487 * suspend_current ().
2489 tls->context.valid = FALSE;
2490 tls->async_state.valid = FALSE;
2491 invalidate_frames (tls);
2498 * Notify a thread that it needs to suspend.
2501 notify_thread (gpointer key, gpointer value, gpointer user_data)
2503 MonoInternalThread *thread = key;
2504 DebuggerTlsData *tls = value;
2505 gsize tid = thread->tid;
2508 if (GetCurrentThreadId () == tid || tls->terminated)
2511 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2514 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2515 * guarantee the signal handler will be called that many times. Instead of tracking
2516 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2517 * has been requested that hasn't been handled yet, otherwise we can have threads
2518 * refuse to die when VM_EXIT is called
2520 #if defined(__APPLE__)
2521 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2525 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2526 * of things like breaking waits etc. which we don't want.
2528 InterlockedIncrement (&tls->interrupt_count);
2531 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2533 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2535 if (mono_thread_info_new_interrupt_enabled ()) {
2536 MonoThreadInfo *info;
2539 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2542 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2544 thread_interrupt (tls, info, NULL, ji);
2546 mono_thread_info_resume (mono_thread_info_get_tid (info));
2548 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2551 * Attached thread which died without detaching.
2553 tls->terminated = TRUE;
2559 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2561 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2564 if (mono_loader_lock_is_owned_by_self ()) {
2566 * Shortcut for the check in suspend_current (). This speeds up processing
2567 * when executing long running code inside the loader lock, i.e. assembly load
2573 if (debugger_thread_id == GetCurrentThreadId ())
2576 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2577 if (suspend_count - tls->resume_count > 0)
2578 tls->suspending = TRUE;
2580 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2582 if (suspend_count - tls->resume_count == 0) {
2584 * We are executing a single threaded invoke but the single step for
2585 * suspending is still active.
2586 * FIXME: This slows down single threaded invokes.
2588 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2592 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2594 /* Can't suspend in these methods */
2595 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2598 save_thread_context (ctx);
2606 * Increase the suspend count of the VM. While the suspend count is greater
2607 * than 0, runtime threads are suspended at certain points during execution.
2612 mono_loader_lock ();
2614 mono_mutex_lock (&suspend_mutex);
2618 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2620 if (suspend_count == 1) {
2621 // FIXME: Is it safe to call this inside the lock ?
2622 start_single_stepping ();
2623 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2626 mono_mutex_unlock (&suspend_mutex);
2628 mono_loader_unlock ();
2634 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2642 g_assert (debugger_thread_id == GetCurrentThreadId ());
2644 mono_loader_lock ();
2646 mono_mutex_lock (&suspend_mutex);
2648 g_assert (suspend_count > 0);
2651 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2653 if (suspend_count == 0) {
2654 // FIXME: Is it safe to call this inside the lock ?
2655 stop_single_stepping ();
2656 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2659 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2660 err = mono_cond_broadcast (&suspend_cond);
2661 g_assert (err == 0);
2663 mono_mutex_unlock (&suspend_mutex);
2664 //g_assert (err == 0);
2666 mono_loader_unlock ();
2672 * Resume just one thread.
2675 resume_thread (MonoInternalThread *thread)
2678 DebuggerTlsData *tls;
2680 g_assert (debugger_thread_id == GetCurrentThreadId ());
2682 mono_loader_lock ();
2684 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2687 mono_mutex_lock (&suspend_mutex);
2689 g_assert (suspend_count > 0);
2691 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2693 tls->resume_count += suspend_count;
2696 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2697 * but only the one whose resume_count field is > 0 will be resumed.
2699 err = mono_cond_broadcast (&suspend_cond);
2700 g_assert (err == 0);
2702 mono_mutex_unlock (&suspend_mutex);
2703 //g_assert (err == 0);
2705 mono_loader_unlock ();
2709 invalidate_frames (DebuggerTlsData *tls)
2714 tls = mono_native_tls_get_value (debugger_tls_id);
2717 for (i = 0; i < tls->frame_count; ++i) {
2718 if (tls->frames [i]->jit)
2719 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2720 g_free (tls->frames [i]);
2722 g_free (tls->frames);
2723 tls->frame_count = 0;
2730 * Suspend the current thread until the runtime is resumed. If the thread has a
2731 * pending invoke, then the invoke is executed before this function returns.
2734 suspend_current (void)
2737 DebuggerTlsData *tls;
2739 g_assert (debugger_thread_id != GetCurrentThreadId ());
2741 if (mono_loader_lock_is_owned_by_self ()) {
2743 * If we own the loader mutex, can't suspend until we release it, since the
2744 * whole runtime can deadlock otherwise.
2749 tls = mono_native_tls_get_value (debugger_tls_id);
2752 mono_mutex_lock (&suspend_mutex);
2754 tls->suspending = FALSE;
2755 tls->really_suspended = TRUE;
2757 if (!tls->suspended) {
2758 tls->suspended = TRUE;
2759 MONO_SEM_POST (&suspend_sem);
2762 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2764 while (suspend_count - tls->resume_count > 0) {
2766 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2768 mono_mutex_unlock (&suspend_mutex);
2770 mono_mutex_lock (&suspend_mutex);
2776 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2777 g_assert (err == 0);
2781 tls->suspended = FALSE;
2782 tls->really_suspended = FALSE;
2784 threads_suspend_count --;
2786 mono_mutex_unlock (&suspend_mutex);
2788 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2790 if (tls->pending_invoke) {
2791 /* Save the original context */
2792 tls->pending_invoke->has_ctx = TRUE;
2793 tls->pending_invoke->ctx = tls->context.ctx;
2798 /* The frame info becomes invalid after a resume */
2799 tls->context.valid = FALSE;
2800 tls->async_state.valid = FALSE;
2801 invalidate_frames (tls);
2805 count_thread (gpointer key, gpointer value, gpointer user_data)
2807 DebuggerTlsData *tls = value;
2809 if (!tls->suspended && !tls->terminated)
2810 *(int*)user_data = *(int*)user_data + 1;
2814 count_threads_to_wait_for (void)
2818 mono_loader_lock ();
2819 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2820 mono_loader_unlock ();
2828 * Wait until the runtime is completely suspended.
2831 wait_for_suspend (void)
2833 int nthreads, nwait, err;
2834 gboolean waited = FALSE;
2836 // FIXME: Threads starting/stopping ?
2837 mono_loader_lock ();
2838 nthreads = mono_g_hash_table_size (thread_to_tls);
2839 mono_loader_unlock ();
2842 nwait = count_threads_to_wait_for ();
2844 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2845 err = MONO_SEM_WAIT (&suspend_sem);
2846 g_assert (err == 0);
2854 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2860 * Return whenever the runtime is suspended.
2865 return count_threads_to_wait_for () == 0;
2868 static MonoSeqPointInfo*
2869 get_seq_points (MonoDomain *domain, MonoMethod *method)
2871 MonoSeqPointInfo *seq_points;
2873 mono_domain_lock (domain);
2874 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2875 if (!seq_points && method->is_inflated) {
2876 /* generic sharing + aot */
2877 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2879 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2881 mono_domain_unlock (domain);
2886 static MonoSeqPointInfo*
2887 find_seq_points (MonoDomain *domain, MonoMethod *method)
2889 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2892 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2893 g_assert (seq_points);
2899 * find_next_seq_point_for_native_offset:
2901 * Find the first sequence point after NATIVE_OFFSET.
2904 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2906 MonoSeqPointInfo *seq_points;
2909 seq_points = find_seq_points (domain, method);
2913 for (i = 0; i < seq_points->len; ++i) {
2914 if (seq_points->seq_points [i].native_offset >= native_offset)
2915 return &seq_points->seq_points [i];
2922 * find_prev_seq_point_for_native_offset:
2924 * Find the first sequence point before NATIVE_OFFSET.
2927 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2929 MonoSeqPointInfo *seq_points;
2932 seq_points = find_seq_points (domain, method);
2936 for (i = seq_points->len - 1; i >= 0; --i) {
2937 if (seq_points->seq_points [i].native_offset <= native_offset)
2938 return &seq_points->seq_points [i];
2947 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2948 * should be the location of a sequence point.
2950 static G_GNUC_UNUSED SeqPoint*
2951 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2953 MonoSeqPointInfo *seq_points;
2958 seq_points = get_seq_points (domain, method);
2963 for (i = 0; i < seq_points->len; ++i) {
2964 if (seq_points->seq_points [i].il_offset == il_offset)
2965 return &seq_points->seq_points [i];
2972 DebuggerTlsData *tls;
2974 } ComputeFramesUserData;
2977 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2979 ComputeFramesUserData *ud = user_data;
2981 MonoMethod *method, *actual_method, *api_method;
2985 if (info->type != FRAME_TYPE_MANAGED) {
2986 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2987 /* Mark the last frame as an invoke frame */
2989 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2995 method = info->ji->method;
2997 method = info->method;
2998 actual_method = info->actual_method;
2999 api_method = method;
3004 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3007 if (info->il_offset == -1) {
3008 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3009 if (ud->frames == NULL) {
3010 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3012 info->il_offset = sp->il_offset;
3014 if (info->il_offset == -1)
3015 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3018 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));
3020 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3021 if (!CHECK_PROTOCOL_VERSION (2, 17))
3022 /* Older clients can't handle this flag */
3024 api_method = mono_marshal_method_from_wrapper (method);
3027 actual_method = api_method;
3028 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3031 frame = g_new0 (StackFrame, 1);
3032 frame->method = method;
3033 frame->actual_method = actual_method;
3034 frame->api_method = api_method;
3035 frame->il_offset = info->il_offset;
3036 frame->native_offset = info->native_offset;
3037 frame->flags = flags;
3038 frame->ji = info->ji;
3039 if (info->reg_locations)
3040 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3043 frame->has_ctx = TRUE;
3045 frame->domain = info->domain;
3047 ud->frames = g_slist_append (ud->frames, frame);
3053 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3055 ComputeFramesUserData *ud = user_data;
3058 * 'tls->filter_ctx' is the location of the throw site.
3060 * mono_walk_stack() will never actually hit the throw site, but unwind
3061 * directly from the filter to the call site; we abort stack unwinding here
3062 * once this happens and resume from the throw site.
3065 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3068 return process_frame (info, ctx, user_data);
3072 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3074 ComputeFramesUserData user_data;
3076 int i, findex, new_frame_count;
3077 StackFrame **new_frames, *f;
3078 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3080 // FIXME: Locking on tls
3081 if (tls->frames && tls->frames_up_to_date)
3084 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3086 user_data.tls = tls;
3087 user_data.frames = NULL;
3088 if (tls->terminated) {
3089 tls->frame_count = 0;
3091 } if (!tls->really_suspended && tls->async_state.valid) {
3092 /* Have to use the state saved by the signal handler */
3093 process_frame (&tls->async_last_frame, NULL, &user_data);
3094 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3095 } else if (tls->filter_state.valid) {
3097 * We are inside an exception filter.
3099 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3101 if (tls->context.valid)
3102 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3104 * After that, we resume unwinding from the location where the exception has been thrown.
3106 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3107 } else if (tls->context.valid) {
3108 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3111 tls->frame_count = 0;
3115 new_frame_count = g_slist_length (user_data.frames);
3116 new_frames = g_new0 (StackFrame*, new_frame_count);
3118 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3122 * Reuse the id for already existing stack frames, so invokes don't invalidate
3123 * the still valid stack frames.
3125 for (i = 0; i < tls->frame_count; ++i) {
3126 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3127 f->id = tls->frames [i]->id;
3132 if (i >= tls->frame_count)
3133 f->id = InterlockedIncrement (&frame_id);
3135 new_frames [findex ++] = f;
3138 g_slist_free (user_data.frames);
3140 invalidate_frames (tls);
3142 tls->frames = new_frames;
3143 tls->frame_count = new_frame_count;
3144 tls->frames_up_to_date = TRUE;
3148 * GHFunc to emit an appdomain creation event
3149 * @param key Don't care
3150 * @param value A loaded appdomain
3151 * @param user_data Don't care
3154 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3156 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3157 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3161 * GHFunc to emit a thread start event
3162 * @param key A thread id
3163 * @param value A thread object
3164 * @param user_data Don't care
3167 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3169 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3170 process_profiler_event (EVENT_KIND_THREAD_START, value);
3174 * GFunc to emit an assembly load event
3175 * @param value A loaded assembly
3176 * @param user_data Don't care
3179 emit_assembly_load (gpointer value, gpointer user_data)
3181 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3185 * GFunc to emit a type load event
3186 * @param value A loaded type
3187 * @param user_data Don't care
3190 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3192 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3196 strdup_tolower (char *s)
3201 for (p = s2; *p; ++p)
3211 * create_event_list:
3213 * Return a list of event request ids matching EVENT, starting from REQS, which
3214 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3216 * We return request ids, instead of requests, to simplify threading, since
3217 * requests could be deleted anytime when the loader lock is not held.
3218 * LOCKING: Assumes the loader lock is held.
3221 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3224 GSList *events = NULL;
3226 *suspend_policy = SUSPEND_POLICY_NONE;
3229 reqs = event_requests;
3234 for (i = 0; i < reqs->len; ++i) {
3235 EventRequest *req = g_ptr_array_index (reqs, i);
3236 if (req->event_kind == event) {
3237 gboolean filtered = FALSE;
3240 for (j = 0; j < req->nmodifiers; ++j) {
3241 Modifier *mod = &req->modifiers [j];
3243 if (mod->kind == MOD_KIND_COUNT) {
3245 if (mod->data.count > 0) {
3246 if (mod->data.count > 0) {
3248 if (mod->data.count == 0)
3252 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3253 if (mod->data.thread != mono_thread_internal_current ())
3255 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3256 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3258 if (ei->caught && !mod->caught)
3260 if (!ei->caught && !mod->uncaught)
3262 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3264 gboolean found = FALSE;
3265 MonoAssembly **assemblies = mod->data.assemblies;
3268 for (k = 0; assemblies [k]; ++k)
3269 if (assemblies [k] == ji->method->klass->image->assembly)
3274 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3275 gpointer iter = NULL;
3277 MonoDebugSourceInfo *sinfo;
3278 char *source_file, *s;
3279 gboolean found = FALSE;
3281 GPtrArray *source_file_list;
3283 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3284 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3287 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3288 for (i = 0; i < source_file_list->len; ++i) {
3289 sinfo = g_ptr_array_index (source_file_list, i);
3291 * Do a case-insesitive match by converting the file name to
3294 s = strdup_tolower (sinfo->source_file);
3295 if (g_hash_table_lookup (mod->data.source_files, s))
3299 g_ptr_array_free (source_file_list, TRUE);
3304 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3307 s = mono_type_full_name (&ei->klass->byval_arg);
3308 if (!g_hash_table_lookup (mod->data.type_names, s))
3311 } else if (mod->kind == MOD_KIND_STEP) {
3312 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3313 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3314 !strcmp (ji->method->name, ".cctor"))
3320 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3321 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3326 /* Send a VM START/DEATH event by default */
3327 if (event == EVENT_KIND_VM_START)
3328 events = g_slist_append (events, GINT_TO_POINTER (0));
3329 if (event == EVENT_KIND_VM_DEATH)
3330 events = g_slist_append (events, GINT_TO_POINTER (0));
3335 static G_GNUC_UNUSED const char*
3336 event_to_string (EventKind event)
3339 case EVENT_KIND_VM_START: return "VM_START";
3340 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3341 case EVENT_KIND_THREAD_START: return "THREAD_START";
3342 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3343 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3344 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3345 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3346 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3347 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3348 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3349 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3350 case EVENT_KIND_STEP: return "STEP";
3351 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3352 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3353 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3354 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3355 case EVENT_KIND_USER_LOG: return "USER_LOG";
3357 g_assert_not_reached ();
3364 * Send an event to the client, suspending the vm if needed.
3365 * LOCKING: Since this can suspend the calling thread, no locks should be held
3367 * The EVENTS list is freed by this function.
3370 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3374 MonoDomain *domain = mono_domain_get ();
3375 MonoThread *thread = NULL;
3376 gboolean send_success = FALSE;
3381 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3385 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3386 // FIXME: We miss those events
3387 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3391 if (vm_death_event_sent) {
3392 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3396 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3397 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3402 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3406 if (event == EVENT_KIND_KEEPALIVE)
3407 suspend_policy = SUSPEND_POLICY_NONE;
3412 if (agent_config.defer) {
3413 /* Make sure the thread id is always set when doing deferred debugging */
3414 if (debugger_thread_id == GetCurrentThreadId ()) {
3415 /* Don't suspend on events from the debugger thread */
3416 suspend_policy = SUSPEND_POLICY_NONE;
3417 thread = mono_thread_get_main ();
3419 else thread = mono_thread_current ();
3421 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3422 // FIXME: Send these with a NULL thread, don't suspend the current thread
3427 nevents = g_slist_length (events);
3428 buffer_init (&buf, 128);
3429 buffer_add_byte (&buf, suspend_policy);
3430 buffer_add_int (&buf, nevents);
3432 for (l = events; l; l = l->next) {
3433 buffer_add_byte (&buf, event); // event kind
3434 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3439 thread = mono_thread_current ();
3441 if (event == EVENT_KIND_VM_START && arg != NULL)
3444 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3447 case EVENT_KIND_THREAD_START:
3448 case EVENT_KIND_THREAD_DEATH:
3450 case EVENT_KIND_APPDOMAIN_CREATE:
3451 case EVENT_KIND_APPDOMAIN_UNLOAD:
3452 buffer_add_domainid (&buf, arg);
3454 case EVENT_KIND_METHOD_ENTRY:
3455 case EVENT_KIND_METHOD_EXIT:
3456 buffer_add_methodid (&buf, domain, arg);
3458 case EVENT_KIND_ASSEMBLY_LOAD:
3459 case EVENT_KIND_ASSEMBLY_UNLOAD:
3460 buffer_add_assemblyid (&buf, domain, arg);
3462 case EVENT_KIND_TYPE_LOAD:
3463 buffer_add_typeid (&buf, domain, arg);
3465 case EVENT_KIND_BREAKPOINT:
3466 case EVENT_KIND_STEP:
3467 buffer_add_methodid (&buf, domain, arg);
3468 buffer_add_long (&buf, il_offset);
3470 case EVENT_KIND_VM_START:
3471 buffer_add_domainid (&buf, mono_get_root_domain ());
3473 case EVENT_KIND_VM_DEATH:
3475 case EVENT_KIND_EXCEPTION: {
3476 EventInfo *ei = arg;
3477 buffer_add_objid (&buf, ei->exc);
3480 case EVENT_KIND_USER_BREAK:
3482 case EVENT_KIND_USER_LOG: {
3483 EventInfo *ei = arg;
3484 buffer_add_int (&buf, ei->level);
3485 buffer_add_string (&buf, ei->category ? ei->category : "");
3486 buffer_add_string (&buf, ei->message ? ei->message : "");
3489 case EVENT_KIND_KEEPALIVE:
3490 suspend_policy = SUSPEND_POLICY_NONE;
3493 g_assert_not_reached ();
3497 if (event == EVENT_KIND_VM_START) {
3498 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3499 if (!agent_config.defer)
3500 start_debugger_thread ();
3503 if (event == EVENT_KIND_VM_DEATH) {
3504 vm_death_event_sent = TRUE;
3505 suspend_policy = SUSPEND_POLICY_NONE;
3508 if (mono_runtime_is_shutting_down ())
3509 suspend_policy = SUSPEND_POLICY_NONE;
3511 if (suspend_policy != SUSPEND_POLICY_NONE) {
3513 * Save the thread context and start suspending before sending the packet,
3514 * since we could be receiving the resume request before send_packet ()
3517 save_thread_context (ctx);
3521 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3525 g_slist_free (events);
3528 if (!send_success) {
3529 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3533 if (event == EVENT_KIND_VM_START) {
3534 vm_start_event_sent = TRUE;
3537 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3539 switch (suspend_policy) {
3540 case SUSPEND_POLICY_NONE:
3542 case SUSPEND_POLICY_ALL:
3545 case SUSPEND_POLICY_EVENT_THREAD:
3549 g_assert_not_reached ();
3554 process_profiler_event (EventKind event, gpointer arg)
3558 EventInfo ei, *ei_arg = NULL;
3560 if (event == EVENT_KIND_TYPE_LOAD) {
3565 mono_loader_lock ();
3566 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3567 mono_loader_unlock ();
3569 process_event (event, arg, 0, NULL, events, suspend_policy);
3573 runtime_initialized (MonoProfiler *prof)
3575 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3576 if (agent_config.defer)
3577 start_debugger_thread ();
3581 runtime_shutdown (MonoProfiler *prof)
3583 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3585 mono_debugger_agent_cleanup ();
3589 thread_startup (MonoProfiler *prof, uintptr_t tid)
3591 MonoInternalThread *thread = mono_thread_internal_current ();
3592 MonoInternalThread *old_thread;
3593 DebuggerTlsData *tls;
3595 if (tid == debugger_thread_id)
3598 g_assert (thread->tid == tid);
3600 mono_loader_lock ();
3601 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3602 mono_loader_unlock ();
3604 if (thread == old_thread) {
3606 * For some reason, thread_startup () might be called for the same thread
3607 * multiple times (attach ?).
3609 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3613 * thread_end () might not be called for some threads, and the tid could
3616 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3617 mono_loader_lock ();
3618 mono_g_hash_table_remove (thread_to_tls, old_thread);
3619 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3620 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3621 mono_loader_unlock ();
3625 tls = mono_native_tls_get_value (debugger_tls_id);
3627 // FIXME: Free this somewhere
3628 tls = g_new0 (DebuggerTlsData, 1);
3629 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3630 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3631 tls->thread = thread;
3632 mono_native_tls_set_value (debugger_tls_id, tls);
3634 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3636 mono_loader_lock ();
3637 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3638 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3639 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3640 mono_loader_unlock ();
3642 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3645 * suspend_vm () could have missed this thread, so wait for a resume.
3651 thread_end (MonoProfiler *prof, uintptr_t tid)
3653 MonoInternalThread *thread;
3654 DebuggerTlsData *tls = NULL;
3656 mono_loader_lock ();
3657 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3659 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3660 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3662 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3663 tls->terminated = TRUE;
3664 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3665 MONO_GC_UNREGISTER_ROOT (tls->thread);
3669 mono_loader_unlock ();
3671 /* We might be called for threads started before we registered the start callback */
3673 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3674 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3679 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3681 mono_loader_lock ();
3682 g_hash_table_insert (domains, domain, domain);
3683 mono_loader_unlock ();
3685 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3689 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3691 clear_breakpoints_for_domain (domain);
3693 mono_loader_lock ();
3694 /* Invalidate each thread's frame stack */
3695 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3696 mono_loader_unlock ();
3698 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3702 * invalidate_each_thread:
3704 * A GHFunc to invalidate frames.
3705 * value must be a DebuggerTlsData*
3708 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3710 invalidate_frames (value);
3714 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3716 /* Sent later in jit_end () */
3717 mono_loader_lock ();
3718 g_ptr_array_add (pending_assembly_loads, assembly);
3719 mono_loader_unlock ();
3723 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3725 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3727 clear_event_requests_for_assembly (assembly);
3728 clear_types_for_assembly (assembly);
3732 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3734 #if defined(HOST_WIN32) && !defined(__GNUC__)
3735 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3737 gpointer stackptr = __builtin_frame_address (1);
3739 MonoInternalThread *thread = mono_thread_internal_current ();
3740 DebuggerTlsData *tls;
3742 mono_loader_lock ();
3744 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3745 /* Could be the debugger thread with assembly/type load hooks */
3747 tls->invoke_addr = stackptr;
3749 mono_loader_unlock ();
3753 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3756 #if defined(HOST_WIN32) && !defined(__GNUC__)
3757 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3759 gpointer stackptr = __builtin_frame_address (1);
3762 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3766 * We need to stop single stepping when exiting a runtime invoke, since if it is
3767 * a step out, it may return to native code, and thus never end.
3769 mono_loader_lock ();
3770 ss_invoke_addr = NULL;
3772 for (i = 0; i < event_requests->len; ++i) {
3773 EventRequest *req = g_ptr_array_index (event_requests, i);
3775 if (req->event_kind == EVENT_KIND_STEP) {
3776 ss_destroy (req->info);
3777 g_ptr_array_remove_index_fast (event_requests, i);
3782 mono_loader_unlock ();
3786 send_type_load (MonoClass *klass)
3788 gboolean type_load = FALSE;
3789 MonoDomain *domain = mono_domain_get ();
3790 AgentDomainInfo *info = NULL;
3792 mono_loader_lock ();
3793 mono_domain_lock (domain);
3795 info = get_agent_domain_info (domain);
3797 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3799 g_hash_table_insert (info->loaded_classes, klass, klass);
3802 mono_domain_unlock (domain);
3803 mono_loader_unlock ();
3805 emit_type_load (klass, klass, NULL);
3809 * Emit load events for all types currently loaded in the domain.
3810 * Takes the loader and domain locks.
3811 * user_data is unused.
3814 send_types_for_domain (MonoDomain *domain, void *user_data)
3816 AgentDomainInfo *info = NULL;
3818 mono_loader_lock ();
3819 mono_domain_lock (domain);
3820 info = get_agent_domain_info (domain);
3822 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3823 mono_domain_unlock (domain);
3824 mono_loader_unlock ();
3828 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3831 * We emit type load events when the first method of the type is JITted,
3832 * since the class load profiler callbacks might be called with the
3833 * loader lock held. They could also occur in the debugger thread.
3834 * Same for assembly load events.
3837 MonoAssembly *assembly = NULL;
3839 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3840 mono_loader_lock ();
3841 if (pending_assembly_loads->len > 0) {
3842 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3843 g_ptr_array_remove_index (pending_assembly_loads, 0);
3845 mono_loader_unlock ();
3848 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3854 send_type_load (method->klass);
3857 add_pending_breakpoints (method, jinfo);
3861 * BREAKPOINTS/SINGLE STEPPING
3865 * Contains information about an inserted breakpoint.
3868 long il_offset, native_offset;
3873 } BreakpointInstance;
3876 * Contains generic information about a breakpoint.
3880 * The method where the breakpoint is placed. Can be NULL in which case it
3881 * is inserted into every method. This is used to implement method entry/
3882 * exit events. Can be a generic method definition, in which case the
3883 * breakpoint is inserted into every instance.
3889 * A list of BreakpointInstance structures describing where the breakpoint
3890 * was inserted. There could be more than one because of
3891 * generics/appdomains/method entry/exit.
3893 GPtrArray *children;
3896 /* List of breakpoints */
3897 static GPtrArray *breakpoints;
3898 /* Maps breakpoint locations to the number of breakpoints at that location */
3899 static GHashTable *bp_locs;
3902 breakpoints_init (void)
3904 breakpoints = g_ptr_array_new ();
3905 bp_locs = g_hash_table_new (NULL, NULL);
3909 * insert_breakpoint:
3911 * Insert the breakpoint described by BP into the method described by
3915 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3918 BreakpointInstance *inst;
3919 SeqPoint *sp = NULL;
3922 mono_error_init (error);
3924 for (i = 0; i < seq_points->len; ++i) {
3925 sp = &seq_points->seq_points [i];
3927 if (sp->il_offset == bp->il_offset)
3931 if (i == seq_points->len) {
3933 * The set of IL offsets with seq points doesn't completely match the
3934 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3936 for (i = 0; i < seq_points->len; ++i) {
3937 sp = &seq_points->seq_points [i];
3939 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3944 if (i == seq_points->len) {
3945 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);
3947 for (i = 0; i < seq_points->len; ++i)
3948 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
3951 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3960 inst = g_new0 (BreakpointInstance, 1);
3962 inst->native_offset = sp->native_offset;
3963 inst->ip = (guint8*)ji->code_start + sp->native_offset;
3965 inst->domain = domain;
3967 mono_loader_lock ();
3969 g_ptr_array_add (bp->children, inst);
3971 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3972 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3973 mono_loader_unlock ();
3976 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3977 mono_arch_set_breakpoint (ji, inst->ip);
3983 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
3987 remove_breakpoint (BreakpointInstance *inst)
3989 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3991 MonoJitInfo *ji = inst->ji;
3992 guint8 *ip = inst->ip;
3994 mono_loader_lock ();
3995 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3996 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3997 mono_loader_unlock ();
3999 g_assert (count > 0);
4002 mono_arch_clear_breakpoint (ji, ip);
4009 static inline gboolean
4010 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4016 if (method == bp->method)
4018 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4021 if (bp->method->is_inflated && method->is_inflated) {
4022 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4023 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4025 /* Open generic methods should match closed generic methods of the same class */
4026 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4027 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4028 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4030 /* FIXME: Handle !mvar */
4031 if (t1->type != MONO_TYPE_MVAR)
4042 * add_pending_breakpoints:
4044 * Insert pending breakpoints into the newly JITted method METHOD.
4047 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4050 MonoSeqPointInfo *seq_points;
4056 domain = mono_domain_get ();
4058 mono_loader_lock ();
4060 for (i = 0; i < breakpoints->len; ++i) {
4061 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4062 gboolean found = FALSE;
4064 if (!bp_matches_method (bp, method))
4067 for (j = 0; j < bp->children->len; ++j) {
4068 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4075 mono_domain_lock (domain);
4076 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4077 if (!seq_points && ji->method->is_inflated)
4078 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4079 mono_domain_unlock (domain);
4081 /* Could be AOT code */
4083 g_assert (seq_points);
4085 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4089 mono_loader_unlock ();
4093 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4099 mono_error_init (error);
4101 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4103 /* Might be AOTed code */
4104 code = mono_aot_get_method (domain, method);
4106 ji = mono_jit_info_table_find (domain, code);
4111 insert_breakpoint (seq_points, domain, ji, bp, error);
4115 clear_breakpoint (MonoBreakpoint *bp);
4120 * Set a breakpoint at IL_OFFSET in METHOD.
4121 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4122 * METHOD can also be a generic method definition, in which case a breakpoint
4123 * is placed in all instances of the method.
4124 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4127 static MonoBreakpoint*
4128 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4131 GHashTableIter iter, iter2;
4134 MonoSeqPointInfo *seq_points;
4137 mono_error_init (error);
4140 // - suspend/resume the vm to prevent code patching problems
4141 // - multiple breakpoints on the same location
4142 // - dynamic methods
4145 bp = g_new0 (MonoBreakpoint, 1);
4146 bp->method = method;
4147 bp->il_offset = il_offset;
4149 bp->children = g_ptr_array_new ();
4151 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));
4153 mono_loader_lock ();
4155 g_hash_table_iter_init (&iter, domains);
4156 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4157 mono_domain_lock (domain);
4159 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4160 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4161 if (bp_matches_method (bp, m))
4162 set_bp_in_method (domain, m, seq_points, bp, error);
4165 mono_domain_unlock (domain);
4168 mono_loader_unlock ();
4170 mono_loader_lock ();
4171 g_ptr_array_add (breakpoints, bp);
4172 mono_loader_unlock ();
4174 if (error && !mono_error_ok (error)) {
4175 clear_breakpoint (bp);
4183 clear_breakpoint (MonoBreakpoint *bp)
4187 // FIXME: locking, races
4188 for (i = 0; i < bp->children->len; ++i) {
4189 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4191 remove_breakpoint (inst);
4196 mono_loader_lock ();
4197 g_ptr_array_remove (breakpoints, bp);
4198 mono_loader_unlock ();
4200 g_ptr_array_free (bp->children, TRUE);
4205 breakpoints_cleanup (void)
4209 mono_loader_lock ();
4211 while (i < event_requests->len) {
4212 EventRequest *req = g_ptr_array_index (event_requests, i);
4214 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4215 clear_breakpoint (req->info);
4216 g_ptr_array_remove_index_fast (event_requests, i);
4223 for (i = 0; i < breakpoints->len; ++i)
4224 g_free (g_ptr_array_index (breakpoints, i));
4226 g_ptr_array_free (breakpoints, TRUE);
4227 g_hash_table_destroy (bp_locs);
4232 mono_loader_unlock ();
4236 * clear_breakpoints_for_domain:
4238 * Clear breakpoint instances which reference DOMAIN.
4241 clear_breakpoints_for_domain (MonoDomain *domain)
4245 /* This could be called after shutdown */
4249 mono_loader_lock ();
4250 for (i = 0; i < breakpoints->len; ++i) {
4251 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4254 while (j < bp->children->len) {
4255 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4257 if (inst->domain == domain) {
4258 remove_breakpoint (inst);
4262 g_ptr_array_remove_index_fast (bp->children, j);
4268 mono_loader_unlock ();
4272 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4274 return bp->method && bp->method->klass->image->assembly == assembly;
4278 process_breakpoint_inner (DebuggerTlsData *tls)
4282 int i, j, suspend_policy;
4283 guint32 native_offset;
4285 BreakpointInstance *inst;
4286 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4287 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4288 EventKind kind = EVENT_KIND_BREAKPOINT;
4289 MonoContext *ctx = &tls->restore_ctx;
4290 MonoSeqPointInfo *info;
4293 // FIXME: Speed this up
4295 ip = MONO_CONTEXT_GET_IP (ctx);
4296 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4298 g_assert (ji->method);
4300 /* Compute the native offset of the breakpoint from the ip */
4301 native_offset = ip - (guint8*)ji->code_start;
4304 * Skip the instruction causing the breakpoint signal.
4306 mono_arch_skip_breakpoint (ctx, ji);
4308 if (ji->method->wrapper_type || tls->disable_breakpoints)
4311 bp_reqs = g_ptr_array_new ();
4312 ss_reqs = g_ptr_array_new ();
4313 ss_reqs_orig = g_ptr_array_new ();
4315 mono_loader_lock ();
4318 * The ip points to the instruction causing the breakpoint event, which is after
4319 * the offset recorded in the seq point map, so find the prev seq point before ip.
4321 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4323 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));
4326 for (i = 0; i < breakpoints->len; ++i) {
4327 bp = g_ptr_array_index (breakpoints, i);
4332 for (j = 0; j < bp->children->len; ++j) {
4333 inst = g_ptr_array_index (bp->children, j);
4334 if (inst->ji == ji && inst->sp == sp) {
4335 if (bp->req->event_kind == EVENT_KIND_STEP) {
4336 g_ptr_array_add (ss_reqs_orig, bp->req);
4338 g_ptr_array_add (bp_reqs, bp->req);
4343 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4344 /* Maybe a method entry/exit event */
4345 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4346 kind = EVENT_KIND_METHOD_ENTRY;
4347 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4348 kind = EVENT_KIND_METHOD_EXIT;
4351 /* Process single step requests */
4352 for (i = 0; i < ss_reqs_orig->len; ++i) {
4353 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4354 SingleStepReq *ss_req = req->info;
4355 gboolean hit = TRUE;
4357 if (ss_req->size == STEP_SIZE_LINE) {
4358 /* Have to check whenever a different source line was reached */
4359 MonoDebugMethodInfo *minfo;
4360 MonoDebugSourceLocation *loc = NULL;
4362 minfo = mono_debug_lookup_method (ji->method);
4365 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4367 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4368 /* Have to continue single stepping */
4369 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4374 ss_req->last_method = ji->method;
4375 ss_req->last_line = loc->row;
4376 mono_debug_free_source_location (loc);
4381 g_ptr_array_add (ss_reqs, req);
4383 /* Start single stepping again from the current sequence point */
4384 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4387 if (ss_reqs->len > 0)
4388 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4389 if (bp_reqs->len > 0)
4390 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4391 if (kind != EVENT_KIND_BREAKPOINT)
4392 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4394 mono_loader_unlock ();
4396 g_ptr_array_free (bp_reqs, TRUE);
4397 g_ptr_array_free (ss_reqs, TRUE);
4400 * FIXME: The first event will suspend, so the second will only be sent after the
4404 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4406 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4407 if (enter_leave_events)
4408 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4411 /* Process a breakpoint/single step event after resuming from a signal handler */
4413 process_signal_event (void (*func) (DebuggerTlsData*))
4415 DebuggerTlsData *tls;
4416 MonoContext orig_restore_ctx, ctx;
4417 static void (*restore_context) (void *);
4419 if (!restore_context)
4420 restore_context = mono_get_restore_context ();
4422 tls = mono_native_tls_get_value (debugger_tls_id);
4423 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4424 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4425 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4429 /* This is called when resuming from a signal handler, so it shouldn't return */
4430 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4431 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4432 restore_context (&ctx);
4433 g_assert_not_reached ();
4437 process_breakpoint (void)
4439 process_signal_event (process_breakpoint_inner);
4443 resume_from_signal_handler (void *sigctx, void *func)
4445 DebuggerTlsData *tls;
4448 /* Save the original context in TLS */
4449 // FIXME: This might not work on an altstack ?
4450 tls = mono_native_tls_get_value (debugger_tls_id);
4453 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4454 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4455 // clob:c could be added to op_seq_point.
4457 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4458 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4459 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4460 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4462 MONO_CONTEXT_SET_IP (&ctx, func);
4464 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4466 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4467 mono_ppc_set_func_into_sigctx (sigctx, func);
4472 mono_debugger_agent_breakpoint_hit (void *sigctx)
4475 * We are called from a signal handler, and running code there causes all kinds of
4476 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4477 * So set up the signal context to return to the real breakpoint handler function.
4479 resume_from_signal_handler (sigctx, process_breakpoint);
4483 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4485 if (frame->managed) {
4486 *(MonoContext*)data = *ctx;
4495 * Called by System.Diagnostics.Debugger:Break ().
4498 mono_debugger_agent_user_break (void)
4500 if (agent_config.enabled) {
4505 /* Obtain a context */
4506 MONO_CONTEXT_SET_IP (&ctx, NULL);
4507 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4508 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4510 mono_loader_lock ();
4511 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4512 mono_loader_unlock ();
4514 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4521 ss_depth_to_string (StepDepth depth)
4524 case STEP_DEPTH_OVER:
4526 case STEP_DEPTH_OUT:
4528 case STEP_DEPTH_INTO:
4531 g_assert_not_reached ();
4537 process_single_step_inner (DebuggerTlsData *tls)
4542 int il_offset, suspend_policy;
4545 MonoContext *ctx = &tls->restore_ctx;
4547 MonoSeqPointInfo *info;
4549 ip = MONO_CONTEXT_GET_IP (ctx);
4551 /* Skip the instruction causing the single step */
4552 mono_arch_skip_single_step (ctx);
4554 if (suspend_count > 0) {
4555 process_suspend (tls, ctx);
4560 // FIXME: A suspend race
4563 if (mono_thread_internal_current () != ss_req->thread)
4566 if (log_level > 0) {
4567 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4569 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));
4572 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4574 g_assert (ji->method);
4576 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4581 * Stopping in memset makes half-initialized vtypes visible.
4582 * Stopping in memcpy makes half-copied vtypes visible.
4584 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4588 * The ip points to the instruction causing the single step event, which is before
4589 * the offset recorded in the seq point map, so find the next seq point after ip.
4591 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4594 il_offset = sp->il_offset;
4596 // FIXME: No tests fail if this is disabled
4598 if (ss_req->size == STEP_SIZE_LINE) {
4602 /* Step until a different source line is reached */
4603 MonoDebugMethodInfo *minfo;
4605 minfo = mono_debug_lookup_method (ji->method);
4608 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4610 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4611 mono_debug_free_source_location (loc);
4616 * Step until we reach a location with line number info,
4617 * otherwise the client can't show a location.
4618 * This can happen for example with statics initialized inline
4619 * outside of a cctor.
4624 ss_req->last_method = ji->method;
4625 ss_req->last_line = loc->row;
4626 mono_debug_free_source_location (loc);
4632 /* Start single stepping again from the current sequence point */
4633 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4635 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4636 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4637 !strcmp (ji->method->name, ".cctor"))
4640 // FIXME: Has to lock earlier
4642 reqs = g_ptr_array_new ();
4644 mono_loader_lock ();
4646 g_ptr_array_add (reqs, ss_req->req);
4648 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4650 g_ptr_array_free (reqs, TRUE);
4652 mono_loader_unlock ();
4654 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4658 process_single_step (void)
4660 process_signal_event (process_single_step_inner);
4664 * mono_debugger_agent_single_step_event:
4666 * Called from a signal handler to handle a single step event.
4669 mono_debugger_agent_single_step_event (void *sigctx)
4671 /* Resume to process_single_step through the signal context */
4673 // FIXME: Since step out/over is implemented using step in, the step in case should
4674 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4677 if (GetCurrentThreadId () == debugger_thread_id) {
4679 * This could happen despite our best effors when the runtime calls
4680 * assembly/type resolve hooks.
4681 * FIXME: Breakpoints too.
4685 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4686 mono_arch_skip_single_step (&ctx);
4687 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4691 resume_from_signal_handler (sigctx, process_single_step);
4695 debugger_agent_single_step_from_context (MonoContext *ctx)
4697 DebuggerTlsData *tls;
4698 MonoContext orig_restore_ctx;
4700 tls = mono_native_tls_get_value (debugger_tls_id);
4703 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4704 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4705 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4707 process_single_step_inner (tls);
4709 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4710 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4714 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4716 DebuggerTlsData *tls;
4717 MonoContext orig_restore_ctx;
4719 tls = mono_native_tls_get_value (debugger_tls_id);
4721 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4722 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4724 process_breakpoint_inner (tls);
4726 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4727 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4731 * start_single_stepping:
4733 * Turn on single stepping. Can be called multiple times, for example,
4734 * by a single step event request + a suspend.
4737 start_single_stepping (void)
4739 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4740 int val = InterlockedIncrement (&ss_count);
4743 mono_arch_start_single_stepping ();
4745 if (ss_req != NULL && ss_invoke_addr == NULL) {
4746 DebuggerTlsData *tls;
4748 mono_loader_lock ();
4750 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4751 ss_invoke_addr = tls->invoke_addr;
4753 mono_loader_unlock ();
4756 g_assert_not_reached ();
4761 stop_single_stepping (void)
4763 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4764 int val = InterlockedDecrement (&ss_count);
4767 mono_arch_stop_single_stepping ();
4769 g_assert_not_reached ();
4776 * Stop the single stepping operation given by SS_REQ.
4779 ss_stop (SingleStepReq *ss_req)
4784 for (l = ss_req->bps; l; l = l->next) {
4785 clear_breakpoint (l->data);
4787 g_slist_free (ss_req->bps);
4791 if (ss_req->global) {
4792 stop_single_stepping ();
4793 ss_req->global = FALSE;
4800 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4801 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4802 * belong to the same thread as CTX.
4805 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4807 int i, j, frame_index;
4810 gboolean enable_global = FALSE;
4812 /* Stop the previous operation */
4816 * Implement single stepping using breakpoints if possible.
4818 if (step_to_catch) {
4819 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4820 ss_req->bps = g_slist_append (ss_req->bps, bp);
4824 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4825 /* Need parent frames */
4826 if (!tls->context.valid)
4827 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4828 compute_frame_info (tls->thread, tls);
4832 * Find the first sequence point in the current or in a previous frame which
4833 * is not the last in its method.
4835 if (ss_req->depth == STEP_DEPTH_OUT) {
4836 /* Ignore seq points in current method */
4837 while (frame_index < tls->frame_count) {
4838 StackFrame *frame = tls->frames [frame_index];
4840 method = frame->method;
4841 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4843 if (sp && sp->next_len != 0)
4846 // There could be method calls before the next seq point in the caller when using nested calls
4847 //enable_global = TRUE;
4849 while (sp && sp->next_len == 0) {
4851 if (frame_index < tls->frame_count) {
4852 StackFrame *frame = tls->frames [frame_index];
4854 method = frame->method;
4855 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4861 if (sp && sp->next_len > 0) {
4862 for (i = 0; i < sp->next_len; ++i) {
4863 next_sp = &info->seq_points [sp->next [i]];
4865 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4866 ss_req->bps = g_slist_append (ss_req->bps, bp);
4870 if (ss_req->depth == STEP_DEPTH_OVER) {
4871 /* Need to stop in catch clauses as well */
4872 for (i = 0; i < tls->frame_count; ++i) {
4873 StackFrame *frame = tls->frames [i];
4876 MonoJitInfo *jinfo = frame->ji;
4877 for (j = 0; j < jinfo->num_clauses; ++j) {
4878 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4880 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4882 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4883 ss_req->bps = g_slist_append (ss_req->bps, bp);
4891 if (ss_req->depth == STEP_DEPTH_INTO) {
4892 /* Enable global stepping so we stop at method entry too */
4893 enable_global = TRUE;
4897 * The ctx/frame info computed above will become invalid when we continue.
4899 tls->context.valid = FALSE;
4900 tls->async_state.valid = FALSE;
4901 invalidate_frames (tls);
4904 if (enable_global) {
4905 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4906 ss_req->global = TRUE;
4907 start_single_stepping ();
4908 } else if (!ss_req->bps) {
4909 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4910 ss_req->global = TRUE;
4911 start_single_stepping ();
4913 ss_req->global = FALSE;
4918 * Start single stepping of thread THREAD
4921 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4923 DebuggerTlsData *tls;
4924 MonoSeqPointInfo *info = NULL;
4925 SeqPoint *sp = NULL;
4926 MonoMethod *method = NULL;
4927 MonoDebugMethodInfo *minfo;
4928 gboolean step_to_catch = FALSE;
4930 if (suspend_count == 0)
4931 return ERR_NOT_SUSPENDED;
4933 wait_for_suspend ();
4935 // FIXME: Multiple requests
4937 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4938 return ERR_NOT_IMPLEMENTED;
4941 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4943 ss_req = g_new0 (SingleStepReq, 1);
4945 ss_req->thread = thread;
4946 ss_req->size = size;
4947 ss_req->depth = depth;
4950 mono_loader_lock ();
4951 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4952 mono_loader_unlock ();
4954 g_assert (tls->context.valid);
4955 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4957 if (tls->has_catch_ctx) {
4959 StackFrameInfo frame;
4960 MonoContext new_ctx;
4961 MonoLMF *lmf = NULL;
4964 * We are stopped at a throw site. Stepping should go to the catch site.
4967 /* Find the the jit info for the catch context */
4968 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4970 g_assert (frame.type == FRAME_TYPE_MANAGED);
4973 * Find the seq point corresponding to the landing site ip, which is the first seq
4976 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4979 method = frame.method;
4981 step_to_catch = TRUE;
4982 /* This make sure the seq point is not skipped by process_single_step () */
4983 ss_req->last_sp = NULL;
4986 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4989 /* Compute the initial line info */
4990 compute_frame_info (thread, tls);
4992 if (tls->frame_count) {
4993 frame = tls->frames [0];
4995 ss_req->last_method = frame->method;
4996 ss_req->last_line = -1;
4998 minfo = mono_debug_lookup_method (frame->method);
4999 if (minfo && frame->il_offset != -1) {
5000 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5003 ss_req->last_line = loc->row;
5010 if (!step_to_catch) {
5013 compute_frame_info (thread, tls);
5015 if (tls->frame_count) {
5016 frame = tls->frames [0];
5018 if (!method && frame->il_offset != -1) {
5019 /* FIXME: Sort the table and use a binary search */
5020 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5022 method = frame->method;
5027 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5033 ss_destroy (SingleStepReq *req)
5036 g_assert (ss_req == req);
5045 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5048 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5054 if (!agent_config.enabled)
5057 mono_loader_lock ();
5058 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5059 mono_loader_unlock ();
5062 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5063 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5065 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5067 g_free (ei.category);
5068 g_free (ei.message);
5072 mono_debugger_agent_debug_log_is_enabled (void)
5074 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5075 return agent_config.enabled;
5079 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5080 MonoContext *catch_ctx)
5086 DebuggerTlsData *tls = NULL;
5088 if (thread_to_tls != NULL) {
5089 MonoInternalThread *thread = mono_thread_internal_current ();
5091 mono_loader_lock ();
5092 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5093 mono_loader_unlock ();
5095 if (tls && tls->abort_requested)
5097 if (tls && tls->disable_breakpoints)
5101 memset (&ei, 0, sizeof (EventInfo));
5103 /* Just-In-Time debugging */
5105 if (agent_config.onuncaught && !inited) {
5106 finish_agent_init (FALSE);
5109 * Send an unsolicited EXCEPTION event with a dummy request id.
5111 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5112 ei.exc = (MonoObject*)exc;
5113 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5116 } else if (agent_config.onthrow && !inited) {
5118 gboolean found = FALSE;
5120 for (l = agent_config.onthrow; l; l = l->next) {
5121 char *ex_type = l->data;
5122 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5124 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5131 finish_agent_init (FALSE);
5134 * Send an unsolicited EXCEPTION event with a dummy request id.
5136 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5137 ei.exc = (MonoObject*)exc;
5138 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5146 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5148 ei.exc = (MonoObject*)exc;
5149 ei.caught = catch_ctx != NULL;
5151 mono_loader_lock ();
5152 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5153 mono_loader_unlock ();
5155 if (tls && catch_ctx) {
5156 tls->catch_ctx = *catch_ctx;
5157 tls->has_catch_ctx = TRUE;
5160 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5163 tls->has_catch_ctx = FALSE;
5167 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5169 DebuggerTlsData *tls;
5174 tls = mono_native_tls_get_value (debugger_tls_id);
5179 * We're about to invoke an exception filter during the first pass of exception handling.
5181 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5182 * 'orig_ctx' is the context where the exception has been thrown.
5185 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5187 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5188 * the call site (line 37) and then continue to Main(), but it would never
5189 * include the throw site (line 32).
5191 * Since exception filters are invoked during the first pass of exception handling,
5192 * the stack frames of the throw site are still intact, so we should include them
5195 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5197 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5198 * but report the location of the 'throw' to the user.
5202 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5206 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5208 DebuggerTlsData *tls;
5213 tls = mono_native_tls_get_value (debugger_tls_id);
5217 tls->filter_state.valid = FALSE;
5221 * buffer_add_value_full:
5223 * Add the encoding of the value at ADDR described by T to the buffer.
5224 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5228 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5234 g_assert (*(void**)addr);
5235 addr = *(void**)addr;
5240 case MONO_TYPE_BOOLEAN:
5243 case MONO_TYPE_CHAR:
5263 case MONO_TYPE_VOID:
5264 buffer_add_byte (buf, t->type);
5266 case MONO_TYPE_BOOLEAN:
5269 buffer_add_byte (buf, t->type);
5270 buffer_add_int (buf, *(gint8*)addr);
5272 case MONO_TYPE_CHAR:
5275 buffer_add_byte (buf, t->type);
5276 buffer_add_int (buf, *(gint16*)addr);
5281 buffer_add_byte (buf, t->type);
5282 buffer_add_int (buf, *(gint32*)addr);
5287 buffer_add_byte (buf, t->type);
5288 buffer_add_long (buf, *(gint64*)addr);
5292 /* Treat it as a vtype */
5294 case MONO_TYPE_PTR: {
5295 gssize val = *(gssize*)addr;
5297 buffer_add_byte (buf, t->type);
5298 buffer_add_long (buf, val);
5302 case MONO_TYPE_STRING:
5303 case MONO_TYPE_SZARRAY:
5304 case MONO_TYPE_OBJECT:
5305 case MONO_TYPE_CLASS:
5306 case MONO_TYPE_ARRAY:
5307 obj = *(MonoObject**)addr;
5310 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5312 if (obj->vtable->klass->valuetype) {
5313 t = &obj->vtable->klass->byval_arg;
5314 addr = mono_object_unbox (obj);
5316 } else if (obj->vtable->klass->rank) {
5317 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5318 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5319 buffer_add_byte (buf, MONO_TYPE_CLASS);
5321 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5323 buffer_add_objid (buf, obj);
5327 case MONO_TYPE_VALUETYPE: {
5331 MonoClass *klass = mono_class_from_mono_type (t);
5333 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5334 buffer_add_byte (buf, klass->enumtype);
5335 buffer_add_typeid (buf, domain, klass);
5339 while ((f = mono_class_get_fields (klass, &iter))) {
5340 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5342 if (mono_field_is_deleted (f))
5346 buffer_add_int (buf, nfields);
5349 while ((f = mono_class_get_fields (klass, &iter))) {
5350 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5352 if (mono_field_is_deleted (f))
5354 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5358 case MONO_TYPE_GENERICINST:
5359 if (mono_type_generic_inst_is_valuetype (t)) {
5371 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5373 buffer_add_value_full (buf, t, addr, domain, FALSE);
5377 obj_is_of_type (MonoObject *obj, MonoType *t)
5379 MonoClass *klass = obj->vtable->klass;
5380 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5381 if (klass == mono_defaults.transparent_proxy_class) {
5382 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5383 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5393 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5396 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5400 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5401 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5402 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5403 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5404 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5405 char *name = mono_type_full_name (t);
5406 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5408 return ERR_INVALID_ARGUMENT;
5412 case MONO_TYPE_BOOLEAN:
5413 *(guint8*)addr = decode_int (buf, &buf, limit);
5415 case MONO_TYPE_CHAR:
5416 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5419 *(gint8*)addr = decode_int (buf, &buf, limit);
5422 *(guint8*)addr = decode_int (buf, &buf, limit);
5425 *(gint16*)addr = decode_int (buf, &buf, limit);
5428 *(guint16*)addr = decode_int (buf, &buf, limit);
5431 *(gint32*)addr = decode_int (buf, &buf, limit);
5434 *(guint32*)addr = decode_int (buf, &buf, limit);
5437 *(gint64*)addr = decode_long (buf, &buf, limit);
5440 *(guint64*)addr = decode_long (buf, &buf, limit);
5443 *(guint32*)addr = decode_int (buf, &buf, limit);
5446 *(guint64*)addr = decode_long (buf, &buf, limit);
5449 /* We send these as I8, so we get them back as such */
5450 g_assert (type == MONO_TYPE_I8);
5451 *(gssize*)addr = decode_long (buf, &buf, limit);
5453 case MONO_TYPE_GENERICINST:
5454 if (MONO_TYPE_ISSTRUCT (t)) {
5455 /* The client sends these as a valuetype */
5463 /* We send these as vtypes, so we get them back as such */
5464 g_assert (type == MONO_TYPE_VALUETYPE);
5467 case MONO_TYPE_VALUETYPE: {
5468 gboolean is_enum = decode_byte (buf, &buf, limit);
5472 gpointer iter = NULL;
5475 /* Enums are sent as a normal vtype */
5477 return ERR_NOT_IMPLEMENTED;
5478 klass = decode_typeid (buf, &buf, limit, &d, &err);
5482 if (klass != mono_class_from_mono_type (t))
5483 return ERR_INVALID_ARGUMENT;
5485 nfields = decode_int (buf, &buf, limit);
5486 while ((f = mono_class_get_fields (klass, &iter))) {
5487 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5489 if (mono_field_is_deleted (f))
5491 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5496 g_assert (nfields == 0);
5501 if (MONO_TYPE_IS_REFERENCE (t)) {
5502 if (type == MONO_TYPE_OBJECT) {
5503 int objid = decode_objid (buf, &buf, limit);
5507 err = get_object (objid, (MonoObject**)&obj);
5512 if (!obj_is_of_type (obj, t)) {
5513 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5514 return ERR_INVALID_ARGUMENT;
5517 if (obj && obj->vtable->domain != domain)
5518 return ERR_INVALID_ARGUMENT;
5520 mono_gc_wbarrier_generic_store (addr, obj);
5521 } else if (type == VALUE_TYPE_ID_NULL) {
5522 *(MonoObject**)addr = NULL;
5524 return ERR_INVALID_ARGUMENT;
5538 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5541 int type = decode_byte (buf, &buf, limit);
5543 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5544 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5545 guint8 *nullable_buf;
5548 * First try decoding it as a Nullable`1
5550 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5555 * Then try decoding as a primitive value or null.
5557 if (targ->type == type) {
5558 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5559 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5561 g_free (nullable_buf);
5564 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5565 g_free (nullable_buf);
5568 } else if (type == VALUE_TYPE_ID_NULL) {
5569 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5575 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5579 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5586 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5587 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5590 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5591 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5593 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5595 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5596 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5597 addr += (gint32)var->offset;
5599 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5601 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5603 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5607 g_assert_not_reached ();
5612 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5618 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5619 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5621 if (MONO_TYPE_IS_REFERENCE (t))
5622 size = sizeof (gpointer);
5624 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5627 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5628 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5630 gboolean is_signed = FALSE;
5632 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5637 v = is_signed ? *(gint8*)val : *(guint8*)val;
5640 v = is_signed ? *(gint16*)val : *(guint16*)val;
5643 v = is_signed ? *(gint32*)val : *(guint32*)val;
5646 v = is_signed ? *(gint64*)val : *(guint64*)val;
5649 g_assert_not_reached ();
5655 /* Set value on the stack or in the return ctx */
5656 if (reg_locations [reg]) {
5657 /* Saved on the stack */
5658 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5659 *(reg_locations [reg]) = v;
5662 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5663 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5666 // FIXME: Move these to mono-context.h/c.
5667 mono_arch_context_set_int_reg (ctx, reg, v);
5669 // FIXME: Can't set registers, so we disable linears
5674 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5675 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5676 addr += (gint32)var->offset;
5678 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5681 addr = *(guint8**)addr;
5687 // FIXME: Write barriers
5688 mono_gc_memmove (addr, val, size);
5690 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5694 g_assert_not_reached ();
5699 clear_event_request (int req_id, int etype)
5703 mono_loader_lock ();
5704 for (i = 0; i < event_requests->len; ++i) {
5705 EventRequest *req = g_ptr_array_index (event_requests, i);
5707 if (req->id == req_id && req->event_kind == etype) {
5708 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5709 clear_breakpoint (req->info);
5710 if (req->event_kind == EVENT_KIND_STEP)
5711 ss_destroy (req->info);
5712 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5713 clear_breakpoint (req->info);
5714 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5715 clear_breakpoint (req->info);
5716 g_ptr_array_remove_index_fast (event_requests, i);
5721 mono_loader_unlock ();
5725 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5727 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5728 return breakpoint_matches_assembly (req->info, assembly);
5732 for (i = 0; i < req->nmodifiers; ++i) {
5733 Modifier *m = &req->modifiers [i];
5735 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5737 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5738 for (j = 0; m->data.assemblies [j]; ++j)
5739 if (m->data.assemblies [j] == assembly)
5749 * clear_event_requests_for_assembly:
5751 * Clear all events requests which reference ASSEMBLY.
5754 clear_event_requests_for_assembly (MonoAssembly *assembly)
5759 mono_loader_lock ();
5763 for (i = 0; i < event_requests->len; ++i) {
5764 EventRequest *req = g_ptr_array_index (event_requests, i);
5766 if (event_req_matches_assembly (req, assembly)) {
5767 clear_event_request (req->id, req->event_kind);
5773 mono_loader_unlock ();
5777 * type_comes_from_assembly:
5779 * GHRFunc that returns TRUE if klass comes from assembly
5782 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5784 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5788 * clear_types_for_assembly:
5790 * Clears types from loaded_classes for a given assembly
5793 clear_types_for_assembly (MonoAssembly *assembly)
5795 MonoDomain *domain = mono_domain_get ();
5796 AgentDomainInfo *info = NULL;
5798 mono_loader_lock ();
5799 info = get_agent_domain_info (domain);
5800 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5801 mono_loader_unlock ();
5805 add_thread (gpointer key, gpointer value, gpointer user_data)
5807 MonoInternalThread *thread = value;
5808 Buffer *buf = user_data;
5810 buffer_add_objid (buf, (MonoObject*)thread);
5814 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5816 guint8 *p = invoke->p;
5817 guint8 *end = invoke->endp;
5820 MonoMethodSignature *sig;
5823 MonoObject *this, *res, *exc;
5826 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5829 MonoStopwatch watch;
5831 if (invoke->method) {
5833 * Invoke this method directly, currently only Environment.Exit () is supported.
5836 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>"));
5837 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5838 g_assert_not_reached ();
5841 m = decode_methodid (p, &p, end, &domain, &err);
5844 sig = mono_method_signature (m);
5846 if (m->klass->valuetype)
5847 this_buf = g_alloca (mono_class_instance_size (m->klass));
5849 this_buf = g_alloca (sizeof (MonoObject*));
5850 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5851 /* Should be null */
5852 int type = decode_byte (p, &p, end);
5853 if (type != VALUE_TYPE_ID_NULL)
5854 return ERR_INVALID_ARGUMENT;
5855 memset (this_buf, 0, mono_class_instance_size (m->klass));
5857 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5862 if (!m->klass->valuetype)
5863 this = *(MonoObject**)this_buf;
5867 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>"));
5869 if (this && this->vtable->domain != domain)
5872 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5873 if (!strcmp (m->name, ".ctor")) {
5874 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5875 return ERR_INVALID_ARGUMENT;
5877 this = mono_object_new (domain, m->klass);
5879 return ERR_INVALID_ARGUMENT;
5883 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
5884 return ERR_INVALID_ARGUMENT;
5886 nargs = decode_int (p, &p, end);
5887 if (nargs != sig->param_count)
5888 return ERR_INVALID_ARGUMENT;
5889 /* Use alloca to get gc tracking */
5890 arg_buf = g_alloca (nargs * sizeof (gpointer));
5891 memset (arg_buf, 0, nargs * sizeof (gpointer));
5892 args = g_alloca (nargs * sizeof (gpointer));
5893 for (i = 0; i < nargs; ++i) {
5894 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5895 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5899 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5902 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5903 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5906 args [i] = arg_buf [i];
5913 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5914 tls->disable_breakpoints = TRUE;
5916 tls->disable_breakpoints = FALSE;
5919 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5921 /* FIXME: Move this to arch specific code */
5922 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5923 if (invoke->has_ctx) {
5926 lmf_addr = mono_get_lmf_addr ();
5929 memset (&ext, 0, sizeof (ext));
5931 ext.lmf.previous_lmf = *(lmf_addr);
5932 /* Mark that this is a MonoLMFExt */
5933 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5934 ext.lmf.rsp = (gssize)&ext;
5935 #elif defined(TARGET_X86)
5936 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5937 /* Mark that this is a MonoLMFExt */
5938 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5939 ext.lmf.ebp = (gssize)&ext;
5940 #elif defined(TARGET_ARM)
5941 ext.lmf.previous_lmf = *(lmf_addr);
5942 /* Mark that this is a MonoLMFExt */
5943 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5944 ext.lmf.sp = (gssize)&ext;
5945 #elif defined(TARGET_POWERPC)
5946 ext.lmf.previous_lmf = *(lmf_addr);
5947 /* Mark that this is a MonoLMFExt */
5948 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5949 ext.lmf.ebp = (gssize)&ext;
5950 #elif defined(TARGET_S390X)
5951 ext.lmf.previous_lmf = *(lmf_addr);
5952 /* Mark that this is a MonoLMFExt */
5953 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5954 ext.lmf.ebp = (gssize)&ext;
5955 #elif defined(TARGET_MIPS)
5956 ext.lmf.previous_lmf = *(lmf_addr);
5957 /* Mark that this is a MonoLMFExt */
5958 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5959 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5961 g_assert_not_reached ();
5964 ext.debugger_invoke = TRUE;
5965 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5967 mono_set_lmf ((MonoLMF*)&ext);
5971 mono_stopwatch_start (&watch);
5972 if (m->klass->valuetype)
5973 res = mono_runtime_invoke (m, this_buf, args, &exc);
5975 res = mono_runtime_invoke (m, this, args, &exc);
5976 mono_stopwatch_stop (&watch);
5977 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)));
5979 buffer_add_byte (buf, 0);
5980 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5982 buffer_add_byte (buf, 1);
5983 if (sig->ret->type == MONO_TYPE_VOID) {
5984 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5985 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5988 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5989 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5990 buffer_add_value (buf, sig->ret, &res, domain);
5991 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
5992 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5993 MonoClass *k = mono_class_from_mono_type (sig->ret);
5994 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
5996 g_assert (nullable_buf);
5997 mono_nullable_init (nullable_buf, res, k);
5998 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6001 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6008 tls->disable_breakpoints = FALSE;
6010 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6011 if (invoke->has_ctx)
6012 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6015 // FIXME: byref arguments
6023 * Invoke the method given by tls->pending_invoke in the current thread.
6026 invoke_method (void)
6028 DebuggerTlsData *tls;
6033 static void (*restore_context) (void *);
6034 MonoContext restore_ctx;
6036 if (!restore_context)
6037 restore_context = mono_get_restore_context ();
6039 tls = mono_native_tls_get_value (debugger_tls_id);
6043 * Store the `InvokeData *' in `tls->invoke' until we're done with
6044 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6047 mono_loader_lock ();
6049 invoke = tls->pending_invoke;
6051 tls->pending_invoke = NULL;
6053 invoke->last_invoke = tls->invoke;
6054 tls->invoke = invoke;
6056 mono_loader_unlock ();
6058 tls->frames_up_to_date = FALSE;
6062 buffer_init (&buf, 128);
6064 err = do_invoke_method (tls, &buf, invoke);
6066 /* Start suspending before sending the reply */
6067 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6068 for (i = 0; i < invoke->suspend_count; ++i)
6072 send_reply_packet (id, err, &buf);
6076 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6078 if (invoke->has_ctx)
6079 save_thread_context (&restore_ctx);
6081 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6082 g_assert (tls->resume_count);
6083 tls->resume_count -= invoke->suspend_count;
6086 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6089 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6091 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6092 * after the mono_runtime_invoke() already returned, but it doesn't matter
6093 * because we reset the abort here.
6096 mono_loader_lock ();
6098 if (tls->abort_requested)
6099 mono_thread_internal_reset_abort (tls->thread);
6101 tls->invoke = tls->invoke->last_invoke;
6102 tls->abort_requested = FALSE;
6104 mono_loader_unlock ();
6113 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6115 MonoThread *thread = value;
6116 DebuggerTlsData *tls;
6119 mono_loader_lock ();
6120 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6122 res = tls->really_suspended;
6123 mono_loader_unlock ();
6129 get_source_files_for_type (MonoClass *klass)
6131 gpointer iter = NULL;
6133 MonoDebugSourceInfo *sinfo;
6137 files = g_ptr_array_new ();
6139 while ((method = mono_class_get_methods (klass, &iter))) {
6140 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6141 GPtrArray *source_file_list;
6144 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6145 for (j = 0; j < source_file_list->len; ++j) {
6146 sinfo = g_ptr_array_index (source_file_list, j);
6147 for (i = 0; i < files->len; ++i)
6148 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6150 if (i == files->len)
6151 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6153 g_ptr_array_free (source_file_list, TRUE);
6161 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6164 case CMD_VM_VERSION: {
6165 char *build_info, *version;
6167 build_info = mono_get_runtime_build_info ();
6168 version = g_strdup_printf ("mono %s", build_info);
6170 buffer_add_string (buf, version); /* vm version */
6171 buffer_add_int (buf, MAJOR_VERSION);
6172 buffer_add_int (buf, MINOR_VERSION);
6173 g_free (build_info);
6177 case CMD_VM_SET_PROTOCOL_VERSION: {
6178 major_version = decode_int (p, &p, end);
6179 minor_version = decode_int (p, &p, end);
6180 protocol_version_set = TRUE;
6181 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6184 case CMD_VM_ALL_THREADS: {
6186 mono_loader_lock ();
6187 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6188 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6189 mono_loader_unlock ();
6192 case CMD_VM_SUSPEND:
6194 wait_for_suspend ();
6197 if (suspend_count == 0)
6198 return ERR_NOT_SUSPENDED;
6201 case CMD_VM_DISPOSE:
6202 /* Clear all event requests */
6203 mono_loader_lock ();
6204 while (event_requests->len > 0) {
6205 EventRequest *req = g_ptr_array_index (event_requests, 0);
6207 clear_event_request (req->id, req->event_kind);
6209 mono_loader_unlock ();
6211 while (suspend_count > 0)
6213 disconnected = TRUE;
6214 vm_start_event_sent = FALSE;
6217 MonoInternalThread *thread;
6218 DebuggerTlsData *tls;
6219 MonoClass *env_class;
6220 MonoMethod *exit_method = NULL;
6224 exit_code = decode_int (p, &p, end);
6226 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6228 /* Have to send a reply before exiting */
6229 send_reply_packet (id, 0, buf);
6231 /* Clear all event requests */
6232 mono_loader_lock ();
6233 while (event_requests->len > 0) {
6234 EventRequest *req = g_ptr_array_index (event_requests, 0);
6236 clear_event_request (req->id, req->event_kind);
6238 mono_loader_unlock ();
6241 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6242 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6243 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6244 * better than doing the shutdown ourselves, since it avoids various races.
6248 wait_for_suspend ();
6250 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6252 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6254 mono_loader_lock ();
6255 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6256 mono_loader_unlock ();
6258 if (thread && exit_method) {
6259 mono_loader_lock ();
6260 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6261 mono_loader_unlock ();
6263 args = g_new0 (gpointer, 1);
6264 args [0] = g_malloc (sizeof (int));
6265 *(int*)(args [0]) = exit_code;
6267 tls->pending_invoke = g_new0 (InvokeData, 1);
6268 tls->pending_invoke->method = exit_method;
6269 tls->pending_invoke->args = args;
6271 while (suspend_count > 0)
6275 * No thread found, do it ourselves.
6276 * FIXME: This can race with normal shutdown etc.
6278 while (suspend_count > 0)
6281 mono_runtime_set_shutting_down ();
6283 mono_threads_set_shutting_down ();
6285 /* Suspend all managed threads since the runtime is going away */
6286 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6287 mono_thread_suspend_all_other_threads ();
6288 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6289 mono_runtime_quit ();
6290 transport_close2 ();
6291 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6297 case CMD_VM_INVOKE_METHOD: {
6298 int objid = decode_objid (p, &p, end);
6300 DebuggerTlsData *tls;
6301 int i, count, err, flags;
6303 err = get_object (objid, (MonoObject**)&thread);
6307 flags = decode_int (p, &p, end);
6309 // Wait for suspending if it already started
6311 wait_for_suspend ();
6312 if (!is_suspended ())
6313 return ERR_NOT_SUSPENDED;
6315 mono_loader_lock ();
6316 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6317 mono_loader_unlock ();
6320 if (!tls->really_suspended)
6321 /* The thread is still running native code, can't do invokes */
6322 return ERR_NOT_SUSPENDED;
6325 * Store the invoke data into tls, the thread will execute it after it is
6328 if (tls->pending_invoke)
6329 return ERR_NOT_SUSPENDED;
6330 tls->pending_invoke = g_new0 (InvokeData, 1);
6331 tls->pending_invoke->id = id;
6332 tls->pending_invoke->flags = flags;
6333 tls->pending_invoke->p = g_malloc (end - p);
6334 memcpy (tls->pending_invoke->p, p, end - p);
6335 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6336 tls->pending_invoke->suspend_count = suspend_count;
6338 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6339 resume_thread (THREAD_TO_INTERNAL (thread));
6342 count = suspend_count;
6343 for (i = 0; i < count; ++i)
6348 case CMD_VM_ABORT_INVOKE: {
6349 int objid = decode_objid (p, &p, end);
6351 DebuggerTlsData *tls;
6354 err = get_object (objid, (MonoObject**)&thread);
6358 invoke_id = decode_int (p, &p, end);
6360 mono_loader_lock ();
6361 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6364 if (tls->abort_requested) {
6365 mono_loader_unlock ();
6370 * Check whether we're still inside the mono_runtime_invoke() and that it's
6371 * actually the correct invocation.
6373 * Careful, we do not stop the thread that's doing the invocation, so we can't
6374 * inspect its stack. However, invoke_method() also acquires the loader lock
6375 * when it's done, so we're safe here.
6379 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6380 mono_loader_unlock ();
6381 return ERR_NO_INVOCATION;
6384 tls->abort_requested = TRUE;
6386 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6387 mono_loader_unlock ();
6391 case CMD_VM_SET_KEEPALIVE: {
6392 int timeout = decode_int (p, &p, end);
6393 agent_config.keepalive = timeout;
6395 #ifndef DISABLE_SOCKET_TRANSPORT
6402 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6403 GHashTableIter iter, kiter;
6408 char *fname, *basename;
6409 gboolean ignore_case;
6410 GSList *class_list, *l;
6411 GPtrArray *res_classes, *res_domains;
6413 fname = decode_string (p, &p, end);
6414 ignore_case = decode_byte (p, &p, end);
6416 basename = g_path_get_basename (fname);
6418 res_classes = g_ptr_array_new ();
6419 res_domains = g_ptr_array_new ();
6421 mono_loader_lock ();
6422 g_hash_table_iter_init (&iter, domains);
6423 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6424 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6426 /* Update 'source_file_to_class' cache */
6427 g_hash_table_iter_init (&kiter, info->loaded_classes);
6428 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6429 if (!g_hash_table_lookup (info->source_files, klass)) {
6430 files = get_source_files_for_type (klass);
6431 g_hash_table_insert (info->source_files, klass, files);
6433 for (i = 0; i < files->len; ++i) {
6434 char *s = g_ptr_array_index (files, i);
6435 char *s2 = g_path_get_basename (s);
6438 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6440 class_list = g_slist_prepend (class_list, klass);
6441 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6443 class_list = g_slist_prepend (class_list, klass);
6444 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6447 /* The _ignorecase hash contains the lowercase path */
6448 s3 = strdup_tolower (s2);
6449 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6451 class_list = g_slist_prepend (class_list, klass);
6452 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6454 class_list = g_slist_prepend (class_list, klass);
6455 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6467 s = strdup_tolower (basename);
6468 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6471 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6474 for (l = class_list; l; l = l->next) {
6477 g_ptr_array_add (res_classes, klass);
6478 g_ptr_array_add (res_domains, domain);
6481 mono_loader_unlock ();
6486 buffer_add_int (buf, res_classes->len);
6487 for (i = 0; i < res_classes->len; ++i)
6488 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6489 g_ptr_array_free (res_classes, TRUE);
6490 g_ptr_array_free (res_domains, TRUE);
6493 case CMD_VM_GET_TYPES: {
6494 GHashTableIter iter;
6498 gboolean ignore_case;
6499 GPtrArray *res_classes, *res_domains;
6500 MonoTypeNameParse info;
6502 name = decode_string (p, &p, end);
6503 ignore_case = decode_byte (p, &p, end);
6505 if (!mono_reflection_parse_type (name, &info)) {
6507 mono_reflection_free_type_info (&info);
6508 return ERR_INVALID_ARGUMENT;
6511 res_classes = g_ptr_array_new ();
6512 res_domains = g_ptr_array_new ();
6514 mono_loader_lock ();
6515 g_hash_table_iter_init (&iter, domains);
6516 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6518 gboolean type_resolve;
6522 mono_domain_assemblies_lock (domain);
6523 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6527 type_resolve = TRUE;
6528 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6530 g_ptr_array_add (res_classes, mono_type_get_class (t));
6531 g_ptr_array_add (res_domains, domain);
6535 mono_domain_assemblies_unlock (domain);
6537 mono_loader_unlock ();
6540 mono_reflection_free_type_info (&info);
6542 buffer_add_int (buf, res_classes->len);
6543 for (i = 0; i < res_classes->len; ++i)
6544 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6545 g_ptr_array_free (res_classes, TRUE);
6546 g_ptr_array_free (res_domains, TRUE);
6551 return ERR_NOT_IMPLEMENTED;
6558 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6564 case CMD_EVENT_REQUEST_SET: {
6566 int i, event_kind, suspend_policy, nmodifiers, mod;
6569 MonoThread *step_thread;
6570 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6574 event_kind = decode_byte (p, &p, end);
6575 suspend_policy = decode_byte (p, &p, end);
6576 nmodifiers = decode_byte (p, &p, end);
6578 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6579 req->id = InterlockedIncrement (&event_request_id);
6580 req->event_kind = event_kind;
6581 req->suspend_policy = suspend_policy;
6582 req->nmodifiers = nmodifiers;
6585 for (i = 0; i < nmodifiers; ++i) {
6586 mod = decode_byte (p, &p, end);
6588 req->modifiers [i].kind = mod;
6589 if (mod == MOD_KIND_COUNT) {
6590 req->modifiers [i].data.count = decode_int (p, &p, end);
6591 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6592 method = decode_methodid (p, &p, end, &domain, &err);
6595 location = decode_long (p, &p, end);
6596 } else if (mod == MOD_KIND_STEP) {
6597 step_thread_id = decode_id (p, &p, end);
6598 size = decode_int (p, &p, end);
6599 depth = decode_int (p, &p, end);
6600 if (CHECK_PROTOCOL_VERSION (2, 16))
6601 filter = decode_int (p, &p, end);
6602 req->modifiers [i].data.filter = filter;
6603 } else if (mod == MOD_KIND_THREAD_ONLY) {
6604 int id = decode_id (p, &p, end);
6606 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6611 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6612 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6616 req->modifiers [i].caught = decode_byte (p, &p, end);
6617 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6618 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" : ""));
6620 req->modifiers [i].data.exc_class = exc_class;
6622 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6624 return ERR_INVALID_ARGUMENT;
6627 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6628 int n = decode_int (p, &p, end);
6631 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6632 for (j = 0; j < n; ++j) {
6633 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6635 g_free (req->modifiers [i].data.assemblies);
6639 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6640 int n = decode_int (p, &p, end);
6643 modifier = &req->modifiers [i];
6644 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6645 for (j = 0; j < n; ++j) {
6646 char *s = decode_string (p, &p, end);
6650 s2 = strdup_tolower (s);
6651 g_hash_table_insert (modifier->data.source_files, s2, s2);
6655 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6656 int n = decode_int (p, &p, end);
6659 modifier = &req->modifiers [i];
6660 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6661 for (j = 0; j < n; ++j) {
6662 char *s = decode_string (p, &p, end);
6665 g_hash_table_insert (modifier->data.type_names, s, s);
6669 return ERR_NOT_IMPLEMENTED;
6673 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6676 req->info = set_breakpoint (method, location, req, &error);
6677 if (!mono_error_ok (&error)) {
6679 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6680 mono_error_cleanup (&error);
6681 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6683 } else if (req->event_kind == EVENT_KIND_STEP) {
6684 g_assert (step_thread_id);
6686 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6692 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6697 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6698 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6699 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6700 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6701 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6702 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6704 if (req->nmodifiers) {
6706 return ERR_NOT_IMPLEMENTED;
6710 mono_loader_lock ();
6711 g_ptr_array_add (event_requests, req);
6713 if (agent_config.defer) {
6714 /* Transmit cached data to the client on receipt of the event request */
6715 switch (req->event_kind) {
6716 case EVENT_KIND_APPDOMAIN_CREATE:
6717 /* Emit load events for currently loaded domains */
6718 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6720 case EVENT_KIND_ASSEMBLY_LOAD:
6721 /* Emit load events for currently loaded assemblies */
6722 mono_assembly_foreach (emit_assembly_load, NULL);
6724 case EVENT_KIND_THREAD_START:
6725 /* Emit start events for currently started threads */
6726 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6728 case EVENT_KIND_TYPE_LOAD:
6729 /* Emit type load events for currently loaded types */
6730 mono_domain_foreach (send_types_for_domain, NULL);
6736 mono_loader_unlock ();
6738 buffer_add_int (buf, req->id);
6741 case CMD_EVENT_REQUEST_CLEAR: {
6742 int etype = decode_byte (p, &p, end);
6743 int req_id = decode_int (p, &p, end);
6745 // FIXME: Make a faster mapping from req_id to request
6746 mono_loader_lock ();
6747 clear_event_request (req_id, etype);
6748 mono_loader_unlock ();
6751 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6754 mono_loader_lock ();
6756 while (i < event_requests->len) {
6757 EventRequest *req = g_ptr_array_index (event_requests, i);
6759 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6760 clear_breakpoint (req->info);
6762 g_ptr_array_remove_index_fast (event_requests, i);
6768 mono_loader_unlock ();
6772 return ERR_NOT_IMPLEMENTED;
6779 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6785 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6786 buffer_add_domainid (buf, mono_get_root_domain ());
6789 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6790 domain = decode_domainid (p, &p, end, NULL, &err);
6793 buffer_add_string (buf, domain->friendly_name);
6796 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6801 domain = decode_domainid (p, &p, end, NULL, &err);
6804 mono_loader_lock ();
6806 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6809 buffer_add_int (buf, count);
6810 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6812 buffer_add_assemblyid (buf, domain, ass);
6814 mono_loader_unlock ();
6817 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6818 domain = decode_domainid (p, &p, end, NULL, &err);
6822 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6825 case CMD_APPDOMAIN_GET_CORLIB: {
6826 domain = decode_domainid (p, &p, end, NULL, &err);
6830 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6833 case CMD_APPDOMAIN_CREATE_STRING: {
6837 domain = decode_domainid (p, &p, end, NULL, &err);
6840 s = decode_string (p, &p, end);
6842 o = mono_string_new (domain, s);
6843 buffer_add_objid (buf, (MonoObject*)o);
6846 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6848 MonoDomain *domain2;
6851 domain = decode_domainid (p, &p, end, NULL, &err);
6854 klass = decode_typeid (p, &p, end, &domain2, &err);
6859 g_assert (domain == domain2);
6861 o = mono_object_new (domain, klass);
6863 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6867 buffer_add_objid (buf, o);
6871 return ERR_NOT_IMPLEMENTED;
6878 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6884 ass = decode_assemblyid (p, &p, end, &domain, &err);
6889 case CMD_ASSEMBLY_GET_LOCATION: {
6890 buffer_add_string (buf, mono_image_get_filename (ass->image));
6893 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6897 if (ass->image->dynamic) {
6898 buffer_add_id (buf, 0);
6900 token = mono_image_get_entry_point (ass->image);
6902 buffer_add_id (buf, 0);
6904 m = mono_get_method (ass->image, token, NULL);
6905 buffer_add_methodid (buf, domain, m);
6910 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6911 buffer_add_moduleid (buf, domain, ass->image);
6914 case CMD_ASSEMBLY_GET_OBJECT: {
6915 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
6916 buffer_add_objid (buf, o);
6919 case CMD_ASSEMBLY_GET_TYPE: {
6920 char *s = decode_string (p, &p, end);
6921 gboolean ignorecase = decode_byte (p, &p, end);
6922 MonoTypeNameParse info;
6924 gboolean type_resolve, res;
6925 MonoDomain *d = mono_domain_get ();
6927 /* This is needed to be able to find referenced assemblies */
6928 res = mono_domain_set (domain, FALSE);
6931 if (!mono_reflection_parse_type (s, &info)) {
6934 if (info.assembly.name)
6936 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6938 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6939 mono_reflection_free_type_info (&info);
6942 mono_domain_set (d, TRUE);
6946 case CMD_ASSEMBLY_GET_NAME: {
6948 MonoAssembly *mass = ass;
6950 name = g_strdup_printf (
6951 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6953 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6954 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6955 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6956 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6958 buffer_add_string (buf, name);
6963 return ERR_NOT_IMPLEMENTED;
6970 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6976 case CMD_MODULE_GET_INFO: {
6977 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
6980 basename = g_path_get_basename (image->name);
6981 buffer_add_string (buf, basename); // name
6982 buffer_add_string (buf, image->module_name); // scopename
6983 buffer_add_string (buf, image->name); // fqname
6984 buffer_add_string (buf, mono_image_get_guid (image)); // guid
6985 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
6990 return ERR_NOT_IMPLEMENTED;
6997 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6999 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7000 /* Special case these so the client doesn't have to handle Type objects */
7002 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7003 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7004 } else if (MONO_TYPE_IS_REFERENCE (t))
7005 buffer_add_value (buf, t, &val, domain);
7007 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7011 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7017 buffer_add_int (buf, 0);
7021 for (i = 0; i < cinfo->num_attrs; ++i) {
7022 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7025 buffer_add_int (buf, nattrs);
7027 for (i = 0; i < cinfo->num_attrs; ++i) {
7028 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7029 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7030 MonoArray *typed_args, *named_args;
7032 CattrNamedArg *arginfo;
7034 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7036 buffer_add_methodid (buf, domain, attr->ctor);
7040 buffer_add_int (buf, mono_array_length (typed_args));
7041 for (j = 0; j < mono_array_length (typed_args); ++j) {
7042 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7044 t = mono_method_signature (attr->ctor)->params [j];
7046 buffer_add_cattr_arg (buf, t, domain, val);
7049 buffer_add_int (buf, 0);
7054 buffer_add_int (buf, mono_array_length (named_args));
7056 for (j = 0; j < mono_array_length (named_args); ++j) {
7057 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7059 if (arginfo [j].prop) {
7060 buffer_add_byte (buf, 0x54);
7061 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7062 } else if (arginfo [j].field) {
7063 buffer_add_byte (buf, 0x53);
7064 buffer_add_fieldid (buf, domain, arginfo [j].field);
7066 g_assert_not_reached ();
7069 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7072 buffer_add_int (buf, 0);
7078 /* FIXME: Code duplication with icall.c */
7080 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7085 mono_class_setup_interfaces (klass, error);
7086 if (!mono_error_ok (error))
7089 for (i = 0; i < klass->interface_count; i++) {
7090 ic = klass->interfaces [i];
7091 g_hash_table_insert (ifaces, ic, ic);
7093 collect_interfaces (ic, ifaces, error);
7094 if (!mono_error_ok (error))
7100 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7110 case CMD_TYPE_GET_INFO: {
7111 buffer_add_string (buf, klass->name_space);
7112 buffer_add_string (buf, klass->name);
7114 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7115 buffer_add_string (buf, name);
7117 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7118 buffer_add_moduleid (buf, domain, klass->image);
7119 buffer_add_typeid (buf, domain, klass->parent);
7120 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7121 buffer_add_typeid (buf, domain, klass->element_class);
7123 buffer_add_id (buf, 0);
7124 buffer_add_int (buf, klass->type_token);
7125 buffer_add_byte (buf, klass->rank);
7126 buffer_add_int (buf, klass->flags);
7128 type = &klass->byval_arg;
7129 // FIXME: Can't decide whenever a class represents a byref type
7132 if (type->type == MONO_TYPE_PTR)
7134 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7136 if (type->type == MONO_TYPE_VALUETYPE)
7138 if (klass->enumtype)
7140 if (klass->generic_container)
7142 if (klass->generic_container || klass->generic_class)
7144 buffer_add_byte (buf, b);
7147 while ((nested = mono_class_get_nested_types (klass, &iter)))
7149 buffer_add_int (buf, nnested);
7151 while ((nested = mono_class_get_nested_types (klass, &iter)))
7152 buffer_add_typeid (buf, domain, nested);
7153 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7154 if (klass->generic_container)
7155 buffer_add_typeid (buf, domain, klass);
7156 else if (klass->generic_class)
7157 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7159 buffer_add_id (buf, 0);
7161 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7164 if (klass->generic_class) {
7165 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7167 count = inst->type_argc;
7168 buffer_add_int (buf, count);
7169 for (i = 0; i < count; i++)
7170 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7171 } else if (klass->generic_container) {
7172 MonoGenericContainer *container = klass->generic_container;
7175 count = container->type_argc;
7176 buffer_add_int (buf, count);
7177 for (i = 0; i < count; i++) {
7178 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7179 buffer_add_typeid (buf, domain, pklass);
7182 buffer_add_int (buf, 0);
7187 case CMD_TYPE_GET_METHODS: {
7190 gpointer iter = NULL;
7193 mono_class_setup_methods (klass);
7195 nmethods = mono_class_num_methods (klass);
7197 buffer_add_int (buf, nmethods);
7199 while ((m = mono_class_get_methods (klass, &iter))) {
7200 buffer_add_methodid (buf, domain, m);
7203 g_assert (i == nmethods);
7206 case CMD_TYPE_GET_FIELDS: {
7209 gpointer iter = NULL;
7212 nfields = mono_class_num_fields (klass);
7214 buffer_add_int (buf, nfields);
7216 while ((f = mono_class_get_fields (klass, &iter))) {
7217 buffer_add_fieldid (buf, domain, f);
7218 buffer_add_string (buf, f->name);
7219 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7220 buffer_add_int (buf, f->type->attrs);
7223 g_assert (i == nfields);
7226 case CMD_TYPE_GET_PROPERTIES: {
7229 gpointer iter = NULL;
7232 nprops = mono_class_num_properties (klass);
7234 buffer_add_int (buf, nprops);
7236 while ((p = mono_class_get_properties (klass, &iter))) {
7237 buffer_add_propertyid (buf, domain, p);
7238 buffer_add_string (buf, p->name);
7239 buffer_add_methodid (buf, domain, p->get);
7240 buffer_add_methodid (buf, domain, p->set);
7241 buffer_add_int (buf, p->attrs);
7244 g_assert (i == nprops);
7247 case CMD_TYPE_GET_CATTRS: {
7248 MonoClass *attr_klass;
7249 MonoCustomAttrInfo *cinfo;
7251 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7252 /* attr_klass can be NULL */
7256 cinfo = mono_custom_attrs_from_class (klass);
7258 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7261 case CMD_TYPE_GET_FIELD_CATTRS: {
7262 MonoClass *attr_klass;
7263 MonoCustomAttrInfo *cinfo;
7264 MonoClassField *field;
7266 field = decode_fieldid (p, &p, end, NULL, &err);
7269 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7273 cinfo = mono_custom_attrs_from_field (klass, field);
7275 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7278 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7279 MonoClass *attr_klass;
7280 MonoCustomAttrInfo *cinfo;
7283 prop = decode_propertyid (p, &p, end, NULL, &err);
7286 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7290 cinfo = mono_custom_attrs_from_property (klass, prop);
7292 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7295 case CMD_TYPE_GET_VALUES:
7296 case CMD_TYPE_GET_VALUES_2: {
7303 MonoThread *thread_obj;
7304 MonoInternalThread *thread = NULL;
7305 guint32 special_static_type;
7307 if (command == CMD_TYPE_GET_VALUES_2) {
7308 int objid = decode_objid (p, &p, end);
7311 err = get_object (objid, (MonoObject**)&thread_obj);
7315 thread = THREAD_TO_INTERNAL (thread_obj);
7318 len = decode_int (p, &p, end);
7319 for (i = 0; i < len; ++i) {
7320 f = decode_fieldid (p, &p, end, NULL, &err);
7324 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7325 return ERR_INVALID_FIELDID;
7326 special_static_type = mono_class_field_get_special_static_type (f);
7327 if (special_static_type != SPECIAL_STATIC_NONE) {
7328 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7329 return ERR_INVALID_FIELDID;
7332 /* Check that the field belongs to the object */
7334 for (k = klass; k; k = k->parent) {
7335 if (k == f->parent) {
7341 return ERR_INVALID_FIELDID;
7343 vtable = mono_class_vtable (domain, f->parent);
7344 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7345 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7346 buffer_add_value (buf, f->type, val, domain);
7351 case CMD_TYPE_SET_VALUES: {
7359 len = decode_int (p, &p, end);
7360 for (i = 0; i < len; ++i) {
7361 f = decode_fieldid (p, &p, end, NULL, &err);
7365 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7366 return ERR_INVALID_FIELDID;
7367 if (mono_class_field_is_special_static (f))
7368 return ERR_INVALID_FIELDID;
7370 /* Check that the field belongs to the object */
7372 for (k = klass; k; k = k->parent) {
7373 if (k == f->parent) {
7379 return ERR_INVALID_FIELDID;
7381 // FIXME: Check for literal/const
7383 vtable = mono_class_vtable (domain, f->parent);
7384 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7385 err = decode_value (f->type, domain, val, p, &p, end);
7390 if (MONO_TYPE_IS_REFERENCE (f->type))
7391 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7393 mono_field_static_set_value (vtable, f, val);
7398 case CMD_TYPE_GET_OBJECT: {
7399 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7400 buffer_add_objid (buf, o);
7403 case CMD_TYPE_GET_SOURCE_FILES:
7404 case CMD_TYPE_GET_SOURCE_FILES_2: {
7405 char *source_file, *base;
7409 files = get_source_files_for_type (klass);
7411 buffer_add_int (buf, files->len);
7412 for (i = 0; i < files->len; ++i) {
7413 source_file = g_ptr_array_index (files, i);
7414 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7415 buffer_add_string (buf, source_file);
7417 base = g_path_get_basename (source_file);
7418 buffer_add_string (buf, base);
7421 g_free (source_file);
7423 g_ptr_array_free (files, TRUE);
7426 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7427 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7431 if (mono_class_is_assignable_from (klass, oklass))
7432 buffer_add_byte (buf, 1);
7434 buffer_add_byte (buf, 0);
7437 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7438 char *name = decode_string (p, &p, end);
7439 int i, flags = decode_int (p, &p, end);
7440 MonoException *ex = NULL;
7441 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7444 return ERR_LOADER_ERROR;
7445 buffer_add_int (buf, array->len);
7446 for (i = 0; i < array->len; ++i) {
7447 MonoMethod *method = g_ptr_array_index (array, i);
7448 buffer_add_methodid (buf, domain, method);
7451 g_ptr_array_free (array, TRUE);
7455 case CMD_TYPE_GET_INTERFACES: {
7457 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7459 MonoClass *tclass, *iface;
7460 GHashTableIter iter;
7464 for (parent = tclass; parent; parent = parent->parent) {
7465 mono_class_setup_interfaces (parent, &error);
7466 if (!mono_error_ok (&error))
7467 return ERR_LOADER_ERROR;
7468 collect_interfaces (parent, iface_hash, &error);
7469 if (!mono_error_ok (&error))
7470 return ERR_LOADER_ERROR;
7473 buffer_add_int (buf, g_hash_table_size (iface_hash));
7475 g_hash_table_iter_init (&iter, iface_hash);
7476 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7477 buffer_add_typeid (buf, domain, iface);
7478 g_hash_table_destroy (iface_hash);
7481 case CMD_TYPE_GET_INTERFACE_MAP: {
7482 int tindex, ioffset;
7483 gboolean variance_used;
7485 int len, nmethods, i;
7489 len = decode_int (p, &p, end);
7490 mono_class_setup_vtable (klass);
7492 for (tindex = 0; tindex < len; ++tindex) {
7493 iclass = decode_typeid (p, &p, end, NULL, &err);
7497 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7499 return ERR_INVALID_ARGUMENT;
7501 nmethods = mono_class_num_methods (iclass);
7502 buffer_add_int (buf, nmethods);
7505 while ((method = mono_class_get_methods (iclass, &iter))) {
7506 buffer_add_methodid (buf, domain, method);
7508 for (i = 0; i < nmethods; ++i)
7509 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7514 return ERR_NOT_IMPLEMENTED;
7521 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7524 MonoDomain *old_domain;
7528 klass = decode_typeid (p, &p, end, &domain, &err);
7532 old_domain = mono_domain_get ();
7534 mono_domain_set (domain, TRUE);
7536 err = type_commands_internal (command, klass, domain, p, end, buf);
7538 mono_domain_set (old_domain, TRUE);
7544 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7546 MonoMethodHeader *header;
7549 case CMD_METHOD_GET_NAME: {
7550 buffer_add_string (buf, method->name);
7553 case CMD_METHOD_GET_DECLARING_TYPE: {
7554 buffer_add_typeid (buf, domain, method->klass);
7557 case CMD_METHOD_GET_DEBUG_INFO: {
7558 MonoDebugMethodInfo *minfo;
7560 int i, j, n_il_offsets;
7563 int *column_numbers;
7565 GPtrArray *source_file_list;
7567 header = mono_method_get_header (method);
7569 buffer_add_int (buf, 0);
7570 buffer_add_string (buf, "");
7571 buffer_add_int (buf, 0);
7575 minfo = mono_debug_lookup_method (method);
7577 buffer_add_int (buf, header->code_size);
7578 buffer_add_string (buf, "");
7579 buffer_add_int (buf, 0);
7580 mono_metadata_free_mh (header);
7584 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7585 buffer_add_int (buf, header->code_size);
7586 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7587 buffer_add_int (buf, source_file_list->len);
7588 for (i = 0; i < source_file_list->len; ++i) {
7589 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7590 buffer_add_string (buf, sinfo->source_file);
7591 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7592 for (j = 0; j < 16; ++j)
7593 buffer_add_byte (buf, sinfo->hash [j]);
7597 buffer_add_string (buf, source_file);
7599 buffer_add_int (buf, n_il_offsets);
7600 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7601 for (i = 0; i < n_il_offsets; ++i) {
7602 const char *srcfile = "";
7604 if (source_files [i] != -1) {
7605 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7606 srcfile = sinfo->source_file;
7608 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7609 buffer_add_int (buf, il_offsets [i]);
7610 buffer_add_int (buf, line_numbers [i]);
7611 if (CHECK_PROTOCOL_VERSION (2, 13))
7612 buffer_add_int (buf, source_files [i]);
7613 if (CHECK_PROTOCOL_VERSION (2, 19))
7614 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7616 g_free (source_file);
7617 g_free (il_offsets);
7618 g_free (line_numbers);
7619 g_free (source_files);
7620 g_ptr_array_free (source_file_list, TRUE);
7621 mono_metadata_free_mh (header);
7624 case CMD_METHOD_GET_PARAM_INFO: {
7625 MonoMethodSignature *sig = mono_method_signature (method);
7629 /* FIXME: mono_class_from_mono_type () and byrefs */
7631 /* FIXME: Use a smaller encoding */
7632 buffer_add_int (buf, sig->call_convention);
7633 buffer_add_int (buf, sig->param_count);
7634 buffer_add_int (buf, sig->generic_param_count);
7635 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7636 for (i = 0; i < sig->param_count; ++i) {
7638 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7641 /* Emit parameter names */
7642 names = g_new (char *, sig->param_count);
7643 mono_method_get_param_names (method, (const char **) names);
7644 for (i = 0; i < sig->param_count; ++i)
7645 buffer_add_string (buf, names [i]);
7650 case CMD_METHOD_GET_LOCALS_INFO: {
7651 int i, j, num_locals;
7652 MonoDebugLocalsInfo *locals;
7654 header = mono_method_get_header (method);
7656 return ERR_INVALID_ARGUMENT;
7658 buffer_add_int (buf, header->num_locals);
7661 for (i = 0; i < header->num_locals; ++i)
7662 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7665 locals = mono_debug_lookup_locals (method);
7667 num_locals = locals->num_locals;
7670 for (i = 0; i < header->num_locals; ++i) {
7671 for (j = 0; j < num_locals; ++j)
7672 if (locals->locals [j].index == i)
7675 buffer_add_string (buf, locals->locals [j].name);
7677 buffer_add_string (buf, "");
7681 for (i = 0; i < header->num_locals; ++i) {
7682 for (j = 0; j < num_locals; ++j)
7683 if (locals->locals [j].index == i)
7685 if (j < num_locals && locals->locals [j].block) {
7686 buffer_add_int (buf, locals->locals [j].block->start_offset);
7687 buffer_add_int (buf, locals->locals [j].block->end_offset);
7689 buffer_add_int (buf, 0);
7690 buffer_add_int (buf, header->code_size);
7693 mono_metadata_free_mh (header);
7696 mono_debug_symfile_free_locals (locals);
7700 case CMD_METHOD_GET_INFO:
7701 buffer_add_int (buf, method->flags);
7702 buffer_add_int (buf, method->iflags);
7703 buffer_add_int (buf, method->token);
7704 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7706 if (method->is_generic)
7708 if (mono_method_signature (method)->generic_param_count)
7710 buffer_add_byte (buf, attrs);
7711 if (method->is_generic || method->is_inflated) {
7714 if (method->is_generic) {
7717 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7719 result = imethod->declaring;
7720 if (imethod->context.class_inst) {
7721 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7722 /*Generic methods gets the context of the GTD.*/
7723 if (mono_class_get_context (klass))
7724 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7728 buffer_add_methodid (buf, domain, result);
7730 buffer_add_id (buf, 0);
7732 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7733 if (mono_method_signature (method)->generic_param_count) {
7736 if (method->is_inflated) {
7737 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7739 count = inst->type_argc;
7740 buffer_add_int (buf, count);
7742 for (i = 0; i < count; i++)
7743 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7745 buffer_add_int (buf, 0);
7747 } else if (method->is_generic) {
7748 MonoGenericContainer *container = mono_method_get_generic_container (method);
7750 count = mono_method_signature (method)->generic_param_count;
7751 buffer_add_int (buf, count);
7752 for (i = 0; i < count; i++) {
7753 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7754 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7755 buffer_add_typeid (buf, domain, pklass);
7758 buffer_add_int (buf, 0);
7761 buffer_add_int (buf, 0);
7766 case CMD_METHOD_GET_BODY: {
7769 header = mono_method_get_header (method);
7771 buffer_add_int (buf, 0);
7773 if (CHECK_PROTOCOL_VERSION (2, 18))
7774 buffer_add_int (buf, 0);
7776 buffer_add_int (buf, header->code_size);
7777 for (i = 0; i < header->code_size; ++i)
7778 buffer_add_byte (buf, header->code [i]);
7780 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7781 buffer_add_int (buf, header->num_clauses);
7782 for (i = 0; i < header->num_clauses; ++i) {
7783 MonoExceptionClause *clause = &header->clauses [i];
7785 buffer_add_int (buf, clause->flags);
7786 buffer_add_int (buf, clause->try_offset);
7787 buffer_add_int (buf, clause->try_len);
7788 buffer_add_int (buf, clause->handler_offset);
7789 buffer_add_int (buf, clause->handler_len);
7790 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7791 buffer_add_typeid (buf, domain, clause->data.catch_class);
7792 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7793 buffer_add_int (buf, clause->data.filter_offset);
7797 mono_metadata_free_mh (header);
7802 case CMD_METHOD_RESOLVE_TOKEN: {
7803 guint32 token = decode_int (p, &p, end);
7806 switch (mono_metadata_token_code (token)) {
7807 case MONO_TOKEN_STRING: {
7811 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7814 s2 = mono_string_to_utf8 (s);
7816 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7817 buffer_add_string (buf, s2);
7823 MonoClass *handle_class;
7825 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7826 val = mono_method_get_wrapper_data (method, token);
7827 handle_class = mono_method_get_wrapper_data (method, token + 1);
7829 if (handle_class == NULL) {
7830 // Can't figure out the token type
7831 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7835 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7839 if (handle_class == mono_defaults.typehandle_class) {
7840 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7841 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7842 buffer_add_typeid (buf, domain, (MonoClass *) val);
7844 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7845 } else if (handle_class == mono_defaults.fieldhandle_class) {
7846 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7847 buffer_add_fieldid (buf, domain, val);
7848 } else if (handle_class == mono_defaults.methodhandle_class) {
7849 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7850 buffer_add_methodid (buf, domain, val);
7851 } else if (handle_class == mono_defaults.string_class) {
7854 s = mono_string_to_utf8 (val);
7855 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7856 buffer_add_string (buf, s);
7859 g_assert_not_reached ();
7867 return ERR_NOT_IMPLEMENTED;
7874 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7877 MonoDomain *old_domain;
7881 method = decode_methodid (p, &p, end, &domain, &err);
7885 old_domain = mono_domain_get ();
7887 mono_domain_set (domain, TRUE);
7889 err = method_commands_internal (command, method, domain, p, end, buf);
7891 mono_domain_set (old_domain, TRUE);
7897 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7899 int objid = decode_objid (p, &p, end);
7901 MonoThread *thread_obj;
7902 MonoInternalThread *thread;
7904 err = get_object (objid, (MonoObject**)&thread_obj);
7908 thread = THREAD_TO_INTERNAL (thread_obj);
7911 case CMD_THREAD_GET_NAME: {
7913 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7916 buffer_add_int (buf, 0);
7921 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7923 buffer_add_int (buf, len);
7924 buffer_add_data (buf, (guint8*)name, len);
7929 case CMD_THREAD_GET_FRAME_INFO: {
7930 DebuggerTlsData *tls;
7931 int i, start_frame, length;
7933 // Wait for suspending if it already started
7934 // FIXME: Races with suspend_count
7935 while (!is_suspended ()) {
7937 wait_for_suspend ();
7941 wait_for_suspend ();
7942 if (!is_suspended ())
7943 return ERR_NOT_SUSPENDED;
7946 start_frame = decode_int (p, &p, end);
7947 length = decode_int (p, &p, end);
7949 if (start_frame != 0 || length != -1)
7950 return ERR_NOT_IMPLEMENTED;
7952 mono_loader_lock ();
7953 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7954 mono_loader_unlock ();
7957 compute_frame_info (thread, tls);
7959 buffer_add_int (buf, tls->frame_count);
7960 for (i = 0; i < tls->frame_count; ++i) {
7961 buffer_add_int (buf, tls->frames [i]->id);
7962 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
7963 buffer_add_int (buf, tls->frames [i]->il_offset);
7965 * Instead of passing the frame type directly to the client, we associate
7966 * it with the previous frame using a set of flags. This avoids lots of
7967 * conditional code in the client, since a frame whose type isn't
7968 * FRAME_TYPE_MANAGED has no method, location, etc.
7970 buffer_add_byte (buf, tls->frames [i]->flags);
7975 case CMD_THREAD_GET_STATE:
7976 buffer_add_int (buf, thread->state);
7978 case CMD_THREAD_GET_INFO:
7979 buffer_add_byte (buf, thread->threadpool_thread);
7981 case CMD_THREAD_GET_ID:
7982 buffer_add_long (buf, (guint64)(gsize)thread);
7984 case CMD_THREAD_GET_TID:
7985 buffer_add_long (buf, (guint64)thread->tid);
7988 return ERR_NOT_IMPLEMENTED;
7995 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7999 MonoThread *thread_obj;
8000 MonoInternalThread *thread;
8001 int pos, i, len, frame_idx;
8002 DebuggerTlsData *tls;
8004 MonoDebugMethodJitInfo *jit;
8005 MonoDebugVarInfo *var;
8006 MonoMethodSignature *sig;
8008 MonoMethodHeader *header;
8010 objid = decode_objid (p, &p, end);
8011 err = get_object (objid, (MonoObject**)&thread_obj);
8015 thread = THREAD_TO_INTERNAL (thread_obj);
8017 id = decode_id (p, &p, end);
8019 mono_loader_lock ();
8020 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8021 mono_loader_unlock ();
8024 for (i = 0; i < tls->frame_count; ++i) {
8025 if (tls->frames [i]->id == id)
8028 if (i == tls->frame_count)
8029 return ERR_INVALID_FRAMEID;
8032 frame = tls->frames [frame_idx];
8034 if (!frame->has_ctx)
8036 return ERR_INVALID_FRAMEID;
8039 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8040 if (!frame->jit && frame->api_method->is_inflated)
8041 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8045 /* This could happen for aot images with no jit debug info */
8046 s = mono_method_full_name (frame->api_method, TRUE);
8047 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8049 return ERR_ABSENT_INFORMATION;
8054 sig = mono_method_signature (frame->actual_method);
8056 if (!get_seq_points (frame->domain, frame->actual_method))
8058 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8060 return ERR_ABSENT_INFORMATION;
8063 case CMD_STACK_FRAME_GET_VALUES: {
8064 len = decode_int (p, &p, end);
8065 header = mono_method_get_header (frame->actual_method);
8067 for (i = 0; i < len; ++i) {
8068 pos = decode_int (p, &p, end);
8073 g_assert (pos >= 0 && pos < jit->num_params);
8075 var = &jit->params [pos];
8077 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8079 g_assert (pos >= 0 && pos < jit->num_locals);
8081 var = &jit->locals [pos];
8083 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8086 mono_metadata_free_mh (header);
8089 case CMD_STACK_FRAME_GET_THIS: {
8090 if (frame->api_method->klass->valuetype) {
8091 if (!sig->hasthis) {
8092 MonoObject *p = NULL;
8093 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8095 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8098 if (!sig->hasthis) {
8099 MonoObject *p = NULL;
8100 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8102 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8107 case CMD_STACK_FRAME_SET_VALUES: {
8110 MonoDebugVarInfo *var;
8112 len = decode_int (p, &p, end);
8113 header = mono_method_get_header (frame->actual_method);
8115 for (i = 0; i < len; ++i) {
8116 pos = decode_int (p, &p, end);
8121 g_assert (pos >= 0 && pos < jit->num_params);
8123 t = sig->params [pos];
8124 var = &jit->params [pos];
8126 g_assert (pos >= 0 && pos < jit->num_locals);
8128 t = header->locals [pos];
8129 var = &jit->locals [pos];
8132 if (MONO_TYPE_IS_REFERENCE (t))
8133 val_buf = g_alloca (sizeof (MonoObject*));
8135 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8136 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8140 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8142 mono_metadata_free_mh (header);
8146 return ERR_NOT_IMPLEMENTED;
8153 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8156 int objid, err, index, len, i, esize;
8159 objid = decode_objid (p, &p, end);
8160 err = get_object (objid, (MonoObject**)&arr);
8165 case CMD_ARRAY_REF_GET_LENGTH:
8166 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8168 buffer_add_int (buf, arr->max_length);
8169 buffer_add_int (buf, 0);
8171 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8172 buffer_add_int (buf, arr->bounds [i].length);
8173 buffer_add_int (buf, arr->bounds [i].lower_bound);
8177 case CMD_ARRAY_REF_GET_VALUES:
8178 index = decode_int (p, &p, end);
8179 len = decode_int (p, &p, end);
8181 g_assert (index >= 0 && len >= 0);
8182 // Reordered to avoid integer overflow
8183 g_assert (!(index > arr->max_length - len));
8185 esize = mono_array_element_size (arr->obj.vtable->klass);
8186 for (i = index; i < index + len; ++i) {
8187 elem = (gpointer*)((char*)arr->vector + (i * esize));
8188 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8191 case CMD_ARRAY_REF_SET_VALUES:
8192 index = decode_int (p, &p, end);
8193 len = decode_int (p, &p, end);
8195 g_assert (index >= 0 && len >= 0);
8196 // Reordered to avoid integer overflow
8197 g_assert (!(index > arr->max_length - len));
8199 esize = mono_array_element_size (arr->obj.vtable->klass);
8200 for (i = index; i < index + len; ++i) {
8201 elem = (gpointer*)((char*)arr->vector + (i * esize));
8203 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8207 return ERR_NOT_IMPLEMENTED;
8214 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8219 int i, index, length;
8222 objid = decode_objid (p, &p, end);
8223 err = get_object (objid, (MonoObject**)&str);
8228 case CMD_STRING_REF_GET_VALUE:
8229 s = mono_string_to_utf8 (str);
8230 buffer_add_string (buf, s);
8233 case CMD_STRING_REF_GET_LENGTH:
8234 buffer_add_long (buf, mono_string_length (str));
8236 case CMD_STRING_REF_GET_CHARS:
8237 index = decode_long (p, &p, end);
8238 length = decode_long (p, &p, end);
8239 if (index > mono_string_length (str) - length)
8240 return ERR_INVALID_ARGUMENT;
8241 c = mono_string_chars (str) + index;
8242 for (i = 0; i < length; ++i)
8243 buffer_add_short (buf, c [i]);
8246 return ERR_NOT_IMPLEMENTED;
8253 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8262 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8263 objid = decode_objid (p, &p, end);
8264 err = get_object (objid, &obj);
8266 buffer_add_int (buf, 1);
8268 buffer_add_int (buf, 0);
8272 objid = decode_objid (p, &p, end);
8273 err = get_object (objid, &obj);
8278 case CMD_OBJECT_REF_GET_TYPE:
8279 /* This handles transparent proxies too */
8280 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8282 case CMD_OBJECT_REF_GET_VALUES:
8283 len = decode_int (p, &p, end);
8285 for (i = 0; i < len; ++i) {
8286 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8290 /* Check that the field belongs to the object */
8292 for (k = obj->vtable->klass; k; k = k->parent) {
8293 if (k == f->parent) {
8299 return ERR_INVALID_FIELDID;
8301 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8305 if (mono_class_field_is_special_static (f))
8306 return ERR_INVALID_FIELDID;
8308 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8309 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8310 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8311 mono_field_static_get_value (vtable, f, val);
8312 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8315 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8319 case CMD_OBJECT_REF_SET_VALUES:
8320 len = decode_int (p, &p, end);
8322 for (i = 0; i < len; ++i) {
8323 f = decode_fieldid (p, &p, end, NULL, &err);
8327 /* Check that the field belongs to the object */
8329 for (k = obj->vtable->klass; k; k = k->parent) {
8330 if (k == f->parent) {
8336 return ERR_INVALID_FIELDID;
8338 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8342 if (mono_class_field_is_special_static (f))
8343 return ERR_INVALID_FIELDID;
8345 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8346 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8348 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8349 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8354 mono_field_static_set_value (vtable, f, val);
8357 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8363 case CMD_OBJECT_REF_GET_ADDRESS:
8364 buffer_add_long (buf, (gssize)obj);
8366 case CMD_OBJECT_REF_GET_DOMAIN:
8367 buffer_add_domainid (buf, obj->vtable->domain);
8369 case CMD_OBJECT_REF_GET_INFO:
8370 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8371 buffer_add_domainid (buf, obj->vtable->domain);
8374 return ERR_NOT_IMPLEMENTED;
8381 command_set_to_string (CommandSet command_set)
8383 switch (command_set) {
8386 case CMD_SET_OBJECT_REF:
8387 return "OBJECT_REF";
8388 case CMD_SET_STRING_REF:
8389 return "STRING_REF";
8390 case CMD_SET_THREAD:
8392 case CMD_SET_ARRAY_REF:
8394 case CMD_SET_EVENT_REQUEST:
8395 return "EVENT_REQUEST";
8396 case CMD_SET_STACK_FRAME:
8397 return "STACK_FRAME";
8398 case CMD_SET_APPDOMAIN:
8400 case CMD_SET_ASSEMBLY:
8402 case CMD_SET_METHOD:
8406 case CMD_SET_MODULE:
8416 cmd_to_string (CommandSet set, int command)
8421 case CMD_VM_VERSION:
8423 case CMD_VM_ALL_THREADS:
8424 return "ALL_THREADS";
8425 case CMD_VM_SUSPEND:
8431 case CMD_VM_DISPOSE:
8433 case CMD_VM_INVOKE_METHOD:
8434 return "INVOKE_METHOD";
8435 case CMD_VM_SET_PROTOCOL_VERSION:
8436 return "SET_PROTOCOL_VERSION";
8437 case CMD_VM_ABORT_INVOKE:
8438 return "ABORT_INVOKE";
8439 case CMD_VM_SET_KEEPALIVE:
8440 return "SET_KEEPALIVE";
8453 wait_for_attach (void)
8455 #ifndef DISABLE_SOCKET_TRANSPORT
8456 if (listen_fd == -1) {
8457 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8461 /* Block and wait for client connection */
8462 conn_fd = socket_transport_accept (listen_fd);
8463 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8464 if (conn_fd == -1) {
8465 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8469 g_assert_not_reached ();
8473 disconnected = !transport_handshake ();
8475 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8485 * This thread handles communication with the debugger client using a JDWP
8488 static guint32 WINAPI
8489 debugger_thread (void *arg)
8491 int res, len, id, flags, command_set = 0, command = 0;
8492 guint8 header [HEADER_LENGTH];
8493 guint8 *data, *p, *end;
8497 gboolean attach_failed = FALSE;
8499 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8501 debugger_thread_id = GetCurrentThreadId ();
8503 mono_jit_thread_attach (mono_get_root_domain ());
8505 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8507 mono_set_is_debugger_attached (TRUE);
8509 if (agent_config.defer) {
8510 if (!wait_for_attach ()) {
8511 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8512 attach_failed = TRUE; // Don't abort process when we can't listen
8514 /* Send start event to client */
8515 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8519 while (!attach_failed) {
8520 res = transport_recv (header, HEADER_LENGTH);
8522 /* This will break if the socket is closed during shutdown too */
8523 if (res != HEADER_LENGTH)
8527 end = header + HEADER_LENGTH;
8529 len = decode_int (p, &p, end);
8530 id = decode_int (p, &p, end);
8531 flags = decode_byte (p, &p, end);
8532 command_set = decode_byte (p, &p, end);
8533 command = decode_byte (p, &p, end);
8535 g_assert (flags == 0);
8538 const char *cmd_str;
8541 cmd_str = cmd_to_string (command_set, command);
8543 sprintf (cmd_num, "%d", command);
8547 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8550 data = g_malloc (len - HEADER_LENGTH);
8551 if (len - HEADER_LENGTH > 0)
8553 res = transport_recv (data, len - HEADER_LENGTH);
8554 if (res != len - HEADER_LENGTH)
8559 end = data + (len - HEADER_LENGTH);
8561 buffer_init (&buf, 128);
8566 /* Process the request */
8567 switch (command_set) {
8569 err = vm_commands (command, id, p, end, &buf);
8570 if (!err && command == CMD_VM_INVOKE_METHOD)
8571 /* Sent after the invoke is complete */
8574 case CMD_SET_EVENT_REQUEST:
8575 err = event_commands (command, p, end, &buf);
8577 case CMD_SET_APPDOMAIN:
8578 err = domain_commands (command, p, end, &buf);
8580 case CMD_SET_ASSEMBLY:
8581 err = assembly_commands (command, p, end, &buf);
8583 case CMD_SET_MODULE:
8584 err = module_commands (command, p, end, &buf);
8587 err = type_commands (command, p, end, &buf);
8589 case CMD_SET_METHOD:
8590 err = method_commands (command, p, end, &buf);
8592 case CMD_SET_THREAD:
8593 err = thread_commands (command, p, end, &buf);
8595 case CMD_SET_STACK_FRAME:
8596 err = frame_commands (command, p, end, &buf);
8598 case CMD_SET_ARRAY_REF:
8599 err = array_commands (command, p, end, &buf);
8601 case CMD_SET_STRING_REF:
8602 err = string_commands (command, p, end, &buf);
8604 case CMD_SET_OBJECT_REF:
8605 err = object_commands (command, p, end, &buf);
8608 err = ERR_NOT_IMPLEMENTED;
8612 send_reply_packet (id, err, &buf);
8617 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8621 mono_set_is_debugger_attached (FALSE);
8623 mono_mutex_lock (&debugger_thread_exited_mutex);
8624 debugger_thread_exited = TRUE;
8625 mono_cond_signal (&debugger_thread_exited_cond);
8626 mono_mutex_unlock (&debugger_thread_exited_mutex);
8628 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8630 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8631 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8632 start_debugger_thread ();
8638 #else /* DISABLE_DEBUGGER_AGENT */
8641 mono_debugger_agent_parse_options (char *options)
8643 g_error ("This runtime is configured with the debugger agent disabled.");
8647 mono_debugger_agent_init (void)
8652 mono_debugger_agent_breakpoint_hit (void *sigctx)
8657 mono_debugger_agent_single_step_event (void *sigctx)
8662 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8667 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8673 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8674 MonoContext *catch_ctx)
8679 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8684 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8689 mono_debugger_agent_user_break (void)
8695 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8700 mono_debugger_agent_debug_log_is_enabled (void)