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;
139 mgreg_t *reg_locations [MONO_MAX_IREGS];
141 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
142 * the frame can become invalid.
147 typedef struct _InvokeData InvokeData;
155 /* This is the context which needs to be restored after the invoke */
159 * If this is set, invoke this method with the arguments given by ARGS.
163 guint32 suspend_count;
165 InvokeData *last_invoke;
169 MonoThreadUnwindState context;
171 gpointer resume_event;
172 /* This is computed on demand when it is requested using the wire protocol */
173 /* It is freed up when the thread is resumed */
177 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
180 gboolean frames_up_to_date;
182 * Points to data about a pending invoke which needs to be executed after the thread
185 InvokeData *pending_invoke;
187 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
192 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
193 * within a finite amount of time.
197 * Set to TRUE if this thread is suspended in suspend_current ().
199 gboolean really_suspended;
200 /* Used to pass the context to the breakpoint/single step handler */
201 MonoContext handler_ctx;
202 /* Whenever thread_stop () was called for this thread */
205 /* Number of thread interruptions not yet processed */
206 gint32 interrupt_count;
208 /* Whenever to disable breakpoints (used during invokes) */
209 gboolean disable_breakpoints;
212 * Number of times this thread has been resumed using resume_thread ().
214 guint32 resume_count;
216 MonoInternalThread *thread;
219 * Information about the frame which transitioned to native code for running
222 StackFrameInfo async_last_frame;
225 * The context where the stack walk can be started for running threads.
227 MonoThreadUnwindState async_state;
230 * The context used for filter clauses
232 MonoThreadUnwindState filter_state;
235 * The callee address of the last mono_runtime_invoke call
237 gpointer invoke_addr;
239 gboolean abort_requested;
242 * The current mono_runtime_invoke invocation.
247 * The context where single stepping should resume while the thread is suspended because
248 * of an EXCEPTION event.
250 MonoContext catch_ctx;
252 gboolean has_catch_ctx;
255 * The context which needs to be restored after handling a single step/breakpoint
256 * event. This is the same as the ctx at step/breakpoint site, but includes changes
257 * to caller saved registers done by set_var ().
259 MonoContext restore_ctx;
264 void (*connect) (const char *address);
265 void (*close1) (void);
266 void (*close2) (void);
267 gboolean (*send) (void *buf, int len);
268 int (*recv) (void *buf, int len);
272 * Wire Protocol definitions
275 #define HEADER_LENGTH 11
277 #define MAJOR_VERSION 2
278 #define MINOR_VERSION 17
282 CMD_SET_OBJECT_REF = 9,
283 CMD_SET_STRING_REF = 10,
285 CMD_SET_ARRAY_REF = 13,
286 CMD_SET_EVENT_REQUEST = 15,
287 CMD_SET_STACK_FRAME = 16,
288 CMD_SET_APPDOMAIN = 20,
289 CMD_SET_ASSEMBLY = 21,
297 EVENT_KIND_VM_START = 0,
298 EVENT_KIND_VM_DEATH = 1,
299 EVENT_KIND_THREAD_START = 2,
300 EVENT_KIND_THREAD_DEATH = 3,
301 EVENT_KIND_APPDOMAIN_CREATE = 4,
302 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
303 EVENT_KIND_METHOD_ENTRY = 6,
304 EVENT_KIND_METHOD_EXIT = 7,
305 EVENT_KIND_ASSEMBLY_LOAD = 8,
306 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
307 EVENT_KIND_BREAKPOINT = 10,
308 EVENT_KIND_STEP = 11,
309 EVENT_KIND_TYPE_LOAD = 12,
310 EVENT_KIND_EXCEPTION = 13,
311 EVENT_KIND_KEEPALIVE = 14,
312 EVENT_KIND_USER_BREAK = 15,
313 EVENT_KIND_USER_LOG = 16
317 SUSPEND_POLICY_NONE = 0,
318 SUSPEND_POLICY_EVENT_THREAD = 1,
319 SUSPEND_POLICY_ALL = 2
324 ERR_INVALID_OBJECT = 20,
325 ERR_INVALID_FIELDID = 25,
326 ERR_INVALID_FRAMEID = 30,
327 ERR_NOT_IMPLEMENTED = 100,
328 ERR_NOT_SUSPENDED = 101,
329 ERR_INVALID_ARGUMENT = 102,
331 ERR_NO_INVOCATION = 104,
332 ERR_ABSENT_INFORMATION = 105,
333 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
334 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
339 MOD_KIND_THREAD_ONLY = 3,
340 MOD_KIND_LOCATION_ONLY = 7,
341 MOD_KIND_EXCEPTION_ONLY = 8,
343 MOD_KIND_ASSEMBLY_ONLY = 11,
344 MOD_KIND_SOURCE_FILE_ONLY = 12,
345 MOD_KIND_TYPE_NAME_ONLY = 13
360 STEP_FILTER_NONE = 0,
361 STEP_FILTER_STATIC_CTOR = 1
365 TOKEN_TYPE_STRING = 0,
367 TOKEN_TYPE_FIELD = 2,
368 TOKEN_TYPE_METHOD = 3,
369 TOKEN_TYPE_UNKNOWN = 4
373 VALUE_TYPE_ID_NULL = 0xf0,
374 VALUE_TYPE_ID_TYPE = 0xf1
378 FRAME_FLAG_DEBUGGER_INVOKE = 1,
379 FRAME_FLAG_NATIVE_TRANSITION = 2
383 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
384 INVOKE_FLAG_SINGLE_THREADED = 2
388 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
389 } BindingFlagsExtensions;
393 CMD_VM_ALL_THREADS = 2,
398 CMD_VM_INVOKE_METHOD = 7,
399 CMD_VM_SET_PROTOCOL_VERSION = 8,
400 CMD_VM_ABORT_INVOKE = 9,
401 CMD_VM_SET_KEEPALIVE = 10,
402 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
403 CMD_VM_GET_TYPES = 12
407 CMD_THREAD_GET_FRAME_INFO = 1,
408 CMD_THREAD_GET_NAME = 2,
409 CMD_THREAD_GET_STATE = 3,
410 CMD_THREAD_GET_INFO = 4,
411 CMD_THREAD_GET_ID = 5,
412 CMD_THREAD_GET_TID = 6
416 CMD_EVENT_REQUEST_SET = 1,
417 CMD_EVENT_REQUEST_CLEAR = 2,
418 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
426 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
427 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
428 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
429 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
430 CMD_APPDOMAIN_CREATE_STRING = 5,
431 CMD_APPDOMAIN_GET_CORLIB = 6,
432 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
436 CMD_ASSEMBLY_GET_LOCATION = 1,
437 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
438 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
439 CMD_ASSEMBLY_GET_OBJECT = 4,
440 CMD_ASSEMBLY_GET_TYPE = 5,
441 CMD_ASSEMBLY_GET_NAME = 6
445 CMD_MODULE_GET_INFO = 1,
449 CMD_METHOD_GET_NAME = 1,
450 CMD_METHOD_GET_DECLARING_TYPE = 2,
451 CMD_METHOD_GET_DEBUG_INFO = 3,
452 CMD_METHOD_GET_PARAM_INFO = 4,
453 CMD_METHOD_GET_LOCALS_INFO = 5,
454 CMD_METHOD_GET_INFO = 6,
455 CMD_METHOD_GET_BODY = 7,
456 CMD_METHOD_RESOLVE_TOKEN = 8,
460 CMD_TYPE_GET_INFO = 1,
461 CMD_TYPE_GET_METHODS = 2,
462 CMD_TYPE_GET_FIELDS = 3,
463 CMD_TYPE_GET_VALUES = 4,
464 CMD_TYPE_GET_OBJECT = 5,
465 CMD_TYPE_GET_SOURCE_FILES = 6,
466 CMD_TYPE_SET_VALUES = 7,
467 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
468 CMD_TYPE_GET_PROPERTIES = 9,
469 CMD_TYPE_GET_CATTRS = 10,
470 CMD_TYPE_GET_FIELD_CATTRS = 11,
471 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
472 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
473 CMD_TYPE_GET_VALUES_2 = 14,
474 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
475 CMD_TYPE_GET_INTERFACES = 16,
476 CMD_TYPE_GET_INTERFACE_MAP = 17,
480 CMD_STACK_FRAME_GET_VALUES = 1,
481 CMD_STACK_FRAME_GET_THIS = 2,
482 CMD_STACK_FRAME_SET_VALUES = 3
486 CMD_ARRAY_REF_GET_LENGTH = 1,
487 CMD_ARRAY_REF_GET_VALUES = 2,
488 CMD_ARRAY_REF_SET_VALUES = 3,
492 CMD_STRING_REF_GET_VALUE = 1,
493 CMD_STRING_REF_GET_LENGTH = 2,
494 CMD_STRING_REF_GET_CHARS = 3
498 CMD_OBJECT_REF_GET_TYPE = 1,
499 CMD_OBJECT_REF_GET_VALUES = 2,
500 CMD_OBJECT_REF_IS_COLLECTED = 3,
501 CMD_OBJECT_REF_GET_ADDRESS = 4,
502 CMD_OBJECT_REF_GET_DOMAIN = 5,
503 CMD_OBJECT_REF_SET_VALUES = 6,
504 CMD_OBJECT_REF_GET_INFO = 7,
510 int count; /* For kind == MOD_KIND_COUNT */
511 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
512 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
513 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
514 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
515 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
516 StepFilter filter; /* For kind == MOD_KIND_STEP */
518 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
527 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
531 * Describes a single step request.
535 MonoInternalThread *thread;
541 MonoMethod *last_method;
543 /* Whenever single stepping is performed using start/stop_single_stepping () */
545 /* The list of breakpoints used to implement step-over */
550 * Contains additional information for an event
553 /* For EVENT_KIND_EXCEPTION */
555 MonoContext catch_ctx;
557 /* For EVENT_KIND_USER_LOG */
559 char *category, *message;
560 /* For EVENT_KIND_TYPE_LOAD */
564 /* Dummy structure used for the profiler callbacks */
569 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
572 #define get_last_sock_error() WSAGetLastError()
573 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
574 #define MONO_EINTR WSAEINTR
576 #define get_last_sock_error() errno
577 #define MONO_EWOULDBLOCK EWOULDBLOCK
578 #define MONO_EINTR EINTR
581 #define CHECK_PROTOCOL_VERSION(major,minor) \
582 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
588 static AgentConfig agent_config;
591 * Whenever the agent is fully initialized.
592 * When using the onuncaught or onthrow options, only some parts of the agent are
593 * initialized on startup, and the full initialization which includes connection
594 * establishment and the startup of the agent thread is only done in response to
597 static gint32 inited;
599 #ifndef DISABLE_SOCKET_TRANSPORT
601 static int listen_fd;
604 static int packet_id = 0;
606 static int objref_id = 0;
608 static int event_request_id = 0;
610 static int frame_id = 0;
612 static GPtrArray *event_requests;
614 static MonoNativeTlsKey debugger_tls_id;
616 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
618 /* Maps MonoInternalThread -> DebuggerTlsData */
619 static MonoGHashTable *thread_to_tls;
621 /* Maps tid -> MonoInternalThread */
622 static MonoGHashTable *tid_to_thread;
624 /* Maps tid -> MonoThread (not MonoInternalThread) */
625 static MonoGHashTable *tid_to_thread_obj;
627 static gsize debugger_thread_id;
629 static HANDLE debugger_thread_handle;
631 static int log_level;
633 static gboolean embedding;
635 static FILE *log_file;
637 /* Assemblies whose assembly load event has no been sent yet */
638 static GPtrArray *pending_assembly_loads;
640 /* Whenever the debugger thread has exited */
641 static gboolean debugger_thread_exited;
643 /* Cond variable used to wait for debugger_thread_exited becoming true */
644 static mono_cond_t debugger_thread_exited_cond;
646 /* Mutex for the cond var above */
647 static mono_mutex_t debugger_thread_exited_mutex;
649 static DebuggerProfiler debugger_profiler;
651 /* The single step request instance */
652 static SingleStepReq *ss_req = NULL;
653 static gpointer ss_invoke_addr = NULL;
655 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
656 /* Number of single stepping operations in progress */
660 /* The protocol version of the client */
661 static int major_version, minor_version;
663 /* Whenever the variables above are set by the client */
664 static gboolean protocol_version_set;
666 /* A hash table containing all active domains */
667 static GHashTable *domains;
669 static void transport_init (void);
670 static void transport_connect (const char *address);
671 static gboolean transport_handshake (void);
672 static void register_transport (DebuggerTransport *trans);
674 static guint32 WINAPI debugger_thread (void *arg);
676 static void runtime_initialized (MonoProfiler *prof);
678 static void runtime_shutdown (MonoProfiler *prof);
680 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
682 static void thread_end (MonoProfiler *prof, uintptr_t tid);
684 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
686 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
688 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
690 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
692 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
694 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
696 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
698 static void emit_assembly_load (gpointer assembly, gpointer user_data);
700 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
702 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
704 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
706 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
708 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
710 static void start_single_stepping (void);
712 static void stop_single_stepping (void);
714 static void suspend_current (void);
716 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
718 static void clear_types_for_assembly (MonoAssembly *assembly);
720 static void clear_breakpoints_for_domain (MonoDomain *domain);
722 static void process_profiler_event (EventKind event, gpointer arg);
724 /* Submodule init/cleanup */
725 static void breakpoints_init (void);
726 static void breakpoints_cleanup (void);
728 static void objrefs_init (void);
729 static void objrefs_cleanup (void);
731 static void ids_init (void);
732 static void ids_cleanup (void);
734 static void suspend_init (void);
736 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
737 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
738 static void ss_destroy (SingleStepReq *req);
740 static void start_debugger_thread (void);
741 static void stop_debugger_thread (void);
743 static void finish_agent_init (gboolean on_startup);
745 static void process_profiler_event (EventKind event, gpointer arg);
747 static void invalidate_frames (DebuggerTlsData *tls);
749 #ifndef DISABLE_SOCKET_TRANSPORT
751 register_socket_transport (void);
755 parse_address (char *address, char **host, int *port)
757 char *pos = strchr (address, ':');
759 if (pos == NULL || pos == address)
762 *host = g_malloc (pos - address + 1);
763 strncpy (*host, address, pos - address);
764 (*host) [pos - address] = '\0';
766 *port = atoi (pos + 1);
774 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
775 fprintf (stderr, "Available options:\n");
776 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
777 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
778 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
779 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
780 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
781 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
782 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
783 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
784 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
788 parse_flag (const char *option, char *flag)
790 if (!strcmp (flag, "y"))
792 else if (!strcmp (flag, "n"))
795 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
802 mono_debugger_agent_parse_options (char *options)
809 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
810 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
814 extra = getenv ("MONO_SDB_ENV_OPTIONS");
816 options = g_strdup_printf ("%s,%s", options, extra);
818 agent_config.enabled = TRUE;
819 agent_config.suspend = TRUE;
820 agent_config.server = FALSE;
821 agent_config.defer = FALSE;
822 agent_config.address = NULL;
824 args = g_strsplit (options, ",", -1);
825 for (ptr = args; ptr && *ptr; ptr ++) {
828 if (strncmp (arg, "transport=", 10) == 0) {
829 agent_config.transport = g_strdup (arg + 10);
830 } else if (strncmp (arg, "address=", 8) == 0) {
831 agent_config.address = g_strdup (arg + 8);
832 } else if (strncmp (arg, "loglevel=", 9) == 0) {
833 agent_config.log_level = atoi (arg + 9);
834 } else if (strncmp (arg, "logfile=", 8) == 0) {
835 agent_config.log_file = g_strdup (arg + 8);
836 } else if (strncmp (arg, "suspend=", 8) == 0) {
837 agent_config.suspend = parse_flag ("suspend", arg + 8);
838 } else if (strncmp (arg, "server=", 7) == 0) {
839 agent_config.server = parse_flag ("server", arg + 7);
840 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
841 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
842 } else if (strncmp (arg, "onthrow=", 8) == 0) {
843 /* We support multiple onthrow= options */
844 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
845 } else if (strncmp (arg, "onthrow", 7) == 0) {
846 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
847 } else if (strncmp (arg, "help", 4) == 0) {
850 } else if (strncmp (arg, "timeout=", 8) == 0) {
851 agent_config.timeout = atoi (arg + 8);
852 } else if (strncmp (arg, "launch=", 7) == 0) {
853 agent_config.launch = g_strdup (arg + 7);
854 } else if (strncmp (arg, "embedding=", 10) == 0) {
855 agent_config.embedding = atoi (arg + 10) == 1;
856 } else if (strncmp (arg, "keepalive=", 10) == 0) {
857 agent_config.keepalive = atoi (arg + 10);
864 if (agent_config.server && !agent_config.suspend) {
865 /* Waiting for deferred attachment */
866 agent_config.defer = TRUE;
867 if (agent_config.address == NULL) {
868 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
872 //agent_config.log_level = 0;
874 if (agent_config.transport == NULL) {
875 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
879 if (agent_config.address == NULL && !agent_config.server) {
880 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
885 if (!strcmp (agent_config.transport, "dt_socket")) {
886 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
887 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
894 mono_debugger_agent_init (void)
896 if (!agent_config.enabled)
901 /* Need to know whenever a thread has acquired the loader mutex */
902 mono_loader_lock_track_ownership (TRUE);
904 event_requests = g_ptr_array_new ();
906 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
907 mono_cond_init (&debugger_thread_exited_cond, NULL);
909 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
910 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
911 mono_profiler_install_runtime_initialized (runtime_initialized);
912 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
913 mono_profiler_install_thread (thread_startup, thread_end);
914 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
915 mono_profiler_install_jit_end (jit_end);
916 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
918 mono_native_tls_alloc (&debugger_tls_id, NULL);
920 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
921 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
923 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
924 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
926 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
927 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
929 pending_assembly_loads = g_ptr_array_new ();
930 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
932 log_level = agent_config.log_level;
934 embedding = agent_config.embedding;
937 if (agent_config.log_file) {
938 log_file = fopen (agent_config.log_file, "w+");
940 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
952 mini_get_debug_options ()->gen_seq_points = TRUE;
954 * This is needed because currently we don't handle liveness info.
956 mini_get_debug_options ()->mdb_optimizations = TRUE;
958 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
959 /* This is needed because we can't set local variables in registers yet */
960 mono_disable_optimizations (MONO_OPT_LINEARS);
964 * The stack walk done from thread_interrupt () needs to be signal safe, but it
965 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
966 * safe (#3411). So load AOT info eagerly when the debugger is running as a
969 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
971 if (!agent_config.onuncaught && !agent_config.onthrow)
972 finish_agent_init (TRUE);
974 /* FIXME: Is this still needed ? */
975 #if defined(__MACH__)
976 mono_thread_info_disable_new_interrupt (TRUE);
983 * Finish the initialization of the agent. This involves connecting the transport
984 * and starting the agent thread. This is either done at startup, or
985 * in response to some event like an unhandled exception.
988 finish_agent_init (gboolean on_startup)
992 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
995 if (agent_config.launch) {
998 // FIXME: Generated address
999 // FIXME: Races with transport_connect ()
1001 argv [0] = agent_config.launch;
1002 argv [1] = agent_config.transport;
1003 argv [2] = agent_config.address;
1006 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1008 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1013 transport_connect (agent_config.address);
1016 /* Do some which is usually done after sending the VMStart () event */
1017 vm_start_event_sent = TRUE;
1018 start_debugger_thread ();
1023 mono_debugger_agent_cleanup (void)
1028 stop_debugger_thread ();
1030 breakpoints_cleanup ();
1034 mono_mutex_destroy (&debugger_thread_exited_mutex);
1035 mono_cond_destroy (&debugger_thread_exited_cond);
1042 #ifndef DISABLE_SOCKET_TRANSPORT
1047 * recv() + handle incomplete reads and EINTR
1050 socket_transport_recv (void *buf, int len)
1059 res = recv (fd, (char *) buf + total, len - total, flags);
1062 if (agent_config.keepalive && res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1063 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1066 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1071 #define HAVE_GETADDRINFO 1
1075 set_keepalive (void)
1080 if (!agent_config.keepalive)
1083 tv.tv_sec = agent_config.keepalive / 1000;
1084 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1086 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1087 g_assert (result >= 0);
1091 socket_transport_accept (int socket_fd)
1093 conn_fd = accept (socket_fd, NULL, NULL);
1094 if (conn_fd == -1) {
1095 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1097 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1104 socket_transport_send (void *data, int len)
1109 res = send (conn_fd, data, len, 0);
1110 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1118 * socket_transport_connect:
1120 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1123 socket_transport_connect (const char *address)
1125 #ifdef HAVE_GETADDRINFO
1126 struct addrinfo hints;
1127 struct addrinfo *result, *rp;
1129 struct hostent *result;
1131 int sfd = -1, s, res;
1132 char port_string [128];
1136 if (agent_config.address) {
1137 res = parse_address (agent_config.address, &host, &port);
1138 g_assert (res == 0);
1148 sprintf (port_string, "%d", port);
1150 mono_network_init ();
1152 /* Obtain address(es) matching host/port */
1153 #ifdef HAVE_GETADDRINFO
1154 memset (&hints, 0, sizeof (struct addrinfo));
1155 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1156 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1158 hints.ai_protocol = 0; /* Any protocol */
1160 s = getaddrinfo (host, port_string, &hints, &result);
1162 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1166 /* The PS3 doesn't even have _r or hstrerror () */
1167 result = gethostbyname (host);
1169 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1174 if (agent_config.server) {
1175 #ifdef HAVE_GETADDRINFO
1176 /* Wait for a connection */
1178 struct sockaddr_in addr;
1181 /* No address, generate one */
1182 sfd = socket (AF_INET, SOCK_STREAM, 0);
1185 /* This will bind the socket to a random port */
1186 res = listen (sfd, 16);
1188 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1193 addrlen = sizeof (addr);
1194 memset (&addr, 0, sizeof (addr));
1195 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1196 g_assert (res == 0);
1198 host = (char*)"127.0.0.1";
1199 port = ntohs (addr.sin_port);
1201 /* Emit the address to stdout */
1202 /* FIXME: Should print another interface, not localhost */
1203 printf ("%s:%d\n", host, port);
1205 /* Listen on the provided address */
1206 for (rp = result; rp != NULL; rp = rp->ai_next) {
1209 sfd = socket (rp->ai_family, rp->ai_socktype,
1214 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1217 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1221 res = listen (sfd, 16);
1230 * this function is not present on win2000 which we still support, and the
1231 * workaround described here:
1232 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1233 * only works with MSVC.
1235 #ifdef HAVE_GETADDRINFO
1236 freeaddrinfo (result);
1241 if (agent_config.defer)
1244 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1246 if (agent_config.timeout) {
1251 tv.tv_usec = agent_config.timeout * 1000;
1253 FD_SET (sfd, &readfds);
1254 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1256 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1261 conn_fd = socket_transport_accept (sfd);
1265 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1268 #endif /* HAVE_GETADDRINFO */
1270 /* Connect to the specified address */
1271 #ifdef HAVE_GETADDRINFO
1272 /* FIXME: Respect the timeout */
1273 for (rp = result; rp != NULL; rp = rp->ai_next) {
1274 sfd = socket (rp->ai_family, rp->ai_socktype,
1279 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1280 break; /* Success */
1286 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1290 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1292 g_assert_not_reached ();
1293 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1295 g_assert_not_reached ();
1301 /* See the comment above */
1302 #ifdef HAVE_GETADDRINFO
1303 freeaddrinfo (result);
1308 disconnected = !transport_handshake ();
1314 socket_transport_close1 (void)
1316 /* This will interrupt the agent thread */
1317 /* Close the read part only so it can still send back replies */
1318 /* Also shut down the connection listener so that we can exit normally */
1320 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1321 shutdown (conn_fd, SD_BOTH);
1322 shutdown (listen_fd, SD_BOTH);
1323 closesocket (listen_fd);
1325 shutdown (conn_fd, SHUT_RD);
1326 shutdown (listen_fd, SHUT_RDWR);
1332 socket_transport_close2 (void)
1335 shutdown (conn_fd, SD_BOTH);
1337 shutdown (conn_fd, SHUT_RDWR);
1342 register_socket_transport (void)
1344 DebuggerTransport trans;
1346 trans.name = "dt_socket";
1347 trans.connect = socket_transport_connect;
1348 trans.close1 = socket_transport_close1;
1349 trans.close2 = socket_transport_close2;
1350 trans.send = socket_transport_send;
1351 trans.recv = socket_transport_recv;
1353 register_transport (&trans);
1356 #endif /* DISABLE_SOCKET_TRANSPORT */
1362 #define MAX_TRANSPORTS 16
1364 static DebuggerTransport *transport;
1366 static DebuggerTransport transports [MAX_TRANSPORTS];
1367 static int ntransports;
1370 register_transport (DebuggerTransport *trans)
1372 g_assert (ntransports < MAX_TRANSPORTS);
1374 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1379 transport_init (void)
1383 #ifndef DISABLE_SOCKET_TRANSPORT
1384 register_socket_transport ();
1387 for (i = 0; i < ntransports; ++i) {
1388 if (!strcmp (agent_config.transport, transports [i].name))
1391 if (i == ntransports) {
1392 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1393 for (i = 0; i < ntransports; ++i)
1394 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1395 fprintf (stderr, "\n");
1398 transport = &transports [i];
1402 transport_connect (const char *address)
1404 transport->connect (address);
1408 transport_close1 (void)
1410 transport->close1 ();
1414 transport_close2 (void)
1416 transport->close2 ();
1420 transport_send (void *buf, int len)
1422 return transport->send (buf, len);
1426 transport_recv (void *buf, int len)
1428 return transport->recv (buf, len);
1432 transport_handshake (void)
1434 char handshake_msg [128];
1438 /* Write handshake message */
1439 sprintf (handshake_msg, "DWP-Handshake");
1441 res = transport_send (handshake_msg, strlen (handshake_msg));
1442 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1443 g_assert (res != -1);
1446 res = transport_recv (buf, strlen (handshake_msg));
1447 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1448 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1453 * To support older clients, the client sends its protocol version after connecting
1454 * using a command. Until that is received, default to our protocol version.
1456 major_version = MAJOR_VERSION;
1457 minor_version = MINOR_VERSION;
1458 protocol_version_set = FALSE;
1460 #ifndef DISABLE_SOCKET_TRANSPORT
1461 // FIXME: Move this somewhere else
1463 * Set TCP_NODELAY on the socket so the client receives events/command
1464 * results immediately.
1468 int result = setsockopt (conn_fd,
1473 g_assert (result >= 0);
1483 stop_debugger_thread (void)
1488 transport_close1 ();
1491 * Wait for the thread to exit.
1493 * If we continue with the shutdown without waiting for it, then the client might
1494 * not receive an answer to its last command like a resume.
1495 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1498 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1499 if (GetCurrentThreadId () != debugger_thread_id) {
1501 mono_mutex_lock (&debugger_thread_exited_mutex);
1502 if (!debugger_thread_exited) {
1504 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1505 mono_mutex_unlock (&debugger_thread_exited_mutex);
1507 mono_mutex_lock (&debugger_thread_exited_mutex);
1510 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1513 mono_mutex_unlock (&debugger_thread_exited_mutex);
1514 } while (!debugger_thread_exited);
1517 transport_close2 ();
1521 start_debugger_thread (void)
1525 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1526 g_assert (debugger_thread_handle);
1530 * Functions to decode protocol data
1534 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1537 g_assert (*endbuf <= limit);
1542 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1545 g_assert (*endbuf <= limit);
1547 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1550 static inline gint64
1551 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1553 guint32 high = decode_int (buf, &buf, limit);
1554 guint32 low = decode_int (buf, &buf, limit);
1558 return ((((guint64)high) << 32) | ((guint64)low));
1562 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1564 return decode_int (buf, endbuf, limit);
1568 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1570 int len = decode_int (buf, &buf, limit);
1578 s = g_malloc (len + 1);
1581 memcpy (s, buf, len);
1590 * Functions to encode protocol data
1594 guint8 *buf, *p, *end;
1598 buffer_init (Buffer *buf, int size)
1600 buf->buf = g_malloc (size);
1602 buf->end = buf->buf + size;
1606 buffer_make_room (Buffer *buf, int size)
1608 if (buf->end - buf->p < size) {
1609 int new_size = buf->end - buf->buf + size + 32;
1610 guint8 *p = g_realloc (buf->buf, new_size);
1611 size = buf->p - buf->buf;
1614 buf->end = buf->buf + new_size;
1619 buffer_add_byte (Buffer *buf, guint8 val)
1621 buffer_make_room (buf, 1);
1627 buffer_add_short (Buffer *buf, guint32 val)
1629 buffer_make_room (buf, 2);
1630 buf->p [0] = (val >> 8) & 0xff;
1631 buf->p [1] = (val >> 0) & 0xff;
1636 buffer_add_int (Buffer *buf, guint32 val)
1638 buffer_make_room (buf, 4);
1639 buf->p [0] = (val >> 24) & 0xff;
1640 buf->p [1] = (val >> 16) & 0xff;
1641 buf->p [2] = (val >> 8) & 0xff;
1642 buf->p [3] = (val >> 0) & 0xff;
1647 buffer_add_long (Buffer *buf, guint64 l)
1649 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1650 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1654 buffer_add_id (Buffer *buf, int id)
1656 buffer_add_int (buf, (guint64)id);
1660 buffer_add_data (Buffer *buf, guint8 *data, int len)
1662 buffer_make_room (buf, len);
1663 memcpy (buf->p, data, len);
1668 buffer_add_string (Buffer *buf, const char *str)
1673 buffer_add_int (buf, 0);
1676 buffer_add_int (buf, len);
1677 buffer_add_data (buf, (guint8*)str, len);
1682 buffer_free (Buffer *buf)
1688 send_packet (int command_set, int command, Buffer *data)
1694 id = InterlockedIncrement (&packet_id);
1696 len = data->p - data->buf + 11;
1697 buffer_init (&buf, len);
1698 buffer_add_int (&buf, len);
1699 buffer_add_int (&buf, id);
1700 buffer_add_byte (&buf, 0); /* flags */
1701 buffer_add_byte (&buf, command_set);
1702 buffer_add_byte (&buf, command);
1703 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1705 res = transport_send (buf.buf, len);
1713 send_reply_packet (int id, int error, Buffer *data)
1719 len = data->p - data->buf + 11;
1720 buffer_init (&buf, len);
1721 buffer_add_int (&buf, len);
1722 buffer_add_int (&buf, id);
1723 buffer_add_byte (&buf, 0x80); /* flags */
1724 buffer_add_byte (&buf, (error >> 8) & 0xff);
1725 buffer_add_byte (&buf, error);
1726 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1728 res = transport_send (buf.buf, len);
1740 * Represents an object accessible by the debugger client.
1743 /* Unique id used in the wire protocol to refer to objects */
1746 * A weakref gc handle pointing to the object. The gc handle is used to
1747 * detect if the object was garbage collected.
1752 /* Maps objid -> ObjRef */
1753 static GHashTable *objrefs;
1756 free_objref (gpointer value)
1760 mono_gchandle_free (o->handle);
1768 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1772 objrefs_cleanup (void)
1774 g_hash_table_destroy (objrefs);
1778 static GHashTable *obj_to_objref;
1781 * Return an ObjRef for OBJ.
1784 get_objref (MonoObject *obj)
1787 GSList *reflist = NULL, *l;
1793 mono_loader_lock ();
1796 obj_to_objref = g_hash_table_new (NULL, NULL);
1798 /* FIXME: The tables can grow indefinitely */
1800 if (mono_gc_is_moving ()) {
1802 * Objects can move, so use a hash table mapping hash codes to lists of
1803 * ObjRef structures.
1805 hash = mono_object_hash (obj);
1807 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1808 for (l = reflist; l; l = l->next) {
1810 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1811 mono_loader_unlock ();
1816 /* Use a hash table with masked pointers to internalize object references */
1817 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1818 /* ref might refer to a different object with the same addr which was GCd */
1819 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1820 mono_loader_unlock ();
1825 ref = g_new0 (ObjRef, 1);
1826 ref->id = InterlockedIncrement (&objref_id);
1827 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1829 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1831 if (mono_gc_is_moving ()) {
1832 reflist = g_slist_append (reflist, ref);
1833 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1835 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1838 mono_loader_unlock ();
1844 get_objid (MonoObject *obj)
1846 return get_objref (obj)->id;
1850 * Set OBJ to the object identified by OBJID.
1851 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1855 get_object_allow_null (int objid, MonoObject **obj)
1865 return ERR_INVALID_OBJECT;
1867 mono_loader_lock ();
1869 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1872 *obj = mono_gchandle_get_target (ref->handle);
1873 mono_loader_unlock ();
1875 return ERR_INVALID_OBJECT;
1878 mono_loader_unlock ();
1879 return ERR_INVALID_OBJECT;
1884 get_object (int objid, MonoObject **obj)
1886 int err = get_object_allow_null (objid, obj);
1891 return ERR_INVALID_OBJECT;
1896 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1898 return decode_id (buf, endbuf, limit);
1902 buffer_add_objid (Buffer *buf, MonoObject *o)
1904 buffer_add_id (buf, get_objid (o));
1923 * Represents a runtime structure accessible to the debugger client
1926 /* Unique id used in the wire protocol */
1928 /* Domain of the runtime structure, NULL if the domain was unloaded */
1935 MonoAssembly *assembly;
1936 MonoClassField *field;
1938 MonoProperty *property;
1943 /* Maps runtime structure -> Id */
1944 GHashTable *val_to_id [ID_NUM];
1945 /* Classes whose class load event has been sent */
1946 GHashTable *loaded_classes;
1947 /* Maps MonoClass->GPtrArray of file names */
1948 GHashTable *source_files;
1949 /* Maps source file basename -> GSList of classes */
1950 GHashTable *source_file_to_class;
1951 /* Same with ignore-case */
1952 GHashTable *source_file_to_class_ignorecase;
1956 static GPtrArray *ids [ID_NUM];
1963 for (i = 0; i < ID_NUM; ++i)
1964 ids [i] = g_ptr_array_new ();
1972 for (i = 0; i < ID_NUM; ++i) {
1974 for (j = 0; j < ids [i]->len; ++j)
1975 g_free (g_ptr_array_index (ids [i], j));
1976 g_ptr_array_free (ids [i], TRUE);
1983 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1985 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1987 GHashTableIter iter;
1988 GPtrArray *file_names;
1993 for (i = 0; i < ID_NUM; ++i)
1994 if (info->val_to_id [i])
1995 g_hash_table_destroy (info->val_to_id [i]);
1996 g_hash_table_destroy (info->loaded_classes);
1998 g_hash_table_iter_init (&iter, info->source_files);
1999 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2000 for (i = 0; i < file_names->len; ++i)
2001 g_free (g_ptr_array_index (file_names, i));
2002 g_ptr_array_free (file_names, TRUE);
2005 g_hash_table_iter_init (&iter, info->source_file_to_class);
2006 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2011 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2012 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2020 domain_jit_info (domain)->agent_info = NULL;
2022 /* Clear ids referencing structures in the domain */
2023 for (i = 0; i < ID_NUM; ++i) {
2025 for (j = 0; j < ids [i]->len; ++j) {
2026 Id *id = g_ptr_array_index (ids [i], j);
2027 if (id->domain == domain)
2033 mono_loader_lock ();
2034 g_hash_table_remove (domains, domain);
2035 mono_loader_unlock ();
2038 static AgentDomainInfo*
2039 get_agent_domain_info (MonoDomain *domain)
2041 AgentDomainInfo *info = NULL;
2043 mono_domain_lock (domain);
2045 info = domain_jit_info (domain)->agent_info;
2047 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2048 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2049 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2050 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2051 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2054 mono_domain_unlock (domain);
2060 get_id (MonoDomain *domain, IdType type, gpointer val)
2063 AgentDomainInfo *info;
2068 mono_loader_lock ();
2070 mono_domain_lock (domain);
2072 info = get_agent_domain_info (domain);
2074 if (info->val_to_id [type] == NULL)
2075 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2077 id = g_hash_table_lookup (info->val_to_id [type], val);
2079 mono_domain_unlock (domain);
2080 mono_loader_unlock ();
2084 id = g_new0 (Id, 1);
2086 id->id = ids [type]->len + 1;
2087 id->domain = domain;
2090 g_hash_table_insert (info->val_to_id [type], val, id);
2092 mono_domain_unlock (domain);
2094 g_ptr_array_add (ids [type], id);
2096 mono_loader_unlock ();
2101 static inline gpointer
2102 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2106 int id = decode_id (buf, endbuf, limit);
2115 // FIXME: error handling
2116 mono_loader_lock ();
2117 g_assert (id > 0 && id <= ids [type]->len);
2119 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2120 mono_loader_unlock ();
2122 if (res->domain == NULL) {
2123 *err = ERR_UNLOADED;
2128 *domain = res->domain;
2130 return res->data.val;
2134 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2136 buffer_add_id (buf, get_id (domain, type, val));
2139 static inline MonoClass*
2140 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2142 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2145 static inline MonoAssembly*
2146 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2148 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2151 static inline MonoImage*
2152 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2154 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2157 static inline MonoMethod*
2158 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2160 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2163 static inline MonoClassField*
2164 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2166 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2169 static inline MonoDomain*
2170 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2172 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2175 static inline MonoProperty*
2176 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2178 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2182 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2184 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2188 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2190 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2194 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2196 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2200 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2202 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2206 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2208 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2212 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2214 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2218 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2220 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2223 static void invoke_method (void);
2230 * save_thread_context:
2232 * Set CTX as the current threads context which is used for computing stack traces.
2233 * This function is signal-safe.
2236 save_thread_context (MonoContext *ctx)
2238 DebuggerTlsData *tls;
2240 tls = mono_native_tls_get_value (debugger_tls_id);
2244 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2246 mono_thread_state_init_from_current (&tls->context);
2249 /* The number of times the runtime is suspended */
2250 static gint32 suspend_count;
2252 /* Number of threads suspended */
2254 * If this is equal to the size of thread_to_tls, the runtime is considered
2257 static gint32 threads_suspend_count;
2259 static mono_mutex_t suspend_mutex;
2261 /* Cond variable used to wait for suspend_count becoming 0 */
2262 static mono_cond_t suspend_cond;
2264 /* Semaphore used to wait for a thread becoming suspended */
2265 static MonoSemType suspend_sem;
2270 mono_mutex_init (&suspend_mutex, NULL);
2271 mono_cond_init (&suspend_cond, NULL);
2272 MONO_SEM_INIT (&suspend_sem, 0);
2277 StackFrameInfo last_frame;
2278 gboolean last_frame_set;
2281 } GetLastFrameUserData;
2284 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2286 GetLastFrameUserData *data = user_data;
2288 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2291 if (!data->last_frame_set) {
2292 /* Store the last frame */
2293 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2294 data->last_frame_set = TRUE;
2297 /* Store the context/lmf for the frame above the last frame */
2298 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2299 data->lmf = info->lmf;
2307 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2308 * INFO is set, process the thread described by INFO.
2309 * This should be signal safe.
2312 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2316 MonoNativeThreadId tid;
2319 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2320 * guarantee the signal handler will be called that many times. Instead of tracking
2321 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2322 * has been requested that hasn't been handled yet, otherwise we can have threads
2323 * refuse to die when VM_EXIT is called
2325 #if defined(__APPLE__)
2326 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2330 * We use interrupt_count to determine whenever this interrupt should be processed
2331 * by us or the normal interrupt processing code in the signal handler.
2332 * There is no race here with notify_thread (), since the signal is sent after
2333 * incrementing interrupt_count.
2335 if (tls->interrupt_count == 0)
2338 InterlockedDecrement (&tls->interrupt_count);
2342 ip = mono_arch_ip_from_context (sigctx);
2344 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2349 tid = mono_thread_info_get_tid (info);
2351 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2353 // FIXME: Races when the thread leaves managed code before hitting a single step
2357 /* Running managed code, will be suspended by the single step code */
2358 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2362 * Running native code, will be suspended when it returns to/enters
2363 * managed code. Treat it as already suspended.
2364 * This might interrupt the code in process_single_step_inner (), we use the
2365 * tls->suspending flag to avoid races when that happens.
2367 if (!tls->suspended && !tls->suspending) {
2369 GetLastFrameUserData data;
2371 // FIXME: printf is not signal safe, but this is only used during
2372 // debugger debugging
2374 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2375 //save_thread_context (&ctx);
2378 /* Already terminated */
2381 tls->context.valid = FALSE;
2384 * We are in a difficult position: we want to be able to provide stack
2385 * traces for this thread, but we can't use the current ctx+lmf, since
2386 * the thread is still running, so it might return to managed code,
2387 * making these invalid.
2388 * So we start a stack walk and save the first frame, along with the
2389 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2390 * suspended when it returns to managed code, so the parent's ctx should
2393 data.last_frame_set = FALSE;
2395 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2397 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2398 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2399 * since we are not in a JITted method.
2401 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2403 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2405 if (data.last_frame_set) {
2406 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2407 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2409 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2412 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2413 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2414 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2416 /* No managed frames */
2417 tls->async_state.valid = FALSE;
2419 mono_memory_barrier ();
2421 tls->suspended = TRUE;
2422 MONO_SEM_POST (&suspend_sem);
2429 * mono_debugger_agent_thread_interrupt:
2431 * Called by the abort signal handler.
2432 * Should be signal safe.
2435 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2437 DebuggerTlsData *tls;
2442 tls = mono_native_tls_get_value (debugger_tls_id);
2446 return thread_interrupt (tls, NULL, sigctx, ji);
2450 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2453 mono_debugger_agent_thread_interrupt (NULL, NULL);
2455 #endif /* HOST_WIN32 */
2458 * reset_native_thread_suspend_state:
2460 * Reset the suspended flag and state on native threads
2463 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2465 DebuggerTlsData *tls = value;
2467 if (!tls->really_suspended && tls->suspended) {
2468 tls->suspended = FALSE;
2470 * The thread might still be running if it was executing native code, so the state won't be invalided by
2471 * suspend_current ().
2473 tls->context.valid = FALSE;
2474 tls->async_state.valid = FALSE;
2475 invalidate_frames (tls);
2482 * Notify a thread that it needs to suspend.
2485 notify_thread (gpointer key, gpointer value, gpointer user_data)
2487 MonoInternalThread *thread = key;
2488 DebuggerTlsData *tls = value;
2489 gsize tid = thread->tid;
2492 if (GetCurrentThreadId () == tid || tls->terminated)
2495 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2498 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2499 * guarantee the signal handler will be called that many times. Instead of tracking
2500 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2501 * has been requested that hasn't been handled yet, otherwise we can have threads
2502 * refuse to die when VM_EXIT is called
2504 #if defined(__APPLE__)
2505 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2509 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2510 * of things like breaking waits etc. which we don't want.
2512 InterlockedIncrement (&tls->interrupt_count);
2515 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2517 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2519 if (mono_thread_info_new_interrupt_enabled ()) {
2520 MonoThreadInfo *info;
2523 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2526 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2528 thread_interrupt (tls, info, NULL, ji);
2530 mono_thread_info_resume (mono_thread_info_get_tid (info));
2532 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2535 * Attached thread which died without detaching.
2537 tls->terminated = TRUE;
2543 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2545 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2548 if (mono_loader_lock_is_owned_by_self ()) {
2550 * Shortcut for the check in suspend_current (). This speeds up processing
2551 * when executing long running code inside the loader lock, i.e. assembly load
2557 if (debugger_thread_id == GetCurrentThreadId ())
2560 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2561 if (suspend_count - tls->resume_count > 0)
2562 tls->suspending = TRUE;
2564 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2566 if (suspend_count - tls->resume_count == 0) {
2568 * We are executing a single threaded invoke but the single step for
2569 * suspending is still active.
2570 * FIXME: This slows down single threaded invokes.
2572 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2576 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2578 /* Can't suspend in these methods */
2579 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2582 save_thread_context (ctx);
2590 * Increase the suspend count of the VM. While the suspend count is greater
2591 * than 0, runtime threads are suspended at certain points during execution.
2596 mono_loader_lock ();
2598 mono_mutex_lock (&suspend_mutex);
2602 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2604 if (suspend_count == 1) {
2605 // FIXME: Is it safe to call this inside the lock ?
2606 start_single_stepping ();
2607 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2610 mono_mutex_unlock (&suspend_mutex);
2612 mono_loader_unlock ();
2618 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2626 g_assert (debugger_thread_id == GetCurrentThreadId ());
2628 mono_loader_lock ();
2630 mono_mutex_lock (&suspend_mutex);
2632 g_assert (suspend_count > 0);
2635 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2637 if (suspend_count == 0) {
2638 // FIXME: Is it safe to call this inside the lock ?
2639 stop_single_stepping ();
2640 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2643 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2644 err = mono_cond_broadcast (&suspend_cond);
2645 g_assert (err == 0);
2647 mono_mutex_unlock (&suspend_mutex);
2648 //g_assert (err == 0);
2650 mono_loader_unlock ();
2656 * Resume just one thread.
2659 resume_thread (MonoInternalThread *thread)
2662 DebuggerTlsData *tls;
2664 g_assert (debugger_thread_id == GetCurrentThreadId ());
2666 mono_loader_lock ();
2668 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2671 mono_mutex_lock (&suspend_mutex);
2673 g_assert (suspend_count > 0);
2675 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2677 tls->resume_count += suspend_count;
2680 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2681 * but only the one whose resume_count field is > 0 will be resumed.
2683 err = mono_cond_broadcast (&suspend_cond);
2684 g_assert (err == 0);
2686 mono_mutex_unlock (&suspend_mutex);
2687 //g_assert (err == 0);
2689 mono_loader_unlock ();
2693 invalidate_frames (DebuggerTlsData *tls)
2698 tls = mono_native_tls_get_value (debugger_tls_id);
2701 for (i = 0; i < tls->frame_count; ++i) {
2702 if (tls->frames [i]->jit)
2703 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2704 g_free (tls->frames [i]);
2706 g_free (tls->frames);
2707 tls->frame_count = 0;
2714 * Suspend the current thread until the runtime is resumed. If the thread has a
2715 * pending invoke, then the invoke is executed before this function returns.
2718 suspend_current (void)
2721 DebuggerTlsData *tls;
2723 g_assert (debugger_thread_id != GetCurrentThreadId ());
2725 if (mono_loader_lock_is_owned_by_self ()) {
2727 * If we own the loader mutex, can't suspend until we release it, since the
2728 * whole runtime can deadlock otherwise.
2733 tls = mono_native_tls_get_value (debugger_tls_id);
2736 mono_mutex_lock (&suspend_mutex);
2738 tls->suspending = FALSE;
2739 tls->really_suspended = TRUE;
2741 if (!tls->suspended) {
2742 tls->suspended = TRUE;
2743 MONO_SEM_POST (&suspend_sem);
2746 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2748 while (suspend_count - tls->resume_count > 0) {
2750 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2752 mono_mutex_unlock (&suspend_mutex);
2754 mono_mutex_lock (&suspend_mutex);
2760 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2761 g_assert (err == 0);
2765 tls->suspended = FALSE;
2766 tls->really_suspended = FALSE;
2768 threads_suspend_count --;
2770 mono_mutex_unlock (&suspend_mutex);
2772 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2774 if (tls->pending_invoke) {
2775 /* Save the original context */
2776 tls->pending_invoke->has_ctx = TRUE;
2777 tls->pending_invoke->ctx = tls->context.ctx;
2782 /* The frame info becomes invalid after a resume */
2783 tls->context.valid = FALSE;
2784 tls->async_state.valid = FALSE;
2785 invalidate_frames (tls);
2789 count_thread (gpointer key, gpointer value, gpointer user_data)
2791 DebuggerTlsData *tls = value;
2793 if (!tls->suspended && !tls->terminated)
2794 *(int*)user_data = *(int*)user_data + 1;
2798 count_threads_to_wait_for (void)
2802 mono_loader_lock ();
2803 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2804 mono_loader_unlock ();
2812 * Wait until the runtime is completely suspended.
2815 wait_for_suspend (void)
2817 int nthreads, nwait, err;
2818 gboolean waited = FALSE;
2820 // FIXME: Threads starting/stopping ?
2821 mono_loader_lock ();
2822 nthreads = mono_g_hash_table_size (thread_to_tls);
2823 mono_loader_unlock ();
2826 nwait = count_threads_to_wait_for ();
2828 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2829 err = MONO_SEM_WAIT (&suspend_sem);
2830 g_assert (err == 0);
2838 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2844 * Return whenever the runtime is suspended.
2849 return count_threads_to_wait_for () == 0;
2852 static MonoSeqPointInfo*
2853 get_seq_points (MonoDomain *domain, MonoMethod *method)
2855 MonoSeqPointInfo *seq_points;
2857 mono_domain_lock (domain);
2858 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2859 if (!seq_points && method->is_inflated) {
2860 /* generic sharing + aot */
2861 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2863 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2865 mono_domain_unlock (domain);
2870 static MonoSeqPointInfo*
2871 find_seq_points (MonoDomain *domain, MonoMethod *method)
2873 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2876 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2877 g_assert (seq_points);
2883 * find_next_seq_point_for_native_offset:
2885 * Find the first sequence point after NATIVE_OFFSET.
2888 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2890 MonoSeqPointInfo *seq_points;
2893 seq_points = find_seq_points (domain, method);
2897 for (i = 0; i < seq_points->len; ++i) {
2898 if (seq_points->seq_points [i].native_offset >= native_offset)
2899 return &seq_points->seq_points [i];
2906 * find_prev_seq_point_for_native_offset:
2908 * Find the first sequence point before NATIVE_OFFSET.
2911 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2913 MonoSeqPointInfo *seq_points;
2916 seq_points = find_seq_points (domain, method);
2920 for (i = seq_points->len - 1; i >= 0; --i) {
2921 if (seq_points->seq_points [i].native_offset <= native_offset)
2922 return &seq_points->seq_points [i];
2931 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2932 * should be the location of a sequence point.
2934 static G_GNUC_UNUSED SeqPoint*
2935 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2937 MonoSeqPointInfo *seq_points;
2942 seq_points = get_seq_points (domain, method);
2947 for (i = 0; i < seq_points->len; ++i) {
2948 if (seq_points->seq_points [i].il_offset == il_offset)
2949 return &seq_points->seq_points [i];
2956 DebuggerTlsData *tls;
2958 } ComputeFramesUserData;
2961 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2963 ComputeFramesUserData *ud = user_data;
2965 MonoMethod *method, *actual_method, *api_method;
2969 if (info->type != FRAME_TYPE_MANAGED) {
2970 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2971 /* Mark the last frame as an invoke frame */
2973 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2979 method = info->ji->method;
2981 method = info->method;
2982 actual_method = info->actual_method;
2983 api_method = method;
2988 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
2991 if (info->il_offset == -1) {
2992 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
2993 if (ud->frames == NULL) {
2994 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
2996 info->il_offset = sp->il_offset;
2998 if (info->il_offset == -1)
2999 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3002 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));
3004 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3005 if (!CHECK_PROTOCOL_VERSION (2, 17))
3006 /* Older clients can't handle this flag */
3008 api_method = mono_marshal_method_from_wrapper (method);
3011 actual_method = api_method;
3012 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3015 frame = g_new0 (StackFrame, 1);
3016 frame->method = method;
3017 frame->actual_method = actual_method;
3018 frame->api_method = api_method;
3019 frame->il_offset = info->il_offset;
3020 frame->native_offset = info->native_offset;
3021 frame->flags = flags;
3022 if (info->reg_locations)
3023 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3026 frame->has_ctx = TRUE;
3028 frame->domain = info->domain;
3030 ud->frames = g_slist_append (ud->frames, frame);
3036 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3038 ComputeFramesUserData *ud = user_data;
3041 * 'tls->filter_ctx' is the location of the throw site.
3043 * mono_walk_stack() will never actually hit the throw site, but unwind
3044 * directly from the filter to the call site; we abort stack unwinding here
3045 * once this happens and resume from the throw site.
3048 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3051 return process_frame (info, ctx, user_data);
3055 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3057 ComputeFramesUserData user_data;
3059 int i, findex, new_frame_count;
3060 StackFrame **new_frames, *f;
3061 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3063 // FIXME: Locking on tls
3064 if (tls->frames && tls->frames_up_to_date)
3067 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3069 user_data.tls = tls;
3070 user_data.frames = NULL;
3071 if (tls->terminated) {
3072 tls->frame_count = 0;
3074 } if (!tls->really_suspended && tls->async_state.valid) {
3075 /* Have to use the state saved by the signal handler */
3076 process_frame (&tls->async_last_frame, NULL, &user_data);
3077 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3078 } else if (tls->filter_state.valid) {
3080 * We are inside an exception filter.
3082 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3084 if (tls->context.valid)
3085 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3087 * After that, we resume unwinding from the location where the exception has been thrown.
3089 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3090 } else if (tls->context.valid) {
3091 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3094 tls->frame_count = 0;
3098 new_frame_count = g_slist_length (user_data.frames);
3099 new_frames = g_new0 (StackFrame*, new_frame_count);
3101 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3105 * Reuse the id for already existing stack frames, so invokes don't invalidate
3106 * the still valid stack frames.
3108 for (i = 0; i < tls->frame_count; ++i) {
3109 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3110 f->id = tls->frames [i]->id;
3115 if (i >= tls->frame_count)
3116 f->id = InterlockedIncrement (&frame_id);
3118 new_frames [findex ++] = f;
3121 g_slist_free (user_data.frames);
3123 invalidate_frames (tls);
3125 tls->frames = new_frames;
3126 tls->frame_count = new_frame_count;
3127 tls->frames_up_to_date = TRUE;
3131 * GHFunc to emit an appdomain creation event
3132 * @param key Don't care
3133 * @param value A loaded appdomain
3134 * @param user_data Don't care
3137 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3139 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3140 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3144 * GHFunc to emit a thread start event
3145 * @param key A thread id
3146 * @param value A thread object
3147 * @param user_data Don't care
3150 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3152 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3153 process_profiler_event (EVENT_KIND_THREAD_START, value);
3157 * GFunc to emit an assembly load event
3158 * @param value A loaded assembly
3159 * @param user_data Don't care
3162 emit_assembly_load (gpointer value, gpointer user_data)
3164 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3168 * GFunc to emit a type load event
3169 * @param value A loaded type
3170 * @param user_data Don't care
3173 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3175 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3179 strdup_tolower (char *s)
3184 for (p = s2; *p; ++p)
3194 * create_event_list:
3196 * Return a list of event request ids matching EVENT, starting from REQS, which
3197 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3199 * We return request ids, instead of requests, to simplify threading, since
3200 * requests could be deleted anytime when the loader lock is not held.
3201 * LOCKING: Assumes the loader lock is held.
3204 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3207 GSList *events = NULL;
3209 *suspend_policy = SUSPEND_POLICY_NONE;
3212 reqs = event_requests;
3217 for (i = 0; i < reqs->len; ++i) {
3218 EventRequest *req = g_ptr_array_index (reqs, i);
3219 if (req->event_kind == event) {
3220 gboolean filtered = FALSE;
3223 for (j = 0; j < req->nmodifiers; ++j) {
3224 Modifier *mod = &req->modifiers [j];
3226 if (mod->kind == MOD_KIND_COUNT) {
3228 if (mod->data.count > 0) {
3229 if (mod->data.count > 0) {
3231 if (mod->data.count == 0)
3235 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3236 if (mod->data.thread != mono_thread_internal_current ())
3238 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3239 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3241 if (ei->caught && !mod->caught)
3243 if (!ei->caught && !mod->uncaught)
3245 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3247 gboolean found = FALSE;
3248 MonoAssembly **assemblies = mod->data.assemblies;
3251 for (k = 0; assemblies [k]; ++k)
3252 if (assemblies [k] == ji->method->klass->image->assembly)
3257 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3258 gpointer iter = NULL;
3260 MonoDebugSourceInfo *sinfo;
3261 char *source_file, *s;
3262 gboolean found = FALSE;
3264 GPtrArray *source_file_list;
3266 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3267 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3270 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL);
3271 for (i = 0; i < source_file_list->len; ++i) {
3272 sinfo = g_ptr_array_index (source_file_list, i);
3274 * Do a case-insesitive match by converting the file name to
3277 s = strdup_tolower (sinfo->source_file);
3278 if (g_hash_table_lookup (mod->data.source_files, s))
3282 g_ptr_array_free (source_file_list, TRUE);
3287 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3290 s = mono_type_full_name (&ei->klass->byval_arg);
3291 if (!g_hash_table_lookup (mod->data.type_names, s))
3294 } else if (mod->kind == MOD_KIND_STEP) {
3295 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3296 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3297 !strcmp (ji->method->name, ".cctor"))
3303 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3304 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3309 /* Send a VM START/DEATH event by default */
3310 if (event == EVENT_KIND_VM_START)
3311 events = g_slist_append (events, GINT_TO_POINTER (0));
3312 if (event == EVENT_KIND_VM_DEATH)
3313 events = g_slist_append (events, GINT_TO_POINTER (0));
3318 static G_GNUC_UNUSED const char*
3319 event_to_string (EventKind event)
3322 case EVENT_KIND_VM_START: return "VM_START";
3323 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3324 case EVENT_KIND_THREAD_START: return "THREAD_START";
3325 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3326 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3327 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3328 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3329 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3330 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3331 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3332 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3333 case EVENT_KIND_STEP: return "STEP";
3334 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3335 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3336 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3337 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3338 case EVENT_KIND_USER_LOG: return "USER_LOG";
3340 g_assert_not_reached ();
3347 * Send an event to the client, suspending the vm if needed.
3348 * LOCKING: Since this can suspend the calling thread, no locks should be held
3350 * The EVENTS list is freed by this function.
3353 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3357 MonoDomain *domain = mono_domain_get ();
3358 MonoThread *thread = NULL;
3359 gboolean send_success = FALSE;
3364 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3368 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3369 // FIXME: We miss those events
3370 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3374 if (vm_death_event_sent) {
3375 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3379 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3380 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3385 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3389 if (event == EVENT_KIND_KEEPALIVE)
3390 suspend_policy = SUSPEND_POLICY_NONE;
3395 if (agent_config.defer) {
3396 /* Make sure the thread id is always set when doing deferred debugging */
3397 if (debugger_thread_id == GetCurrentThreadId ()) {
3398 /* Don't suspend on events from the debugger thread */
3399 suspend_policy = SUSPEND_POLICY_NONE;
3400 thread = mono_thread_get_main ();
3402 else thread = mono_thread_current ();
3404 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3405 // FIXME: Send these with a NULL thread, don't suspend the current thread
3410 nevents = g_slist_length (events);
3411 buffer_init (&buf, 128);
3412 buffer_add_byte (&buf, suspend_policy);
3413 buffer_add_int (&buf, nevents);
3415 for (l = events; l; l = l->next) {
3416 buffer_add_byte (&buf, event); // event kind
3417 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3422 thread = mono_thread_current ();
3424 if (event == EVENT_KIND_VM_START && arg != NULL)
3427 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3430 case EVENT_KIND_THREAD_START:
3431 case EVENT_KIND_THREAD_DEATH:
3433 case EVENT_KIND_APPDOMAIN_CREATE:
3434 case EVENT_KIND_APPDOMAIN_UNLOAD:
3435 buffer_add_domainid (&buf, arg);
3437 case EVENT_KIND_METHOD_ENTRY:
3438 case EVENT_KIND_METHOD_EXIT:
3439 buffer_add_methodid (&buf, domain, arg);
3441 case EVENT_KIND_ASSEMBLY_LOAD:
3442 case EVENT_KIND_ASSEMBLY_UNLOAD:
3443 buffer_add_assemblyid (&buf, domain, arg);
3445 case EVENT_KIND_TYPE_LOAD:
3446 buffer_add_typeid (&buf, domain, arg);
3448 case EVENT_KIND_BREAKPOINT:
3449 case EVENT_KIND_STEP:
3450 buffer_add_methodid (&buf, domain, arg);
3451 buffer_add_long (&buf, il_offset);
3453 case EVENT_KIND_VM_START:
3454 buffer_add_domainid (&buf, mono_get_root_domain ());
3456 case EVENT_KIND_VM_DEATH:
3458 case EVENT_KIND_EXCEPTION: {
3459 EventInfo *ei = arg;
3460 buffer_add_objid (&buf, ei->exc);
3463 case EVENT_KIND_USER_BREAK:
3465 case EVENT_KIND_USER_LOG: {
3466 EventInfo *ei = arg;
3467 buffer_add_int (&buf, ei->level);
3468 buffer_add_string (&buf, ei->category ? ei->category : "");
3469 buffer_add_string (&buf, ei->message ? ei->message : "");
3472 case EVENT_KIND_KEEPALIVE:
3473 suspend_policy = SUSPEND_POLICY_NONE;
3476 g_assert_not_reached ();
3480 if (event == EVENT_KIND_VM_START) {
3481 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3482 if (!agent_config.defer)
3483 start_debugger_thread ();
3486 if (event == EVENT_KIND_VM_DEATH) {
3487 vm_death_event_sent = TRUE;
3488 suspend_policy = SUSPEND_POLICY_NONE;
3491 if (mono_runtime_is_shutting_down ())
3492 suspend_policy = SUSPEND_POLICY_NONE;
3494 if (suspend_policy != SUSPEND_POLICY_NONE) {
3496 * Save the thread context and start suspending before sending the packet,
3497 * since we could be receiving the resume request before send_packet ()
3500 save_thread_context (ctx);
3504 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3508 g_slist_free (events);
3511 if (!send_success) {
3512 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3516 if (event == EVENT_KIND_VM_START) {
3517 vm_start_event_sent = TRUE;
3520 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3522 switch (suspend_policy) {
3523 case SUSPEND_POLICY_NONE:
3525 case SUSPEND_POLICY_ALL:
3528 case SUSPEND_POLICY_EVENT_THREAD:
3532 g_assert_not_reached ();
3537 process_profiler_event (EventKind event, gpointer arg)
3541 EventInfo ei, *ei_arg = NULL;
3543 if (event == EVENT_KIND_TYPE_LOAD) {
3548 mono_loader_lock ();
3549 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3550 mono_loader_unlock ();
3552 process_event (event, arg, 0, NULL, events, suspend_policy);
3556 runtime_initialized (MonoProfiler *prof)
3558 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3559 if (agent_config.defer)
3560 start_debugger_thread ();
3564 runtime_shutdown (MonoProfiler *prof)
3566 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3568 mono_debugger_agent_cleanup ();
3572 thread_startup (MonoProfiler *prof, uintptr_t tid)
3574 MonoInternalThread *thread = mono_thread_internal_current ();
3575 MonoInternalThread *old_thread;
3576 DebuggerTlsData *tls;
3578 if (tid == debugger_thread_id)
3581 g_assert (thread->tid == tid);
3583 mono_loader_lock ();
3584 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3585 mono_loader_unlock ();
3587 if (thread == old_thread) {
3589 * For some reason, thread_startup () might be called for the same thread
3590 * multiple times (attach ?).
3592 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3596 * thread_end () might not be called for some threads, and the tid could
3599 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3600 mono_loader_lock ();
3601 mono_g_hash_table_remove (thread_to_tls, old_thread);
3602 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3603 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3604 mono_loader_unlock ();
3608 tls = mono_native_tls_get_value (debugger_tls_id);
3610 // FIXME: Free this somewhere
3611 tls = g_new0 (DebuggerTlsData, 1);
3612 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3613 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3614 tls->thread = thread;
3615 mono_native_tls_set_value (debugger_tls_id, tls);
3617 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3619 mono_loader_lock ();
3620 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3621 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3622 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3623 mono_loader_unlock ();
3625 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3628 * suspend_vm () could have missed this thread, so wait for a resume.
3634 thread_end (MonoProfiler *prof, uintptr_t tid)
3636 MonoInternalThread *thread;
3637 DebuggerTlsData *tls = NULL;
3639 mono_loader_lock ();
3640 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3642 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3643 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3645 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3646 tls->terminated = TRUE;
3647 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3648 MONO_GC_UNREGISTER_ROOT (tls->thread);
3652 mono_loader_unlock ();
3654 /* We might be called for threads started before we registered the start callback */
3656 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3657 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3662 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3664 mono_loader_lock ();
3665 g_hash_table_insert (domains, domain, domain);
3666 mono_loader_unlock ();
3668 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3672 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3674 clear_breakpoints_for_domain (domain);
3676 mono_loader_lock ();
3677 /* Invalidate each thread's frame stack */
3678 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3679 mono_loader_unlock ();
3681 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3685 * invalidate_each_thread:
3687 * A GHFunc to invalidate frames.
3688 * value must be a DebuggerTlsData*
3691 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3693 invalidate_frames (value);
3697 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3699 /* Sent later in jit_end () */
3700 mono_loader_lock ();
3701 g_ptr_array_add (pending_assembly_loads, assembly);
3702 mono_loader_unlock ();
3706 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3708 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3710 clear_event_requests_for_assembly (assembly);
3711 clear_types_for_assembly (assembly);
3715 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3717 #if defined(HOST_WIN32) && !defined(__GNUC__)
3718 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3720 gpointer stackptr = __builtin_frame_address (1);
3722 MonoInternalThread *thread = mono_thread_internal_current ();
3723 DebuggerTlsData *tls;
3725 mono_loader_lock ();
3727 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3728 /* Could be the debugger thread with assembly/type load hooks */
3730 tls->invoke_addr = stackptr;
3732 mono_loader_unlock ();
3736 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3739 #if defined(HOST_WIN32) && !defined(__GNUC__)
3740 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3742 gpointer stackptr = __builtin_frame_address (1);
3745 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3749 * We need to stop single stepping when exiting a runtime invoke, since if it is
3750 * a step out, it may return to native code, and thus never end.
3752 mono_loader_lock ();
3753 ss_invoke_addr = NULL;
3755 for (i = 0; i < event_requests->len; ++i) {
3756 EventRequest *req = g_ptr_array_index (event_requests, i);
3758 if (req->event_kind == EVENT_KIND_STEP) {
3759 ss_destroy (req->info);
3760 g_ptr_array_remove_index_fast (event_requests, i);
3765 mono_loader_unlock ();
3769 send_type_load (MonoClass *klass)
3771 gboolean type_load = FALSE;
3772 MonoDomain *domain = mono_domain_get ();
3773 AgentDomainInfo *info = NULL;
3775 mono_loader_lock ();
3776 mono_domain_lock (domain);
3778 info = get_agent_domain_info (domain);
3780 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3782 g_hash_table_insert (info->loaded_classes, klass, klass);
3785 mono_domain_unlock (domain);
3786 mono_loader_unlock ();
3788 emit_type_load (klass, klass, NULL);
3792 * Emit load events for all types currently loaded in the domain.
3793 * Takes the loader and domain locks.
3794 * user_data is unused.
3797 send_types_for_domain (MonoDomain *domain, void *user_data)
3799 AgentDomainInfo *info = NULL;
3801 mono_loader_lock ();
3802 mono_domain_lock (domain);
3803 info = get_agent_domain_info (domain);
3805 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3806 mono_domain_unlock (domain);
3807 mono_loader_unlock ();
3811 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3814 * We emit type load events when the first method of the type is JITted,
3815 * since the class load profiler callbacks might be called with the
3816 * loader lock held. They could also occur in the debugger thread.
3817 * Same for assembly load events.
3820 MonoAssembly *assembly = NULL;
3822 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3823 mono_loader_lock ();
3824 if (pending_assembly_loads->len > 0) {
3825 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3826 g_ptr_array_remove_index (pending_assembly_loads, 0);
3828 mono_loader_unlock ();
3831 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3837 send_type_load (method->klass);
3840 add_pending_breakpoints (method, jinfo);
3844 * BREAKPOINTS/SINGLE STEPPING
3848 * Contains information about an inserted breakpoint.
3851 long il_offset, native_offset;
3856 } BreakpointInstance;
3859 * Contains generic information about a breakpoint.
3863 * The method where the breakpoint is placed. Can be NULL in which case it
3864 * is inserted into every method. This is used to implement method entry/
3865 * exit events. Can be a generic method definition, in which case the
3866 * breakpoint is inserted into every instance.
3872 * A list of BreakpointInstance structures describing where the breakpoint
3873 * was inserted. There could be more than one because of
3874 * generics/appdomains/method entry/exit.
3876 GPtrArray *children;
3879 /* List of breakpoints */
3880 static GPtrArray *breakpoints;
3881 /* Maps breakpoint locations to the number of breakpoints at that location */
3882 static GHashTable *bp_locs;
3885 breakpoints_init (void)
3887 breakpoints = g_ptr_array_new ();
3888 bp_locs = g_hash_table_new (NULL, NULL);
3892 * insert_breakpoint:
3894 * Insert the breakpoint described by BP into the method described by
3898 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3901 BreakpointInstance *inst;
3902 SeqPoint *sp = NULL;
3905 mono_error_init (error);
3907 for (i = 0; i < seq_points->len; ++i) {
3908 sp = &seq_points->seq_points [i];
3910 if (sp->il_offset == bp->il_offset)
3914 if (i == seq_points->len) {
3916 * The set of IL offsets with seq points doesn't completely match the
3917 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3919 for (i = 0; i < seq_points->len; ++i) {
3920 sp = &seq_points->seq_points [i];
3922 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3927 if (i == seq_points->len) {
3928 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);
3930 for (i = 0; i < seq_points->len; ++i)
3931 printf ("%d\n", seq_points->seq_points [i].il_offset);
3934 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3943 inst = g_new0 (BreakpointInstance, 1);
3945 inst->native_offset = sp->native_offset;
3946 inst->ip = (guint8*)ji->code_start + sp->native_offset;
3948 inst->domain = domain;
3950 mono_loader_lock ();
3952 g_ptr_array_add (bp->children, inst);
3954 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3955 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3956 mono_loader_unlock ();
3959 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3960 mono_arch_set_breakpoint (ji, inst->ip);
3966 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
3970 remove_breakpoint (BreakpointInstance *inst)
3972 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3974 MonoJitInfo *ji = inst->ji;
3975 guint8 *ip = inst->ip;
3977 mono_loader_lock ();
3978 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3979 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3980 mono_loader_unlock ();
3982 g_assert (count > 0);
3985 mono_arch_clear_breakpoint (ji, ip);
3992 static inline gboolean
3993 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3999 if (method == bp->method)
4001 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4004 if (bp->method->is_inflated && method->is_inflated) {
4005 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4006 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4008 /* Open generic methods should match closed generic methods of the same class */
4009 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4010 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4011 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4013 /* FIXME: Handle !mvar */
4014 if (t1->type != MONO_TYPE_MVAR)
4025 * add_pending_breakpoints:
4027 * Insert pending breakpoints into the newly JITted method METHOD.
4030 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4033 MonoSeqPointInfo *seq_points;
4039 domain = mono_domain_get ();
4041 mono_loader_lock ();
4043 for (i = 0; i < breakpoints->len; ++i) {
4044 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4045 gboolean found = FALSE;
4047 if (!bp_matches_method (bp, method))
4050 for (j = 0; j < bp->children->len; ++j) {
4051 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4058 mono_domain_lock (domain);
4059 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4060 if (!seq_points && ji->method->is_inflated)
4061 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4062 mono_domain_unlock (domain);
4064 /* Could be AOT code */
4066 g_assert (seq_points);
4068 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4072 mono_loader_unlock ();
4076 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4082 mono_error_init (error);
4084 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4086 /* Might be AOTed code */
4087 code = mono_aot_get_method (domain, method);
4089 ji = mono_jit_info_table_find (domain, code);
4094 insert_breakpoint (seq_points, domain, ji, bp, error);
4098 clear_breakpoint (MonoBreakpoint *bp);
4103 * Set a breakpoint at IL_OFFSET in METHOD.
4104 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4105 * METHOD can also be a generic method definition, in which case a breakpoint
4106 * is placed in all instances of the method.
4107 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4110 static MonoBreakpoint*
4111 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4114 GHashTableIter iter, iter2;
4117 MonoSeqPointInfo *seq_points;
4120 mono_error_init (error);
4123 // - suspend/resume the vm to prevent code patching problems
4124 // - multiple breakpoints on the same location
4125 // - dynamic methods
4128 bp = g_new0 (MonoBreakpoint, 1);
4129 bp->method = method;
4130 bp->il_offset = il_offset;
4132 bp->children = g_ptr_array_new ();
4134 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));
4136 mono_loader_lock ();
4138 g_hash_table_iter_init (&iter, domains);
4139 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4140 mono_domain_lock (domain);
4142 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4143 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4144 if (bp_matches_method (bp, m))
4145 set_bp_in_method (domain, m, seq_points, bp, error);
4148 mono_domain_unlock (domain);
4151 mono_loader_unlock ();
4153 mono_loader_lock ();
4154 g_ptr_array_add (breakpoints, bp);
4155 mono_loader_unlock ();
4157 if (error && !mono_error_ok (error)) {
4158 clear_breakpoint (bp);
4166 clear_breakpoint (MonoBreakpoint *bp)
4170 // FIXME: locking, races
4171 for (i = 0; i < bp->children->len; ++i) {
4172 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4174 remove_breakpoint (inst);
4179 mono_loader_lock ();
4180 g_ptr_array_remove (breakpoints, bp);
4181 mono_loader_unlock ();
4183 g_ptr_array_free (bp->children, TRUE);
4188 breakpoints_cleanup (void)
4192 mono_loader_lock ();
4194 while (i < event_requests->len) {
4195 EventRequest *req = g_ptr_array_index (event_requests, i);
4197 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4198 clear_breakpoint (req->info);
4199 g_ptr_array_remove_index_fast (event_requests, i);
4206 for (i = 0; i < breakpoints->len; ++i)
4207 g_free (g_ptr_array_index (breakpoints, i));
4209 g_ptr_array_free (breakpoints, TRUE);
4210 g_hash_table_destroy (bp_locs);
4215 mono_loader_unlock ();
4219 * clear_breakpoints_for_domain:
4221 * Clear breakpoint instances which reference DOMAIN.
4224 clear_breakpoints_for_domain (MonoDomain *domain)
4228 /* This could be called after shutdown */
4232 mono_loader_lock ();
4233 for (i = 0; i < breakpoints->len; ++i) {
4234 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4237 while (j < bp->children->len) {
4238 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4240 if (inst->domain == domain) {
4241 remove_breakpoint (inst);
4245 g_ptr_array_remove_index_fast (bp->children, j);
4251 mono_loader_unlock ();
4255 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4257 return bp->method && bp->method->klass->image->assembly == assembly;
4261 process_breakpoint_inner (DebuggerTlsData *tls)
4265 int i, j, suspend_policy;
4266 guint32 native_offset;
4268 BreakpointInstance *inst;
4269 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4270 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4271 EventKind kind = EVENT_KIND_BREAKPOINT;
4272 MonoContext *ctx = &tls->restore_ctx;
4273 MonoSeqPointInfo *info;
4276 // FIXME: Speed this up
4278 ip = MONO_CONTEXT_GET_IP (ctx);
4279 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4281 g_assert (ji->method);
4283 /* Compute the native offset of the breakpoint from the ip */
4284 native_offset = ip - (guint8*)ji->code_start;
4287 * Skip the instruction causing the breakpoint signal.
4289 mono_arch_skip_breakpoint (ctx, ji);
4291 if (ji->method->wrapper_type || tls->disable_breakpoints)
4294 bp_reqs = g_ptr_array_new ();
4295 ss_reqs = g_ptr_array_new ();
4296 ss_reqs_orig = g_ptr_array_new ();
4298 mono_loader_lock ();
4301 * The ip points to the instruction causing the breakpoint event, which is after
4302 * the offset recorded in the seq point map, so find the prev seq point before ip.
4304 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4306 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));
4309 for (i = 0; i < breakpoints->len; ++i) {
4310 bp = g_ptr_array_index (breakpoints, i);
4315 for (j = 0; j < bp->children->len; ++j) {
4316 inst = g_ptr_array_index (bp->children, j);
4317 if (inst->ji == ji && inst->sp == sp) {
4318 if (bp->req->event_kind == EVENT_KIND_STEP) {
4319 g_ptr_array_add (ss_reqs_orig, bp->req);
4321 g_ptr_array_add (bp_reqs, bp->req);
4326 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4327 /* Maybe a method entry/exit event */
4328 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4329 kind = EVENT_KIND_METHOD_ENTRY;
4330 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4331 kind = EVENT_KIND_METHOD_EXIT;
4334 /* Process single step requests */
4335 for (i = 0; i < ss_reqs_orig->len; ++i) {
4336 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4337 SingleStepReq *ss_req = req->info;
4338 gboolean hit = TRUE;
4340 if (ss_req->size == STEP_SIZE_LINE) {
4341 /* Have to check whenever a different source line was reached */
4342 MonoDebugMethodInfo *minfo;
4343 MonoDebugSourceLocation *loc = NULL;
4345 minfo = mono_debug_lookup_method (ji->method);
4348 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4350 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4351 /* Have to continue single stepping */
4352 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4357 ss_req->last_method = ji->method;
4358 ss_req->last_line = loc->row;
4359 mono_debug_free_source_location (loc);
4364 g_ptr_array_add (ss_reqs, req);
4366 /* Start single stepping again from the current sequence point */
4367 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4370 if (ss_reqs->len > 0)
4371 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4372 if (bp_reqs->len > 0)
4373 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4374 if (kind != EVENT_KIND_BREAKPOINT)
4375 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4377 mono_loader_unlock ();
4379 g_ptr_array_free (bp_reqs, TRUE);
4380 g_ptr_array_free (ss_reqs, TRUE);
4383 * FIXME: The first event will suspend, so the second will only be sent after the
4387 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4389 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4390 if (enter_leave_events)
4391 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4394 /* Process a breakpoint/single step event after resuming from a signal handler */
4396 process_signal_event (void (*func) (DebuggerTlsData*))
4398 DebuggerTlsData *tls;
4399 MonoContext orig_restore_ctx, ctx;
4400 static void (*restore_context) (void *);
4402 if (!restore_context)
4403 restore_context = mono_get_restore_context ();
4405 tls = mono_native_tls_get_value (debugger_tls_id);
4406 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4407 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4408 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4412 /* This is called when resuming from a signal handler, so it shouldn't return */
4413 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4414 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4415 restore_context (&ctx);
4416 g_assert_not_reached ();
4420 process_breakpoint (void)
4422 process_signal_event (process_breakpoint_inner);
4426 resume_from_signal_handler (void *sigctx, void *func)
4428 DebuggerTlsData *tls;
4431 /* Save the original context in TLS */
4432 // FIXME: This might not work on an altstack ?
4433 tls = mono_native_tls_get_value (debugger_tls_id);
4436 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4437 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4438 // clob:c could be added to op_seq_point.
4440 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4441 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4442 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4443 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4445 MONO_CONTEXT_SET_IP (&ctx, func);
4447 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4449 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4450 mono_ppc_set_func_into_sigctx (sigctx, func);
4455 mono_debugger_agent_breakpoint_hit (void *sigctx)
4458 * We are called from a signal handler, and running code there causes all kinds of
4459 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4460 * So set up the signal context to return to the real breakpoint handler function.
4463 resume_from_signal_handler (sigctx, process_breakpoint);
4467 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4469 if (frame->managed) {
4470 *(MonoContext*)data = *ctx;
4479 * Called by System.Diagnostics.Debugger:Break ().
4482 mono_debugger_agent_user_break (void)
4484 if (agent_config.enabled) {
4489 /* Obtain a context */
4490 MONO_CONTEXT_SET_IP (&ctx, NULL);
4491 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4492 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4494 mono_loader_lock ();
4495 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4496 mono_loader_unlock ();
4498 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4505 ss_depth_to_string (StepDepth depth)
4508 case STEP_DEPTH_OVER:
4510 case STEP_DEPTH_OUT:
4512 case STEP_DEPTH_INTO:
4515 g_assert_not_reached ();
4521 process_single_step_inner (DebuggerTlsData *tls)
4526 int il_offset, suspend_policy;
4529 MonoContext *ctx = &tls->restore_ctx;
4531 MonoSeqPointInfo *info;
4533 ip = MONO_CONTEXT_GET_IP (ctx);
4535 /* Skip the instruction causing the single step */
4536 mono_arch_skip_single_step (ctx);
4538 if (suspend_count > 0) {
4539 process_suspend (tls, ctx);
4544 // FIXME: A suspend race
4547 if (mono_thread_internal_current () != ss_req->thread)
4550 if (log_level > 0) {
4551 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4553 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));
4556 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4558 g_assert (ji->method);
4560 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4565 * Stopping in memset makes half-initialized vtypes visible.
4566 * Stopping in memcpy makes half-copied vtypes visible.
4568 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4572 * The ip points to the instruction causing the single step event, which is before
4573 * the offset recorded in the seq point map, so find the next seq point after ip.
4575 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4578 il_offset = sp->il_offset;
4580 // FIXME: No tests fail if this is disabled
4582 if (ss_req->size == STEP_SIZE_LINE) {
4586 /* Step until a different source line is reached */
4587 MonoDebugMethodInfo *minfo;
4589 minfo = mono_debug_lookup_method (ji->method);
4592 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4594 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4595 mono_debug_free_source_location (loc);
4600 * Step until we reach a location with line number info,
4601 * otherwise the client can't show a location.
4602 * This can happen for example with statics initialized inline
4603 * outside of a cctor.
4608 ss_req->last_method = ji->method;
4609 ss_req->last_line = loc->row;
4610 mono_debug_free_source_location (loc);
4616 /* Start single stepping again from the current sequence point */
4617 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4619 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4620 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4621 !strcmp (ji->method->name, ".cctor"))
4624 // FIXME: Has to lock earlier
4626 reqs = g_ptr_array_new ();
4628 mono_loader_lock ();
4630 g_ptr_array_add (reqs, ss_req->req);
4632 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4634 g_ptr_array_free (reqs, TRUE);
4636 mono_loader_unlock ();
4638 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4642 process_single_step (void)
4644 process_signal_event (process_single_step_inner);
4648 * mono_debugger_agent_single_step_event:
4650 * Called from a signal handler to handle a single step event.
4653 mono_debugger_agent_single_step_event (void *sigctx)
4655 /* Resume to process_single_step through the signal context */
4657 // FIXME: Since step out/over is implemented using step in, the step in case should
4658 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4661 if (GetCurrentThreadId () == debugger_thread_id) {
4663 * This could happen despite our best effors when the runtime calls
4664 * assembly/type resolve hooks.
4665 * FIXME: Breakpoints too.
4669 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4670 mono_arch_skip_single_step (&ctx);
4671 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4675 resume_from_signal_handler (sigctx, process_single_step);
4679 debugger_agent_single_step_from_context (MonoContext *ctx)
4681 DebuggerTlsData *tls;
4682 MonoContext orig_restore_ctx;
4684 tls = mono_native_tls_get_value (debugger_tls_id);
4687 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4688 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4689 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4691 process_single_step_inner (tls);
4693 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4694 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4698 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4700 DebuggerTlsData *tls;
4701 MonoContext orig_restore_ctx;
4703 tls = mono_native_tls_get_value (debugger_tls_id);
4705 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4706 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4708 process_breakpoint_inner (tls);
4710 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4711 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4715 * start_single_stepping:
4717 * Turn on single stepping. Can be called multiple times, for example,
4718 * by a single step event request + a suspend.
4721 start_single_stepping (void)
4723 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4724 int val = InterlockedIncrement (&ss_count);
4727 mono_arch_start_single_stepping ();
4729 if (ss_req != NULL && ss_invoke_addr == NULL) {
4730 DebuggerTlsData *tls;
4732 mono_loader_lock ();
4734 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4735 ss_invoke_addr = tls->invoke_addr;
4737 mono_loader_unlock ();
4740 g_assert_not_reached ();
4745 stop_single_stepping (void)
4747 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4748 int val = InterlockedDecrement (&ss_count);
4751 mono_arch_stop_single_stepping ();
4753 g_assert_not_reached ();
4760 * Stop the single stepping operation given by SS_REQ.
4763 ss_stop (SingleStepReq *ss_req)
4768 for (l = ss_req->bps; l; l = l->next) {
4769 clear_breakpoint (l->data);
4771 g_slist_free (ss_req->bps);
4775 if (ss_req->global) {
4776 stop_single_stepping ();
4777 ss_req->global = FALSE;
4784 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4785 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4786 * belong to the same thread as CTX.
4789 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4794 gboolean enable_global = FALSE;
4796 /* Stop the previous operation */
4800 * Implement single stepping using breakpoints if possible.
4802 if (step_to_catch) {
4803 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4804 ss_req->bps = g_slist_append (ss_req->bps, bp);
4808 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT) && ctx) {
4809 /* Need parent frames */
4810 if (!tls->context.valid)
4811 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4812 compute_frame_info (tls->thread, tls);
4816 * Find the first sequence point in the current or in a previous frame which
4817 * is not the last in its method.
4819 if (ss_req->depth == STEP_DEPTH_OUT) {
4820 /* Ignore seq points in current method */
4821 while (frame_index < tls->frame_count) {
4822 StackFrame *frame = tls->frames [frame_index];
4824 method = frame->method;
4825 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4827 if (sp && sp->next_len != 0)
4830 // There could be method calls before the next seq point in the caller when using nested calls
4831 //enable_global = TRUE;
4833 while (sp && sp->next_len == 0) {
4835 if (frame_index < tls->frame_count) {
4836 StackFrame *frame = tls->frames [frame_index];
4838 method = frame->method;
4839 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4845 if (sp && sp->next_len > 0) {
4846 for (i = 0; i < sp->next_len; ++i) {
4847 next_sp = &info->seq_points [sp->next [i]];
4849 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4850 ss_req->bps = g_slist_append (ss_req->bps, bp);
4854 if (ss_req->depth == STEP_DEPTH_INTO) {
4855 /* Enable global stepping so we stop at method entry too */
4856 enable_global = TRUE;
4860 * The ctx/frame info computed above will become invalid when we continue.
4862 tls->context.valid = FALSE;
4863 tls->async_state.valid = FALSE;
4864 invalidate_frames (tls);
4867 if (enable_global) {
4868 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4869 ss_req->global = TRUE;
4870 start_single_stepping ();
4871 } else if (!ss_req->bps) {
4872 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4873 ss_req->global = TRUE;
4874 start_single_stepping ();
4876 ss_req->global = FALSE;
4881 * Start single stepping of thread THREAD
4884 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4886 DebuggerTlsData *tls;
4887 MonoSeqPointInfo *info = NULL;
4888 SeqPoint *sp = NULL;
4889 MonoMethod *method = NULL;
4890 MonoDebugMethodInfo *minfo;
4891 gboolean step_to_catch = FALSE;
4893 if (suspend_count == 0)
4894 return ERR_NOT_SUSPENDED;
4896 wait_for_suspend ();
4898 // FIXME: Multiple requests
4900 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4901 return ERR_NOT_IMPLEMENTED;
4904 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4906 ss_req = g_new0 (SingleStepReq, 1);
4908 ss_req->thread = thread;
4909 ss_req->size = size;
4910 ss_req->depth = depth;
4913 mono_loader_lock ();
4914 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4915 mono_loader_unlock ();
4917 g_assert (tls->context.valid);
4918 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4920 if (tls->has_catch_ctx) {
4922 StackFrameInfo frame;
4923 MonoContext new_ctx;
4924 MonoLMF *lmf = NULL;
4927 * We are stopped at a throw site. Stepping should go to the catch site.
4930 /* Find the the jit info for the catch context */
4931 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4933 g_assert (frame.type == FRAME_TYPE_MANAGED);
4936 * Find the seq point corresponding to the landing site ip, which is the first seq
4939 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4942 method = frame.method;
4944 step_to_catch = TRUE;
4945 /* This make sure the seq point is not skipped by process_single_step () */
4946 ss_req->last_sp = NULL;
4949 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4952 /* Compute the initial line info */
4953 compute_frame_info (thread, tls);
4955 if (tls->frame_count) {
4956 frame = tls->frames [0];
4958 ss_req->last_method = frame->method;
4959 ss_req->last_line = -1;
4961 minfo = mono_debug_lookup_method (frame->method);
4962 if (minfo && frame->il_offset != -1) {
4963 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4966 ss_req->last_line = loc->row;
4973 if (!step_to_catch) {
4976 compute_frame_info (thread, tls);
4978 if (tls->frame_count) {
4979 frame = tls->frames [0];
4981 if (!method && frame->il_offset != -1) {
4982 /* FIXME: Sort the table and use a binary search */
4983 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4985 method = frame->method;
4990 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
4996 ss_destroy (SingleStepReq *req)
4999 g_assert (ss_req == req);
5008 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5011 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5017 if (!agent_config.enabled)
5020 mono_loader_lock ();
5021 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5022 mono_loader_unlock ();
5025 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5026 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5028 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5030 g_free (ei.category);
5031 g_free (ei.message);
5035 mono_debugger_agent_debug_log_is_enabled (void)
5037 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5038 return agent_config.enabled;
5042 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5043 MonoContext *catch_ctx)
5049 DebuggerTlsData *tls = NULL;
5051 if (thread_to_tls != NULL) {
5052 MonoInternalThread *thread = mono_thread_internal_current ();
5054 mono_loader_lock ();
5055 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5056 mono_loader_unlock ();
5058 if (tls && tls->abort_requested)
5060 if (tls && tls->disable_breakpoints)
5064 memset (&ei, 0, sizeof (EventInfo));
5066 /* Just-In-Time debugging */
5068 if (agent_config.onuncaught && !inited) {
5069 finish_agent_init (FALSE);
5072 * Send an unsolicited EXCEPTION event with a dummy request id.
5074 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5075 ei.exc = (MonoObject*)exc;
5076 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5079 } else if (agent_config.onthrow && !inited) {
5081 gboolean found = FALSE;
5083 for (l = agent_config.onthrow; l; l = l->next) {
5084 char *ex_type = l->data;
5085 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5087 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5094 finish_agent_init (FALSE);
5097 * Send an unsolicited EXCEPTION event with a dummy request id.
5099 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5100 ei.exc = (MonoObject*)exc;
5101 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5109 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5111 ei.exc = (MonoObject*)exc;
5112 ei.caught = catch_ctx != NULL;
5114 mono_loader_lock ();
5115 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5116 mono_loader_unlock ();
5118 if (tls && catch_ctx) {
5119 tls->catch_ctx = *catch_ctx;
5120 tls->has_catch_ctx = TRUE;
5123 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5126 tls->has_catch_ctx = FALSE;
5130 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5132 DebuggerTlsData *tls;
5137 tls = mono_native_tls_get_value (debugger_tls_id);
5142 * We're about to invoke an exception filter during the first pass of exception handling.
5144 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5145 * 'orig_ctx' is the context where the exception has been thrown.
5148 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5150 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5151 * the call site (line 37) and then continue to Main(), but it would never
5152 * include the throw site (line 32).
5154 * Since exception filters are invoked during the first pass of exception handling,
5155 * the stack frames of the throw site are still intact, so we should include them
5158 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5160 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5161 * but report the location of the 'throw' to the user.
5165 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5169 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5171 DebuggerTlsData *tls;
5176 tls = mono_native_tls_get_value (debugger_tls_id);
5180 tls->filter_state.valid = FALSE;
5184 * buffer_add_value_full:
5186 * Add the encoding of the value at ADDR described by T to the buffer.
5187 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5191 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5197 g_assert (*(void**)addr);
5198 addr = *(void**)addr;
5203 case MONO_TYPE_BOOLEAN:
5206 case MONO_TYPE_CHAR:
5226 case MONO_TYPE_VOID:
5227 buffer_add_byte (buf, t->type);
5229 case MONO_TYPE_BOOLEAN:
5232 buffer_add_byte (buf, t->type);
5233 buffer_add_int (buf, *(gint8*)addr);
5235 case MONO_TYPE_CHAR:
5238 buffer_add_byte (buf, t->type);
5239 buffer_add_int (buf, *(gint16*)addr);
5244 buffer_add_byte (buf, t->type);
5245 buffer_add_int (buf, *(gint32*)addr);
5250 buffer_add_byte (buf, t->type);
5251 buffer_add_long (buf, *(gint64*)addr);
5255 /* Treat it as a vtype */
5257 case MONO_TYPE_PTR: {
5258 gssize val = *(gssize*)addr;
5260 buffer_add_byte (buf, t->type);
5261 buffer_add_long (buf, val);
5265 case MONO_TYPE_STRING:
5266 case MONO_TYPE_SZARRAY:
5267 case MONO_TYPE_OBJECT:
5268 case MONO_TYPE_CLASS:
5269 case MONO_TYPE_ARRAY:
5270 obj = *(MonoObject**)addr;
5273 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5275 if (obj->vtable->klass->valuetype) {
5276 t = &obj->vtable->klass->byval_arg;
5277 addr = mono_object_unbox (obj);
5279 } else if (obj->vtable->klass->rank) {
5280 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5281 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5282 buffer_add_byte (buf, MONO_TYPE_CLASS);
5284 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5286 buffer_add_objid (buf, obj);
5290 case MONO_TYPE_VALUETYPE: {
5294 MonoClass *klass = mono_class_from_mono_type (t);
5296 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5297 buffer_add_byte (buf, klass->enumtype);
5298 buffer_add_typeid (buf, domain, klass);
5302 while ((f = mono_class_get_fields (klass, &iter))) {
5303 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5305 if (mono_field_is_deleted (f))
5309 buffer_add_int (buf, nfields);
5312 while ((f = mono_class_get_fields (klass, &iter))) {
5313 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5315 if (mono_field_is_deleted (f))
5317 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5321 case MONO_TYPE_GENERICINST:
5322 if (mono_type_generic_inst_is_valuetype (t)) {
5334 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5336 buffer_add_value_full (buf, t, addr, domain, FALSE);
5340 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5343 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5347 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5348 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5349 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5350 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5351 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5352 char *name = mono_type_full_name (t);
5353 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5355 return ERR_INVALID_ARGUMENT;
5359 case MONO_TYPE_BOOLEAN:
5360 *(guint8*)addr = decode_int (buf, &buf, limit);
5362 case MONO_TYPE_CHAR:
5363 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5366 *(gint8*)addr = decode_int (buf, &buf, limit);
5369 *(guint8*)addr = decode_int (buf, &buf, limit);
5372 *(gint16*)addr = decode_int (buf, &buf, limit);
5375 *(guint16*)addr = decode_int (buf, &buf, limit);
5378 *(gint32*)addr = decode_int (buf, &buf, limit);
5381 *(guint32*)addr = decode_int (buf, &buf, limit);
5384 *(gint64*)addr = decode_long (buf, &buf, limit);
5387 *(guint64*)addr = decode_long (buf, &buf, limit);
5390 *(guint32*)addr = decode_int (buf, &buf, limit);
5393 *(guint64*)addr = decode_long (buf, &buf, limit);
5396 /* We send these as I8, so we get them back as such */
5397 g_assert (type == MONO_TYPE_I8);
5398 *(gssize*)addr = decode_long (buf, &buf, limit);
5400 case MONO_TYPE_GENERICINST:
5401 if (MONO_TYPE_ISSTRUCT (t)) {
5402 /* The client sends these as a valuetype */
5410 /* We send these as vtypes, so we get them back as such */
5411 g_assert (type == MONO_TYPE_VALUETYPE);
5414 case MONO_TYPE_VALUETYPE: {
5415 gboolean is_enum = decode_byte (buf, &buf, limit);
5419 gpointer iter = NULL;
5422 /* Enums are sent as a normal vtype */
5424 return ERR_NOT_IMPLEMENTED;
5425 klass = decode_typeid (buf, &buf, limit, &d, &err);
5429 if (klass != mono_class_from_mono_type (t))
5430 return ERR_INVALID_ARGUMENT;
5432 nfields = decode_int (buf, &buf, limit);
5433 while ((f = mono_class_get_fields (klass, &iter))) {
5434 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5436 if (mono_field_is_deleted (f))
5438 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5443 g_assert (nfields == 0);
5448 if (MONO_TYPE_IS_REFERENCE (t)) {
5449 if (type == MONO_TYPE_OBJECT) {
5450 int objid = decode_objid (buf, &buf, limit);
5454 err = get_object (objid, (MonoObject**)&obj);
5458 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
5459 return ERR_INVALID_ARGUMENT;
5460 if (obj && obj->vtable->domain != domain)
5461 return ERR_INVALID_ARGUMENT;
5463 mono_gc_wbarrier_generic_store (addr, obj);
5464 } else if (type == VALUE_TYPE_ID_NULL) {
5465 *(MonoObject**)addr = NULL;
5467 return ERR_INVALID_ARGUMENT;
5481 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5484 int type = decode_byte (buf, &buf, limit);
5486 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5487 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5488 guint8 *nullable_buf;
5491 * First try decoding it as a Nullable`1
5493 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5498 * Then try decoding as a primitive value or null.
5500 if (targ->type == type) {
5501 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5502 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5504 g_free (nullable_buf);
5507 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5508 g_free (nullable_buf);
5511 } else if (type == VALUE_TYPE_ID_NULL) {
5512 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5518 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5522 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5529 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5530 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5533 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5534 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5536 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5538 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5539 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5540 addr += (gint32)var->offset;
5542 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5544 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5546 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5550 g_assert_not_reached ();
5555 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5561 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5562 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5564 if (MONO_TYPE_IS_REFERENCE (t))
5565 size = sizeof (gpointer);
5567 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5570 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5571 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5573 gboolean is_signed = FALSE;
5575 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5580 v = is_signed ? *(gint8*)val : *(guint8*)val;
5583 v = is_signed ? *(gint16*)val : *(guint16*)val;
5586 v = is_signed ? *(gint32*)val : *(guint32*)val;
5589 v = is_signed ? *(gint64*)val : *(guint64*)val;
5592 g_assert_not_reached ();
5598 /* Set value on the stack or in the return ctx */
5599 if (reg_locations [reg]) {
5600 /* Saved on the stack */
5601 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5602 *(reg_locations [reg]) = v;
5605 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5606 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5609 // FIXME: Move these to mono-context.h/c.
5610 mono_arch_context_set_int_reg (ctx, reg, v);
5612 // FIXME: Can't set registers, so we disable linears
5617 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5618 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5619 addr += (gint32)var->offset;
5621 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5624 addr = *(guint8**)addr;
5630 // FIXME: Write barriers
5631 mono_gc_memmove (addr, val, size);
5633 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5637 g_assert_not_reached ();
5642 clear_event_request (int req_id, int etype)
5646 mono_loader_lock ();
5647 for (i = 0; i < event_requests->len; ++i) {
5648 EventRequest *req = g_ptr_array_index (event_requests, i);
5650 if (req->id == req_id && req->event_kind == etype) {
5651 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5652 clear_breakpoint (req->info);
5653 if (req->event_kind == EVENT_KIND_STEP)
5654 ss_destroy (req->info);
5655 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5656 clear_breakpoint (req->info);
5657 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5658 clear_breakpoint (req->info);
5659 g_ptr_array_remove_index_fast (event_requests, i);
5664 mono_loader_unlock ();
5668 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5670 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5671 return breakpoint_matches_assembly (req->info, assembly);
5675 for (i = 0; i < req->nmodifiers; ++i) {
5676 Modifier *m = &req->modifiers [i];
5678 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5680 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5681 for (j = 0; m->data.assemblies [j]; ++j)
5682 if (m->data.assemblies [j] == assembly)
5692 * clear_event_requests_for_assembly:
5694 * Clear all events requests which reference ASSEMBLY.
5697 clear_event_requests_for_assembly (MonoAssembly *assembly)
5702 mono_loader_lock ();
5706 for (i = 0; i < event_requests->len; ++i) {
5707 EventRequest *req = g_ptr_array_index (event_requests, i);
5709 if (event_req_matches_assembly (req, assembly)) {
5710 clear_event_request (req->id, req->event_kind);
5716 mono_loader_unlock ();
5720 * type_comes_from_assembly:
5722 * GHRFunc that returns TRUE if klass comes from assembly
5725 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5727 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5731 * clear_types_for_assembly:
5733 * Clears types from loaded_classes for a given assembly
5736 clear_types_for_assembly (MonoAssembly *assembly)
5738 MonoDomain *domain = mono_domain_get ();
5739 AgentDomainInfo *info = NULL;
5741 mono_loader_lock ();
5742 info = get_agent_domain_info (domain);
5743 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5744 mono_loader_unlock ();
5748 add_thread (gpointer key, gpointer value, gpointer user_data)
5750 MonoInternalThread *thread = value;
5751 Buffer *buf = user_data;
5753 buffer_add_objid (buf, (MonoObject*)thread);
5757 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5759 guint8 *p = invoke->p;
5760 guint8 *end = invoke->endp;
5763 MonoMethodSignature *sig;
5766 MonoObject *this, *res, *exc;
5769 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5772 MonoStopwatch watch;
5774 if (invoke->method) {
5776 * Invoke this method directly, currently only Environment.Exit () is supported.
5779 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>"));
5780 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5781 g_assert_not_reached ();
5784 m = decode_methodid (p, &p, end, &domain, &err);
5787 sig = mono_method_signature (m);
5789 if (m->klass->valuetype)
5790 this_buf = g_alloca (mono_class_instance_size (m->klass));
5792 this_buf = g_alloca (sizeof (MonoObject*));
5793 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5794 /* Should be null */
5795 int type = decode_byte (p, &p, end);
5796 if (type != VALUE_TYPE_ID_NULL)
5797 return ERR_INVALID_ARGUMENT;
5798 memset (this_buf, 0, mono_class_instance_size (m->klass));
5800 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5805 if (!m->klass->valuetype)
5806 this = *(MonoObject**)this_buf;
5810 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>"));
5812 if (this && this->vtable->domain != domain)
5815 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5816 if (!strcmp (m->name, ".ctor")) {
5817 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5818 return ERR_INVALID_ARGUMENT;
5820 this = mono_object_new (domain, m->klass);
5822 return ERR_INVALID_ARGUMENT;
5826 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5827 return ERR_INVALID_ARGUMENT;
5829 nargs = decode_int (p, &p, end);
5830 if (nargs != sig->param_count)
5831 return ERR_INVALID_ARGUMENT;
5832 /* Use alloca to get gc tracking */
5833 arg_buf = g_alloca (nargs * sizeof (gpointer));
5834 memset (arg_buf, 0, nargs * sizeof (gpointer));
5835 args = g_alloca (nargs * sizeof (gpointer));
5836 for (i = 0; i < nargs; ++i) {
5837 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5838 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5842 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5845 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5846 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5849 args [i] = arg_buf [i];
5856 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5857 tls->disable_breakpoints = TRUE;
5859 tls->disable_breakpoints = FALSE;
5862 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5864 /* FIXME: Move this to arch specific code */
5865 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5866 if (invoke->has_ctx) {
5869 lmf_addr = mono_get_lmf_addr ();
5872 memset (&ext, 0, sizeof (ext));
5874 ext.lmf.previous_lmf = *(lmf_addr);
5875 /* Mark that this is a MonoLMFExt */
5876 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5877 ext.lmf.rsp = (gssize)&ext;
5878 #elif defined(TARGET_X86)
5879 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5880 /* Mark that this is a MonoLMFExt */
5881 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5882 ext.lmf.ebp = (gssize)&ext;
5883 #elif defined(TARGET_ARM)
5884 ext.lmf.previous_lmf = *(lmf_addr);
5885 /* Mark that this is a MonoLMFExt */
5886 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5887 ext.lmf.sp = (gssize)&ext;
5888 #elif defined(TARGET_POWERPC)
5889 ext.lmf.previous_lmf = *(lmf_addr);
5890 /* Mark that this is a MonoLMFExt */
5891 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5892 ext.lmf.ebp = (gssize)&ext;
5893 #elif defined(TARGET_S390X)
5894 ext.lmf.previous_lmf = *(lmf_addr);
5895 /* Mark that this is a MonoLMFExt */
5896 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5897 ext.lmf.ebp = (gssize)&ext;
5898 #elif defined(TARGET_MIPS)
5899 ext.lmf.previous_lmf = *(lmf_addr);
5900 /* Mark that this is a MonoLMFExt */
5901 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5902 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5904 g_assert_not_reached ();
5907 ext.debugger_invoke = TRUE;
5908 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5910 mono_set_lmf ((MonoLMF*)&ext);
5914 mono_stopwatch_start (&watch);
5915 if (m->klass->valuetype)
5916 res = mono_runtime_invoke (m, this_buf, args, &exc);
5918 res = mono_runtime_invoke (m, this, args, &exc);
5919 mono_stopwatch_stop (&watch);
5920 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)));
5922 buffer_add_byte (buf, 0);
5923 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5925 buffer_add_byte (buf, 1);
5926 if (sig->ret->type == MONO_TYPE_VOID) {
5927 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5928 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5931 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5932 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5933 buffer_add_value (buf, sig->ret, &res, domain);
5934 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
5935 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5936 MonoClass *k = mono_class_from_mono_type (sig->ret);
5937 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
5939 g_assert (nullable_buf);
5940 mono_nullable_init (nullable_buf, res, k);
5941 buffer_add_value (buf, sig->ret, nullable_buf, domain);
5944 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5951 tls->disable_breakpoints = FALSE;
5953 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5954 if (invoke->has_ctx)
5955 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5958 // FIXME: byref arguments
5966 * Invoke the method given by tls->pending_invoke in the current thread.
5969 invoke_method (void)
5971 DebuggerTlsData *tls;
5976 static void (*restore_context) (void *);
5977 MonoContext restore_ctx;
5979 if (!restore_context)
5980 restore_context = mono_get_restore_context ();
5982 tls = mono_native_tls_get_value (debugger_tls_id);
5986 * Store the `InvokeData *' in `tls->invoke' until we're done with
5987 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5990 mono_loader_lock ();
5992 invoke = tls->pending_invoke;
5994 tls->pending_invoke = NULL;
5996 invoke->last_invoke = tls->invoke;
5997 tls->invoke = invoke;
5999 mono_loader_unlock ();
6001 tls->frames_up_to_date = FALSE;
6005 buffer_init (&buf, 128);
6007 err = do_invoke_method (tls, &buf, invoke);
6009 /* Start suspending before sending the reply */
6010 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6011 for (i = 0; i < invoke->suspend_count; ++i)
6015 send_reply_packet (id, err, &buf);
6019 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6021 if (invoke->has_ctx)
6022 save_thread_context (&restore_ctx);
6024 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6025 g_assert (tls->resume_count);
6026 tls->resume_count -= invoke->suspend_count;
6029 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6032 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6034 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6035 * after the mono_runtime_invoke() already returned, but it doesn't matter
6036 * because we reset the abort here.
6039 mono_loader_lock ();
6041 if (tls->abort_requested)
6042 mono_thread_internal_reset_abort (tls->thread);
6044 tls->invoke = tls->invoke->last_invoke;
6045 tls->abort_requested = FALSE;
6047 mono_loader_unlock ();
6056 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6058 MonoThread *thread = value;
6059 DebuggerTlsData *tls;
6062 mono_loader_lock ();
6063 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6065 res = tls->really_suspended;
6066 mono_loader_unlock ();
6072 get_source_files_for_type (MonoClass *klass)
6074 gpointer iter = NULL;
6076 MonoDebugSourceInfo *sinfo;
6080 files = g_ptr_array_new ();
6082 while ((method = mono_class_get_methods (klass, &iter))) {
6083 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6084 GPtrArray *source_file_list;
6087 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL);
6088 for (j = 0; j < source_file_list->len; ++j) {
6089 sinfo = g_ptr_array_index (source_file_list, j);
6090 for (i = 0; i < files->len; ++i)
6091 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6093 if (i == files->len)
6094 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6096 g_ptr_array_free (source_file_list, TRUE);
6104 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6107 case CMD_VM_VERSION: {
6108 char *build_info, *version;
6110 build_info = mono_get_runtime_build_info ();
6111 version = g_strdup_printf ("mono %s", build_info);
6113 buffer_add_string (buf, version); /* vm version */
6114 buffer_add_int (buf, MAJOR_VERSION);
6115 buffer_add_int (buf, MINOR_VERSION);
6116 g_free (build_info);
6120 case CMD_VM_SET_PROTOCOL_VERSION: {
6121 major_version = decode_int (p, &p, end);
6122 minor_version = decode_int (p, &p, end);
6123 protocol_version_set = TRUE;
6124 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6127 case CMD_VM_ALL_THREADS: {
6129 mono_loader_lock ();
6130 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6131 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6132 mono_loader_unlock ();
6135 case CMD_VM_SUSPEND:
6137 wait_for_suspend ();
6140 if (suspend_count == 0)
6141 return ERR_NOT_SUSPENDED;
6144 case CMD_VM_DISPOSE:
6145 /* Clear all event requests */
6146 mono_loader_lock ();
6147 while (event_requests->len > 0) {
6148 EventRequest *req = g_ptr_array_index (event_requests, 0);
6150 clear_event_request (req->id, req->event_kind);
6152 mono_loader_unlock ();
6154 while (suspend_count > 0)
6156 disconnected = TRUE;
6157 vm_start_event_sent = FALSE;
6160 MonoInternalThread *thread;
6161 DebuggerTlsData *tls;
6162 MonoClass *env_class;
6163 MonoMethod *exit_method = NULL;
6167 exit_code = decode_int (p, &p, end);
6169 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6171 /* Have to send a reply before exiting */
6172 send_reply_packet (id, 0, buf);
6174 /* Clear all event requests */
6175 mono_loader_lock ();
6176 while (event_requests->len > 0) {
6177 EventRequest *req = g_ptr_array_index (event_requests, 0);
6179 clear_event_request (req->id, req->event_kind);
6181 mono_loader_unlock ();
6184 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6185 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6186 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6187 * better than doing the shutdown ourselves, since it avoids various races.
6191 wait_for_suspend ();
6193 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6195 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6197 mono_loader_lock ();
6198 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6199 mono_loader_unlock ();
6201 if (thread && exit_method) {
6202 mono_loader_lock ();
6203 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6204 mono_loader_unlock ();
6206 args = g_new0 (gpointer, 1);
6207 args [0] = g_malloc (sizeof (int));
6208 *(int*)(args [0]) = exit_code;
6210 tls->pending_invoke = g_new0 (InvokeData, 1);
6211 tls->pending_invoke->method = exit_method;
6212 tls->pending_invoke->args = args;
6214 while (suspend_count > 0)
6218 * No thread found, do it ourselves.
6219 * FIXME: This can race with normal shutdown etc.
6221 while (suspend_count > 0)
6224 mono_runtime_set_shutting_down ();
6226 mono_threads_set_shutting_down ();
6228 /* Suspend all managed threads since the runtime is going away */
6229 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6230 mono_thread_suspend_all_other_threads ();
6231 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6232 mono_runtime_quit ();
6233 transport_close2 ();
6234 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6240 case CMD_VM_INVOKE_METHOD: {
6241 int objid = decode_objid (p, &p, end);
6243 DebuggerTlsData *tls;
6244 int i, count, err, flags;
6246 err = get_object (objid, (MonoObject**)&thread);
6250 flags = decode_int (p, &p, end);
6252 // Wait for suspending if it already started
6254 wait_for_suspend ();
6255 if (!is_suspended ())
6256 return ERR_NOT_SUSPENDED;
6258 mono_loader_lock ();
6259 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6260 mono_loader_unlock ();
6263 if (!tls->really_suspended)
6264 /* The thread is still running native code, can't do invokes */
6265 return ERR_NOT_SUSPENDED;
6268 * Store the invoke data into tls, the thread will execute it after it is
6271 if (tls->pending_invoke)
6272 return ERR_NOT_SUSPENDED;
6273 tls->pending_invoke = g_new0 (InvokeData, 1);
6274 tls->pending_invoke->id = id;
6275 tls->pending_invoke->flags = flags;
6276 tls->pending_invoke->p = g_malloc (end - p);
6277 memcpy (tls->pending_invoke->p, p, end - p);
6278 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6279 tls->pending_invoke->suspend_count = suspend_count;
6281 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6282 resume_thread (THREAD_TO_INTERNAL (thread));
6285 count = suspend_count;
6286 for (i = 0; i < count; ++i)
6291 case CMD_VM_ABORT_INVOKE: {
6292 int objid = decode_objid (p, &p, end);
6294 DebuggerTlsData *tls;
6297 err = get_object (objid, (MonoObject**)&thread);
6301 invoke_id = decode_int (p, &p, end);
6303 mono_loader_lock ();
6304 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6307 if (tls->abort_requested) {
6308 mono_loader_unlock ();
6313 * Check whether we're still inside the mono_runtime_invoke() and that it's
6314 * actually the correct invocation.
6316 * Careful, we do not stop the thread that's doing the invocation, so we can't
6317 * inspect its stack. However, invoke_method() also acquires the loader lock
6318 * when it's done, so we're safe here.
6322 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6323 mono_loader_unlock ();
6324 return ERR_NO_INVOCATION;
6327 tls->abort_requested = TRUE;
6329 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6330 mono_loader_unlock ();
6334 case CMD_VM_SET_KEEPALIVE: {
6335 int timeout = decode_int (p, &p, end);
6336 agent_config.keepalive = timeout;
6338 #ifndef DISABLE_SOCKET_TRANSPORT
6345 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6346 GHashTableIter iter, kiter;
6351 char *fname, *basename;
6352 gboolean ignore_case;
6353 GSList *class_list, *l;
6354 GPtrArray *res_classes, *res_domains;
6356 fname = decode_string (p, &p, end);
6357 ignore_case = decode_byte (p, &p, end);
6359 basename = g_path_get_basename (fname);
6361 res_classes = g_ptr_array_new ();
6362 res_domains = g_ptr_array_new ();
6364 mono_loader_lock ();
6365 g_hash_table_iter_init (&iter, domains);
6366 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6367 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6369 /* Update 'source_file_to_class' cache */
6370 g_hash_table_iter_init (&kiter, info->loaded_classes);
6371 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6372 if (!g_hash_table_lookup (info->source_files, klass)) {
6373 files = get_source_files_for_type (klass);
6374 g_hash_table_insert (info->source_files, klass, files);
6376 for (i = 0; i < files->len; ++i) {
6377 char *s = g_ptr_array_index (files, i);
6378 char *s2 = g_path_get_basename (s);
6381 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6383 class_list = g_slist_prepend (class_list, klass);
6384 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6386 class_list = g_slist_prepend (class_list, klass);
6387 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6390 /* The _ignorecase hash contains the lowercase path */
6391 s3 = strdup_tolower (s2);
6392 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6394 class_list = g_slist_prepend (class_list, klass);
6395 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6397 class_list = g_slist_prepend (class_list, klass);
6398 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6410 s = strdup_tolower (basename);
6411 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6414 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6417 for (l = class_list; l; l = l->next) {
6420 g_ptr_array_add (res_classes, klass);
6421 g_ptr_array_add (res_domains, domain);
6424 mono_loader_unlock ();
6429 buffer_add_int (buf, res_classes->len);
6430 for (i = 0; i < res_classes->len; ++i)
6431 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6432 g_ptr_array_free (res_classes, TRUE);
6433 g_ptr_array_free (res_domains, TRUE);
6436 case CMD_VM_GET_TYPES: {
6437 GHashTableIter iter;
6441 gboolean ignore_case;
6442 GPtrArray *res_classes, *res_domains;
6443 MonoTypeNameParse info;
6445 name = decode_string (p, &p, end);
6446 ignore_case = decode_byte (p, &p, end);
6448 if (!mono_reflection_parse_type (name, &info)) {
6450 mono_reflection_free_type_info (&info);
6451 return ERR_INVALID_ARGUMENT;
6454 res_classes = g_ptr_array_new ();
6455 res_domains = g_ptr_array_new ();
6457 mono_loader_lock ();
6458 g_hash_table_iter_init (&iter, domains);
6459 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6461 gboolean type_resolve;
6465 mono_domain_assemblies_lock (domain);
6466 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6470 type_resolve = TRUE;
6471 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6473 g_ptr_array_add (res_classes, mono_type_get_class (t));
6474 g_ptr_array_add (res_domains, domain);
6478 mono_domain_assemblies_unlock (domain);
6480 mono_loader_unlock ();
6483 mono_reflection_free_type_info (&info);
6485 buffer_add_int (buf, res_classes->len);
6486 for (i = 0; i < res_classes->len; ++i)
6487 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6488 g_ptr_array_free (res_classes, TRUE);
6489 g_ptr_array_free (res_domains, TRUE);
6494 return ERR_NOT_IMPLEMENTED;
6501 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6507 case CMD_EVENT_REQUEST_SET: {
6509 int i, event_kind, suspend_policy, nmodifiers, mod;
6512 MonoThread *step_thread;
6513 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6517 event_kind = decode_byte (p, &p, end);
6518 suspend_policy = decode_byte (p, &p, end);
6519 nmodifiers = decode_byte (p, &p, end);
6521 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6522 req->id = InterlockedIncrement (&event_request_id);
6523 req->event_kind = event_kind;
6524 req->suspend_policy = suspend_policy;
6525 req->nmodifiers = nmodifiers;
6528 for (i = 0; i < nmodifiers; ++i) {
6529 mod = decode_byte (p, &p, end);
6531 req->modifiers [i].kind = mod;
6532 if (mod == MOD_KIND_COUNT) {
6533 req->modifiers [i].data.count = decode_int (p, &p, end);
6534 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6535 method = decode_methodid (p, &p, end, &domain, &err);
6538 location = decode_long (p, &p, end);
6539 } else if (mod == MOD_KIND_STEP) {
6540 step_thread_id = decode_id (p, &p, end);
6541 size = decode_int (p, &p, end);
6542 depth = decode_int (p, &p, end);
6543 if (CHECK_PROTOCOL_VERSION (2, 16))
6544 filter = decode_int (p, &p, end);
6545 req->modifiers [i].data.filter = filter;
6546 } else if (mod == MOD_KIND_THREAD_ONLY) {
6547 int id = decode_id (p, &p, end);
6549 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6554 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6555 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6559 req->modifiers [i].caught = decode_byte (p, &p, end);
6560 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6561 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" : ""));
6563 req->modifiers [i].data.exc_class = exc_class;
6565 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6567 return ERR_INVALID_ARGUMENT;
6570 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6571 int n = decode_int (p, &p, end);
6574 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6575 for (j = 0; j < n; ++j) {
6576 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6578 g_free (req->modifiers [i].data.assemblies);
6582 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6583 int n = decode_int (p, &p, end);
6586 modifier = &req->modifiers [i];
6587 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6588 for (j = 0; j < n; ++j) {
6589 char *s = decode_string (p, &p, end);
6593 s2 = strdup_tolower (s);
6594 g_hash_table_insert (modifier->data.source_files, s2, s2);
6598 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6599 int n = decode_int (p, &p, end);
6602 modifier = &req->modifiers [i];
6603 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6604 for (j = 0; j < n; ++j) {
6605 char *s = decode_string (p, &p, end);
6608 g_hash_table_insert (modifier->data.type_names, s, s);
6612 return ERR_NOT_IMPLEMENTED;
6616 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6619 req->info = set_breakpoint (method, location, req, &error);
6620 if (!mono_error_ok (&error)) {
6622 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6623 mono_error_cleanup (&error);
6624 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6626 } else if (req->event_kind == EVENT_KIND_STEP) {
6627 g_assert (step_thread_id);
6629 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6635 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6640 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6641 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6642 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6643 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6644 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6645 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6647 if (req->nmodifiers) {
6649 return ERR_NOT_IMPLEMENTED;
6653 mono_loader_lock ();
6654 g_ptr_array_add (event_requests, req);
6656 if (agent_config.defer) {
6657 /* Transmit cached data to the client on receipt of the event request */
6658 switch (req->event_kind) {
6659 case EVENT_KIND_APPDOMAIN_CREATE:
6660 /* Emit load events for currently loaded domains */
6661 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6663 case EVENT_KIND_ASSEMBLY_LOAD:
6664 /* Emit load events for currently loaded assemblies */
6665 mono_assembly_foreach (emit_assembly_load, NULL);
6667 case EVENT_KIND_THREAD_START:
6668 /* Emit start events for currently started threads */
6669 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6671 case EVENT_KIND_TYPE_LOAD:
6672 /* Emit type load events for currently loaded types */
6673 mono_domain_foreach (send_types_for_domain, NULL);
6679 mono_loader_unlock ();
6681 buffer_add_int (buf, req->id);
6684 case CMD_EVENT_REQUEST_CLEAR: {
6685 int etype = decode_byte (p, &p, end);
6686 int req_id = decode_int (p, &p, end);
6688 // FIXME: Make a faster mapping from req_id to request
6689 mono_loader_lock ();
6690 clear_event_request (req_id, etype);
6691 mono_loader_unlock ();
6694 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6697 mono_loader_lock ();
6699 while (i < event_requests->len) {
6700 EventRequest *req = g_ptr_array_index (event_requests, i);
6702 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6703 clear_breakpoint (req->info);
6705 g_ptr_array_remove_index_fast (event_requests, i);
6711 mono_loader_unlock ();
6715 return ERR_NOT_IMPLEMENTED;
6722 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6728 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6729 buffer_add_domainid (buf, mono_get_root_domain ());
6732 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6733 domain = decode_domainid (p, &p, end, NULL, &err);
6736 buffer_add_string (buf, domain->friendly_name);
6739 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6744 domain = decode_domainid (p, &p, end, NULL, &err);
6747 mono_loader_lock ();
6749 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6752 buffer_add_int (buf, count);
6753 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6755 buffer_add_assemblyid (buf, domain, ass);
6757 mono_loader_unlock ();
6760 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6761 domain = decode_domainid (p, &p, end, NULL, &err);
6765 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6768 case CMD_APPDOMAIN_GET_CORLIB: {
6769 domain = decode_domainid (p, &p, end, NULL, &err);
6773 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6776 case CMD_APPDOMAIN_CREATE_STRING: {
6780 domain = decode_domainid (p, &p, end, NULL, &err);
6783 s = decode_string (p, &p, end);
6785 o = mono_string_new (domain, s);
6786 buffer_add_objid (buf, (MonoObject*)o);
6789 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6791 MonoDomain *domain2;
6794 domain = decode_domainid (p, &p, end, NULL, &err);
6797 klass = decode_typeid (p, &p, end, &domain2, &err);
6802 g_assert (domain == domain2);
6804 o = mono_object_new (domain, klass);
6806 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6810 buffer_add_objid (buf, o);
6814 return ERR_NOT_IMPLEMENTED;
6821 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6827 ass = decode_assemblyid (p, &p, end, &domain, &err);
6832 case CMD_ASSEMBLY_GET_LOCATION: {
6833 buffer_add_string (buf, mono_image_get_filename (ass->image));
6836 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6840 if (ass->image->dynamic) {
6841 buffer_add_id (buf, 0);
6843 token = mono_image_get_entry_point (ass->image);
6845 buffer_add_id (buf, 0);
6847 m = mono_get_method (ass->image, token, NULL);
6848 buffer_add_methodid (buf, domain, m);
6853 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6854 buffer_add_moduleid (buf, domain, ass->image);
6857 case CMD_ASSEMBLY_GET_OBJECT: {
6858 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
6859 buffer_add_objid (buf, o);
6862 case CMD_ASSEMBLY_GET_TYPE: {
6863 char *s = decode_string (p, &p, end);
6864 gboolean ignorecase = decode_byte (p, &p, end);
6865 MonoTypeNameParse info;
6867 gboolean type_resolve, res;
6868 MonoDomain *d = mono_domain_get ();
6870 /* This is needed to be able to find referenced assemblies */
6871 res = mono_domain_set (domain, FALSE);
6874 if (!mono_reflection_parse_type (s, &info)) {
6877 if (info.assembly.name)
6879 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6881 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6882 mono_reflection_free_type_info (&info);
6885 mono_domain_set (d, TRUE);
6889 case CMD_ASSEMBLY_GET_NAME: {
6891 MonoAssembly *mass = ass;
6893 name = g_strdup_printf (
6894 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6896 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6897 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6898 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6899 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6901 buffer_add_string (buf, name);
6906 return ERR_NOT_IMPLEMENTED;
6913 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6919 case CMD_MODULE_GET_INFO: {
6920 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
6923 basename = g_path_get_basename (image->name);
6924 buffer_add_string (buf, basename); // name
6925 buffer_add_string (buf, image->module_name); // scopename
6926 buffer_add_string (buf, image->name); // fqname
6927 buffer_add_string (buf, mono_image_get_guid (image)); // guid
6928 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
6933 return ERR_NOT_IMPLEMENTED;
6940 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6942 if (val && val->vtable->klass == mono_defaults.monotype_class) {
6943 /* Special case these so the client doesn't have to handle Type objects */
6945 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6946 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
6947 } else if (MONO_TYPE_IS_REFERENCE (t))
6948 buffer_add_value (buf, t, &val, domain);
6950 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6954 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6960 buffer_add_int (buf, 0);
6964 for (i = 0; i < cinfo->num_attrs; ++i) {
6965 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6968 buffer_add_int (buf, nattrs);
6970 for (i = 0; i < cinfo->num_attrs; ++i) {
6971 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6972 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6973 MonoArray *typed_args, *named_args;
6975 CattrNamedArg *arginfo;
6977 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6979 buffer_add_methodid (buf, domain, attr->ctor);
6983 buffer_add_int (buf, mono_array_length (typed_args));
6984 for (j = 0; j < mono_array_length (typed_args); ++j) {
6985 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6987 t = mono_method_signature (attr->ctor)->params [j];
6989 buffer_add_cattr_arg (buf, t, domain, val);
6992 buffer_add_int (buf, 0);
6997 buffer_add_int (buf, mono_array_length (named_args));
6999 for (j = 0; j < mono_array_length (named_args); ++j) {
7000 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7002 if (arginfo [j].prop) {
7003 buffer_add_byte (buf, 0x54);
7004 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7005 } else if (arginfo [j].field) {
7006 buffer_add_byte (buf, 0x53);
7007 buffer_add_fieldid (buf, domain, arginfo [j].field);
7009 g_assert_not_reached ();
7012 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7015 buffer_add_int (buf, 0);
7021 /* FIXME: Code duplication with icall.c */
7023 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7028 mono_class_setup_interfaces (klass, error);
7029 if (!mono_error_ok (error))
7032 for (i = 0; i < klass->interface_count; i++) {
7033 ic = klass->interfaces [i];
7034 g_hash_table_insert (ifaces, ic, ic);
7036 collect_interfaces (ic, ifaces, error);
7037 if (!mono_error_ok (error))
7043 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7053 case CMD_TYPE_GET_INFO: {
7054 buffer_add_string (buf, klass->name_space);
7055 buffer_add_string (buf, klass->name);
7057 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7058 buffer_add_string (buf, name);
7060 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7061 buffer_add_moduleid (buf, domain, klass->image);
7062 buffer_add_typeid (buf, domain, klass->parent);
7063 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7064 buffer_add_typeid (buf, domain, klass->element_class);
7066 buffer_add_id (buf, 0);
7067 buffer_add_int (buf, klass->type_token);
7068 buffer_add_byte (buf, klass->rank);
7069 buffer_add_int (buf, klass->flags);
7071 type = &klass->byval_arg;
7072 // FIXME: Can't decide whenever a class represents a byref type
7075 if (type->type == MONO_TYPE_PTR)
7077 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7079 if (type->type == MONO_TYPE_VALUETYPE)
7081 if (klass->enumtype)
7083 if (klass->generic_container)
7085 if (klass->generic_container || klass->generic_class)
7087 buffer_add_byte (buf, b);
7090 while ((nested = mono_class_get_nested_types (klass, &iter)))
7092 buffer_add_int (buf, nnested);
7094 while ((nested = mono_class_get_nested_types (klass, &iter)))
7095 buffer_add_typeid (buf, domain, nested);
7096 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7097 if (klass->generic_container)
7098 buffer_add_typeid (buf, domain, klass);
7099 else if (klass->generic_class)
7100 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7102 buffer_add_id (buf, 0);
7104 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7107 if (klass->generic_class) {
7108 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7110 count = inst->type_argc;
7111 buffer_add_int (buf, count);
7112 for (i = 0; i < count; i++)
7113 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7114 } else if (klass->generic_container) {
7115 MonoGenericContainer *container = klass->generic_container;
7118 count = container->type_argc;
7119 buffer_add_int (buf, count);
7120 for (i = 0; i < count; i++) {
7121 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7122 buffer_add_typeid (buf, domain, pklass);
7125 buffer_add_int (buf, 0);
7130 case CMD_TYPE_GET_METHODS: {
7133 gpointer iter = NULL;
7136 mono_class_setup_methods (klass);
7138 nmethods = mono_class_num_methods (klass);
7140 buffer_add_int (buf, nmethods);
7142 while ((m = mono_class_get_methods (klass, &iter))) {
7143 buffer_add_methodid (buf, domain, m);
7146 g_assert (i == nmethods);
7149 case CMD_TYPE_GET_FIELDS: {
7152 gpointer iter = NULL;
7155 nfields = mono_class_num_fields (klass);
7157 buffer_add_int (buf, nfields);
7159 while ((f = mono_class_get_fields (klass, &iter))) {
7160 buffer_add_fieldid (buf, domain, f);
7161 buffer_add_string (buf, f->name);
7162 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7163 buffer_add_int (buf, f->type->attrs);
7166 g_assert (i == nfields);
7169 case CMD_TYPE_GET_PROPERTIES: {
7172 gpointer iter = NULL;
7175 nprops = mono_class_num_properties (klass);
7177 buffer_add_int (buf, nprops);
7179 while ((p = mono_class_get_properties (klass, &iter))) {
7180 buffer_add_propertyid (buf, domain, p);
7181 buffer_add_string (buf, p->name);
7182 buffer_add_methodid (buf, domain, p->get);
7183 buffer_add_methodid (buf, domain, p->set);
7184 buffer_add_int (buf, p->attrs);
7187 g_assert (i == nprops);
7190 case CMD_TYPE_GET_CATTRS: {
7191 MonoClass *attr_klass;
7192 MonoCustomAttrInfo *cinfo;
7194 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7195 /* attr_klass can be NULL */
7199 cinfo = mono_custom_attrs_from_class (klass);
7201 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7204 case CMD_TYPE_GET_FIELD_CATTRS: {
7205 MonoClass *attr_klass;
7206 MonoCustomAttrInfo *cinfo;
7207 MonoClassField *field;
7209 field = decode_fieldid (p, &p, end, NULL, &err);
7212 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7216 cinfo = mono_custom_attrs_from_field (klass, field);
7218 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7221 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7222 MonoClass *attr_klass;
7223 MonoCustomAttrInfo *cinfo;
7226 prop = decode_propertyid (p, &p, end, NULL, &err);
7229 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7233 cinfo = mono_custom_attrs_from_property (klass, prop);
7235 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7238 case CMD_TYPE_GET_VALUES:
7239 case CMD_TYPE_GET_VALUES_2: {
7246 MonoThread *thread_obj;
7247 MonoInternalThread *thread = NULL;
7248 guint32 special_static_type;
7250 if (command == CMD_TYPE_GET_VALUES_2) {
7251 int objid = decode_objid (p, &p, end);
7254 err = get_object (objid, (MonoObject**)&thread_obj);
7258 thread = THREAD_TO_INTERNAL (thread_obj);
7261 len = decode_int (p, &p, end);
7262 for (i = 0; i < len; ++i) {
7263 f = decode_fieldid (p, &p, end, NULL, &err);
7267 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7268 return ERR_INVALID_FIELDID;
7269 special_static_type = mono_class_field_get_special_static_type (f);
7270 if (special_static_type != SPECIAL_STATIC_NONE) {
7271 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7272 return ERR_INVALID_FIELDID;
7275 /* Check that the field belongs to the object */
7277 for (k = klass; k; k = k->parent) {
7278 if (k == f->parent) {
7284 return ERR_INVALID_FIELDID;
7286 vtable = mono_class_vtable (domain, f->parent);
7287 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7288 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7289 buffer_add_value (buf, f->type, val, domain);
7294 case CMD_TYPE_SET_VALUES: {
7302 len = decode_int (p, &p, end);
7303 for (i = 0; i < len; ++i) {
7304 f = decode_fieldid (p, &p, end, NULL, &err);
7308 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7309 return ERR_INVALID_FIELDID;
7310 if (mono_class_field_is_special_static (f))
7311 return ERR_INVALID_FIELDID;
7313 /* Check that the field belongs to the object */
7315 for (k = klass; k; k = k->parent) {
7316 if (k == f->parent) {
7322 return ERR_INVALID_FIELDID;
7324 // FIXME: Check for literal/const
7326 vtable = mono_class_vtable (domain, f->parent);
7327 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7328 err = decode_value (f->type, domain, val, p, &p, end);
7333 if (MONO_TYPE_IS_REFERENCE (f->type))
7334 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7336 mono_field_static_set_value (vtable, f, val);
7341 case CMD_TYPE_GET_OBJECT: {
7342 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7343 buffer_add_objid (buf, o);
7346 case CMD_TYPE_GET_SOURCE_FILES:
7347 case CMD_TYPE_GET_SOURCE_FILES_2: {
7348 char *source_file, *base;
7352 files = get_source_files_for_type (klass);
7354 buffer_add_int (buf, files->len);
7355 for (i = 0; i < files->len; ++i) {
7356 source_file = g_ptr_array_index (files, i);
7357 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7358 buffer_add_string (buf, source_file);
7360 base = g_path_get_basename (source_file);
7361 buffer_add_string (buf, base);
7364 g_free (source_file);
7366 g_ptr_array_free (files, TRUE);
7369 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7370 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7374 if (mono_class_is_assignable_from (klass, oklass))
7375 buffer_add_byte (buf, 1);
7377 buffer_add_byte (buf, 0);
7380 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7381 char *name = decode_string (p, &p, end);
7382 int i, flags = decode_int (p, &p, end);
7383 MonoException *ex = NULL;
7384 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7387 return ERR_LOADER_ERROR;
7388 buffer_add_int (buf, array->len);
7389 for (i = 0; i < array->len; ++i) {
7390 MonoMethod *method = g_ptr_array_index (array, i);
7391 buffer_add_methodid (buf, domain, method);
7394 g_ptr_array_free (array, TRUE);
7398 case CMD_TYPE_GET_INTERFACES: {
7400 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7402 MonoClass *tclass, *iface;
7403 GHashTableIter iter;
7407 for (parent = tclass; parent; parent = parent->parent) {
7408 mono_class_setup_interfaces (parent, &error);
7409 if (!mono_error_ok (&error))
7410 return ERR_LOADER_ERROR;
7411 collect_interfaces (parent, iface_hash, &error);
7412 if (!mono_error_ok (&error))
7413 return ERR_LOADER_ERROR;
7416 buffer_add_int (buf, g_hash_table_size (iface_hash));
7418 g_hash_table_iter_init (&iter, iface_hash);
7419 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7420 buffer_add_typeid (buf, domain, iface);
7421 g_hash_table_destroy (iface_hash);
7424 case CMD_TYPE_GET_INTERFACE_MAP: {
7425 int tindex, ioffset;
7426 gboolean variance_used;
7428 int len, nmethods, i;
7432 len = decode_int (p, &p, end);
7433 mono_class_setup_vtable (klass);
7435 for (tindex = 0; tindex < len; ++tindex) {
7436 iclass = decode_typeid (p, &p, end, NULL, &err);
7440 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7442 return ERR_INVALID_ARGUMENT;
7444 nmethods = mono_class_num_methods (iclass);
7445 buffer_add_int (buf, nmethods);
7448 while ((method = mono_class_get_methods (iclass, &iter))) {
7449 buffer_add_methodid (buf, domain, method);
7451 for (i = 0; i < nmethods; ++i)
7452 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7457 return ERR_NOT_IMPLEMENTED;
7464 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7467 MonoDomain *old_domain;
7471 klass = decode_typeid (p, &p, end, &domain, &err);
7475 old_domain = mono_domain_get ();
7477 mono_domain_set (domain, TRUE);
7479 err = type_commands_internal (command, klass, domain, p, end, buf);
7481 mono_domain_set (old_domain, TRUE);
7487 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7489 MonoMethodHeader *header;
7492 case CMD_METHOD_GET_NAME: {
7493 buffer_add_string (buf, method->name);
7496 case CMD_METHOD_GET_DECLARING_TYPE: {
7497 buffer_add_typeid (buf, domain, method->klass);
7500 case CMD_METHOD_GET_DEBUG_INFO: {
7501 MonoDebugMethodInfo *minfo;
7503 int i, j, n_il_offsets;
7507 GPtrArray *source_file_list;
7509 header = mono_method_get_header (method);
7511 buffer_add_int (buf, 0);
7512 buffer_add_string (buf, "");
7513 buffer_add_int (buf, 0);
7517 minfo = mono_debug_lookup_method (method);
7519 buffer_add_int (buf, header->code_size);
7520 buffer_add_string (buf, "");
7521 buffer_add_int (buf, 0);
7522 mono_metadata_free_mh (header);
7526 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &source_files);
7527 buffer_add_int (buf, header->code_size);
7528 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7529 buffer_add_int (buf, source_file_list->len);
7530 for (i = 0; i < source_file_list->len; ++i) {
7531 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7532 buffer_add_string (buf, sinfo->source_file);
7533 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7534 for (j = 0; j < 16; ++j)
7535 buffer_add_byte (buf, sinfo->hash [j]);
7539 buffer_add_string (buf, source_file);
7541 buffer_add_int (buf, n_il_offsets);
7542 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7543 for (i = 0; i < n_il_offsets; ++i) {
7544 const char *srcfile = "";
7546 if (source_files [i] != -1) {
7547 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7548 srcfile = sinfo->source_file;
7550 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d\n", il_offsets [i], srcfile, line_numbers [i]));
7551 buffer_add_int (buf, il_offsets [i]);
7552 buffer_add_int (buf, line_numbers [i]);
7553 if (CHECK_PROTOCOL_VERSION (2, 13))
7554 buffer_add_int (buf, source_files [i]);
7556 g_free (source_file);
7557 g_free (il_offsets);
7558 g_free (line_numbers);
7559 g_free (source_files);
7560 g_ptr_array_free (source_file_list, TRUE);
7561 mono_metadata_free_mh (header);
7564 case CMD_METHOD_GET_PARAM_INFO: {
7565 MonoMethodSignature *sig = mono_method_signature (method);
7569 /* FIXME: mono_class_from_mono_type () and byrefs */
7571 /* FIXME: Use a smaller encoding */
7572 buffer_add_int (buf, sig->call_convention);
7573 buffer_add_int (buf, sig->param_count);
7574 buffer_add_int (buf, sig->generic_param_count);
7575 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7576 for (i = 0; i < sig->param_count; ++i) {
7578 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7581 /* Emit parameter names */
7582 names = g_new (char *, sig->param_count);
7583 mono_method_get_param_names (method, (const char **) names);
7584 for (i = 0; i < sig->param_count; ++i)
7585 buffer_add_string (buf, names [i]);
7590 case CMD_METHOD_GET_LOCALS_INFO: {
7591 int i, j, num_locals;
7592 MonoDebugLocalsInfo *locals;
7594 header = mono_method_get_header (method);
7596 return ERR_INVALID_ARGUMENT;
7598 buffer_add_int (buf, header->num_locals);
7601 for (i = 0; i < header->num_locals; ++i)
7602 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7605 locals = mono_debug_lookup_locals (method);
7607 num_locals = locals->num_locals;
7610 for (i = 0; i < header->num_locals; ++i) {
7611 for (j = 0; j < num_locals; ++j)
7612 if (locals->locals [j].index == i)
7615 buffer_add_string (buf, locals->locals [j].name);
7617 buffer_add_string (buf, "");
7621 for (i = 0; i < header->num_locals; ++i) {
7622 for (j = 0; j < num_locals; ++j)
7623 if (locals->locals [j].index == i)
7625 if (j < num_locals && locals->locals [j].block) {
7626 buffer_add_int (buf, locals->locals [j].block->start_offset);
7627 buffer_add_int (buf, locals->locals [j].block->end_offset);
7629 buffer_add_int (buf, 0);
7630 buffer_add_int (buf, header->code_size);
7633 mono_metadata_free_mh (header);
7636 mono_debug_symfile_free_locals (locals);
7640 case CMD_METHOD_GET_INFO:
7641 buffer_add_int (buf, method->flags);
7642 buffer_add_int (buf, method->iflags);
7643 buffer_add_int (buf, method->token);
7644 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7646 if (method->is_generic)
7648 if (mono_method_signature (method)->generic_param_count)
7650 buffer_add_byte (buf, attrs);
7651 if (method->is_generic || method->is_inflated) {
7654 if (method->is_generic) {
7657 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7659 result = imethod->declaring;
7660 if (imethod->context.class_inst) {
7661 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7662 /*Generic methods gets the context of the GTD.*/
7663 if (mono_class_get_context (klass))
7664 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7668 buffer_add_methodid (buf, domain, result);
7670 buffer_add_id (buf, 0);
7672 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7673 if (mono_method_signature (method)->generic_param_count) {
7676 if (method->is_inflated) {
7677 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7679 count = inst->type_argc;
7680 buffer_add_int (buf, count);
7682 for (i = 0; i < count; i++)
7683 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7685 buffer_add_int (buf, 0);
7687 } else if (method->is_generic) {
7688 MonoGenericContainer *container = mono_method_get_generic_container (method);
7690 count = mono_method_signature (method)->generic_param_count;
7691 buffer_add_int (buf, count);
7692 for (i = 0; i < count; i++) {
7693 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7694 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7695 buffer_add_typeid (buf, domain, pklass);
7698 buffer_add_int (buf, 0);
7701 buffer_add_int (buf, 0);
7706 case CMD_METHOD_GET_BODY: {
7709 header = mono_method_get_header (method);
7711 buffer_add_int (buf, 0);
7713 buffer_add_int (buf, header->code_size);
7714 for (i = 0; i < header->code_size; ++i)
7715 buffer_add_byte (buf, header->code [i]);
7717 mono_metadata_free_mh (header);
7720 case CMD_METHOD_RESOLVE_TOKEN: {
7721 guint32 token = decode_int (p, &p, end);
7724 switch (mono_metadata_token_code (token)) {
7725 case MONO_TOKEN_STRING: {
7729 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7732 s2 = mono_string_to_utf8 (s);
7734 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7735 buffer_add_string (buf, s2);
7741 MonoClass *handle_class;
7743 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7744 val = mono_method_get_wrapper_data (method, token);
7745 handle_class = mono_method_get_wrapper_data (method, token + 1);
7747 if (handle_class == NULL) {
7748 // Can't figure out the token type
7749 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7753 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7757 if (handle_class == mono_defaults.typehandle_class) {
7758 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7759 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7760 buffer_add_typeid (buf, domain, (MonoClass *) val);
7762 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7763 } else if (handle_class == mono_defaults.fieldhandle_class) {
7764 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7765 buffer_add_fieldid (buf, domain, val);
7766 } else if (handle_class == mono_defaults.methodhandle_class) {
7767 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7768 buffer_add_methodid (buf, domain, val);
7769 } else if (handle_class == mono_defaults.string_class) {
7772 s = mono_string_to_utf8 (val);
7773 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7774 buffer_add_string (buf, s);
7777 g_assert_not_reached ();
7785 return ERR_NOT_IMPLEMENTED;
7792 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7795 MonoDomain *old_domain;
7799 method = decode_methodid (p, &p, end, &domain, &err);
7803 old_domain = mono_domain_get ();
7805 mono_domain_set (domain, TRUE);
7807 err = method_commands_internal (command, method, domain, p, end, buf);
7809 mono_domain_set (old_domain, TRUE);
7815 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7817 int objid = decode_objid (p, &p, end);
7819 MonoThread *thread_obj;
7820 MonoInternalThread *thread;
7822 err = get_object (objid, (MonoObject**)&thread_obj);
7826 thread = THREAD_TO_INTERNAL (thread_obj);
7829 case CMD_THREAD_GET_NAME: {
7831 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7834 buffer_add_int (buf, 0);
7839 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7841 buffer_add_int (buf, len);
7842 buffer_add_data (buf, (guint8*)name, len);
7847 case CMD_THREAD_GET_FRAME_INFO: {
7848 DebuggerTlsData *tls;
7849 int i, start_frame, length;
7851 // Wait for suspending if it already started
7852 // FIXME: Races with suspend_count
7853 while (!is_suspended ()) {
7855 wait_for_suspend ();
7859 wait_for_suspend ();
7860 if (!is_suspended ())
7861 return ERR_NOT_SUSPENDED;
7864 start_frame = decode_int (p, &p, end);
7865 length = decode_int (p, &p, end);
7867 if (start_frame != 0 || length != -1)
7868 return ERR_NOT_IMPLEMENTED;
7870 mono_loader_lock ();
7871 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7872 mono_loader_unlock ();
7875 compute_frame_info (thread, tls);
7877 buffer_add_int (buf, tls->frame_count);
7878 for (i = 0; i < tls->frame_count; ++i) {
7879 buffer_add_int (buf, tls->frames [i]->id);
7880 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
7881 buffer_add_int (buf, tls->frames [i]->il_offset);
7883 * Instead of passing the frame type directly to the client, we associate
7884 * it with the previous frame using a set of flags. This avoids lots of
7885 * conditional code in the client, since a frame whose type isn't
7886 * FRAME_TYPE_MANAGED has no method, location, etc.
7888 buffer_add_byte (buf, tls->frames [i]->flags);
7893 case CMD_THREAD_GET_STATE:
7894 buffer_add_int (buf, thread->state);
7896 case CMD_THREAD_GET_INFO:
7897 buffer_add_byte (buf, thread->threadpool_thread);
7899 case CMD_THREAD_GET_ID:
7900 buffer_add_long (buf, (guint64)(gsize)thread);
7902 case CMD_THREAD_GET_TID:
7903 buffer_add_long (buf, (guint64)thread->tid);
7906 return ERR_NOT_IMPLEMENTED;
7913 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7917 MonoThread *thread_obj;
7918 MonoInternalThread *thread;
7919 int pos, i, len, frame_idx;
7920 DebuggerTlsData *tls;
7922 MonoDebugMethodJitInfo *jit;
7923 MonoDebugVarInfo *var;
7924 MonoMethodSignature *sig;
7926 MonoMethodHeader *header;
7928 objid = decode_objid (p, &p, end);
7929 err = get_object (objid, (MonoObject**)&thread_obj);
7933 thread = THREAD_TO_INTERNAL (thread_obj);
7935 id = decode_id (p, &p, end);
7937 mono_loader_lock ();
7938 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7939 mono_loader_unlock ();
7942 for (i = 0; i < tls->frame_count; ++i) {
7943 if (tls->frames [i]->id == id)
7946 if (i == tls->frame_count)
7947 return ERR_INVALID_FRAMEID;
7950 frame = tls->frames [frame_idx];
7952 if (!frame->has_ctx)
7954 return ERR_INVALID_FRAMEID;
7957 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
7958 if (!frame->jit && frame->api_method->is_inflated)
7959 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
7963 /* This could happen for aot images with no jit debug info */
7964 s = mono_method_full_name (frame->api_method, TRUE);
7965 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
7967 return ERR_ABSENT_INFORMATION;
7972 sig = mono_method_signature (frame->actual_method);
7974 if (!get_seq_points (frame->domain, frame->actual_method))
7976 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
7978 return ERR_ABSENT_INFORMATION;
7981 case CMD_STACK_FRAME_GET_VALUES: {
7982 len = decode_int (p, &p, end);
7983 header = mono_method_get_header (frame->actual_method);
7985 for (i = 0; i < len; ++i) {
7986 pos = decode_int (p, &p, end);
7991 g_assert (pos >= 0 && pos < jit->num_params);
7993 var = &jit->params [pos];
7995 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
7997 g_assert (pos >= 0 && pos < jit->num_locals);
7999 var = &jit->locals [pos];
8001 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8004 mono_metadata_free_mh (header);
8007 case CMD_STACK_FRAME_GET_THIS: {
8008 if (frame->api_method->klass->valuetype) {
8009 if (!sig->hasthis) {
8010 MonoObject *p = NULL;
8011 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8013 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8016 if (!sig->hasthis) {
8017 MonoObject *p = NULL;
8018 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8020 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8025 case CMD_STACK_FRAME_SET_VALUES: {
8028 MonoDebugVarInfo *var;
8030 len = decode_int (p, &p, end);
8031 header = mono_method_get_header (frame->actual_method);
8033 for (i = 0; i < len; ++i) {
8034 pos = decode_int (p, &p, end);
8039 g_assert (pos >= 0 && pos < jit->num_params);
8041 t = sig->params [pos];
8042 var = &jit->params [pos];
8044 g_assert (pos >= 0 && pos < jit->num_locals);
8046 t = header->locals [pos];
8047 var = &jit->locals [pos];
8050 if (MONO_TYPE_IS_REFERENCE (t))
8051 val_buf = g_alloca (sizeof (MonoObject*));
8053 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8054 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8058 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8060 mono_metadata_free_mh (header);
8064 return ERR_NOT_IMPLEMENTED;
8071 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8074 int objid, err, index, len, i, esize;
8077 objid = decode_objid (p, &p, end);
8078 err = get_object (objid, (MonoObject**)&arr);
8083 case CMD_ARRAY_REF_GET_LENGTH:
8084 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8086 buffer_add_int (buf, arr->max_length);
8087 buffer_add_int (buf, 0);
8089 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8090 buffer_add_int (buf, arr->bounds [i].length);
8091 buffer_add_int (buf, arr->bounds [i].lower_bound);
8095 case CMD_ARRAY_REF_GET_VALUES:
8096 index = decode_int (p, &p, end);
8097 len = decode_int (p, &p, end);
8099 g_assert (index >= 0 && len >= 0);
8100 // Reordered to avoid integer overflow
8101 g_assert (!(index > arr->max_length - len));
8103 esize = mono_array_element_size (arr->obj.vtable->klass);
8104 for (i = index; i < index + len; ++i) {
8105 elem = (gpointer*)((char*)arr->vector + (i * esize));
8106 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8109 case CMD_ARRAY_REF_SET_VALUES:
8110 index = decode_int (p, &p, end);
8111 len = decode_int (p, &p, end);
8113 g_assert (index >= 0 && len >= 0);
8114 // Reordered to avoid integer overflow
8115 g_assert (!(index > arr->max_length - len));
8117 esize = mono_array_element_size (arr->obj.vtable->klass);
8118 for (i = index; i < index + len; ++i) {
8119 elem = (gpointer*)((char*)arr->vector + (i * esize));
8121 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8125 return ERR_NOT_IMPLEMENTED;
8132 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8137 int i, index, length;
8140 objid = decode_objid (p, &p, end);
8141 err = get_object (objid, (MonoObject**)&str);
8146 case CMD_STRING_REF_GET_VALUE:
8147 s = mono_string_to_utf8 (str);
8148 buffer_add_string (buf, s);
8151 case CMD_STRING_REF_GET_LENGTH:
8152 buffer_add_long (buf, mono_string_length (str));
8154 case CMD_STRING_REF_GET_CHARS:
8155 index = decode_long (p, &p, end);
8156 length = decode_long (p, &p, end);
8157 if (index > mono_string_length (str) - length)
8158 return ERR_INVALID_ARGUMENT;
8159 c = mono_string_chars (str) + index;
8160 for (i = 0; i < length; ++i)
8161 buffer_add_short (buf, c [i]);
8164 return ERR_NOT_IMPLEMENTED;
8171 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8180 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8181 objid = decode_objid (p, &p, end);
8182 err = get_object (objid, &obj);
8184 buffer_add_int (buf, 1);
8186 buffer_add_int (buf, 0);
8190 objid = decode_objid (p, &p, end);
8191 err = get_object (objid, &obj);
8196 case CMD_OBJECT_REF_GET_TYPE:
8197 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8199 case CMD_OBJECT_REF_GET_VALUES:
8200 len = decode_int (p, &p, end);
8202 for (i = 0; i < len; ++i) {
8203 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8207 /* Check that the field belongs to the object */
8209 for (k = obj->vtable->klass; k; k = k->parent) {
8210 if (k == f->parent) {
8216 return ERR_INVALID_FIELDID;
8218 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8222 if (mono_class_field_is_special_static (f))
8223 return ERR_INVALID_FIELDID;
8225 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8226 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8227 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8228 mono_field_static_get_value (vtable, f, val);
8229 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8232 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8236 case CMD_OBJECT_REF_SET_VALUES:
8237 len = decode_int (p, &p, end);
8239 for (i = 0; i < len; ++i) {
8240 f = decode_fieldid (p, &p, end, NULL, &err);
8244 /* Check that the field belongs to the object */
8246 for (k = obj->vtable->klass; k; k = k->parent) {
8247 if (k == f->parent) {
8253 return ERR_INVALID_FIELDID;
8255 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8259 if (mono_class_field_is_special_static (f))
8260 return ERR_INVALID_FIELDID;
8262 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8263 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8265 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8266 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8271 mono_field_static_set_value (vtable, f, val);
8274 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8280 case CMD_OBJECT_REF_GET_ADDRESS:
8281 buffer_add_long (buf, (gssize)obj);
8283 case CMD_OBJECT_REF_GET_DOMAIN:
8284 buffer_add_domainid (buf, obj->vtable->domain);
8286 case CMD_OBJECT_REF_GET_INFO:
8287 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
8288 buffer_add_domainid (buf, obj->vtable->domain);
8291 return ERR_NOT_IMPLEMENTED;
8298 command_set_to_string (CommandSet command_set)
8300 switch (command_set) {
8303 case CMD_SET_OBJECT_REF:
8304 return "OBJECT_REF";
8305 case CMD_SET_STRING_REF:
8306 return "STRING_REF";
8307 case CMD_SET_THREAD:
8309 case CMD_SET_ARRAY_REF:
8311 case CMD_SET_EVENT_REQUEST:
8312 return "EVENT_REQUEST";
8313 case CMD_SET_STACK_FRAME:
8314 return "STACK_FRAME";
8315 case CMD_SET_APPDOMAIN:
8317 case CMD_SET_ASSEMBLY:
8319 case CMD_SET_METHOD:
8323 case CMD_SET_MODULE:
8333 cmd_to_string (CommandSet set, int command)
8338 case CMD_VM_VERSION:
8340 case CMD_VM_ALL_THREADS:
8341 return "ALL_THREADS";
8342 case CMD_VM_SUSPEND:
8348 case CMD_VM_DISPOSE:
8350 case CMD_VM_INVOKE_METHOD:
8351 return "INVOKE_METHOD";
8352 case CMD_VM_SET_PROTOCOL_VERSION:
8353 return "SET_PROTOCOL_VERSION";
8354 case CMD_VM_ABORT_INVOKE:
8355 return "ABORT_INVOKE";
8368 wait_for_attach (void)
8370 #ifndef DISABLE_SOCKET_TRANSPORT
8371 if (listen_fd == -1) {
8372 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8376 /* Block and wait for client connection */
8377 conn_fd = socket_transport_accept (listen_fd);
8378 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8379 if (conn_fd == -1) {
8380 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8384 g_assert_not_reached ();
8388 disconnected = !transport_handshake ();
8390 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8400 * This thread handles communication with the debugger client using a JDWP
8403 static guint32 WINAPI
8404 debugger_thread (void *arg)
8406 int res, len, id, flags, command_set = 0, command = 0;
8407 guint8 header [HEADER_LENGTH];
8408 guint8 *data, *p, *end;
8412 gboolean attach_failed = FALSE;
8414 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8416 debugger_thread_id = GetCurrentThreadId ();
8418 mono_jit_thread_attach (mono_get_root_domain ());
8420 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8422 mono_set_is_debugger_attached (TRUE);
8424 if (agent_config.defer) {
8425 if (!wait_for_attach ()) {
8426 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8427 attach_failed = TRUE; // Don't abort process when we can't listen
8429 /* Send start event to client */
8430 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8434 while (!attach_failed) {
8435 res = transport_recv (header, HEADER_LENGTH);
8437 /* This will break if the socket is closed during shutdown too */
8438 if (res != HEADER_LENGTH)
8442 end = header + HEADER_LENGTH;
8444 len = decode_int (p, &p, end);
8445 id = decode_int (p, &p, end);
8446 flags = decode_byte (p, &p, end);
8447 command_set = decode_byte (p, &p, end);
8448 command = decode_byte (p, &p, end);
8450 g_assert (flags == 0);
8453 const char *cmd_str;
8456 cmd_str = cmd_to_string (command_set, command);
8458 sprintf (cmd_num, "%d", command);
8462 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8465 data = g_malloc (len - HEADER_LENGTH);
8466 if (len - HEADER_LENGTH > 0)
8468 res = transport_recv (data, len - HEADER_LENGTH);
8469 if (res != len - HEADER_LENGTH)
8474 end = data + (len - HEADER_LENGTH);
8476 buffer_init (&buf, 128);
8481 /* Process the request */
8482 switch (command_set) {
8484 err = vm_commands (command, id, p, end, &buf);
8485 if (!err && command == CMD_VM_INVOKE_METHOD)
8486 /* Sent after the invoke is complete */
8489 case CMD_SET_EVENT_REQUEST:
8490 err = event_commands (command, p, end, &buf);
8492 case CMD_SET_APPDOMAIN:
8493 err = domain_commands (command, p, end, &buf);
8495 case CMD_SET_ASSEMBLY:
8496 err = assembly_commands (command, p, end, &buf);
8498 case CMD_SET_MODULE:
8499 err = module_commands (command, p, end, &buf);
8502 err = type_commands (command, p, end, &buf);
8504 case CMD_SET_METHOD:
8505 err = method_commands (command, p, end, &buf);
8507 case CMD_SET_THREAD:
8508 err = thread_commands (command, p, end, &buf);
8510 case CMD_SET_STACK_FRAME:
8511 err = frame_commands (command, p, end, &buf);
8513 case CMD_SET_ARRAY_REF:
8514 err = array_commands (command, p, end, &buf);
8516 case CMD_SET_STRING_REF:
8517 err = string_commands (command, p, end, &buf);
8519 case CMD_SET_OBJECT_REF:
8520 err = object_commands (command, p, end, &buf);
8523 err = ERR_NOT_IMPLEMENTED;
8527 send_reply_packet (id, err, &buf);
8532 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8536 mono_set_is_debugger_attached (FALSE);
8538 mono_mutex_lock (&debugger_thread_exited_mutex);
8539 debugger_thread_exited = TRUE;
8540 mono_cond_signal (&debugger_thread_exited_cond);
8541 mono_mutex_unlock (&debugger_thread_exited_mutex);
8543 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8545 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8546 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8547 start_debugger_thread ();
8553 #else /* DISABLE_DEBUGGER_AGENT */
8556 mono_debugger_agent_parse_options (char *options)
8558 g_error ("This runtime is configured with the debugger agent disabled.");
8562 mono_debugger_agent_init (void)
8567 mono_debugger_agent_breakpoint_hit (void *sigctx)
8572 mono_debugger_agent_single_step_event (void *sigctx)
8577 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8582 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8588 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8589 MonoContext *catch_ctx)
8594 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8599 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8604 mono_debugger_agent_user_break (void)
8610 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8615 mono_debugger_agent_debug_log_is_enabled (void)