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 MonoDebugMethodJitInfo *jit;
134 mgreg_t *reg_locations [MONO_MAX_IREGS];
136 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
137 * the frame can become invalid.
142 typedef struct _InvokeData InvokeData;
150 /* This is the context which needs to be restored after the invoke */
154 * If this is set, invoke this method with the arguments given by ARGS.
158 guint32 suspend_count;
160 InvokeData *last_invoke;
164 MonoThreadUnwindState context;
166 gpointer resume_event;
167 /* This is computed on demand when it is requested using the wire protocol */
168 /* It is freed up when the thread is resumed */
172 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
175 gboolean frames_up_to_date;
177 * Points to data about a pending invoke which needs to be executed after the thread
180 InvokeData *pending_invoke;
182 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
187 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
188 * within a finite amount of time.
192 * Set to TRUE if this thread is suspended in suspend_current ().
194 gboolean really_suspended;
195 /* Used to pass the context to the breakpoint/single step handler */
196 MonoContext handler_ctx;
197 /* Whenever thread_stop () was called for this thread */
200 /* Number of thread interruptions not yet processed */
201 gint32 interrupt_count;
203 /* Whenever to disable breakpoints (used during invokes) */
204 gboolean disable_breakpoints;
207 * Number of times this thread has been resumed using resume_thread ().
209 guint32 resume_count;
211 MonoInternalThread *thread;
214 * Information about the frame which transitioned to native code for running
217 StackFrameInfo async_last_frame;
220 * The context where the stack walk can be started for running threads.
222 MonoThreadUnwindState async_state;
225 * The context used for filter clauses
227 MonoThreadUnwindState filter_state;
230 * The callee address of the last mono_runtime_invoke call
232 gpointer invoke_addr;
234 gboolean abort_requested;
237 * The current mono_runtime_invoke invocation.
242 * The context where single stepping should resume while the thread is suspended because
243 * of an EXCEPTION event.
245 MonoContext catch_ctx;
247 gboolean has_catch_ctx;
250 * The context which needs to be restored after handling a single step/breakpoint
251 * event. This is the same as the ctx at step/breakpoint site, but includes changes
252 * to caller saved registers done by set_var ().
254 MonoContext restore_ctx;
259 void (*connect) (const char *address);
260 void (*close1) (void);
261 void (*close2) (void);
262 gboolean (*send) (void *buf, int len);
263 int (*recv) (void *buf, int len);
267 * Wire Protocol definitions
270 #define HEADER_LENGTH 11
272 #define MAJOR_VERSION 2
273 #define MINOR_VERSION 11
277 CMD_SET_OBJECT_REF = 9,
278 CMD_SET_STRING_REF = 10,
280 CMD_SET_ARRAY_REF = 13,
281 CMD_SET_EVENT_REQUEST = 15,
282 CMD_SET_STACK_FRAME = 16,
283 CMD_SET_APPDOMAIN = 20,
284 CMD_SET_ASSEMBLY = 21,
292 EVENT_KIND_VM_START = 0,
293 EVENT_KIND_VM_DEATH = 1,
294 EVENT_KIND_THREAD_START = 2,
295 EVENT_KIND_THREAD_DEATH = 3,
296 EVENT_KIND_APPDOMAIN_CREATE = 4,
297 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
298 EVENT_KIND_METHOD_ENTRY = 6,
299 EVENT_KIND_METHOD_EXIT = 7,
300 EVENT_KIND_ASSEMBLY_LOAD = 8,
301 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
302 EVENT_KIND_BREAKPOINT = 10,
303 EVENT_KIND_STEP = 11,
304 EVENT_KIND_TYPE_LOAD = 12,
305 EVENT_KIND_EXCEPTION = 13,
306 EVENT_KIND_KEEPALIVE = 14,
307 EVENT_KIND_USER_BREAK = 15,
308 EVENT_KIND_USER_LOG = 16
312 SUSPEND_POLICY_NONE = 0,
313 SUSPEND_POLICY_EVENT_THREAD = 1,
314 SUSPEND_POLICY_ALL = 2
319 ERR_INVALID_OBJECT = 20,
320 ERR_INVALID_FIELDID = 25,
321 ERR_INVALID_FRAMEID = 30,
322 ERR_NOT_IMPLEMENTED = 100,
323 ERR_NOT_SUSPENDED = 101,
324 ERR_INVALID_ARGUMENT = 102,
326 ERR_NO_INVOCATION = 104,
327 ERR_ABSENT_INFORMATION = 105,
328 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
329 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
334 MOD_KIND_THREAD_ONLY = 3,
335 MOD_KIND_LOCATION_ONLY = 7,
336 MOD_KIND_EXCEPTION_ONLY = 8,
338 MOD_KIND_ASSEMBLY_ONLY = 11,
339 MOD_KIND_SOURCE_FILE_ONLY = 12,
340 MOD_KIND_TYPE_NAME_ONLY = 13
355 TOKEN_TYPE_STRING = 0,
357 TOKEN_TYPE_FIELD = 2,
358 TOKEN_TYPE_METHOD = 3,
359 TOKEN_TYPE_UNKNOWN = 4
363 VALUE_TYPE_ID_NULL = 0xf0,
364 VALUE_TYPE_ID_TYPE = 0xf1
368 FRAME_FLAG_DEBUGGER_INVOKE = 1
372 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
373 INVOKE_FLAG_SINGLE_THREADED = 2
377 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
378 } BindingFlagsExtensions;
382 CMD_VM_ALL_THREADS = 2,
387 CMD_VM_INVOKE_METHOD = 7,
388 CMD_VM_SET_PROTOCOL_VERSION = 8,
389 CMD_VM_ABORT_INVOKE = 9,
390 CMD_VM_SET_KEEPALIVE = 10,
391 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
392 CMD_VM_GET_TYPES = 12
396 CMD_THREAD_GET_FRAME_INFO = 1,
397 CMD_THREAD_GET_NAME = 2,
398 CMD_THREAD_GET_STATE = 3,
399 CMD_THREAD_GET_INFO = 4,
400 CMD_THREAD_GET_ID = 5,
401 CMD_THREAD_GET_TID = 6
405 CMD_EVENT_REQUEST_SET = 1,
406 CMD_EVENT_REQUEST_CLEAR = 2,
407 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
415 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
416 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
417 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
418 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
419 CMD_APPDOMAIN_CREATE_STRING = 5,
420 CMD_APPDOMAIN_GET_CORLIB = 6,
421 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
425 CMD_ASSEMBLY_GET_LOCATION = 1,
426 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
427 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
428 CMD_ASSEMBLY_GET_OBJECT = 4,
429 CMD_ASSEMBLY_GET_TYPE = 5,
430 CMD_ASSEMBLY_GET_NAME = 6
434 CMD_MODULE_GET_INFO = 1,
438 CMD_METHOD_GET_NAME = 1,
439 CMD_METHOD_GET_DECLARING_TYPE = 2,
440 CMD_METHOD_GET_DEBUG_INFO = 3,
441 CMD_METHOD_GET_PARAM_INFO = 4,
442 CMD_METHOD_GET_LOCALS_INFO = 5,
443 CMD_METHOD_GET_INFO = 6,
444 CMD_METHOD_GET_BODY = 7,
445 CMD_METHOD_RESOLVE_TOKEN = 8,
449 CMD_TYPE_GET_INFO = 1,
450 CMD_TYPE_GET_METHODS = 2,
451 CMD_TYPE_GET_FIELDS = 3,
452 CMD_TYPE_GET_VALUES = 4,
453 CMD_TYPE_GET_OBJECT = 5,
454 CMD_TYPE_GET_SOURCE_FILES = 6,
455 CMD_TYPE_SET_VALUES = 7,
456 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
457 CMD_TYPE_GET_PROPERTIES = 9,
458 CMD_TYPE_GET_CATTRS = 10,
459 CMD_TYPE_GET_FIELD_CATTRS = 11,
460 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
461 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
462 CMD_TYPE_GET_VALUES_2 = 14,
463 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
464 CMD_TYPE_GET_INTERFACES = 16,
465 CMD_TYPE_GET_INTERFACE_MAP = 17,
469 CMD_STACK_FRAME_GET_VALUES = 1,
470 CMD_STACK_FRAME_GET_THIS = 2,
471 CMD_STACK_FRAME_SET_VALUES = 3
475 CMD_ARRAY_REF_GET_LENGTH = 1,
476 CMD_ARRAY_REF_GET_VALUES = 2,
477 CMD_ARRAY_REF_SET_VALUES = 3,
481 CMD_STRING_REF_GET_VALUE = 1,
482 CMD_STRING_REF_GET_LENGTH = 2,
483 CMD_STRING_REF_GET_CHARS = 3
487 CMD_OBJECT_REF_GET_TYPE = 1,
488 CMD_OBJECT_REF_GET_VALUES = 2,
489 CMD_OBJECT_REF_IS_COLLECTED = 3,
490 CMD_OBJECT_REF_GET_ADDRESS = 4,
491 CMD_OBJECT_REF_GET_DOMAIN = 5,
492 CMD_OBJECT_REF_SET_VALUES = 6,
493 CMD_OBJECT_REF_GET_INFO = 7,
499 int count; /* For kind == MOD_KIND_COUNT */
500 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
501 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
502 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
503 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
504 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
506 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
515 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
519 * Describes a single step request.
523 MonoInternalThread *thread;
528 MonoMethod *last_method;
530 /* Whenever single stepping is performed using start/stop_single_stepping () */
532 /* The list of breakpoints used to implement step-over */
537 * Contains additional information for an event
540 /* For EVENT_KIND_EXCEPTION */
542 MonoContext catch_ctx;
544 /* For EVENT_KIND_USER_LOG */
546 char *category, *message;
547 /* For EVENT_KIND_TYPE_LOAD */
551 /* Dummy structure used for the profiler callbacks */
556 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
559 #define get_last_sock_error() WSAGetLastError()
560 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
561 #define MONO_EINTR WSAEINTR
563 #define get_last_sock_error() errno
564 #define MONO_EWOULDBLOCK EWOULDBLOCK
565 #define MONO_EINTR EINTR
572 static AgentConfig agent_config;
575 * Whenever the agent is fully initialized.
576 * When using the onuncaught or onthrow options, only some parts of the agent are
577 * initialized on startup, and the full initialization which includes connection
578 * establishment and the startup of the agent thread is only done in response to
581 static gint32 inited;
583 #ifndef DISABLE_SOCKET_TRANSPORT
585 static int listen_fd;
588 static int packet_id = 0;
590 static int objref_id = 0;
592 static int event_request_id = 0;
594 static int frame_id = 0;
596 static GPtrArray *event_requests;
598 static MonoNativeTlsKey debugger_tls_id;
600 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
602 /* Maps MonoInternalThread -> DebuggerTlsData */
603 static MonoGHashTable *thread_to_tls;
605 /* Maps tid -> MonoInternalThread */
606 static MonoGHashTable *tid_to_thread;
608 /* Maps tid -> MonoThread (not MonoInternalThread) */
609 static MonoGHashTable *tid_to_thread_obj;
611 static gsize debugger_thread_id;
613 static HANDLE debugger_thread_handle;
615 static int log_level;
617 static gboolean embedding;
619 static FILE *log_file;
621 /* Assemblies whose assembly load event has no been sent yet */
622 static GPtrArray *pending_assembly_loads;
624 /* Whenever the debugger thread has exited */
625 static gboolean debugger_thread_exited;
627 /* Cond variable used to wait for debugger_thread_exited becoming true */
628 static mono_cond_t debugger_thread_exited_cond;
630 /* Mutex for the cond var above */
631 static mono_mutex_t debugger_thread_exited_mutex;
633 static DebuggerProfiler debugger_profiler;
635 /* The single step request instance */
636 static SingleStepReq *ss_req = NULL;
637 static gpointer ss_invoke_addr = NULL;
639 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
640 /* Number of single stepping operations in progress */
644 /* The protocol version of the client */
645 static int major_version, minor_version;
647 /* Whenever the variables above are set by the client */
648 static gboolean protocol_version_set;
650 /* A hash table containing all active domains */
651 static GHashTable *domains;
653 static void transport_init (void);
654 static void transport_connect (const char *address);
655 static gboolean transport_handshake (void);
656 static void register_transport (DebuggerTransport *trans);
658 static guint32 WINAPI debugger_thread (void *arg);
660 static void runtime_initialized (MonoProfiler *prof);
662 static void runtime_shutdown (MonoProfiler *prof);
664 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
666 static void thread_end (MonoProfiler *prof, uintptr_t tid);
668 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
670 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
672 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
674 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
676 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
678 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
680 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
682 static void emit_assembly_load (gpointer assembly, gpointer user_data);
684 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
686 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
688 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
690 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
692 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
694 static void start_single_stepping (void);
696 static void stop_single_stepping (void);
698 static void suspend_current (void);
700 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
702 static void clear_types_for_assembly (MonoAssembly *assembly);
704 static void clear_breakpoints_for_domain (MonoDomain *domain);
706 static void process_profiler_event (EventKind event, gpointer arg);
708 /* Submodule init/cleanup */
709 static void breakpoints_init (void);
710 static void breakpoints_cleanup (void);
712 static void objrefs_init (void);
713 static void objrefs_cleanup (void);
715 static void ids_init (void);
716 static void ids_cleanup (void);
718 static void suspend_init (void);
720 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
721 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
722 static void ss_destroy (SingleStepReq *req);
724 static void start_debugger_thread (void);
725 static void stop_debugger_thread (void);
727 static void finish_agent_init (gboolean on_startup);
729 static void process_profiler_event (EventKind event, gpointer arg);
731 #ifndef DISABLE_SOCKET_TRANSPORT
733 register_socket_transport (void);
737 parse_address (char *address, char **host, int *port)
739 char *pos = strchr (address, ':');
741 if (pos == NULL || pos == address)
744 *host = g_malloc (pos - address + 1);
745 strncpy (*host, address, pos - address);
746 (*host) [pos - address] = '\0';
748 *port = atoi (pos + 1);
756 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
757 fprintf (stderr, "Available options:\n");
758 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
759 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
760 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
761 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
762 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
763 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
764 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
765 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
766 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
770 parse_flag (const char *option, char *flag)
772 if (!strcmp (flag, "y"))
774 else if (!strcmp (flag, "n"))
777 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
784 mono_debugger_agent_parse_options (char *options)
791 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
792 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
796 extra = getenv ("MONO_SDB_ENV_OPTIONS");
798 options = g_strdup_printf ("%s,%s", options, extra);
800 agent_config.enabled = TRUE;
801 agent_config.suspend = TRUE;
802 agent_config.server = FALSE;
803 agent_config.defer = FALSE;
804 agent_config.address = NULL;
806 args = g_strsplit (options, ",", -1);
807 for (ptr = args; ptr && *ptr; ptr ++) {
810 if (strncmp (arg, "transport=", 10) == 0) {
811 agent_config.transport = g_strdup (arg + 10);
812 } else if (strncmp (arg, "address=", 8) == 0) {
813 agent_config.address = g_strdup (arg + 8);
814 } else if (strncmp (arg, "loglevel=", 9) == 0) {
815 agent_config.log_level = atoi (arg + 9);
816 } else if (strncmp (arg, "logfile=", 8) == 0) {
817 agent_config.log_file = g_strdup (arg + 8);
818 } else if (strncmp (arg, "suspend=", 8) == 0) {
819 agent_config.suspend = parse_flag ("suspend", arg + 8);
820 } else if (strncmp (arg, "server=", 7) == 0) {
821 agent_config.server = parse_flag ("server", arg + 7);
822 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
823 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
824 } else if (strncmp (arg, "onthrow=", 8) == 0) {
825 /* We support multiple onthrow= options */
826 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
827 } else if (strncmp (arg, "onthrow", 7) == 0) {
828 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
829 } else if (strncmp (arg, "help", 4) == 0) {
832 } else if (strncmp (arg, "timeout=", 8) == 0) {
833 agent_config.timeout = atoi (arg + 8);
834 } else if (strncmp (arg, "launch=", 7) == 0) {
835 agent_config.launch = g_strdup (arg + 7);
836 } else if (strncmp (arg, "embedding=", 10) == 0) {
837 agent_config.embedding = atoi (arg + 10) == 1;
838 } else if (strncmp (arg, "keepalive=", 10) == 0) {
839 agent_config.keepalive = atoi (arg + 10);
846 if (agent_config.server && !agent_config.suspend) {
847 /* Waiting for deferred attachment */
848 agent_config.defer = TRUE;
849 if (agent_config.address == NULL) {
850 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
854 if (agent_config.transport == NULL) {
855 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
859 if (agent_config.address == NULL && !agent_config.server) {
860 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
865 if (!strcmp (agent_config.transport, "dt_socket")) {
866 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
867 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
874 mono_debugger_agent_init (void)
876 if (!agent_config.enabled)
881 /* Need to know whenever a thread has acquired the loader mutex */
882 mono_loader_lock_track_ownership (TRUE);
884 event_requests = g_ptr_array_new ();
886 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
887 mono_cond_init (&debugger_thread_exited_cond, NULL);
889 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
890 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
891 mono_profiler_install_runtime_initialized (runtime_initialized);
892 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
893 mono_profiler_install_thread (thread_startup, thread_end);
894 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
895 mono_profiler_install_jit_end (jit_end);
896 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
898 mono_native_tls_alloc (&debugger_tls_id, NULL);
900 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
901 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
903 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
904 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
906 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
907 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
909 pending_assembly_loads = g_ptr_array_new ();
910 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
912 log_level = agent_config.log_level;
914 embedding = agent_config.embedding;
917 if (agent_config.log_file) {
918 log_file = fopen (agent_config.log_file, "w+");
920 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
932 mini_get_debug_options ()->gen_seq_points = TRUE;
934 * This is needed because currently we don't handle liveness info.
936 mini_get_debug_options ()->mdb_optimizations = TRUE;
938 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
939 /* This is needed because we can't set local variables in registers yet */
940 mono_disable_optimizations (MONO_OPT_LINEARS);
943 if (!agent_config.onuncaught && !agent_config.onthrow)
944 finish_agent_init (TRUE);
946 /* FIXME: Is this still needed ? */
947 #if defined(__MACH__)
948 mono_thread_info_disable_new_interrupt (TRUE);
955 * Finish the initialization of the agent. This involves connecting the transport
956 * and starting the agent thread. This is either done at startup, or
957 * in response to some event like an unhandled exception.
960 finish_agent_init (gboolean on_startup)
964 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
967 if (agent_config.launch) {
970 // FIXME: Generated address
971 // FIXME: Races with transport_connect ()
973 argv [0] = agent_config.launch;
974 argv [1] = agent_config.transport;
975 argv [2] = agent_config.address;
978 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
980 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
985 transport_connect (agent_config.address);
988 /* Do some which is usually done after sending the VMStart () event */
989 vm_start_event_sent = TRUE;
990 start_debugger_thread ();
995 mono_debugger_agent_cleanup (void)
1000 stop_debugger_thread ();
1002 breakpoints_cleanup ();
1006 mono_mutex_destroy (&debugger_thread_exited_mutex);
1007 mono_cond_destroy (&debugger_thread_exited_cond);
1014 #ifndef DISABLE_SOCKET_TRANSPORT
1019 * recv() + handle incomplete reads and EINTR
1022 socket_transport_recv (void *buf, int len)
1031 res = recv (fd, (char *) buf + total, len - total, flags);
1034 if (agent_config.keepalive && res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1035 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1038 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1043 #define HAVE_GETADDRINFO 1
1047 set_keepalive (void)
1052 if (!agent_config.keepalive)
1055 tv.tv_sec = agent_config.keepalive / 1000;
1056 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1058 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1059 g_assert (result >= 0);
1063 socket_transport_accept (int socket_fd)
1065 conn_fd = accept (socket_fd, NULL, NULL);
1066 if (conn_fd == -1) {
1067 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1069 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1076 socket_transport_send (void *data, int len)
1081 res = send (conn_fd, data, len, 0);
1082 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1090 * socket_transport_connect:
1092 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1095 socket_transport_connect (const char *address)
1097 #ifdef HAVE_GETADDRINFO
1098 struct addrinfo hints;
1099 struct addrinfo *result, *rp;
1101 struct hostent *result;
1103 int sfd = -1, s, res;
1104 char port_string [128];
1108 if (agent_config.address) {
1109 res = parse_address (agent_config.address, &host, &port);
1110 g_assert (res == 0);
1120 sprintf (port_string, "%d", port);
1122 mono_network_init ();
1124 /* Obtain address(es) matching host/port */
1125 #ifdef HAVE_GETADDRINFO
1126 memset (&hints, 0, sizeof (struct addrinfo));
1127 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1128 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1130 hints.ai_protocol = 0; /* Any protocol */
1132 s = getaddrinfo (host, port_string, &hints, &result);
1134 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1138 /* The PS3 doesn't even have _r or hstrerror () */
1139 result = gethostbyname (host);
1141 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1146 if (agent_config.server) {
1147 #ifdef HAVE_GETADDRINFO
1148 /* Wait for a connection */
1150 struct sockaddr_in addr;
1153 /* No address, generate one */
1154 sfd = socket (AF_INET, SOCK_STREAM, 0);
1157 /* This will bind the socket to a random port */
1158 res = listen (sfd, 16);
1160 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1165 addrlen = sizeof (addr);
1166 memset (&addr, 0, sizeof (addr));
1167 res = getsockname (sfd, &addr, &addrlen);
1168 g_assert (res == 0);
1170 host = (char*)"127.0.0.1";
1171 port = ntohs (addr.sin_port);
1173 /* Emit the address to stdout */
1174 /* FIXME: Should print another interface, not localhost */
1175 printf ("%s:%d\n", host, port);
1177 /* Listen on the provided address */
1178 for (rp = result; rp != NULL; rp = rp->ai_next) {
1181 sfd = socket (rp->ai_family, rp->ai_socktype,
1186 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1189 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1193 res = listen (sfd, 16);
1202 * this function is not present on win2000 which we still support, and the
1203 * workaround described here:
1204 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1205 * only works with MSVC.
1207 #ifdef HAVE_GETADDRINFO
1208 freeaddrinfo (result);
1213 if (agent_config.defer)
1216 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1218 if (agent_config.timeout) {
1223 tv.tv_usec = agent_config.timeout * 1000;
1225 FD_SET (sfd, &readfds);
1226 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1228 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1233 conn_fd = socket_transport_accept (sfd);
1237 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1240 #endif /* HAVE_GETADDRINFO */
1242 /* Connect to the specified address */
1243 #ifdef HAVE_GETADDRINFO
1244 /* FIXME: Respect the timeout */
1245 for (rp = result; rp != NULL; rp = rp->ai_next) {
1246 sfd = socket (rp->ai_family, rp->ai_socktype,
1251 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1252 break; /* Success */
1258 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1262 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1264 g_assert_not_reached ();
1265 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1267 g_assert_not_reached ();
1273 /* See the comment above */
1274 #ifdef HAVE_GETADDRINFO
1275 freeaddrinfo (result);
1280 disconnected = !transport_handshake ();
1286 socket_transport_close1 (void)
1288 /* This will interrupt the agent thread */
1289 /* Close the read part only so it can still send back replies */
1290 /* Also shut down the connection listener so that we can exit normally */
1292 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1293 shutdown (conn_fd, SD_BOTH);
1294 shutdown (listen_fd, SD_BOTH);
1295 closesocket (listen_fd);
1297 shutdown (conn_fd, SHUT_RD);
1298 shutdown (listen_fd, SHUT_RDWR);
1304 socket_transport_close2 (void)
1307 shutdown (conn_fd, SD_BOTH);
1309 shutdown (conn_fd, SHUT_RDWR);
1314 register_socket_transport (void)
1316 DebuggerTransport trans;
1318 trans.name = "dt_socket";
1319 trans.connect = socket_transport_connect;
1320 trans.close1 = socket_transport_close1;
1321 trans.close2 = socket_transport_close2;
1322 trans.send = socket_transport_send;
1323 trans.recv = socket_transport_recv;
1325 register_transport (&trans);
1328 #endif /* DISABLE_SOCKET_TRANSPORT */
1334 #define MAX_TRANSPORTS 16
1336 static DebuggerTransport *transport;
1338 static DebuggerTransport transports [MAX_TRANSPORTS];
1339 static int ntransports;
1342 register_transport (DebuggerTransport *trans)
1344 g_assert (ntransports < MAX_TRANSPORTS);
1346 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1351 transport_init (void)
1355 #ifndef DISABLE_SOCKET_TRANSPORT
1356 register_socket_transport ();
1359 for (i = 0; i < ntransports; ++i) {
1360 if (!strcmp (agent_config.transport, transports [i].name))
1363 if (i == ntransports) {
1364 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1365 for (i = 0; i < ntransports; ++i)
1366 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1367 fprintf (stderr, "\n");
1370 transport = &transports [i];
1374 transport_connect (const char *address)
1376 transport->connect (address);
1380 transport_close1 (void)
1382 transport->close1 ();
1386 transport_close2 (void)
1388 transport->close2 ();
1392 transport_send (void *buf, int len)
1394 return transport->send (buf, len);
1398 transport_recv (void *buf, int len)
1400 return transport->recv (buf, len);
1404 transport_handshake (void)
1406 char handshake_msg [128];
1410 /* Write handshake message */
1411 sprintf (handshake_msg, "DWP-Handshake");
1413 res = transport_send (handshake_msg, strlen (handshake_msg));
1414 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1415 g_assert (res != -1);
1418 res = transport_recv (buf, strlen (handshake_msg));
1419 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1420 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1425 * To support older clients, the client sends its protocol version after connecting
1426 * using a command. Until that is received, default to our protocol version.
1428 major_version = MAJOR_VERSION;
1429 minor_version = MINOR_VERSION;
1430 protocol_version_set = FALSE;
1432 #ifndef DISABLE_SOCKET_TRANSPORT
1433 // FIXME: Move this somewhere else
1435 * Set TCP_NODELAY on the socket so the client receives events/command
1436 * results immediately.
1440 int result = setsockopt (conn_fd,
1445 g_assert (result >= 0);
1455 stop_debugger_thread (void)
1460 transport_close1 ();
1463 * Wait for the thread to exit.
1465 * If we continue with the shutdown without waiting for it, then the client might
1466 * not receive an answer to its last command like a resume.
1467 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1470 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1471 if (GetCurrentThreadId () != debugger_thread_id) {
1473 mono_mutex_lock (&debugger_thread_exited_mutex);
1474 if (!debugger_thread_exited) {
1476 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1477 mono_mutex_unlock (&debugger_thread_exited_mutex);
1479 mono_mutex_lock (&debugger_thread_exited_mutex);
1482 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1485 mono_mutex_unlock (&debugger_thread_exited_mutex);
1486 } while (!debugger_thread_exited);
1489 transport_close2 ();
1493 start_debugger_thread (void)
1497 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1498 g_assert (debugger_thread_handle);
1502 * Functions to decode protocol data
1506 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1509 g_assert (*endbuf <= limit);
1514 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1517 g_assert (*endbuf <= limit);
1519 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1522 static inline gint64
1523 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1525 guint32 high = decode_int (buf, &buf, limit);
1526 guint32 low = decode_int (buf, &buf, limit);
1530 return ((((guint64)high) << 32) | ((guint64)low));
1534 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1536 return decode_int (buf, endbuf, limit);
1540 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1542 int len = decode_int (buf, &buf, limit);
1550 s = g_malloc (len + 1);
1553 memcpy (s, buf, len);
1562 * Functions to encode protocol data
1566 guint8 *buf, *p, *end;
1570 buffer_init (Buffer *buf, int size)
1572 buf->buf = g_malloc (size);
1574 buf->end = buf->buf + size;
1578 buffer_make_room (Buffer *buf, int size)
1580 if (buf->end - buf->p < size) {
1581 int new_size = buf->end - buf->buf + size + 32;
1582 guint8 *p = g_realloc (buf->buf, new_size);
1583 size = buf->p - buf->buf;
1586 buf->end = buf->buf + new_size;
1591 buffer_add_byte (Buffer *buf, guint8 val)
1593 buffer_make_room (buf, 1);
1599 buffer_add_short (Buffer *buf, guint32 val)
1601 buffer_make_room (buf, 2);
1602 buf->p [0] = (val >> 8) & 0xff;
1603 buf->p [1] = (val >> 0) & 0xff;
1608 buffer_add_int (Buffer *buf, guint32 val)
1610 buffer_make_room (buf, 4);
1611 buf->p [0] = (val >> 24) & 0xff;
1612 buf->p [1] = (val >> 16) & 0xff;
1613 buf->p [2] = (val >> 8) & 0xff;
1614 buf->p [3] = (val >> 0) & 0xff;
1619 buffer_add_long (Buffer *buf, guint64 l)
1621 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1622 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1626 buffer_add_id (Buffer *buf, int id)
1628 buffer_add_int (buf, (guint64)id);
1632 buffer_add_data (Buffer *buf, guint8 *data, int len)
1634 buffer_make_room (buf, len);
1635 memcpy (buf->p, data, len);
1640 buffer_add_string (Buffer *buf, const char *str)
1645 buffer_add_int (buf, 0);
1648 buffer_add_int (buf, len);
1649 buffer_add_data (buf, (guint8*)str, len);
1654 buffer_free (Buffer *buf)
1660 send_packet (int command_set, int command, Buffer *data)
1666 id = InterlockedIncrement (&packet_id);
1668 len = data->p - data->buf + 11;
1669 buffer_init (&buf, len);
1670 buffer_add_int (&buf, len);
1671 buffer_add_int (&buf, id);
1672 buffer_add_byte (&buf, 0); /* flags */
1673 buffer_add_byte (&buf, command_set);
1674 buffer_add_byte (&buf, command);
1675 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1677 res = transport_send (buf.buf, len);
1685 send_reply_packet (int id, int error, Buffer *data)
1691 len = data->p - data->buf + 11;
1692 buffer_init (&buf, len);
1693 buffer_add_int (&buf, len);
1694 buffer_add_int (&buf, id);
1695 buffer_add_byte (&buf, 0x80); /* flags */
1696 buffer_add_byte (&buf, (error >> 8) & 0xff);
1697 buffer_add_byte (&buf, error);
1698 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1700 res = transport_send (buf.buf, len);
1712 * Represents an object accessible by the debugger client.
1715 /* Unique id used in the wire protocol to refer to objects */
1718 * A weakref gc handle pointing to the object. The gc handle is used to
1719 * detect if the object was garbage collected.
1724 /* Maps objid -> ObjRef */
1725 static GHashTable *objrefs;
1728 free_objref (gpointer value)
1732 mono_gchandle_free (o->handle);
1740 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1744 objrefs_cleanup (void)
1746 g_hash_table_destroy (objrefs);
1750 static GHashTable *obj_to_objref;
1753 * Return an ObjRef for OBJ.
1756 get_objref (MonoObject *obj)
1759 GSList *reflist = NULL, *l;
1765 mono_loader_lock ();
1768 obj_to_objref = g_hash_table_new (NULL, NULL);
1770 /* FIXME: The tables can grow indefinitely */
1772 if (mono_gc_is_moving ()) {
1774 * Objects can move, so use a hash table mapping hash codes to lists of
1775 * ObjRef structures.
1777 hash = mono_object_hash (obj);
1779 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1780 for (l = reflist; l; l = l->next) {
1782 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1783 mono_loader_unlock ();
1788 /* Use a hash table with masked pointers to internalize object references */
1789 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1790 /* ref might refer to a different object with the same addr which was GCd */
1791 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1792 mono_loader_unlock ();
1797 ref = g_new0 (ObjRef, 1);
1798 ref->id = InterlockedIncrement (&objref_id);
1799 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1801 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1803 if (mono_gc_is_moving ()) {
1804 reflist = g_slist_append (reflist, ref);
1805 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1807 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1810 mono_loader_unlock ();
1816 get_objid (MonoObject *obj)
1818 return get_objref (obj)->id;
1822 * Set OBJ to the object identified by OBJID.
1823 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1827 get_object_allow_null (int objid, MonoObject **obj)
1837 return ERR_INVALID_OBJECT;
1839 mono_loader_lock ();
1841 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1844 *obj = mono_gchandle_get_target (ref->handle);
1845 mono_loader_unlock ();
1847 return ERR_INVALID_OBJECT;
1850 mono_loader_unlock ();
1851 return ERR_INVALID_OBJECT;
1856 get_object (int objid, MonoObject **obj)
1858 int err = get_object_allow_null (objid, obj);
1863 return ERR_INVALID_OBJECT;
1868 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1870 return decode_id (buf, endbuf, limit);
1874 buffer_add_objid (Buffer *buf, MonoObject *o)
1876 buffer_add_id (buf, get_objid (o));
1895 * Represents a runtime structure accessible to the debugger client
1898 /* Unique id used in the wire protocol */
1900 /* Domain of the runtime structure, NULL if the domain was unloaded */
1907 MonoAssembly *assembly;
1908 MonoClassField *field;
1910 MonoProperty *property;
1915 /* Maps runtime structure -> Id */
1916 GHashTable *val_to_id [ID_NUM];
1917 /* Classes whose class load event has been sent */
1918 GHashTable *loaded_classes;
1919 /* Maps MonoClass->GPtrArray of file names */
1920 GHashTable *source_files;
1921 /* Maps source file basename -> GSList of classes */
1922 GHashTable *source_file_to_class;
1926 static GPtrArray *ids [ID_NUM];
1933 for (i = 0; i < ID_NUM; ++i)
1934 ids [i] = g_ptr_array_new ();
1942 for (i = 0; i < ID_NUM; ++i) {
1944 for (j = 0; j < ids [i]->len; ++j)
1945 g_free (g_ptr_array_index (ids [i], j));
1946 g_ptr_array_free (ids [i], TRUE);
1953 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1955 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1957 GHashTableIter iter;
1958 GPtrArray *file_names;
1963 for (i = 0; i < ID_NUM; ++i)
1964 if (info->val_to_id [i])
1965 g_hash_table_destroy (info->val_to_id [i]);
1966 g_hash_table_destroy (info->loaded_classes);
1968 g_hash_table_iter_init (&iter, info->source_files);
1969 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
1970 for (i = 0; i < file_names->len; ++i)
1971 g_free (g_ptr_array_index (file_names, i));
1972 g_ptr_array_free (file_names, TRUE);
1975 g_hash_table_iter_init (&iter, info->source_file_to_class);
1976 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
1984 domain_jit_info (domain)->agent_info = NULL;
1986 /* Clear ids referencing structures in the domain */
1987 for (i = 0; i < ID_NUM; ++i) {
1989 for (j = 0; j < ids [i]->len; ++j) {
1990 Id *id = g_ptr_array_index (ids [i], j);
1991 if (id->domain == domain)
1997 mono_loader_lock ();
1998 g_hash_table_remove (domains, domain);
1999 mono_loader_unlock ();
2002 static AgentDomainInfo*
2003 get_agent_domain_info (MonoDomain *domain)
2005 AgentDomainInfo *info = NULL;
2007 mono_domain_lock (domain);
2009 info = domain_jit_info (domain)->agent_info;
2011 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2012 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2013 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2014 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2017 mono_domain_unlock (domain);
2023 get_id (MonoDomain *domain, IdType type, gpointer val)
2026 AgentDomainInfo *info;
2031 mono_loader_lock ();
2033 mono_domain_lock (domain);
2035 info = get_agent_domain_info (domain);
2037 if (info->val_to_id [type] == NULL)
2038 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2040 id = g_hash_table_lookup (info->val_to_id [type], val);
2042 mono_domain_unlock (domain);
2043 mono_loader_unlock ();
2047 id = g_new0 (Id, 1);
2049 id->id = ids [type]->len + 1;
2050 id->domain = domain;
2053 g_hash_table_insert (info->val_to_id [type], val, id);
2055 mono_domain_unlock (domain);
2057 g_ptr_array_add (ids [type], id);
2059 mono_loader_unlock ();
2064 static inline gpointer
2065 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2069 int id = decode_id (buf, endbuf, limit);
2078 // FIXME: error handling
2079 mono_loader_lock ();
2080 g_assert (id > 0 && id <= ids [type]->len);
2082 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2083 mono_loader_unlock ();
2085 if (res->domain == NULL) {
2086 *err = ERR_UNLOADED;
2091 *domain = res->domain;
2093 return res->data.val;
2097 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2099 buffer_add_id (buf, get_id (domain, type, val));
2102 static inline MonoClass*
2103 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2105 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2108 static inline MonoAssembly*
2109 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2111 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2114 static inline MonoImage*
2115 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2117 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2120 static inline MonoMethod*
2121 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2123 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2126 static inline MonoClassField*
2127 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2129 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2132 static inline MonoDomain*
2133 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2135 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2138 static inline MonoProperty*
2139 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2141 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2145 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2147 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2151 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2153 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2157 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2159 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2163 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2165 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2169 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2171 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2175 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2177 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2181 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2183 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2186 static void invoke_method (void);
2193 * save_thread_context:
2195 * Set CTX as the current threads context which is used for computing stack traces.
2196 * This function is signal-safe.
2199 save_thread_context (MonoContext *ctx)
2201 DebuggerTlsData *tls;
2203 tls = mono_native_tls_get_value (debugger_tls_id);
2207 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2209 mono_thread_state_init_from_current (&tls->context);
2212 /* The number of times the runtime is suspended */
2213 static gint32 suspend_count;
2215 /* Number of threads suspended */
2217 * If this is equal to the size of thread_to_tls, the runtime is considered
2220 static gint32 threads_suspend_count;
2222 static mono_mutex_t suspend_mutex;
2224 /* Cond variable used to wait for suspend_count becoming 0 */
2225 static mono_cond_t suspend_cond;
2227 /* Semaphore used to wait for a thread becoming suspended */
2228 static MonoSemType suspend_sem;
2233 mono_mutex_init (&suspend_mutex, NULL);
2234 mono_cond_init (&suspend_cond, NULL);
2235 MONO_SEM_INIT (&suspend_sem, 0);
2240 StackFrameInfo last_frame;
2241 gboolean last_frame_set;
2244 } GetLastFrameUserData;
2247 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2249 GetLastFrameUserData *data = user_data;
2251 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2254 if (!data->last_frame_set) {
2255 /* Store the last frame */
2256 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2257 data->last_frame_set = TRUE;
2260 /* Store the context/lmf for the frame above the last frame */
2261 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2262 data->lmf = info->lmf;
2271 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2272 * INFO is set, process the thread described by INFO.
2273 * This should be signal safe.
2276 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2280 MonoNativeThreadId tid;
2283 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2284 * guarantee the signal handler will be called that many times. Instead of tracking
2285 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2286 * has been requested that hasn't been handled yet, otherwise we can have threads
2287 * refuse to die when VM_EXIT is called
2289 #if defined(__APPLE__)
2290 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2294 * We use interrupt_count to determine whenever this interrupt should be processed
2295 * by us or the normal interrupt processing code in the signal handler.
2296 * There is no race here with notify_thread (), since the signal is sent after
2297 * incrementing interrupt_count.
2299 if (tls->interrupt_count == 0)
2302 InterlockedDecrement (&tls->interrupt_count);
2306 ip = mono_arch_ip_from_context (sigctx);
2308 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2313 tid = mono_thread_info_get_tid (info);
2315 tid = GetCurrentThreadId ();
2317 // FIXME: Races when the thread leaves managed code before hitting a single step
2321 /* Running managed code, will be suspended by the single step code */
2322 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2326 * Running native code, will be suspended when it returns to/enters
2327 * managed code. Treat it as already suspended.
2328 * This might interrupt the code in process_single_step_inner (), we use the
2329 * tls->suspending flag to avoid races when that happens.
2331 if (!tls->suspended && !tls->suspending) {
2333 GetLastFrameUserData data;
2335 // FIXME: printf is not signal safe, but this is only used during
2336 // debugger debugging
2338 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2339 //save_thread_context (&ctx);
2342 /* Already terminated */
2345 tls->context.valid = FALSE;
2348 * We are in a difficult position: we want to be able to provide stack
2349 * traces for this thread, but we can't use the current ctx+lmf, since
2350 * the thread is still running, so it might return to managed code,
2351 * making these invalid.
2352 * So we start a stack walk and save the first frame, along with the
2353 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2354 * suspended when it returns to managed code, so the parent's ctx should
2357 data.last_frame_set = FALSE;
2359 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2361 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2362 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2363 * since we are not in a JITted method.
2365 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2367 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2369 if (data.last_frame_set) {
2370 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2371 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2373 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2376 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2377 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2378 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2380 /* No managed frames */
2381 tls->async_state.valid = FALSE;
2383 mono_memory_barrier ();
2385 tls->suspended = TRUE;
2386 MONO_SEM_POST (&suspend_sem);
2393 * mono_debugger_agent_thread_interrupt:
2395 * Called by the abort signal handler.
2396 * Should be signal safe.
2399 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2401 DebuggerTlsData *tls;
2406 tls = mono_native_tls_get_value (debugger_tls_id);
2410 return thread_interrupt (tls, NULL, sigctx, ji);
2414 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2417 mono_debugger_agent_thread_interrupt (NULL, NULL);
2419 #endif /* HOST_WIN32 */
2422 * reset_native_thread_suspend_state:
2424 * Reset the suspended flag on native threads
2427 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2429 DebuggerTlsData *tls = value;
2431 if (!tls->really_suspended && tls->suspended)
2432 tls->suspended = FALSE;
2438 * Notify a thread that it needs to suspend.
2441 notify_thread (gpointer key, gpointer value, gpointer user_data)
2443 MonoInternalThread *thread = key;
2444 DebuggerTlsData *tls = value;
2445 gsize tid = thread->tid;
2448 if (GetCurrentThreadId () == tid || tls->terminated)
2451 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2454 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2455 * guarantee the signal handler will be called that many times. Instead of tracking
2456 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2457 * has been requested that hasn't been handled yet, otherwise we can have threads
2458 * refuse to die when VM_EXIT is called
2460 #if defined(__APPLE__)
2461 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2465 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2466 * of things like breaking waits etc. which we don't want.
2468 InterlockedIncrement (&tls->interrupt_count);
2471 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2473 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2475 if (mono_thread_info_new_interrupt_enabled ()) {
2476 MonoThreadInfo *info;
2479 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2482 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2484 thread_interrupt (tls, info, NULL, ji);
2486 mono_thread_info_resume (mono_thread_info_get_tid (info));
2488 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2491 * Attached thread which died without detaching.
2493 tls->terminated = TRUE;
2499 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2501 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2504 if (mono_loader_lock_is_owned_by_self ()) {
2506 * Shortcut for the check in suspend_current (). This speeds up processing
2507 * when executing long running code inside the loader lock, i.e. assembly load
2513 if (debugger_thread_id == GetCurrentThreadId ())
2516 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2517 if (suspend_count - tls->resume_count > 0)
2518 tls->suspending = TRUE;
2520 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2522 if (suspend_count - tls->resume_count == 0) {
2524 * We are executing a single threaded invoke but the single step for
2525 * suspending is still active.
2526 * FIXME: This slows down single threaded invokes.
2528 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2532 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2534 /* Can't suspend in these methods */
2535 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2538 save_thread_context (ctx);
2546 * Increase the suspend count of the VM. While the suspend count is greater
2547 * than 0, runtime threads are suspended at certain points during execution.
2552 mono_loader_lock ();
2554 mono_mutex_lock (&suspend_mutex);
2558 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2560 if (suspend_count == 1) {
2561 // FIXME: Is it safe to call this inside the lock ?
2562 start_single_stepping ();
2563 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2566 mono_mutex_unlock (&suspend_mutex);
2568 mono_loader_unlock ();
2574 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2582 g_assert (debugger_thread_id == GetCurrentThreadId ());
2584 mono_loader_lock ();
2586 mono_mutex_lock (&suspend_mutex);
2588 g_assert (suspend_count > 0);
2591 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
2593 if (suspend_count == 0) {
2594 // FIXME: Is it safe to call this inside the lock ?
2595 stop_single_stepping ();
2596 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2599 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2600 err = mono_cond_broadcast (&suspend_cond);
2601 g_assert (err == 0);
2603 mono_mutex_unlock (&suspend_mutex);
2604 //g_assert (err == 0);
2606 mono_loader_unlock ();
2612 * Resume just one thread.
2615 resume_thread (MonoInternalThread *thread)
2618 DebuggerTlsData *tls;
2620 g_assert (debugger_thread_id == GetCurrentThreadId ());
2622 mono_loader_lock ();
2624 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2627 mono_mutex_lock (&suspend_mutex);
2629 g_assert (suspend_count > 0);
2631 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2633 tls->resume_count += suspend_count;
2636 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2637 * but only the one whose resume_count field is > 0 will be resumed.
2639 err = mono_cond_broadcast (&suspend_cond);
2640 g_assert (err == 0);
2642 mono_mutex_unlock (&suspend_mutex);
2643 //g_assert (err == 0);
2645 mono_loader_unlock ();
2649 invalidate_frames (DebuggerTlsData *tls)
2654 tls = mono_native_tls_get_value (debugger_tls_id);
2657 for (i = 0; i < tls->frame_count; ++i) {
2658 if (tls->frames [i]->jit)
2659 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2660 g_free (tls->frames [i]);
2662 g_free (tls->frames);
2663 tls->frame_count = 0;
2670 * Suspend the current thread until the runtime is resumed. If the thread has a
2671 * pending invoke, then the invoke is executed before this function returns.
2674 suspend_current (void)
2677 DebuggerTlsData *tls;
2679 g_assert (debugger_thread_id != GetCurrentThreadId ());
2681 if (mono_loader_lock_is_owned_by_self ()) {
2683 * If we own the loader mutex, can't suspend until we release it, since the
2684 * whole runtime can deadlock otherwise.
2689 tls = mono_native_tls_get_value (debugger_tls_id);
2692 mono_mutex_lock (&suspend_mutex);
2694 tls->suspending = FALSE;
2695 tls->really_suspended = TRUE;
2697 if (!tls->suspended) {
2698 tls->suspended = TRUE;
2699 MONO_SEM_POST (&suspend_sem);
2702 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2704 while (suspend_count - tls->resume_count > 0) {
2706 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2708 mono_mutex_unlock (&suspend_mutex);
2710 mono_mutex_lock (&suspend_mutex);
2716 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2717 g_assert (err == 0);
2721 tls->suspended = FALSE;
2722 tls->really_suspended = FALSE;
2724 threads_suspend_count --;
2726 mono_mutex_unlock (&suspend_mutex);
2728 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2730 if (tls->pending_invoke) {
2731 /* Save the original context */
2732 tls->pending_invoke->has_ctx = TRUE;
2733 tls->pending_invoke->ctx = tls->context.ctx;
2738 /* The frame info becomes invalid after a resume */
2739 tls->context.valid = FALSE;
2740 tls->async_state.valid = FALSE;
2741 invalidate_frames (NULL);
2745 count_thread (gpointer key, gpointer value, gpointer user_data)
2747 DebuggerTlsData *tls = value;
2749 if (!tls->suspended && !tls->terminated)
2750 *(int*)user_data = *(int*)user_data + 1;
2754 count_threads_to_wait_for (void)
2758 mono_loader_lock ();
2759 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2760 mono_loader_unlock ();
2768 * Wait until the runtime is completely suspended.
2771 wait_for_suspend (void)
2773 int nthreads, nwait, err;
2774 gboolean waited = FALSE;
2776 // FIXME: Threads starting/stopping ?
2777 mono_loader_lock ();
2778 nthreads = mono_g_hash_table_size (thread_to_tls);
2779 mono_loader_unlock ();
2782 nwait = count_threads_to_wait_for ();
2784 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2785 err = MONO_SEM_WAIT (&suspend_sem);
2786 g_assert (err == 0);
2794 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2800 * Return whenever the runtime is suspended.
2805 return count_threads_to_wait_for () == 0;
2808 static MonoSeqPointInfo*
2809 find_seq_points (MonoDomain *domain, MonoMethod *method)
2811 MonoSeqPointInfo *seq_points;
2813 mono_domain_lock (domain);
2814 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2815 if (!seq_points && method->is_inflated) {
2816 /* generic sharing + aot */
2817 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2819 mono_domain_unlock (domain);
2821 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2822 g_assert (seq_points);
2828 * find_next_seq_point_for_native_offset:
2830 * Find the first sequence point after NATIVE_OFFSET.
2833 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2835 MonoSeqPointInfo *seq_points;
2838 seq_points = find_seq_points (domain, method);
2842 for (i = 0; i < seq_points->len; ++i) {
2843 if (seq_points->seq_points [i].native_offset >= native_offset)
2844 return &seq_points->seq_points [i];
2851 * find_prev_seq_point_for_native_offset:
2853 * Find the first sequence point before NATIVE_OFFSET.
2856 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2858 MonoSeqPointInfo *seq_points;
2861 seq_points = find_seq_points (domain, method);
2865 for (i = seq_points->len - 1; i >= 0; --i) {
2866 if (seq_points->seq_points [i].native_offset <= native_offset)
2867 return &seq_points->seq_points [i];
2876 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2877 * should be the location of a sequence point.
2880 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2882 MonoSeqPointInfo *seq_points;
2885 seq_points = find_seq_points (domain, method);
2888 for (i = 0; i < seq_points->len; ++i) {
2889 if (seq_points->seq_points [i].il_offset == il_offset)
2890 return &seq_points->seq_points [i];
2897 DebuggerTlsData *tls;
2899 } ComputeFramesUserData;
2902 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2904 ComputeFramesUserData *ud = user_data;
2906 MonoMethod *method, *actual_method;
2908 if (info->type != FRAME_TYPE_MANAGED) {
2909 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
2910 /* Mark the last frame as an invoke frame */
2912 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
2918 method = info->ji->method;
2920 method = info->method;
2921 actual_method = info->actual_method;
2923 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
2926 if (info->il_offset == -1) {
2927 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
2928 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
2931 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));
2933 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
2935 * mono_arch_find_jit_info () returns the context stored in the LMF for
2936 * native frames, but it should unwind once. This is why we have duplicate
2937 * frames on the stack sometimes.
2938 * !managed also seems to be set for dynamic methods.
2943 frame = g_new0 (StackFrame, 1);
2944 frame->method = method;
2945 frame->actual_method = actual_method;
2946 frame->il_offset = info->il_offset;
2947 frame->native_offset = info->native_offset;
2948 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
2951 frame->has_ctx = TRUE;
2953 frame->domain = info->domain;
2955 ud->frames = g_slist_append (ud->frames, frame);
2961 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2963 ComputeFramesUserData *ud = user_data;
2966 * 'tls->filter_ctx' is the location of the throw site.
2968 * mono_walk_stack() will never actually hit the throw site, but unwind
2969 * directly from the filter to the call site; we abort stack unwinding here
2970 * once this happens and resume from the throw site.
2973 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
2976 return process_frame (info, ctx, user_data);
2980 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
2982 ComputeFramesUserData user_data;
2984 int i, findex, new_frame_count;
2985 StackFrame **new_frames, *f;
2986 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
2988 // FIXME: Locking on tls
2989 if (tls->frames && tls->frames_up_to_date)
2992 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
2994 user_data.tls = tls;
2995 user_data.frames = NULL;
2996 if (tls->terminated) {
2997 tls->frame_count = 0;
2999 } if (!tls->really_suspended && tls->async_state.valid) {
3000 /* Have to use the state saved by the signal handler */
3001 process_frame (&tls->async_last_frame, NULL, &user_data);
3002 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3003 } else if (tls->filter_state.valid) {
3005 * We are inside an exception filter.
3007 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3009 if (tls->context.valid)
3010 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3012 * After that, we resume unwinding from the location where the exception has been thrown.
3014 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3015 } else if (tls->context.valid) {
3016 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3019 tls->frame_count = 0;
3023 new_frame_count = g_slist_length (user_data.frames);
3024 new_frames = g_new0 (StackFrame*, new_frame_count);
3026 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3030 * Reuse the id for already existing stack frames, so invokes don't invalidate
3031 * the still valid stack frames.
3033 for (i = 0; i < tls->frame_count; ++i) {
3034 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3035 f->id = tls->frames [i]->id;
3040 if (i >= tls->frame_count)
3041 f->id = InterlockedIncrement (&frame_id);
3043 new_frames [findex ++] = f;
3046 g_slist_free (user_data.frames);
3048 invalidate_frames (tls);
3050 tls->frames = new_frames;
3051 tls->frame_count = new_frame_count;
3052 tls->frames_up_to_date = TRUE;
3056 * GHFunc to emit an appdomain creation event
3057 * @param key Don't care
3058 * @param value A loaded appdomain
3059 * @param user_data Don't care
3062 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3064 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3065 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3069 * GHFunc to emit a thread start event
3070 * @param key A thread id
3071 * @param value A thread object
3072 * @param user_data Don't care
3075 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3077 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3078 process_profiler_event (EVENT_KIND_THREAD_START, value);
3082 * GFunc to emit an assembly load event
3083 * @param value A loaded assembly
3084 * @param user_data Don't care
3087 emit_assembly_load (gpointer value, gpointer user_data)
3089 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3093 * GFunc to emit a type load event
3094 * @param value A loaded type
3095 * @param user_data Don't care
3098 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3100 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3109 * create_event_list:
3111 * Return a list of event request ids matching EVENT, starting from REQS, which
3112 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3114 * We return request ids, instead of requests, to simplify threading, since
3115 * requests could be deleted anytime when the loader lock is not held.
3116 * LOCKING: Assumes the loader lock is held.
3119 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3122 GSList *events = NULL;
3124 *suspend_policy = SUSPEND_POLICY_NONE;
3127 reqs = event_requests;
3132 for (i = 0; i < reqs->len; ++i) {
3133 EventRequest *req = g_ptr_array_index (reqs, i);
3134 if (req->event_kind == event) {
3135 gboolean filtered = FALSE;
3138 for (j = 0; j < req->nmodifiers; ++j) {
3139 Modifier *mod = &req->modifiers [j];
3141 if (mod->kind == MOD_KIND_COUNT) {
3143 if (mod->data.count > 0) {
3144 if (mod->data.count > 0) {
3146 if (mod->data.count == 0)
3150 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3151 if (mod->data.thread != mono_thread_internal_current ())
3153 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3154 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3156 if (ei->caught && !mod->caught)
3158 if (!ei->caught && !mod->uncaught)
3160 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3162 gboolean found = FALSE;
3163 MonoAssembly **assemblies = mod->data.assemblies;
3166 for (k = 0; assemblies [k]; ++k)
3167 if (assemblies [k] == ji->method->klass->image->assembly)
3172 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3173 gpointer iter = NULL;
3176 gboolean found = FALSE;
3178 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3179 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3182 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
3186 if (g_hash_table_lookup (mod->data.source_files, source_file))
3188 g_free (source_file);
3193 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3196 s = mono_type_full_name (&ei->klass->byval_arg);
3197 if (!g_hash_table_lookup (mod->data.type_names, s))
3204 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3205 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3210 /* Send a VM START/DEATH event by default */
3211 if (event == EVENT_KIND_VM_START)
3212 events = g_slist_append (events, GINT_TO_POINTER (0));
3213 if (event == EVENT_KIND_VM_DEATH)
3214 events = g_slist_append (events, GINT_TO_POINTER (0));
3219 static G_GNUC_UNUSED const char*
3220 event_to_string (EventKind event)
3223 case EVENT_KIND_VM_START: return "VM_START";
3224 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3225 case EVENT_KIND_THREAD_START: return "THREAD_START";
3226 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3227 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3228 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3229 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3230 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3231 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3232 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3233 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3234 case EVENT_KIND_STEP: return "STEP";
3235 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3236 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3237 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3238 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3239 case EVENT_KIND_USER_LOG: return "USER_LOG";
3241 g_assert_not_reached ();
3248 * Send an event to the client, suspending the vm if needed.
3249 * LOCKING: Since this can suspend the calling thread, no locks should be held
3251 * The EVENTS list is freed by this function.
3254 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3258 MonoDomain *domain = mono_domain_get ();
3259 MonoThread *thread = NULL;
3260 gboolean send_success = FALSE;
3263 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3267 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3268 // FIXME: We miss those events
3269 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3273 if (vm_death_event_sent) {
3274 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3278 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3279 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3284 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3288 if (event == EVENT_KIND_KEEPALIVE)
3289 suspend_policy = SUSPEND_POLICY_NONE;
3294 if (agent_config.defer) {
3295 /* Make sure the thread id is always set when doing deferred debugging */
3296 if (debugger_thread_id == GetCurrentThreadId ()) {
3297 /* Don't suspend on events from the debugger thread */
3298 suspend_policy = SUSPEND_POLICY_NONE;
3299 thread = mono_thread_get_main ();
3301 else thread = mono_thread_current ();
3303 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3304 // FIXME: Send these with a NULL thread, don't suspend the current thread
3309 buffer_init (&buf, 128);
3310 buffer_add_byte (&buf, suspend_policy);
3311 buffer_add_int (&buf, g_slist_length (events)); // n of events
3313 for (l = events; l; l = l->next) {
3314 buffer_add_byte (&buf, event); // event kind
3315 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3318 thread = mono_thread_current ();
3320 if (event == EVENT_KIND_VM_START && arg != NULL)
3323 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3326 case EVENT_KIND_THREAD_START:
3327 case EVENT_KIND_THREAD_DEATH:
3329 case EVENT_KIND_APPDOMAIN_CREATE:
3330 case EVENT_KIND_APPDOMAIN_UNLOAD:
3331 buffer_add_domainid (&buf, arg);
3333 case EVENT_KIND_METHOD_ENTRY:
3334 case EVENT_KIND_METHOD_EXIT:
3335 buffer_add_methodid (&buf, domain, arg);
3337 case EVENT_KIND_ASSEMBLY_LOAD:
3338 case EVENT_KIND_ASSEMBLY_UNLOAD:
3339 buffer_add_assemblyid (&buf, domain, arg);
3341 case EVENT_KIND_TYPE_LOAD:
3342 buffer_add_typeid (&buf, domain, arg);
3344 case EVENT_KIND_BREAKPOINT:
3345 case EVENT_KIND_STEP:
3346 buffer_add_methodid (&buf, domain, arg);
3347 buffer_add_long (&buf, il_offset);
3349 case EVENT_KIND_VM_START:
3350 buffer_add_domainid (&buf, mono_get_root_domain ());
3352 case EVENT_KIND_VM_DEATH:
3354 case EVENT_KIND_EXCEPTION: {
3355 EventInfo *ei = arg;
3356 buffer_add_objid (&buf, ei->exc);
3359 case EVENT_KIND_USER_BREAK:
3361 case EVENT_KIND_USER_LOG: {
3362 EventInfo *ei = arg;
3363 buffer_add_int (&buf, ei->level);
3364 buffer_add_string (&buf, ei->category ? ei->category : "");
3365 buffer_add_string (&buf, ei->message ? ei->message : "");
3368 case EVENT_KIND_KEEPALIVE:
3369 suspend_policy = SUSPEND_POLICY_NONE;
3372 g_assert_not_reached ();
3376 if (event == EVENT_KIND_VM_START) {
3377 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3378 if (!agent_config.defer)
3379 start_debugger_thread ();
3382 if (event == EVENT_KIND_VM_DEATH) {
3383 vm_death_event_sent = TRUE;
3384 suspend_policy = SUSPEND_POLICY_NONE;
3387 if (mono_runtime_is_shutting_down ())
3388 suspend_policy = SUSPEND_POLICY_NONE;
3390 if (suspend_policy != SUSPEND_POLICY_NONE) {
3392 * Save the thread context and start suspending before sending the packet,
3393 * since we could be receiving the resume request before send_packet ()
3396 save_thread_context (ctx);
3400 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3404 g_slist_free (events);
3407 if (!send_success) {
3408 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3412 if (event == EVENT_KIND_VM_START) {
3413 vm_start_event_sent = TRUE;
3416 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
3419 switch (suspend_policy) {
3420 case SUSPEND_POLICY_NONE:
3422 case SUSPEND_POLICY_ALL:
3425 case SUSPEND_POLICY_EVENT_THREAD:
3429 g_assert_not_reached ();
3434 process_profiler_event (EventKind event, gpointer arg)
3438 EventInfo ei, *ei_arg = NULL;
3440 if (event == EVENT_KIND_TYPE_LOAD) {
3445 mono_loader_lock ();
3446 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3447 mono_loader_unlock ();
3449 process_event (event, arg, 0, NULL, events, suspend_policy);
3453 runtime_initialized (MonoProfiler *prof)
3455 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3456 if (agent_config.defer)
3457 start_debugger_thread ();
3461 runtime_shutdown (MonoProfiler *prof)
3463 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3465 mono_debugger_agent_cleanup ();
3469 thread_startup (MonoProfiler *prof, uintptr_t tid)
3471 MonoInternalThread *thread = mono_thread_internal_current ();
3472 MonoInternalThread *old_thread;
3473 DebuggerTlsData *tls;
3475 if (tid == debugger_thread_id)
3478 g_assert (thread->tid == tid);
3480 mono_loader_lock ();
3481 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3482 mono_loader_unlock ();
3484 if (thread == old_thread) {
3486 * For some reason, thread_startup () might be called for the same thread
3487 * multiple times (attach ?).
3489 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3493 * thread_end () might not be called for some threads, and the tid could
3496 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3497 mono_loader_lock ();
3498 mono_g_hash_table_remove (thread_to_tls, old_thread);
3499 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3500 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3501 mono_loader_unlock ();
3505 tls = mono_native_tls_get_value (debugger_tls_id);
3507 // FIXME: Free this somewhere
3508 tls = g_new0 (DebuggerTlsData, 1);
3509 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
3510 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3511 tls->thread = thread;
3512 mono_native_tls_set_value (debugger_tls_id, tls);
3514 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3516 mono_loader_lock ();
3517 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3518 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3519 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3520 mono_loader_unlock ();
3522 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3525 * suspend_vm () could have missed this thread, so wait for a resume.
3531 thread_end (MonoProfiler *prof, uintptr_t tid)
3533 MonoInternalThread *thread;
3534 DebuggerTlsData *tls = NULL;
3536 mono_loader_lock ();
3537 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3539 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3540 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3541 tls->terminated = TRUE;
3542 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3543 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3544 MONO_GC_UNREGISTER_ROOT (tls->thread);
3547 mono_loader_unlock ();
3549 /* We might be called for threads started before we registered the start callback */
3551 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3552 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3557 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3559 mono_loader_lock ();
3560 g_hash_table_insert (domains, domain, domain);
3561 mono_loader_unlock ();
3563 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3567 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3569 clear_breakpoints_for_domain (domain);
3571 mono_loader_lock ();
3572 /* Invalidate each thread's frame stack */
3573 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3574 mono_loader_unlock ();
3576 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3580 * invalidate_each_thread:
3582 * A GHFunc to invalidate frames.
3583 * value must be a DebuggerTlsData*
3586 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3588 invalidate_frames (value);
3592 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3594 /* Sent later in jit_end () */
3595 mono_loader_lock ();
3596 g_ptr_array_add (pending_assembly_loads, assembly);
3597 mono_loader_unlock ();
3601 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3603 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3605 clear_event_requests_for_assembly (assembly);
3606 clear_types_for_assembly (assembly);
3610 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3612 #if defined(HOST_WIN32) && !defined(__GNUC__)
3613 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3615 gpointer stackptr = __builtin_frame_address (1);
3617 MonoInternalThread *thread = mono_thread_internal_current ();
3618 DebuggerTlsData *tls;
3620 mono_loader_lock ();
3622 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3623 /* Could be the debugger thread with assembly/type load hooks */
3625 tls->invoke_addr = stackptr;
3627 mono_loader_unlock ();
3631 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3634 #if defined(HOST_WIN32) && !defined(__GNUC__)
3635 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3637 gpointer stackptr = __builtin_frame_address (1);
3640 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3644 * We need to stop single stepping when exiting a runtime invoke, since if it is
3645 * a step out, it may return to native code, and thus never end.
3647 mono_loader_lock ();
3648 ss_invoke_addr = NULL;
3650 for (i = 0; i < event_requests->len; ++i) {
3651 EventRequest *req = g_ptr_array_index (event_requests, i);
3653 if (req->event_kind == EVENT_KIND_STEP) {
3654 ss_destroy (req->info);
3655 g_ptr_array_remove_index_fast (event_requests, i);
3660 mono_loader_unlock ();
3664 send_type_load (MonoClass *klass)
3666 gboolean type_load = FALSE;
3667 MonoDomain *domain = mono_domain_get ();
3668 AgentDomainInfo *info = NULL;
3670 mono_loader_lock ();
3671 mono_domain_lock (domain);
3673 info = get_agent_domain_info (domain);
3675 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3677 g_hash_table_insert (info->loaded_classes, klass, klass);
3680 mono_domain_unlock (domain);
3681 mono_loader_unlock ();
3683 emit_type_load (klass, klass, NULL);
3687 * Emit load events for all types currently loaded in the domain.
3688 * Takes the loader and domain locks.
3689 * user_data is unused.
3692 send_types_for_domain (MonoDomain *domain, void *user_data)
3694 AgentDomainInfo *info = NULL;
3696 mono_loader_lock ();
3697 mono_domain_lock (domain);
3698 info = get_agent_domain_info (domain);
3700 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3701 mono_domain_unlock (domain);
3702 mono_loader_unlock ();
3706 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3709 * We emit type load events when the first method of the type is JITted,
3710 * since the class load profiler callbacks might be called with the
3711 * loader lock held. They could also occur in the debugger thread.
3712 * Same for assembly load events.
3715 MonoAssembly *assembly = NULL;
3717 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3718 mono_loader_lock ();
3719 if (pending_assembly_loads->len > 0) {
3720 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3721 g_ptr_array_remove_index (pending_assembly_loads, 0);
3723 mono_loader_unlock ();
3726 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3732 send_type_load (method->klass);
3735 add_pending_breakpoints (method, jinfo);
3739 * BREAKPOINTS/SINGLE STEPPING
3743 * Contains information about an inserted breakpoint.
3746 long il_offset, native_offset;
3751 } BreakpointInstance;
3754 * Contains generic information about a breakpoint.
3758 * The method where the breakpoint is placed. Can be NULL in which case it
3759 * is inserted into every method. This is used to implement method entry/
3760 * exit events. Can be a generic method definition, in which case the
3761 * breakpoint is inserted into every instance.
3767 * A list of BreakpointInstance structures describing where the breakpoint
3768 * was inserted. There could be more than one because of
3769 * generics/appdomains/method entry/exit.
3771 GPtrArray *children;
3774 /* List of breakpoints */
3775 static GPtrArray *breakpoints;
3776 /* Maps breakpoint locations to the number of breakpoints at that location */
3777 static GHashTable *bp_locs;
3780 breakpoints_init (void)
3782 breakpoints = g_ptr_array_new ();
3783 bp_locs = g_hash_table_new (NULL, NULL);
3787 * insert_breakpoint:
3789 * Insert the breakpoint described by BP into the method described by
3793 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3796 BreakpointInstance *inst;
3797 SeqPoint *sp = NULL;
3800 mono_error_init (error);
3802 for (i = 0; i < seq_points->len; ++i) {
3803 sp = &seq_points->seq_points [i];
3805 if (sp->il_offset == bp->il_offset)
3809 if (i == seq_points->len) {
3811 * The set of IL offsets with seq points doesn't completely match the
3812 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3814 for (i = 0; i < seq_points->len; ++i) {
3815 sp = &seq_points->seq_points [i];
3817 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3822 if (i == seq_points->len) {
3823 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);
3825 for (i = 0; i < seq_points->len; ++i)
3826 printf ("%d\n", seq_points->seq_points [i].il_offset);
3829 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
3838 inst = g_new0 (BreakpointInstance, 1);
3840 inst->native_offset = sp->native_offset;
3841 inst->ip = (guint8*)ji->code_start + sp->native_offset;
3843 inst->domain = domain;
3845 mono_loader_lock ();
3847 g_ptr_array_add (bp->children, inst);
3849 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
3850 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
3851 mono_loader_unlock ();
3854 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3855 mono_arch_set_breakpoint (ji, inst->ip);
3861 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
3865 remove_breakpoint (BreakpointInstance *inst)
3867 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3869 MonoJitInfo *ji = inst->ji;
3870 guint8 *ip = inst->ip;
3872 mono_loader_lock ();
3873 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
3874 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
3875 mono_loader_unlock ();
3877 g_assert (count > 0);
3880 mono_arch_clear_breakpoint (ji, ip);
3887 static inline gboolean
3888 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
3890 return (!bp->method || method == bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method));
3894 * add_pending_breakpoints:
3896 * Insert pending breakpoints into the newly JITted method METHOD.
3899 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
3902 MonoSeqPointInfo *seq_points;
3908 domain = mono_domain_get ();
3910 mono_loader_lock ();
3912 for (i = 0; i < breakpoints->len; ++i) {
3913 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
3914 gboolean found = FALSE;
3916 if (!bp_matches_method (bp, method))
3919 for (j = 0; j < bp->children->len; ++j) {
3920 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
3927 mono_domain_lock (domain);
3928 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
3929 if (!seq_points && ji->method->is_inflated)
3930 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
3931 mono_domain_unlock (domain);
3933 /* Could be AOT code */
3935 g_assert (seq_points);
3937 insert_breakpoint (seq_points, domain, ji, bp, NULL);
3941 mono_loader_unlock ();
3945 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
3951 mono_error_init (error);
3953 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
3955 /* Might be AOTed code */
3956 code = mono_aot_get_method (domain, method);
3958 ji = mono_jit_info_table_find (domain, code);
3963 insert_breakpoint (seq_points, domain, ji, bp, error);
3967 clear_breakpoint (MonoBreakpoint *bp);
3972 * Set a breakpoint at IL_OFFSET in METHOD.
3973 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
3974 * METHOD can also be a generic method definition, in which case a breakpoint
3975 * is placed in all instances of the method.
3976 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
3979 static MonoBreakpoint*
3980 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
3983 GHashTableIter iter, iter2;
3986 MonoSeqPointInfo *seq_points;
3989 mono_error_init (error);
3992 // - suspend/resume the vm to prevent code patching problems
3993 // - multiple breakpoints on the same location
3994 // - dynamic methods
3997 bp = g_new0 (MonoBreakpoint, 1);
3998 bp->method = method;
3999 bp->il_offset = il_offset;
4001 bp->children = g_ptr_array_new ();
4003 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));
4005 mono_loader_lock ();
4007 g_hash_table_iter_init (&iter, domains);
4008 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4009 mono_domain_lock (domain);
4011 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4012 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4013 if (bp_matches_method (bp, m))
4014 set_bp_in_method (domain, m, seq_points, bp, error);
4017 mono_domain_unlock (domain);
4020 mono_loader_unlock ();
4022 mono_loader_lock ();
4023 g_ptr_array_add (breakpoints, bp);
4024 mono_loader_unlock ();
4026 if (error && !mono_error_ok (error)) {
4027 clear_breakpoint (bp);
4035 clear_breakpoint (MonoBreakpoint *bp)
4039 // FIXME: locking, races
4040 for (i = 0; i < bp->children->len; ++i) {
4041 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4043 remove_breakpoint (inst);
4048 mono_loader_lock ();
4049 g_ptr_array_remove (breakpoints, bp);
4050 mono_loader_unlock ();
4052 g_ptr_array_free (bp->children, TRUE);
4057 breakpoints_cleanup (void)
4061 mono_loader_lock ();
4063 while (i < event_requests->len) {
4064 EventRequest *req = g_ptr_array_index (event_requests, i);
4066 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4067 clear_breakpoint (req->info);
4068 g_ptr_array_remove_index_fast (event_requests, i);
4075 for (i = 0; i < breakpoints->len; ++i)
4076 g_free (g_ptr_array_index (breakpoints, i));
4078 g_ptr_array_free (breakpoints, TRUE);
4079 g_hash_table_destroy (bp_locs);
4084 mono_loader_unlock ();
4088 * clear_breakpoints_for_domain:
4090 * Clear breakpoint instances which reference DOMAIN.
4093 clear_breakpoints_for_domain (MonoDomain *domain)
4097 /* This could be called after shutdown */
4101 mono_loader_lock ();
4102 for (i = 0; i < breakpoints->len; ++i) {
4103 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4106 while (j < bp->children->len) {
4107 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4109 if (inst->domain == domain) {
4110 remove_breakpoint (inst);
4114 g_ptr_array_remove_index_fast (bp->children, j);
4120 mono_loader_unlock ();
4124 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4126 return bp->method && bp->method->klass->image->assembly == assembly;
4130 process_breakpoint_inner (DebuggerTlsData *tls)
4134 int i, j, suspend_policy;
4135 guint32 native_offset;
4137 BreakpointInstance *inst;
4138 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4139 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4140 EventKind kind = EVENT_KIND_BREAKPOINT;
4141 MonoContext *ctx = &tls->restore_ctx;
4142 MonoSeqPointInfo *info;
4145 // FIXME: Speed this up
4147 ip = MONO_CONTEXT_GET_IP (ctx);
4148 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4150 g_assert (ji->method);
4152 /* Compute the native offset of the breakpoint from the ip */
4153 native_offset = ip - (guint8*)ji->code_start;
4156 * Skip the instruction causing the breakpoint signal.
4158 mono_arch_skip_breakpoint (ctx, ji);
4160 if (ji->method->wrapper_type || tls->disable_breakpoints)
4163 bp_reqs = g_ptr_array_new ();
4164 ss_reqs = g_ptr_array_new ();
4165 ss_reqs_orig = g_ptr_array_new ();
4167 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
4169 mono_loader_lock ();
4172 * The ip points to the instruction causing the breakpoint event, which is after
4173 * the offset recorded in the seq point map, so find the prev seq point before ip.
4175 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4178 for (i = 0; i < breakpoints->len; ++i) {
4179 bp = g_ptr_array_index (breakpoints, i);
4184 for (j = 0; j < bp->children->len; ++j) {
4185 inst = g_ptr_array_index (bp->children, j);
4186 if (inst->ji == ji && inst->sp == sp) {
4187 if (bp->req->event_kind == EVENT_KIND_STEP) {
4188 g_ptr_array_add (ss_reqs_orig, bp->req);
4190 g_ptr_array_add (bp_reqs, bp->req);
4195 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4196 /* Maybe a method entry/exit event */
4197 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4198 kind = EVENT_KIND_METHOD_ENTRY;
4199 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4200 kind = EVENT_KIND_METHOD_EXIT;
4203 /* Process single step requests */
4204 for (i = 0; i < ss_reqs_orig->len; ++i) {
4205 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4206 SingleStepReq *ss_req = req->info;
4207 gboolean hit = TRUE;
4209 if (ss_req->size == STEP_SIZE_LINE) {
4210 /* Have to check whenever a different source line was reached */
4211 MonoDebugMethodInfo *minfo;
4212 MonoDebugSourceLocation *loc = NULL;
4214 minfo = mono_debug_lookup_method (ji->method);
4217 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4219 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line))
4220 /* Have to continue single stepping */
4224 ss_req->last_method = ji->method;
4225 ss_req->last_line = loc->row;
4226 mono_debug_free_source_location (loc);
4231 g_ptr_array_add (ss_reqs, req);
4233 /* Start single stepping again from the current sequence point */
4234 ss_start (ss_req, ji->method, sp, info, ctx, NULL, FALSE);
4237 if (ss_reqs->len > 0)
4238 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4239 if (bp_reqs->len > 0)
4240 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4241 if (kind != EVENT_KIND_BREAKPOINT)
4242 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4244 mono_loader_unlock ();
4246 g_ptr_array_free (bp_reqs, TRUE);
4247 g_ptr_array_free (ss_reqs, TRUE);
4250 * FIXME: The first event will suspend, so the second will only be sent after the
4254 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4256 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4257 if (enter_leave_events)
4258 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4261 /* Process a breakpoint/single step event after resuming from a signal handler */
4263 process_signal_event (void (*func) (DebuggerTlsData*))
4265 DebuggerTlsData *tls;
4266 MonoContext orig_restore_ctx, ctx;
4267 static void (*restore_context) (void *);
4269 if (!restore_context)
4270 restore_context = mono_get_restore_context ();
4272 tls = mono_native_tls_get_value (debugger_tls_id);
4273 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4274 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4275 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4279 /* This is called when resuming from a signal handler, so it shouldn't return */
4280 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4281 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4282 restore_context (&ctx);
4283 g_assert_not_reached ();
4287 process_breakpoint (void)
4289 process_signal_event (process_breakpoint_inner);
4293 resume_from_signal_handler (void *sigctx, void *func)
4295 DebuggerTlsData *tls;
4298 /* Save the original context in TLS */
4299 // FIXME: This might not work on an altstack ?
4300 tls = mono_native_tls_get_value (debugger_tls_id);
4303 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4304 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4305 // clob:c could be added to op_seq_point.
4307 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4308 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4309 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4310 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4312 MONO_CONTEXT_SET_IP (&ctx, func);
4314 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4316 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4317 mono_ppc_set_func_into_sigctx (sigctx, func);
4322 mono_debugger_agent_breakpoint_hit (void *sigctx)
4325 * We are called from a signal handler, and running code there causes all kinds of
4326 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4327 * So set up the signal context to return to the real breakpoint handler function.
4330 resume_from_signal_handler (sigctx, process_breakpoint);
4334 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4336 if (frame->managed) {
4337 *(MonoContext*)data = *ctx;
4346 * Called by System.Diagnostics.Debugger:Break ().
4349 mono_debugger_agent_user_break (void)
4351 if (agent_config.enabled) {
4356 /* Obtain a context */
4357 MONO_CONTEXT_SET_IP (&ctx, NULL);
4358 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4359 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4361 mono_loader_lock ();
4362 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4363 mono_loader_unlock ();
4365 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4372 ss_depth_to_string (StepDepth depth)
4375 case STEP_DEPTH_OVER:
4377 case STEP_DEPTH_OUT:
4379 case STEP_DEPTH_INTO:
4382 g_assert_not_reached ();
4388 process_single_step_inner (DebuggerTlsData *tls)
4393 int il_offset, suspend_policy;
4396 MonoContext *ctx = &tls->restore_ctx;
4399 // FIXME: Speed this up
4401 ip = MONO_CONTEXT_GET_IP (ctx);
4403 /* Skip the instruction causing the single step */
4404 mono_arch_skip_single_step (ctx);
4406 if (suspend_count > 0) {
4407 process_suspend (tls, ctx);
4412 // FIXME: A suspend race
4415 if (mono_thread_internal_current () != ss_req->thread)
4418 if (log_level > 0) {
4419 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4421 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));
4425 * We implement step over/out by single stepping until we reach the same
4426 * frame/parent frame.
4429 * - stack growing upward
4433 if (ss_req->depth != STEP_DEPTH_INTO) {
4434 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
4436 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
4439 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
4442 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4444 g_assert (ji->method);
4446 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4451 * Stopping in memset makes half-initialized vtypes visible.
4452 * Stopping in memcpy makes half-copied vtypes visible.
4454 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4458 * The ip points to the instruction causing the single step event, which is before
4459 * the offset recorded in the seq point map, so find the next seq point after ip.
4461 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, NULL);
4464 il_offset = sp->il_offset;
4466 if (ss_req->size == STEP_SIZE_LINE) {
4467 /* Step until a different source line is reached */
4468 MonoDebugMethodInfo *minfo;
4470 minfo = mono_debug_lookup_method (ji->method);
4473 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4475 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4476 mono_debug_free_source_location (loc);
4481 * Step until we reach a location with line number info,
4482 * otherwise the client can't show a location.
4483 * This can happen for example with statics initialized inline
4484 * outside of a cctor.
4489 ss_req->last_method = ji->method;
4490 ss_req->last_line = loc->row;
4491 mono_debug_free_source_location (loc);
4496 // FIXME: Has to lock earlier
4498 reqs = g_ptr_array_new ();
4500 mono_loader_lock ();
4502 g_ptr_array_add (reqs, ss_req->req);
4504 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4506 g_ptr_array_free (reqs, TRUE);
4508 mono_loader_unlock ();
4510 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4514 process_single_step (void)
4516 process_signal_event (process_single_step_inner);
4520 * mono_debugger_agent_single_step_event:
4522 * Called from a signal handler to handle a single step event.
4525 mono_debugger_agent_single_step_event (void *sigctx)
4527 /* Resume to process_single_step through the signal context */
4529 // FIXME: Since step out/over is implemented using step in, the step in case should
4530 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4533 if (GetCurrentThreadId () == debugger_thread_id) {
4535 * This could happen despite our best effors when the runtime calls
4536 * assembly/type resolve hooks.
4537 * FIXME: Breakpoints too.
4541 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4542 mono_arch_skip_single_step (&ctx);
4543 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4547 resume_from_signal_handler (sigctx, process_single_step);
4551 debugger_agent_single_step_from_context (MonoContext *ctx)
4553 DebuggerTlsData *tls;
4554 MonoContext orig_restore_ctx;
4556 tls = mono_native_tls_get_value (debugger_tls_id);
4559 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4560 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4561 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4563 process_single_step_inner (tls);
4565 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4566 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4570 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4572 DebuggerTlsData *tls;
4573 MonoContext orig_restore_ctx;
4575 tls = mono_native_tls_get_value (debugger_tls_id);
4577 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4578 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4580 process_breakpoint_inner (tls);
4582 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4583 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4587 * start_single_stepping:
4589 * Turn on single stepping. Can be called multiple times, for example,
4590 * by a single step event request + a suspend.
4593 start_single_stepping (void)
4595 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4596 int val = InterlockedIncrement (&ss_count);
4599 mono_arch_start_single_stepping ();
4601 if (ss_req != NULL && ss_invoke_addr == NULL) {
4602 DebuggerTlsData *tls;
4604 mono_loader_lock ();
4606 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4607 ss_invoke_addr = tls->invoke_addr;
4609 mono_loader_unlock ();
4612 g_assert_not_reached ();
4617 stop_single_stepping (void)
4619 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4620 int val = InterlockedDecrement (&ss_count);
4623 mono_arch_stop_single_stepping ();
4625 g_assert_not_reached ();
4632 * Stop the single stepping operation given by SS_REQ.
4635 ss_stop (SingleStepReq *ss_req)
4640 for (l = ss_req->bps; l; l = l->next) {
4641 clear_breakpoint (l->data);
4643 g_slist_free (ss_req->bps);
4647 if (ss_req->global) {
4648 stop_single_stepping ();
4649 ss_req->global = FALSE;
4656 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4659 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4665 /* Stop the previous operation */
4669 * Implement single stepping using breakpoints if possible.
4671 if (step_to_catch) {
4672 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4673 ss_req->bps = g_slist_append (ss_req->bps, bp);
4674 } else if (ss_req->depth == STEP_DEPTH_OVER) {
4677 * Find the first sequence point in the current or in a previous frame which
4678 * is not the last in its method.
4680 while (sp && sp->next_len == 0) {
4682 if (tls && frame_index < tls->frame_count) {
4683 StackFrame *frame = tls->frames [frame_index];
4685 method = frame->method;
4686 if (frame->il_offset != -1) {
4687 sp = find_seq_point (frame->domain, frame->method, frame->il_offset, &info);
4693 if (sp && sp->next_len > 0) {
4694 for (i = 0; i < sp->next_len; ++i) {
4695 next_sp = &info->seq_points [sp->next [i]];
4697 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4698 ss_req->bps = g_slist_append (ss_req->bps, bp);
4704 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4705 ss_req->global = TRUE;
4706 start_single_stepping ();
4708 ss_req->global = FALSE;
4713 * Start single stepping of thread THREAD
4716 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4718 DebuggerTlsData *tls;
4719 MonoSeqPointInfo *info = NULL;
4720 SeqPoint *sp = NULL;
4721 MonoMethod *method = NULL;
4722 MonoDebugMethodInfo *minfo;
4723 gboolean step_to_catch = FALSE;
4725 if (suspend_count == 0)
4726 return ERR_NOT_SUSPENDED;
4728 wait_for_suspend ();
4730 // FIXME: Multiple requests
4732 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4733 return ERR_NOT_IMPLEMENTED;
4736 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4738 ss_req = g_new0 (SingleStepReq, 1);
4740 ss_req->thread = thread;
4741 ss_req->size = size;
4742 ss_req->depth = depth;
4745 mono_loader_lock ();
4746 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4747 mono_loader_unlock ();
4749 g_assert (tls->context.valid);
4750 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4752 if (tls->has_catch_ctx) {
4754 StackFrameInfo frame;
4755 MonoContext new_ctx;
4756 MonoLMF *lmf = NULL;
4759 * We are stopped at a throw site. Stepping should go to the catch site.
4762 /* Find the the jit info for the catch context */
4763 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
4765 g_assert (frame.type == FRAME_TYPE_MANAGED);
4768 * Find the seq point corresponding to the landing site ip, which is the first seq
4771 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
4774 method = frame.method;
4776 step_to_catch = TRUE;
4777 /* This make sure the seq point is not skipped by process_single_step () */
4778 ss_req->last_sp = NULL;
4781 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
4784 /* Compute the initial line info */
4785 compute_frame_info (thread, tls);
4787 if (tls->frame_count) {
4788 frame = tls->frames [0];
4790 ss_req->last_method = frame->method;
4791 ss_req->last_line = -1;
4793 minfo = mono_debug_lookup_method (frame->method);
4794 if (minfo && frame->il_offset != -1) {
4795 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
4798 ss_req->last_line = loc->row;
4805 if (!step_to_catch && ss_req->depth == STEP_DEPTH_OVER) {
4808 compute_frame_info (thread, tls);
4810 if (tls->frame_count) {
4811 frame = tls->frames [0];
4813 if (!method && frame->il_offset != -1) {
4814 /* FIXME: Sort the table and use a binary search */
4815 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4817 method = frame->method;
4822 ss_start (ss_req, method, sp, info, NULL, tls, step_to_catch);
4828 ss_destroy (SingleStepReq *req)
4831 g_assert (ss_req == req);
4840 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
4843 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
4849 if (!agent_config.enabled)
4852 mono_loader_lock ();
4853 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
4854 mono_loader_unlock ();
4857 ei.category = category ? mono_string_to_utf8 (category) : NULL;
4858 ei.message = message ? mono_string_to_utf8 (message) : NULL;
4860 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
4862 g_free (ei.category);
4863 g_free (ei.message);
4867 mono_debugger_agent_debug_log_is_enabled (void)
4869 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
4870 return agent_config.enabled;
4874 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
4875 MonoContext *catch_ctx)
4881 DebuggerTlsData *tls = NULL;
4883 if (thread_to_tls != NULL) {
4884 MonoInternalThread *thread = mono_thread_internal_current ();
4886 mono_loader_lock ();
4887 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4888 mono_loader_unlock ();
4890 if (tls && tls->abort_requested)
4892 if (tls && tls->disable_breakpoints)
4896 memset (&ei, 0, sizeof (EventInfo));
4898 /* Just-In-Time debugging */
4900 if (agent_config.onuncaught && !inited) {
4901 finish_agent_init (FALSE);
4904 * Send an unsolicited EXCEPTION event with a dummy request id.
4906 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4907 ei.exc = (MonoObject*)exc;
4908 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4911 } else if (agent_config.onthrow && !inited) {
4913 gboolean found = FALSE;
4915 for (l = agent_config.onthrow; l; l = l->next) {
4916 char *ex_type = l->data;
4917 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
4919 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
4926 finish_agent_init (FALSE);
4929 * Send an unsolicited EXCEPTION event with a dummy request id.
4931 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
4932 ei.exc = (MonoObject*)exc;
4933 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
4941 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
4943 ei.exc = (MonoObject*)exc;
4944 ei.caught = catch_ctx != NULL;
4946 mono_loader_lock ();
4947 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
4948 mono_loader_unlock ();
4950 if (tls && catch_ctx) {
4951 tls->catch_ctx = *catch_ctx;
4952 tls->has_catch_ctx = TRUE;
4955 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
4958 tls->has_catch_ctx = FALSE;
4962 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
4964 DebuggerTlsData *tls;
4969 tls = mono_native_tls_get_value (debugger_tls_id);
4974 * We're about to invoke an exception filter during the first pass of exception handling.
4976 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
4977 * 'orig_ctx' is the context where the exception has been thrown.
4980 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
4982 * If we're stopped in Filter(), normal stack unwinding would first unwind to
4983 * the call site (line 37) and then continue to Main(), but it would never
4984 * include the throw site (line 32).
4986 * Since exception filters are invoked during the first pass of exception handling,
4987 * the stack frames of the throw site are still intact, so we should include them
4990 * We do this here by saving the context of the throw site in 'tls->filter_state'.
4992 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
4993 * but report the location of the 'throw' to the user.
4997 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5001 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5003 DebuggerTlsData *tls;
5008 tls = mono_native_tls_get_value (debugger_tls_id);
5012 tls->filter_state.valid = FALSE;
5016 * buffer_add_value_full:
5018 * Add the encoding of the value at ADDR described by T to the buffer.
5019 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5023 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5029 g_assert (*(void**)addr);
5030 addr = *(void**)addr;
5035 case MONO_TYPE_BOOLEAN:
5038 case MONO_TYPE_CHAR:
5058 case MONO_TYPE_VOID:
5059 buffer_add_byte (buf, t->type);
5061 case MONO_TYPE_BOOLEAN:
5064 buffer_add_byte (buf, t->type);
5065 buffer_add_int (buf, *(gint8*)addr);
5067 case MONO_TYPE_CHAR:
5070 buffer_add_byte (buf, t->type);
5071 buffer_add_int (buf, *(gint16*)addr);
5076 buffer_add_byte (buf, t->type);
5077 buffer_add_int (buf, *(gint32*)addr);
5082 buffer_add_byte (buf, t->type);
5083 buffer_add_long (buf, *(gint64*)addr);
5087 /* Treat it as a vtype */
5089 case MONO_TYPE_PTR: {
5090 gssize val = *(gssize*)addr;
5092 buffer_add_byte (buf, t->type);
5093 buffer_add_long (buf, val);
5097 case MONO_TYPE_STRING:
5098 case MONO_TYPE_SZARRAY:
5099 case MONO_TYPE_OBJECT:
5100 case MONO_TYPE_CLASS:
5101 case MONO_TYPE_ARRAY:
5102 obj = *(MonoObject**)addr;
5105 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5107 if (obj->vtable->klass->valuetype) {
5108 t = &obj->vtable->klass->byval_arg;
5109 addr = mono_object_unbox (obj);
5111 } else if (obj->vtable->klass->rank) {
5112 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5113 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5114 buffer_add_byte (buf, MONO_TYPE_CLASS);
5116 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5118 buffer_add_objid (buf, obj);
5122 case MONO_TYPE_VALUETYPE: {
5126 MonoClass *klass = mono_class_from_mono_type (t);
5128 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5129 buffer_add_byte (buf, klass->enumtype);
5130 buffer_add_typeid (buf, domain, klass);
5134 while ((f = mono_class_get_fields (klass, &iter))) {
5135 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5137 if (mono_field_is_deleted (f))
5141 buffer_add_int (buf, nfields);
5144 while ((f = mono_class_get_fields (klass, &iter))) {
5145 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5147 if (mono_field_is_deleted (f))
5149 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5153 case MONO_TYPE_GENERICINST:
5154 if (mono_type_generic_inst_is_valuetype (t)) {
5166 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5168 buffer_add_value_full (buf, t, addr, domain, FALSE);
5172 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5175 int type = decode_byte (buf, &buf, limit);
5177 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5178 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5179 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5180 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5181 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5182 char *name = mono_type_full_name (t);
5183 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5185 return ERR_INVALID_ARGUMENT;
5189 case MONO_TYPE_BOOLEAN:
5190 *(guint8*)addr = decode_int (buf, &buf, limit);
5192 case MONO_TYPE_CHAR:
5193 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5196 *(gint8*)addr = decode_int (buf, &buf, limit);
5199 *(guint8*)addr = decode_int (buf, &buf, limit);
5202 *(gint16*)addr = decode_int (buf, &buf, limit);
5205 *(guint16*)addr = decode_int (buf, &buf, limit);
5208 *(gint32*)addr = decode_int (buf, &buf, limit);
5211 *(guint32*)addr = decode_int (buf, &buf, limit);
5214 *(gint64*)addr = decode_long (buf, &buf, limit);
5217 *(guint64*)addr = decode_long (buf, &buf, limit);
5220 *(guint32*)addr = decode_int (buf, &buf, limit);
5223 *(guint64*)addr = decode_long (buf, &buf, limit);
5226 /* We send these as I8, so we get them back as such */
5227 g_assert (type == MONO_TYPE_I8);
5228 *(gssize*)addr = decode_long (buf, &buf, limit);
5230 case MONO_TYPE_GENERICINST:
5231 if (MONO_TYPE_ISSTRUCT (t)) {
5232 /* The client sends these as a valuetype */
5240 /* We send these as vtypes, so we get them back as such */
5241 g_assert (type == MONO_TYPE_VALUETYPE);
5244 case MONO_TYPE_VALUETYPE: {
5245 gboolean is_enum = decode_byte (buf, &buf, limit);
5249 gpointer iter = NULL;
5252 /* Enums are sent as a normal vtype */
5254 return ERR_NOT_IMPLEMENTED;
5255 klass = decode_typeid (buf, &buf, limit, &d, &err);
5259 if (klass != mono_class_from_mono_type (t))
5260 return ERR_INVALID_ARGUMENT;
5262 nfields = decode_int (buf, &buf, limit);
5263 while ((f = mono_class_get_fields (klass, &iter))) {
5264 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5266 if (mono_field_is_deleted (f))
5268 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5273 g_assert (nfields == 0);
5278 if (MONO_TYPE_IS_REFERENCE (t)) {
5279 if (type == MONO_TYPE_OBJECT) {
5280 int objid = decode_objid (buf, &buf, limit);
5284 err = get_object (objid, (MonoObject**)&obj);
5288 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
5289 return ERR_INVALID_ARGUMENT;
5290 if (obj && obj->vtable->domain != domain)
5291 return ERR_INVALID_ARGUMENT;
5293 mono_gc_wbarrier_generic_store (addr, obj);
5294 } else if (type == VALUE_TYPE_ID_NULL) {
5295 *(MonoObject**)addr = NULL;
5297 return ERR_INVALID_ARGUMENT;
5311 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5318 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5319 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5322 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5323 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5325 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5327 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5328 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5329 addr += (gint32)var->offset;
5331 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5333 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5335 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5339 g_assert_not_reached ();
5344 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5350 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5351 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5353 if (MONO_TYPE_IS_REFERENCE (t))
5354 size = sizeof (gpointer);
5356 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5359 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5360 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5362 gboolean is_signed = FALSE;
5364 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5369 v = is_signed ? *(gint8*)val : *(guint8*)val;
5372 v = is_signed ? *(gint16*)val : *(guint16*)val;
5375 v = is_signed ? *(gint32*)val : *(guint32*)val;
5378 v = is_signed ? *(gint64*)val : *(guint64*)val;
5381 g_assert_not_reached ();
5384 /* Set value on the stack or in the return ctx */
5385 if (reg_locations [reg]) {
5386 /* Saved on the stack */
5387 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5388 *(reg_locations [reg]) = v;
5391 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5392 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5395 // FIXME: Move these to mono-context.h/c.
5396 mono_arch_context_set_int_reg (ctx, reg, v);
5398 // FIXME: Can't set registers, so we disable linears
5403 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5404 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5405 addr += (gint32)var->offset;
5407 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5409 // FIXME: Write barriers
5410 memcpy (addr, val, size);
5412 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5416 g_assert_not_reached ();
5421 clear_event_request (int req_id, int etype)
5425 mono_loader_lock ();
5426 for (i = 0; i < event_requests->len; ++i) {
5427 EventRequest *req = g_ptr_array_index (event_requests, i);
5429 if (req->id == req_id && req->event_kind == etype) {
5430 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5431 clear_breakpoint (req->info);
5432 if (req->event_kind == EVENT_KIND_STEP)
5433 ss_destroy (req->info);
5434 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5435 clear_breakpoint (req->info);
5436 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5437 clear_breakpoint (req->info);
5438 g_ptr_array_remove_index_fast (event_requests, i);
5443 mono_loader_unlock ();
5447 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5449 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5450 return breakpoint_matches_assembly (req->info, assembly);
5454 for (i = 0; i < req->nmodifiers; ++i) {
5455 Modifier *m = &req->modifiers [i];
5457 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5459 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5460 for (j = 0; m->data.assemblies [j]; ++j)
5461 if (m->data.assemblies [j] == assembly)
5471 * clear_event_requests_for_assembly:
5473 * Clear all events requests which reference ASSEMBLY.
5476 clear_event_requests_for_assembly (MonoAssembly *assembly)
5481 mono_loader_lock ();
5485 for (i = 0; i < event_requests->len; ++i) {
5486 EventRequest *req = g_ptr_array_index (event_requests, i);
5488 if (event_req_matches_assembly (req, assembly)) {
5489 clear_event_request (req->id, req->event_kind);
5495 mono_loader_unlock ();
5499 * type_comes_from_assembly:
5501 * GHRFunc that returns TRUE if klass comes from assembly
5504 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5506 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5510 * clear_types_for_assembly:
5512 * Clears types from loaded_classes for a given assembly
5515 clear_types_for_assembly (MonoAssembly *assembly)
5517 MonoDomain *domain = mono_domain_get ();
5518 AgentDomainInfo *info = NULL;
5520 mono_loader_lock ();
5521 info = get_agent_domain_info (domain);
5522 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5523 mono_loader_unlock ();
5527 add_thread (gpointer key, gpointer value, gpointer user_data)
5529 MonoInternalThread *thread = value;
5530 Buffer *buf = user_data;
5532 buffer_add_objid (buf, (MonoObject*)thread);
5536 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke)
5538 guint8 *p = invoke->p;
5539 guint8 *end = invoke->endp;
5542 MonoMethodSignature *sig;
5545 MonoObject *this, *res, *exc;
5548 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5551 MonoStopwatch watch;
5553 if (invoke->method) {
5555 * Invoke this method directly, currently only Environment.Exit () is supported.
5558 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>"));
5559 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5560 g_assert_not_reached ();
5563 m = decode_methodid (p, &p, end, &domain, &err);
5566 sig = mono_method_signature (m);
5568 if (m->klass->valuetype)
5569 this_buf = g_alloca (mono_class_instance_size (m->klass));
5571 this_buf = g_alloca (sizeof (MonoObject*));
5572 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5573 /* Should be null */
5574 int type = decode_byte (p, &p, end);
5575 if (type != VALUE_TYPE_ID_NULL)
5576 return ERR_INVALID_ARGUMENT;
5577 memset (this_buf, 0, mono_class_instance_size (m->klass));
5579 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5584 if (!m->klass->valuetype)
5585 this = *(MonoObject**)this_buf;
5589 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>"));
5591 if (this && this->vtable->domain != domain)
5594 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5595 if (!strcmp (m->name, ".ctor")) {
5596 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5597 return ERR_INVALID_ARGUMENT;
5599 this = mono_object_new (domain, m->klass);
5601 return ERR_INVALID_ARGUMENT;
5605 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
5606 return ERR_INVALID_ARGUMENT;
5608 nargs = decode_int (p, &p, end);
5609 if (nargs != sig->param_count)
5610 return ERR_INVALID_ARGUMENT;
5611 /* Use alloca to get gc tracking */
5612 arg_buf = g_alloca (nargs * sizeof (gpointer));
5613 memset (arg_buf, 0, nargs * sizeof (gpointer));
5614 args = g_alloca (nargs * sizeof (gpointer));
5615 for (i = 0; i < nargs; ++i) {
5616 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5617 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5621 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5624 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5625 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5628 args [i] = arg_buf [i];
5635 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5636 tls->disable_breakpoints = TRUE;
5638 tls->disable_breakpoints = FALSE;
5641 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5643 /* FIXME: Move this to arch specific code */
5644 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5645 if (invoke->has_ctx) {
5648 lmf_addr = mono_get_lmf_addr ();
5651 memset (&ext, 0, sizeof (ext));
5653 ext.lmf.previous_lmf = *(lmf_addr);
5654 /* Mark that this is a MonoLMFExt */
5655 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5656 ext.lmf.rsp = (gssize)&ext;
5657 #elif defined(TARGET_X86)
5658 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
5659 /* Mark that this is a MonoLMFExt */
5660 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5661 ext.lmf.ebp = (gssize)&ext;
5662 #elif defined(TARGET_ARM)
5663 ext.lmf.previous_lmf = *(lmf_addr);
5664 /* Mark that this is a MonoLMFExt */
5665 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5666 ext.lmf.sp = (gssize)&ext;
5667 #elif defined(TARGET_POWERPC)
5668 ext.lmf.previous_lmf = *(lmf_addr);
5669 /* Mark that this is a MonoLMFExt */
5670 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5671 ext.lmf.ebp = (gssize)&ext;
5672 #elif defined(TARGET_S390X)
5673 ext.lmf.previous_lmf = *(lmf_addr);
5674 /* Mark that this is a MonoLMFExt */
5675 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5676 ext.lmf.ebp = (gssize)&ext;
5677 #elif defined(TARGET_MIPS)
5678 ext.lmf.previous_lmf = *(lmf_addr);
5679 /* Mark that this is a MonoLMFExt */
5680 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5681 ext.lmf.iregs [mips_sp] = (gssize)&ext;
5683 g_assert_not_reached ();
5686 ext.debugger_invoke = TRUE;
5687 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
5689 mono_set_lmf ((MonoLMF*)&ext);
5693 mono_stopwatch_start (&watch);
5694 if (m->klass->valuetype)
5695 res = mono_runtime_invoke (m, this_buf, args, &exc);
5697 res = mono_runtime_invoke (m, this, args, &exc);
5698 mono_stopwatch_stop (&watch);
5699 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)));
5701 buffer_add_byte (buf, 0);
5702 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
5704 buffer_add_byte (buf, 1);
5705 if (sig->ret->type == MONO_TYPE_VOID) {
5706 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
5707 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
5710 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
5711 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
5712 buffer_add_value (buf, sig->ret, &res, domain);
5713 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
5714 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
5716 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &res, domain);
5718 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5721 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
5728 tls->disable_breakpoints = FALSE;
5730 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5731 if (invoke->has_ctx)
5732 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
5735 // FIXME: byref arguments
5743 * Invoke the method given by tls->pending_invoke in the current thread.
5746 invoke_method (void)
5748 DebuggerTlsData *tls;
5753 static void (*restore_context) (void *);
5754 MonoContext restore_ctx;
5756 if (!restore_context)
5757 restore_context = mono_get_restore_context ();
5759 tls = mono_native_tls_get_value (debugger_tls_id);
5763 * Store the `InvokeData *' in `tls->invoke' until we're done with
5764 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
5767 mono_loader_lock ();
5769 invoke = tls->pending_invoke;
5771 tls->pending_invoke = NULL;
5773 invoke->last_invoke = tls->invoke;
5774 tls->invoke = invoke;
5776 mono_loader_unlock ();
5778 tls->frames_up_to_date = FALSE;
5782 buffer_init (&buf, 128);
5784 err = do_invoke_method (tls, &buf, invoke);
5786 /* Start suspending before sending the reply */
5787 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED))
5790 send_reply_packet (id, err, &buf);
5794 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
5796 if (invoke->has_ctx)
5797 save_thread_context (&restore_ctx);
5799 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
5800 g_assert (tls->resume_count);
5801 tls->resume_count -= invoke->suspend_count;
5804 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
5807 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
5809 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
5810 * after the mono_runtime_invoke() already returned, but it doesn't matter
5811 * because we reset the abort here.
5814 mono_loader_lock ();
5816 if (tls->abort_requested)
5817 mono_thread_internal_reset_abort (tls->thread);
5819 tls->invoke = tls->invoke->last_invoke;
5820 tls->abort_requested = FALSE;
5822 mono_loader_unlock ();
5831 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
5833 MonoThread *thread = value;
5834 DebuggerTlsData *tls;
5837 mono_loader_lock ();
5838 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5840 res = tls->really_suspended;
5841 mono_loader_unlock ();
5847 get_source_files_for_type (MonoClass *klass)
5849 gpointer iter = NULL;
5855 files = g_ptr_array_new ();
5857 while ((method = mono_class_get_methods (klass, &iter))) {
5858 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
5861 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
5865 for (i = 0; i < files->len; ++i)
5866 if (!strcmp (g_ptr_array_index (files, i), source_file))
5868 if (i == files->len)
5869 g_ptr_array_add (files, g_strdup (source_file));
5870 g_free (source_file);
5878 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
5881 case CMD_VM_VERSION: {
5882 char *build_info, *version;
5884 build_info = mono_get_runtime_build_info ();
5885 version = g_strdup_printf ("mono %s", build_info);
5887 buffer_add_string (buf, version); /* vm version */
5888 buffer_add_int (buf, MAJOR_VERSION);
5889 buffer_add_int (buf, MINOR_VERSION);
5890 g_free (build_info);
5894 case CMD_VM_SET_PROTOCOL_VERSION: {
5895 major_version = decode_int (p, &p, end);
5896 minor_version = decode_int (p, &p, end);
5897 protocol_version_set = TRUE;
5898 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
5901 case CMD_VM_ALL_THREADS: {
5903 mono_loader_lock ();
5904 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
5905 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
5906 mono_loader_unlock ();
5909 case CMD_VM_SUSPEND:
5911 wait_for_suspend ();
5914 if (suspend_count == 0)
5915 return ERR_NOT_SUSPENDED;
5918 case CMD_VM_DISPOSE:
5919 /* Clear all event requests */
5920 mono_loader_lock ();
5921 while (event_requests->len > 0) {
5922 EventRequest *req = g_ptr_array_index (event_requests, 0);
5924 clear_event_request (req->id, req->event_kind);
5926 mono_loader_unlock ();
5928 while (suspend_count > 0)
5930 disconnected = TRUE;
5931 vm_start_event_sent = FALSE;
5934 MonoInternalThread *thread;
5935 DebuggerTlsData *tls;
5936 MonoClass *env_class;
5937 MonoMethod *exit_method = NULL;
5941 exit_code = decode_int (p, &p, end);
5943 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
5945 /* Have to send a reply before exiting */
5946 send_reply_packet (id, 0, buf);
5948 /* Clear all event requests */
5949 mono_loader_lock ();
5950 while (event_requests->len > 0) {
5951 EventRequest *req = g_ptr_array_index (event_requests, 0);
5953 clear_event_request (req->id, req->event_kind);
5955 mono_loader_unlock ();
5958 * The JDWP documentation says that the shutdown is not orderly. It doesn't
5959 * specify whenever a VM_DEATH event is sent. We currently do an orderly
5960 * shutdown by hijacking a thread to execute Environment.Exit (). This is
5961 * better than doing the shutdown ourselves, since it avoids various races.
5965 wait_for_suspend ();
5967 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
5969 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
5971 mono_loader_lock ();
5972 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
5973 mono_loader_unlock ();
5975 if (thread && exit_method) {
5976 mono_loader_lock ();
5977 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5978 mono_loader_unlock ();
5980 args = g_new0 (gpointer, 1);
5981 args [0] = g_malloc (sizeof (int));
5982 *(int*)(args [0]) = exit_code;
5984 tls->pending_invoke = g_new0 (InvokeData, 1);
5985 tls->pending_invoke->method = exit_method;
5986 tls->pending_invoke->args = args;
5988 while (suspend_count > 0)
5992 * No thread found, do it ourselves.
5993 * FIXME: This can race with normal shutdown etc.
5995 while (suspend_count > 0)
5998 mono_runtime_set_shutting_down ();
6000 mono_threads_set_shutting_down ();
6002 /* Suspend all managed threads since the runtime is going away */
6003 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6004 mono_thread_suspend_all_other_threads ();
6005 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6006 mono_runtime_quit ();
6007 transport_close2 ();
6008 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6014 case CMD_VM_INVOKE_METHOD: {
6015 int objid = decode_objid (p, &p, end);
6017 DebuggerTlsData *tls;
6020 err = get_object (objid, (MonoObject**)&thread);
6024 flags = decode_int (p, &p, end);
6026 // Wait for suspending if it already started
6028 wait_for_suspend ();
6029 if (!is_suspended ())
6030 return ERR_NOT_SUSPENDED;
6032 mono_loader_lock ();
6033 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6034 mono_loader_unlock ();
6037 if (!tls->really_suspended)
6038 /* The thread is still running native code, can't do invokes */
6039 return ERR_NOT_SUSPENDED;
6042 * Store the invoke data into tls, the thread will execute it after it is
6045 if (tls->pending_invoke)
6047 tls->pending_invoke = g_new0 (InvokeData, 1);
6048 tls->pending_invoke->id = id;
6049 tls->pending_invoke->flags = flags;
6050 tls->pending_invoke->p = g_malloc (end - p);
6051 memcpy (tls->pending_invoke->p, p, end - p);
6052 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6053 tls->pending_invoke->suspend_count = suspend_count;
6055 if (flags & INVOKE_FLAG_SINGLE_THREADED)
6056 resume_thread (THREAD_TO_INTERNAL (thread));
6061 case CMD_VM_ABORT_INVOKE: {
6062 int objid = decode_objid (p, &p, end);
6064 DebuggerTlsData *tls;
6067 err = get_object (objid, (MonoObject**)&thread);
6071 invoke_id = decode_int (p, &p, end);
6073 mono_loader_lock ();
6074 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6077 if (tls->abort_requested) {
6078 mono_loader_unlock ();
6083 * Check whether we're still inside the mono_runtime_invoke() and that it's
6084 * actually the correct invocation.
6086 * Careful, we do not stop the thread that's doing the invocation, so we can't
6087 * inspect its stack. However, invoke_method() also acquires the loader lock
6088 * when it's done, so we're safe here.
6092 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6093 mono_loader_unlock ();
6094 return ERR_NO_INVOCATION;
6097 tls->abort_requested = TRUE;
6099 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6100 mono_loader_unlock ();
6104 case CMD_VM_SET_KEEPALIVE: {
6105 int timeout = decode_int (p, &p, end);
6106 agent_config.keepalive = timeout;
6108 #ifndef DISABLE_SOCKET_TRANSPORT
6115 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6116 GHashTableIter iter, kiter;
6121 char *fname, *basename;
6122 gboolean ignore_case;
6123 GSList *class_list, *l;
6124 GPtrArray *res_classes, *res_domains;
6126 fname = decode_string (p, &p, end);
6127 ignore_case = decode_byte (p, &p, end);
6129 basename = g_path_get_basename (fname);
6131 res_classes = g_ptr_array_new ();
6132 res_domains = g_ptr_array_new ();
6134 mono_loader_lock ();
6135 g_hash_table_iter_init (&iter, domains);
6136 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6137 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6139 /* Update 'source_file_to_class' cache */
6140 g_hash_table_iter_init (&kiter, info->loaded_classes);
6141 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6142 if (!g_hash_table_lookup (info->source_files, klass)) {
6143 files = get_source_files_for_type (klass);
6144 g_hash_table_insert (info->source_files, klass, files);
6146 for (i = 0; i < files->len; ++i) {
6147 char *s = g_ptr_array_index (files, i);
6148 char *s2 = g_path_get_basename (s);
6150 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6152 class_list = g_slist_prepend (class_list, klass);
6153 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6155 class_list = g_slist_prepend (class_list, klass);
6156 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6167 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6168 for (l = class_list; l; l = l->next) {
6171 g_ptr_array_add (res_classes, klass);
6172 g_ptr_array_add (res_domains, domain);
6175 mono_loader_unlock ();
6180 buffer_add_int (buf, res_classes->len);
6181 for (i = 0; i < res_classes->len; ++i)
6182 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6183 g_ptr_array_free (res_classes, TRUE);
6184 g_ptr_array_free (res_domains, TRUE);
6187 case CMD_VM_GET_TYPES: {
6188 GHashTableIter iter;
6192 gboolean ignore_case;
6193 GPtrArray *res_classes, *res_domains;
6194 MonoTypeNameParse info;
6196 name = decode_string (p, &p, end);
6197 ignore_case = decode_byte (p, &p, end);
6199 if (!mono_reflection_parse_type (name, &info)) {
6201 mono_reflection_free_type_info (&info);
6202 return ERR_INVALID_ARGUMENT;
6205 res_classes = g_ptr_array_new ();
6206 res_domains = g_ptr_array_new ();
6208 mono_loader_lock ();
6209 g_hash_table_iter_init (&iter, domains);
6210 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6212 gboolean type_resolve;
6216 mono_domain_assemblies_lock (domain);
6217 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6221 type_resolve = TRUE;
6222 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6224 g_ptr_array_add (res_classes, mono_type_get_class (t));
6225 g_ptr_array_add (res_domains, domain);
6229 mono_domain_assemblies_unlock (domain);
6231 mono_loader_unlock ();
6234 mono_reflection_free_type_info (&info);
6236 buffer_add_int (buf, res_classes->len);
6237 for (i = 0; i < res_classes->len; ++i)
6238 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6239 g_ptr_array_free (res_classes, TRUE);
6240 g_ptr_array_free (res_domains, TRUE);
6245 return ERR_NOT_IMPLEMENTED;
6252 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6258 case CMD_EVENT_REQUEST_SET: {
6260 int i, event_kind, suspend_policy, nmodifiers, mod;
6263 MonoThread *step_thread;
6264 int size = 0, depth = 0, step_thread_id = 0;
6268 event_kind = decode_byte (p, &p, end);
6269 suspend_policy = decode_byte (p, &p, end);
6270 nmodifiers = decode_byte (p, &p, end);
6272 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6273 req->id = InterlockedIncrement (&event_request_id);
6274 req->event_kind = event_kind;
6275 req->suspend_policy = suspend_policy;
6276 req->nmodifiers = nmodifiers;
6279 for (i = 0; i < nmodifiers; ++i) {
6280 mod = decode_byte (p, &p, end);
6282 req->modifiers [i].kind = mod;
6283 if (mod == MOD_KIND_COUNT) {
6284 req->modifiers [i].data.count = decode_int (p, &p, end);
6285 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6286 method = decode_methodid (p, &p, end, &domain, &err);
6289 location = decode_long (p, &p, end);
6290 } else if (mod == MOD_KIND_STEP) {
6291 step_thread_id = decode_id (p, &p, end);
6292 size = decode_int (p, &p, end);
6293 depth = decode_int (p, &p, end);
6294 } else if (mod == MOD_KIND_THREAD_ONLY) {
6295 int id = decode_id (p, &p, end);
6297 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6302 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6303 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6307 req->modifiers [i].caught = decode_byte (p, &p, end);
6308 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6309 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" : ""));
6311 req->modifiers [i].data.exc_class = exc_class;
6313 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6315 return ERR_INVALID_ARGUMENT;
6318 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6319 int n = decode_int (p, &p, end);
6322 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6323 for (j = 0; j < n; ++j) {
6324 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6326 g_free (req->modifiers [i].data.assemblies);
6330 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6331 int n = decode_int (p, &p, end);
6334 modifier = &req->modifiers [i];
6335 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6336 for (j = 0; j < n; ++j) {
6337 char *s = decode_string (p, &p, end);
6340 g_hash_table_insert (modifier->data.source_files, s, s);
6342 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6343 int n = decode_int (p, &p, end);
6346 modifier = &req->modifiers [i];
6347 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6348 for (j = 0; j < n; ++j) {
6349 char *s = decode_string (p, &p, end);
6352 g_hash_table_insert (modifier->data.type_names, s, s);
6356 return ERR_NOT_IMPLEMENTED;
6360 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6363 req->info = set_breakpoint (method, location, req, &error);
6364 if (!mono_error_ok (&error)) {
6366 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6367 mono_error_cleanup (&error);
6368 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6370 } else if (req->event_kind == EVENT_KIND_STEP) {
6371 g_assert (step_thread_id);
6373 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6379 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6384 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6385 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6386 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6387 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6388 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6389 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6391 if (req->nmodifiers) {
6393 return ERR_NOT_IMPLEMENTED;
6397 mono_loader_lock ();
6398 g_ptr_array_add (event_requests, req);
6400 if (agent_config.defer) {
6401 /* Transmit cached data to the client on receipt of the event request */
6402 switch (req->event_kind) {
6403 case EVENT_KIND_APPDOMAIN_CREATE:
6404 /* Emit load events for currently loaded domains */
6405 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6407 case EVENT_KIND_ASSEMBLY_LOAD:
6408 /* Emit load events for currently loaded assemblies */
6409 mono_assembly_foreach (emit_assembly_load, NULL);
6411 case EVENT_KIND_THREAD_START:
6412 /* Emit start events for currently started threads */
6413 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6415 case EVENT_KIND_TYPE_LOAD:
6416 /* Emit type load events for currently loaded types */
6417 mono_domain_foreach (send_types_for_domain, NULL);
6423 mono_loader_unlock ();
6425 buffer_add_int (buf, req->id);
6428 case CMD_EVENT_REQUEST_CLEAR: {
6429 int etype = decode_byte (p, &p, end);
6430 int req_id = decode_int (p, &p, end);
6432 // FIXME: Make a faster mapping from req_id to request
6433 mono_loader_lock ();
6434 clear_event_request (req_id, etype);
6435 mono_loader_unlock ();
6438 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6441 mono_loader_lock ();
6443 while (i < event_requests->len) {
6444 EventRequest *req = g_ptr_array_index (event_requests, i);
6446 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6447 clear_breakpoint (req->info);
6449 g_ptr_array_remove_index_fast (event_requests, i);
6455 mono_loader_unlock ();
6459 return ERR_NOT_IMPLEMENTED;
6466 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6472 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6473 buffer_add_domainid (buf, mono_get_root_domain ());
6476 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6477 domain = decode_domainid (p, &p, end, NULL, &err);
6480 buffer_add_string (buf, domain->friendly_name);
6483 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6488 domain = decode_domainid (p, &p, end, NULL, &err);
6491 mono_loader_lock ();
6493 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6496 buffer_add_int (buf, count);
6497 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6499 buffer_add_assemblyid (buf, domain, ass);
6501 mono_loader_unlock ();
6504 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6505 domain = decode_domainid (p, &p, end, NULL, &err);
6509 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6512 case CMD_APPDOMAIN_GET_CORLIB: {
6513 domain = decode_domainid (p, &p, end, NULL, &err);
6517 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6520 case CMD_APPDOMAIN_CREATE_STRING: {
6524 domain = decode_domainid (p, &p, end, NULL, &err);
6527 s = decode_string (p, &p, end);
6529 o = mono_string_new (domain, s);
6530 buffer_add_objid (buf, (MonoObject*)o);
6533 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6535 MonoDomain *domain2;
6538 domain = decode_domainid (p, &p, end, NULL, &err);
6541 klass = decode_typeid (p, &p, end, &domain2, &err);
6546 g_assert (domain == domain2);
6548 o = mono_object_new (domain, klass);
6550 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6554 buffer_add_objid (buf, o);
6558 return ERR_NOT_IMPLEMENTED;
6565 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6571 ass = decode_assemblyid (p, &p, end, &domain, &err);
6576 case CMD_ASSEMBLY_GET_LOCATION: {
6577 buffer_add_string (buf, mono_image_get_filename (ass->image));
6580 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6584 if (ass->image->dynamic) {
6585 buffer_add_id (buf, 0);
6587 token = mono_image_get_entry_point (ass->image);
6589 buffer_add_id (buf, 0);
6591 m = mono_get_method (ass->image, token, NULL);
6592 buffer_add_methodid (buf, domain, m);
6597 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6598 buffer_add_moduleid (buf, domain, ass->image);
6601 case CMD_ASSEMBLY_GET_OBJECT: {
6602 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
6603 buffer_add_objid (buf, o);
6606 case CMD_ASSEMBLY_GET_TYPE: {
6607 char *s = decode_string (p, &p, end);
6608 gboolean ignorecase = decode_byte (p, &p, end);
6609 MonoTypeNameParse info;
6611 gboolean type_resolve, res;
6612 MonoDomain *d = mono_domain_get ();
6614 /* This is needed to be able to find referenced assemblies */
6615 res = mono_domain_set (domain, FALSE);
6618 if (!mono_reflection_parse_type (s, &info)) {
6621 if (info.assembly.name)
6623 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
6625 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
6626 mono_reflection_free_type_info (&info);
6629 mono_domain_set (d, TRUE);
6633 case CMD_ASSEMBLY_GET_NAME: {
6635 MonoAssembly *mass = ass;
6637 name = g_strdup_printf (
6638 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
6640 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
6641 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
6642 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
6643 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
6645 buffer_add_string (buf, name);
6650 return ERR_NOT_IMPLEMENTED;
6657 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6663 case CMD_MODULE_GET_INFO: {
6664 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
6667 basename = g_path_get_basename (image->name);
6668 buffer_add_string (buf, basename); // name
6669 buffer_add_string (buf, image->module_name); // scopename
6670 buffer_add_string (buf, image->name); // fqname
6671 buffer_add_string (buf, mono_image_get_guid (image)); // guid
6672 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
6677 return ERR_NOT_IMPLEMENTED;
6684 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6686 if (val && val->vtable->klass == mono_defaults.monotype_class) {
6687 /* Special case these so the client doesn't have to handle Type objects */
6689 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6690 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
6691 } else if (MONO_TYPE_IS_REFERENCE (t))
6692 buffer_add_value (buf, t, &val, domain);
6694 buffer_add_value (buf, t, mono_object_unbox (val), domain);
6698 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6704 buffer_add_int (buf, 0);
6708 for (i = 0; i < cinfo->num_attrs; ++i) {
6709 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6712 buffer_add_int (buf, nattrs);
6714 for (i = 0; i < cinfo->num_attrs; ++i) {
6715 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6716 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6717 MonoArray *typed_args, *named_args;
6719 CattrNamedArg *arginfo;
6721 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
6723 buffer_add_methodid (buf, domain, attr->ctor);
6727 buffer_add_int (buf, mono_array_length (typed_args));
6728 for (j = 0; j < mono_array_length (typed_args); ++j) {
6729 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
6731 t = mono_method_signature (attr->ctor)->params [j];
6733 buffer_add_cattr_arg (buf, t, domain, val);
6736 buffer_add_int (buf, 0);
6741 buffer_add_int (buf, mono_array_length (named_args));
6743 for (j = 0; j < mono_array_length (named_args); ++j) {
6744 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
6746 if (arginfo [j].prop) {
6747 buffer_add_byte (buf, 0x54);
6748 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6749 } else if (arginfo [j].field) {
6750 buffer_add_byte (buf, 0x53);
6752 g_assert_not_reached ();
6755 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6758 buffer_add_int (buf, 0);
6764 /* FIXME: Code duplication with icall.c */
6766 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
6771 mono_class_setup_interfaces (klass, error);
6772 if (!mono_error_ok (error))
6775 for (i = 0; i < klass->interface_count; i++) {
6776 ic = klass->interfaces [i];
6777 g_hash_table_insert (ifaces, ic, ic);
6779 collect_interfaces (ic, ifaces, error);
6780 if (!mono_error_ok (error))
6786 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
6796 case CMD_TYPE_GET_INFO: {
6797 buffer_add_string (buf, klass->name_space);
6798 buffer_add_string (buf, klass->name);
6800 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
6801 buffer_add_string (buf, name);
6803 buffer_add_assemblyid (buf, domain, klass->image->assembly);
6804 buffer_add_moduleid (buf, domain, klass->image);
6805 buffer_add_typeid (buf, domain, klass->parent);
6806 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
6807 buffer_add_typeid (buf, domain, klass->element_class);
6809 buffer_add_id (buf, 0);
6810 buffer_add_int (buf, klass->type_token);
6811 buffer_add_byte (buf, klass->rank);
6812 buffer_add_int (buf, klass->flags);
6814 type = &klass->byval_arg;
6815 // FIXME: Can't decide whenever a class represents a byref type
6818 if (type->type == MONO_TYPE_PTR)
6820 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
6822 if (type->type == MONO_TYPE_VALUETYPE)
6824 if (klass->enumtype)
6826 buffer_add_byte (buf, b);
6829 while ((nested = mono_class_get_nested_types (klass, &iter)))
6831 buffer_add_int (buf, nnested);
6833 while ((nested = mono_class_get_nested_types (klass, &iter)))
6834 buffer_add_typeid (buf, domain, nested);
6837 case CMD_TYPE_GET_METHODS: {
6840 gpointer iter = NULL;
6843 mono_class_setup_methods (klass);
6845 nmethods = mono_class_num_methods (klass);
6847 buffer_add_int (buf, nmethods);
6849 while ((m = mono_class_get_methods (klass, &iter))) {
6850 buffer_add_methodid (buf, domain, m);
6853 g_assert (i == nmethods);
6856 case CMD_TYPE_GET_FIELDS: {
6859 gpointer iter = NULL;
6862 nfields = mono_class_num_fields (klass);
6864 buffer_add_int (buf, nfields);
6866 while ((f = mono_class_get_fields (klass, &iter))) {
6867 buffer_add_fieldid (buf, domain, f);
6868 buffer_add_string (buf, f->name);
6869 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
6870 buffer_add_int (buf, f->type->attrs);
6873 g_assert (i == nfields);
6876 case CMD_TYPE_GET_PROPERTIES: {
6879 gpointer iter = NULL;
6882 nprops = mono_class_num_properties (klass);
6884 buffer_add_int (buf, nprops);
6886 while ((p = mono_class_get_properties (klass, &iter))) {
6887 buffer_add_propertyid (buf, domain, p);
6888 buffer_add_string (buf, p->name);
6889 buffer_add_methodid (buf, domain, p->get);
6890 buffer_add_methodid (buf, domain, p->set);
6891 buffer_add_int (buf, p->attrs);
6894 g_assert (i == nprops);
6897 case CMD_TYPE_GET_CATTRS: {
6898 MonoClass *attr_klass;
6899 MonoCustomAttrInfo *cinfo;
6901 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6902 /* attr_klass can be NULL */
6906 cinfo = mono_custom_attrs_from_class (klass);
6908 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6911 case CMD_TYPE_GET_FIELD_CATTRS: {
6912 MonoClass *attr_klass;
6913 MonoCustomAttrInfo *cinfo;
6914 MonoClassField *field;
6916 field = decode_fieldid (p, &p, end, NULL, &err);
6919 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6923 cinfo = mono_custom_attrs_from_field (klass, field);
6925 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6928 case CMD_TYPE_GET_PROPERTY_CATTRS: {
6929 MonoClass *attr_klass;
6930 MonoCustomAttrInfo *cinfo;
6933 prop = decode_propertyid (p, &p, end, NULL, &err);
6936 attr_klass = decode_typeid (p, &p, end, NULL, &err);
6940 cinfo = mono_custom_attrs_from_property (klass, prop);
6942 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
6945 case CMD_TYPE_GET_VALUES:
6946 case CMD_TYPE_GET_VALUES_2: {
6953 MonoThread *thread_obj;
6954 MonoInternalThread *thread = NULL;
6955 guint32 special_static_type;
6957 if (command == CMD_TYPE_GET_VALUES_2) {
6958 int objid = decode_objid (p, &p, end);
6961 err = get_object (objid, (MonoObject**)&thread_obj);
6965 thread = THREAD_TO_INTERNAL (thread_obj);
6968 len = decode_int (p, &p, end);
6969 for (i = 0; i < len; ++i) {
6970 f = decode_fieldid (p, &p, end, NULL, &err);
6974 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
6975 return ERR_INVALID_FIELDID;
6976 special_static_type = mono_class_field_get_special_static_type (f);
6977 if (special_static_type != SPECIAL_STATIC_NONE) {
6978 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
6979 return ERR_INVALID_FIELDID;
6982 /* Check that the field belongs to the object */
6984 for (k = klass; k; k = k->parent) {
6985 if (k == f->parent) {
6991 return ERR_INVALID_FIELDID;
6993 vtable = mono_class_vtable (domain, f->parent);
6994 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
6995 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
6996 buffer_add_value (buf, f->type, val, domain);
7001 case CMD_TYPE_SET_VALUES: {
7009 len = decode_int (p, &p, end);
7010 for (i = 0; i < len; ++i) {
7011 f = decode_fieldid (p, &p, end, NULL, &err);
7015 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7016 return ERR_INVALID_FIELDID;
7017 if (mono_class_field_is_special_static (f))
7018 return ERR_INVALID_FIELDID;
7020 /* Check that the field belongs to the object */
7022 for (k = klass; k; k = k->parent) {
7023 if (k == f->parent) {
7029 return ERR_INVALID_FIELDID;
7031 // FIXME: Check for literal/const
7033 vtable = mono_class_vtable (domain, f->parent);
7034 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7035 err = decode_value (f->type, domain, val, p, &p, end);
7040 if (MONO_TYPE_IS_REFERENCE (f->type))
7041 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7043 mono_field_static_set_value (vtable, f, val);
7048 case CMD_TYPE_GET_OBJECT: {
7049 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
7050 buffer_add_objid (buf, o);
7053 case CMD_TYPE_GET_SOURCE_FILES:
7054 case CMD_TYPE_GET_SOURCE_FILES_2: {
7055 char *source_file, *base;
7059 files = get_source_files_for_type (klass);
7061 buffer_add_int (buf, files->len);
7062 for (i = 0; i < files->len; ++i) {
7063 source_file = g_ptr_array_index (files, i);
7064 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7065 buffer_add_string (buf, source_file);
7067 base = g_path_get_basename (source_file);
7068 buffer_add_string (buf, base);
7071 g_free (source_file);
7073 g_ptr_array_free (files, TRUE);
7076 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7077 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7081 if (mono_class_is_assignable_from (klass, oklass))
7082 buffer_add_byte (buf, 1);
7084 buffer_add_byte (buf, 0);
7087 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7088 char *name = decode_string (p, &p, end);
7089 int i, flags = decode_int (p, &p, end);
7090 MonoException *ex = NULL;
7091 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7094 return ERR_LOADER_ERROR;
7095 buffer_add_int (buf, array->len);
7096 for (i = 0; i < array->len; ++i) {
7097 MonoMethod *method = g_ptr_array_index (array, i);
7098 buffer_add_methodid (buf, domain, method);
7101 g_ptr_array_free (array, TRUE);
7105 case CMD_TYPE_GET_INTERFACES: {
7107 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7109 MonoClass *tclass, *iface;
7110 GHashTableIter iter;
7114 for (parent = tclass; parent; parent = parent->parent) {
7115 mono_class_setup_interfaces (parent, &error);
7116 if (!mono_error_ok (&error))
7117 return ERR_LOADER_ERROR;
7118 collect_interfaces (parent, iface_hash, &error);
7119 if (!mono_error_ok (&error))
7120 return ERR_LOADER_ERROR;
7123 buffer_add_int (buf, g_hash_table_size (iface_hash));
7125 g_hash_table_iter_init (&iter, iface_hash);
7126 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7127 buffer_add_typeid (buf, domain, iface);
7128 g_hash_table_destroy (iface_hash);
7131 case CMD_TYPE_GET_INTERFACE_MAP: {
7132 int tindex, ioffset;
7133 gboolean variance_used;
7135 int len, nmethods, i;
7139 len = decode_int (p, &p, end);
7140 mono_class_setup_vtable (klass);
7142 for (tindex = 0; tindex < len; ++tindex) {
7143 iclass = decode_typeid (p, &p, end, NULL, &err);
7147 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7149 return ERR_INVALID_ARGUMENT;
7151 nmethods = mono_class_num_methods (iclass);
7152 buffer_add_int (buf, nmethods);
7155 while ((method = mono_class_get_methods (iclass, &iter))) {
7156 buffer_add_methodid (buf, domain, method);
7158 for (i = 0; i < nmethods; ++i)
7159 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7164 return ERR_NOT_IMPLEMENTED;
7171 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7174 MonoDomain *old_domain;
7178 klass = decode_typeid (p, &p, end, &domain, &err);
7182 old_domain = mono_domain_get ();
7184 mono_domain_set (domain, TRUE);
7186 err = type_commands_internal (command, klass, domain, p, end, buf);
7188 mono_domain_set (old_domain, TRUE);
7194 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7196 MonoMethodHeader *header;
7199 case CMD_METHOD_GET_NAME: {
7200 buffer_add_string (buf, method->name);
7203 case CMD_METHOD_GET_DECLARING_TYPE: {
7204 buffer_add_typeid (buf, domain, method->klass);
7207 case CMD_METHOD_GET_DEBUG_INFO: {
7208 MonoDebugMethodInfo *minfo;
7210 int i, n_il_offsets;
7214 header = mono_method_get_header (method);
7216 buffer_add_int (buf, 0);
7217 buffer_add_string (buf, "");
7218 buffer_add_int (buf, 0);
7222 minfo = mono_debug_lookup_method (method);
7224 buffer_add_int (buf, header->code_size);
7225 buffer_add_string (buf, "");
7226 buffer_add_int (buf, 0);
7227 mono_metadata_free_mh (header);
7231 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
7232 buffer_add_int (buf, header->code_size);
7233 buffer_add_string (buf, source_file);
7234 buffer_add_int (buf, n_il_offsets);
7235 DEBUG (10, printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7236 for (i = 0; i < n_il_offsets; ++i) {
7237 DEBUG (10, printf ("IL%x -> %d\n", il_offsets [i], line_numbers [i]));
7238 buffer_add_int (buf, il_offsets [i]);
7239 buffer_add_int (buf, line_numbers [i]);
7241 g_free (source_file);
7242 g_free (il_offsets);
7243 g_free (line_numbers);
7244 mono_metadata_free_mh (header);
7247 case CMD_METHOD_GET_PARAM_INFO: {
7248 MonoMethodSignature *sig = mono_method_signature (method);
7252 /* FIXME: mono_class_from_mono_type () and byrefs */
7254 /* FIXME: Use a smaller encoding */
7255 buffer_add_int (buf, sig->call_convention);
7256 buffer_add_int (buf, sig->param_count);
7257 buffer_add_int (buf, sig->generic_param_count);
7258 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7259 for (i = 0; i < sig->param_count; ++i) {
7261 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7264 /* Emit parameter names */
7265 names = g_new (char *, sig->param_count);
7266 mono_method_get_param_names (method, (const char **) names);
7267 for (i = 0; i < sig->param_count; ++i)
7268 buffer_add_string (buf, names [i]);
7273 case CMD_METHOD_GET_LOCALS_INFO: {
7274 int i, j, num_locals;
7275 MonoDebugLocalsInfo *locals;
7277 header = mono_method_get_header (method);
7280 buffer_add_int (buf, header->num_locals);
7283 for (i = 0; i < header->num_locals; ++i)
7284 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7287 locals = mono_debug_lookup_locals (method);
7289 num_locals = locals->num_locals;
7292 for (i = 0; i < header->num_locals; ++i) {
7293 for (j = 0; j < num_locals; ++j)
7294 if (locals->locals [j].index == i)
7297 buffer_add_string (buf, locals->locals [j].name);
7299 buffer_add_string (buf, "");
7303 for (i = 0; i < header->num_locals; ++i) {
7304 for (j = 0; j < num_locals; ++j)
7305 if (locals->locals [j].index == i)
7307 if (j < num_locals && locals->locals [j].block) {
7308 buffer_add_int (buf, locals->locals [j].block->start_offset);
7309 buffer_add_int (buf, locals->locals [j].block->end_offset);
7311 buffer_add_int (buf, 0);
7312 buffer_add_int (buf, header->code_size);
7315 mono_metadata_free_mh (header);
7318 mono_debug_symfile_free_locals (locals);
7322 case CMD_METHOD_GET_INFO:
7323 buffer_add_int (buf, method->flags);
7324 buffer_add_int (buf, method->iflags);
7325 buffer_add_int (buf, method->token);
7327 case CMD_METHOD_GET_BODY: {
7330 header = mono_method_get_header (method);
7332 buffer_add_int (buf, 0);
7334 buffer_add_int (buf, header->code_size);
7335 for (i = 0; i < header->code_size; ++i)
7336 buffer_add_byte (buf, header->code [i]);
7338 mono_metadata_free_mh (header);
7341 case CMD_METHOD_RESOLVE_TOKEN: {
7342 guint32 token = decode_int (p, &p, end);
7345 switch (mono_metadata_token_code (token)) {
7346 case MONO_TOKEN_STRING: {
7350 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7353 s2 = mono_string_to_utf8 (s);
7355 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7356 buffer_add_string (buf, s2);
7362 MonoClass *handle_class;
7364 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7365 val = mono_method_get_wrapper_data (method, token);
7366 handle_class = mono_method_get_wrapper_data (method, token + 1);
7368 if (handle_class == NULL) {
7369 // Can't figure out the token type
7370 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7374 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7378 if (handle_class == mono_defaults.typehandle_class) {
7379 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7380 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7381 buffer_add_typeid (buf, domain, (MonoClass *) val);
7383 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7384 } else if (handle_class == mono_defaults.fieldhandle_class) {
7385 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7386 buffer_add_fieldid (buf, domain, val);
7387 } else if (handle_class == mono_defaults.methodhandle_class) {
7388 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7389 buffer_add_methodid (buf, domain, val);
7390 } else if (handle_class == mono_defaults.string_class) {
7393 s = mono_string_to_utf8 (val);
7394 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7395 buffer_add_string (buf, s);
7398 g_assert_not_reached ();
7406 return ERR_NOT_IMPLEMENTED;
7413 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7416 MonoDomain *old_domain;
7420 method = decode_methodid (p, &p, end, &domain, &err);
7424 old_domain = mono_domain_get ();
7426 mono_domain_set (domain, TRUE);
7428 err = method_commands_internal (command, method, domain, p, end, buf);
7430 mono_domain_set (old_domain, TRUE);
7436 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7438 int objid = decode_objid (p, &p, end);
7440 MonoThread *thread_obj;
7441 MonoInternalThread *thread;
7443 err = get_object (objid, (MonoObject**)&thread_obj);
7447 thread = THREAD_TO_INTERNAL (thread_obj);
7450 case CMD_THREAD_GET_NAME: {
7452 gunichar2 *s = mono_thread_get_name (thread, &name_len);
7455 buffer_add_int (buf, 0);
7460 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
7462 buffer_add_int (buf, len);
7463 buffer_add_data (buf, (guint8*)name, len);
7468 case CMD_THREAD_GET_FRAME_INFO: {
7469 DebuggerTlsData *tls;
7470 int i, start_frame, length;
7472 // Wait for suspending if it already started
7474 wait_for_suspend ();
7475 if (!is_suspended ())
7476 return ERR_NOT_SUSPENDED;
7478 start_frame = decode_int (p, &p, end);
7479 length = decode_int (p, &p, end);
7481 if (start_frame != 0 || length != -1)
7482 return ERR_NOT_IMPLEMENTED;
7484 mono_loader_lock ();
7485 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7486 mono_loader_unlock ();
7489 compute_frame_info (thread, tls);
7491 buffer_add_int (buf, tls->frame_count);
7492 for (i = 0; i < tls->frame_count; ++i) {
7493 buffer_add_int (buf, tls->frames [i]->id);
7494 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
7495 buffer_add_int (buf, tls->frames [i]->il_offset);
7497 * Instead of passing the frame type directly to the client, we associate
7498 * it with the previous frame using a set of flags. This avoids lots of
7499 * conditional code in the client, since a frame whose type isn't
7500 * FRAME_TYPE_MANAGED has no method, location, etc.
7502 buffer_add_byte (buf, tls->frames [i]->flags);
7507 case CMD_THREAD_GET_STATE:
7508 buffer_add_int (buf, thread->state);
7510 case CMD_THREAD_GET_INFO:
7511 buffer_add_byte (buf, thread->threadpool_thread);
7513 case CMD_THREAD_GET_ID:
7514 buffer_add_long (buf, (guint64)(gsize)thread);
7516 case CMD_THREAD_GET_TID:
7517 buffer_add_long (buf, (guint64)thread->tid);
7520 return ERR_NOT_IMPLEMENTED;
7527 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7531 MonoThread *thread_obj;
7532 MonoInternalThread *thread;
7533 int pos, i, len, frame_idx;
7534 DebuggerTlsData *tls;
7536 MonoDebugMethodJitInfo *jit;
7537 MonoDebugVarInfo *var;
7538 MonoMethodSignature *sig;
7540 MonoMethodHeader *header;
7542 objid = decode_objid (p, &p, end);
7543 err = get_object (objid, (MonoObject**)&thread_obj);
7547 thread = THREAD_TO_INTERNAL (thread_obj);
7549 id = decode_id (p, &p, end);
7551 mono_loader_lock ();
7552 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7553 mono_loader_unlock ();
7556 for (i = 0; i < tls->frame_count; ++i) {
7557 if (tls->frames [i]->id == id)
7560 if (i == tls->frame_count)
7561 return ERR_INVALID_FRAMEID;
7564 frame = tls->frames [frame_idx];
7566 if (!frame->has_ctx)
7568 return ERR_INVALID_FRAMEID;
7571 frame->jit = mono_debug_find_method (frame->method, frame->domain);
7572 if (!frame->jit && frame->method->is_inflated)
7573 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->method), frame->domain);
7577 /* This could happen for aot images with no jit debug info */
7578 s = mono_method_full_name (frame->method, TRUE);
7579 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
7581 return ERR_ABSENT_INFORMATION;
7586 sig = mono_method_signature (frame->actual_method);
7589 case CMD_STACK_FRAME_GET_VALUES: {
7590 len = decode_int (p, &p, end);
7591 header = mono_method_get_header (frame->actual_method);
7593 for (i = 0; i < len; ++i) {
7594 pos = decode_int (p, &p, end);
7599 g_assert (pos >= 0 && pos < jit->num_params);
7601 var = &jit->params [pos];
7603 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
7605 g_assert (pos >= 0 && pos < jit->num_locals);
7607 var = &jit->locals [pos];
7609 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
7612 mono_metadata_free_mh (header);
7615 case CMD_STACK_FRAME_GET_THIS: {
7616 if (frame->method->klass->valuetype) {
7617 if (!sig->hasthis) {
7618 MonoObject *p = NULL;
7619 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
7621 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7624 if (!sig->hasthis) {
7625 MonoObject *p = NULL;
7626 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
7628 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
7633 case CMD_STACK_FRAME_SET_VALUES: {
7636 MonoDebugVarInfo *var;
7638 len = decode_int (p, &p, end);
7639 header = mono_method_get_header (frame->actual_method);
7641 for (i = 0; i < len; ++i) {
7642 pos = decode_int (p, &p, end);
7647 g_assert (pos >= 0 && pos < jit->num_params);
7649 t = sig->params [pos];
7650 var = &jit->params [pos];
7652 g_assert (pos >= 0 && pos < jit->num_locals);
7654 t = header->locals [pos];
7655 var = &jit->locals [pos];
7658 if (MONO_TYPE_IS_REFERENCE (t))
7659 val_buf = g_alloca (sizeof (MonoObject*));
7661 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
7662 err = decode_value (t, frame->domain, val_buf, p, &p, end);
7666 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
7668 mono_metadata_free_mh (header);
7672 return ERR_NOT_IMPLEMENTED;
7679 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7682 int objid, err, index, len, i, esize;
7685 objid = decode_objid (p, &p, end);
7686 err = get_object (objid, (MonoObject**)&arr);
7691 case CMD_ARRAY_REF_GET_LENGTH:
7692 buffer_add_int (buf, arr->obj.vtable->klass->rank);
7694 buffer_add_int (buf, arr->max_length);
7695 buffer_add_int (buf, 0);
7697 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
7698 buffer_add_int (buf, arr->bounds [i].length);
7699 buffer_add_int (buf, arr->bounds [i].lower_bound);
7703 case CMD_ARRAY_REF_GET_VALUES:
7704 index = decode_int (p, &p, end);
7705 len = decode_int (p, &p, end);
7707 g_assert (index >= 0 && len >= 0);
7708 // Reordered to avoid integer overflow
7709 g_assert (!(index > arr->max_length - len));
7711 esize = mono_array_element_size (arr->obj.vtable->klass);
7712 for (i = index; i < index + len; ++i) {
7713 elem = (gpointer*)((char*)arr->vector + (i * esize));
7714 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
7717 case CMD_ARRAY_REF_SET_VALUES:
7718 index = decode_int (p, &p, end);
7719 len = decode_int (p, &p, end);
7721 g_assert (index >= 0 && len >= 0);
7722 // Reordered to avoid integer overflow
7723 g_assert (!(index > arr->max_length - len));
7725 esize = mono_array_element_size (arr->obj.vtable->klass);
7726 for (i = index; i < index + len; ++i) {
7727 elem = (gpointer*)((char*)arr->vector + (i * esize));
7729 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
7733 return ERR_NOT_IMPLEMENTED;
7740 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7745 int i, index, length;
7748 objid = decode_objid (p, &p, end);
7749 err = get_object (objid, (MonoObject**)&str);
7754 case CMD_STRING_REF_GET_VALUE:
7755 s = mono_string_to_utf8 (str);
7756 buffer_add_string (buf, s);
7759 case CMD_STRING_REF_GET_LENGTH:
7760 buffer_add_long (buf, mono_string_length (str));
7762 case CMD_STRING_REF_GET_CHARS:
7763 index = decode_long (p, &p, end);
7764 length = decode_long (p, &p, end);
7765 if (index > mono_string_length (str) - length)
7766 return ERR_INVALID_ARGUMENT;
7767 c = mono_string_chars (str) + index;
7768 for (i = 0; i < length; ++i)
7769 buffer_add_short (buf, c [i]);
7772 return ERR_NOT_IMPLEMENTED;
7779 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7788 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
7789 objid = decode_objid (p, &p, end);
7790 err = get_object (objid, &obj);
7792 buffer_add_int (buf, 1);
7794 buffer_add_int (buf, 0);
7798 objid = decode_objid (p, &p, end);
7799 err = get_object (objid, &obj);
7804 case CMD_OBJECT_REF_GET_TYPE:
7805 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
7807 case CMD_OBJECT_REF_GET_VALUES:
7808 len = decode_int (p, &p, end);
7810 for (i = 0; i < len; ++i) {
7811 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
7815 /* Check that the field belongs to the object */
7817 for (k = obj->vtable->klass; k; k = k->parent) {
7818 if (k == f->parent) {
7824 return ERR_INVALID_FIELDID;
7826 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
7830 if (mono_class_field_is_special_static (f))
7831 return ERR_INVALID_FIELDID;
7833 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
7834 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
7835 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7836 mono_field_static_get_value (vtable, f, val);
7837 buffer_add_value (buf, f->type, val, obj->vtable->domain);
7840 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
7844 case CMD_OBJECT_REF_SET_VALUES:
7845 len = decode_int (p, &p, end);
7847 for (i = 0; i < len; ++i) {
7848 f = decode_fieldid (p, &p, end, NULL, &err);
7852 /* Check that the field belongs to the object */
7854 for (k = obj->vtable->klass; k; k = k->parent) {
7855 if (k == f->parent) {
7861 return ERR_INVALID_FIELDID;
7863 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
7867 if (mono_class_field_is_special_static (f))
7868 return ERR_INVALID_FIELDID;
7870 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
7871 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
7873 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7874 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
7879 mono_field_static_set_value (vtable, f, val);
7882 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
7888 case CMD_OBJECT_REF_GET_ADDRESS:
7889 buffer_add_long (buf, (gssize)obj);
7891 case CMD_OBJECT_REF_GET_DOMAIN:
7892 buffer_add_domainid (buf, obj->vtable->domain);
7894 case CMD_OBJECT_REF_GET_INFO:
7895 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
7896 buffer_add_domainid (buf, obj->vtable->domain);
7899 return ERR_NOT_IMPLEMENTED;
7906 command_set_to_string (CommandSet command_set)
7908 switch (command_set) {
7911 case CMD_SET_OBJECT_REF:
7912 return "OBJECT_REF";
7913 case CMD_SET_STRING_REF:
7914 return "STRING_REF";
7915 case CMD_SET_THREAD:
7917 case CMD_SET_ARRAY_REF:
7919 case CMD_SET_EVENT_REQUEST:
7920 return "EVENT_REQUEST";
7921 case CMD_SET_STACK_FRAME:
7922 return "STACK_FRAME";
7923 case CMD_SET_APPDOMAIN:
7925 case CMD_SET_ASSEMBLY:
7927 case CMD_SET_METHOD:
7931 case CMD_SET_MODULE:
7941 cmd_to_string (CommandSet set, int command)
7946 case CMD_VM_VERSION:
7948 case CMD_VM_ALL_THREADS:
7949 return "ALL_THREADS";
7950 case CMD_VM_SUSPEND:
7956 case CMD_VM_DISPOSE:
7958 case CMD_VM_INVOKE_METHOD:
7959 return "INVOKE_METHOD";
7960 case CMD_VM_SET_PROTOCOL_VERSION:
7961 return "SET_PROTOCOL_VERSION";
7962 case CMD_VM_ABORT_INVOKE:
7963 return "ABORT_INVOKE";
7976 wait_for_attach (void)
7978 #ifndef DISABLE_SOCKET_TRANSPORT
7979 if (listen_fd == -1) {
7980 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
7984 /* Block and wait for client connection */
7985 conn_fd = socket_transport_accept (listen_fd);
7986 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
7987 if (conn_fd == -1) {
7988 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
7992 g_assert_not_reached ();
7996 disconnected = !transport_handshake ();
7998 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8008 * This thread handles communication with the debugger client using a JDWP
8011 static guint32 WINAPI
8012 debugger_thread (void *arg)
8014 int res, len, id, flags, command_set = 0, command = 0;
8015 guint8 header [HEADER_LENGTH];
8016 guint8 *data, *p, *end;
8020 gboolean attach_failed = FALSE;
8022 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8024 debugger_thread_id = GetCurrentThreadId ();
8026 mono_jit_thread_attach (mono_get_root_domain ());
8028 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8030 mono_set_is_debugger_attached (TRUE);
8032 if (agent_config.defer) {
8033 if (!wait_for_attach ()) {
8034 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8035 attach_failed = TRUE; // Don't abort process when we can't listen
8037 /* Send start event to client */
8038 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8042 while (!attach_failed) {
8043 res = transport_recv (header, HEADER_LENGTH);
8045 /* This will break if the socket is closed during shutdown too */
8046 if (res != HEADER_LENGTH)
8050 end = header + HEADER_LENGTH;
8052 len = decode_int (p, &p, end);
8053 id = decode_int (p, &p, end);
8054 flags = decode_byte (p, &p, end);
8055 command_set = decode_byte (p, &p, end);
8056 command = decode_byte (p, &p, end);
8058 g_assert (flags == 0);
8061 const char *cmd_str;
8064 cmd_str = cmd_to_string (command_set, command);
8066 sprintf (cmd_num, "%d", command);
8070 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8073 data = g_malloc (len - HEADER_LENGTH);
8074 if (len - HEADER_LENGTH > 0)
8076 res = transport_recv (data, len - HEADER_LENGTH);
8077 if (res != len - HEADER_LENGTH)
8082 end = data + (len - HEADER_LENGTH);
8084 buffer_init (&buf, 128);
8089 /* Process the request */
8090 switch (command_set) {
8092 err = vm_commands (command, id, p, end, &buf);
8093 if (!err && command == CMD_VM_INVOKE_METHOD)
8094 /* Sent after the invoke is complete */
8097 case CMD_SET_EVENT_REQUEST:
8098 err = event_commands (command, p, end, &buf);
8100 case CMD_SET_APPDOMAIN:
8101 err = domain_commands (command, p, end, &buf);
8103 case CMD_SET_ASSEMBLY:
8104 err = assembly_commands (command, p, end, &buf);
8106 case CMD_SET_MODULE:
8107 err = module_commands (command, p, end, &buf);
8110 err = type_commands (command, p, end, &buf);
8112 case CMD_SET_METHOD:
8113 err = method_commands (command, p, end, &buf);
8115 case CMD_SET_THREAD:
8116 err = thread_commands (command, p, end, &buf);
8118 case CMD_SET_STACK_FRAME:
8119 err = frame_commands (command, p, end, &buf);
8121 case CMD_SET_ARRAY_REF:
8122 err = array_commands (command, p, end, &buf);
8124 case CMD_SET_STRING_REF:
8125 err = string_commands (command, p, end, &buf);
8127 case CMD_SET_OBJECT_REF:
8128 err = object_commands (command, p, end, &buf);
8131 err = ERR_NOT_IMPLEMENTED;
8135 send_reply_packet (id, err, &buf);
8140 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8144 mono_set_is_debugger_attached (FALSE);
8146 mono_mutex_lock (&debugger_thread_exited_mutex);
8147 debugger_thread_exited = TRUE;
8148 mono_cond_signal (&debugger_thread_exited_cond);
8149 mono_mutex_unlock (&debugger_thread_exited_mutex);
8151 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8153 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8154 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8155 start_debugger_thread ();
8161 #else /* DISABLE_DEBUGGER_AGENT */
8164 mono_debugger_agent_parse_options (char *options)
8166 g_error ("This runtime is configured with the debugger agent disabled.");
8170 mono_debugger_agent_init (void)
8175 mono_debugger_agent_breakpoint_hit (void *sigctx)
8180 mono_debugger_agent_single_step_event (void *sigctx)
8185 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8190 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8196 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8197 MonoContext *catch_ctx)
8202 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8207 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8212 mono_debugger_agent_user_break (void)
8218 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8223 mono_debugger_agent_debug_log_is_enabled (void)