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/environment.h>
73 #include <mono/metadata/threads-types.h>
74 #include <mono/metadata/socket-io.h>
75 #include <mono/metadata/assembly.h>
76 #include <mono/metadata/runtime.h>
77 #include <mono/metadata/threadpool.h>
78 #include <mono/metadata/verify-internals.h>
79 #include <mono/utils/mono-semaphore.h>
80 #include <mono/utils/mono-error-internals.h>
81 #include <mono/utils/mono-stack-unwinding.h>
82 #include <mono/utils/mono-time.h>
83 #include <mono/utils/mono-threads.h>
84 #include "debugger-agent.h"
88 On iOS we can't use System.Environment.Exit () as it will do the wrong
91 #if !defined (TARGET_IOS)
92 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
96 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
97 #define DISABLE_DEBUGGER_AGENT 1
100 #ifdef DISABLE_SOFT_DEBUG
101 #define DISABLE_DEBUGGER_AGENT 1
104 #ifndef DISABLE_DEBUGGER_AGENT
106 #include <mono/utils/mono-mutex.h>
108 /* Definitions to make backporting to 2.6 easier */
109 //#define MonoInternalThread MonoThread
110 //#define mono_thread_internal_current mono_thread_current
111 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
134 guint32 il_offset, native_offset;
138 * If method is gshared, this is the actual instance, otherwise this is equal to
141 MonoMethod *actual_method;
143 * This is the method which is visible to debugger clients. Same as method,
144 * except for native-to-managed wrappers.
146 MonoMethod *api_method;
148 MonoDebugMethodJitInfo *jit;
151 mgreg_t *reg_locations [MONO_MAX_IREGS];
153 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
154 * the frame can become invalid.
159 typedef struct _InvokeData InvokeData;
167 /* This is the context which needs to be restored after the invoke */
171 * If this is set, invoke this method with the arguments given by ARGS.
175 guint32 suspend_count;
178 InvokeData *last_invoke;
182 MonoThreadUnwindState context;
184 /* This is computed on demand when it is requested using the wire protocol */
185 /* It is freed up when the thread is resumed */
189 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
192 gboolean frames_up_to_date;
194 * Points to data about a pending invoke which needs to be executed after the thread
197 InvokeData *pending_invoke;
199 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
204 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
205 * within a finite amount of time.
209 * Set to TRUE if this thread is suspended in suspend_current ().
211 gboolean really_suspended;
212 /* Used to pass the context to the breakpoint/single step handler */
213 MonoContext handler_ctx;
214 /* Whenever thread_stop () was called for this thread */
217 /* Number of thread interruptions not yet processed */
218 gint32 interrupt_count;
220 /* Whenever to disable breakpoints (used during invokes) */
221 gboolean disable_breakpoints;
224 * Number of times this thread has been resumed using resume_thread ().
226 guint32 resume_count;
228 MonoInternalThread *thread;
231 * Information about the frame which transitioned to native code for running
234 StackFrameInfo async_last_frame;
237 * The context where the stack walk can be started for running threads.
239 MonoThreadUnwindState async_state;
242 * The context used for filter clauses
244 MonoThreadUnwindState filter_state;
247 * The callee address of the last mono_runtime_invoke call
249 gpointer invoke_addr;
251 gboolean abort_requested;
254 * The current mono_runtime_invoke invocation.
259 * The context where single stepping should resume while the thread is suspended because
260 * of an EXCEPTION event.
262 MonoThreadUnwindState catch_state;
265 * The context which needs to be restored after handling a single step/breakpoint
266 * event. This is the same as the ctx at step/breakpoint site, but includes changes
267 * to caller saved registers done by set_var ().
269 MonoContext restore_ctx;
274 void (*connect) (const char *address);
275 void (*close1) (void);
276 void (*close2) (void);
277 gboolean (*send) (void *buf, int len);
278 int (*recv) (void *buf, int len);
282 * Wire Protocol definitions
285 #define HEADER_LENGTH 11
287 #define MAJOR_VERSION 2
288 #define MINOR_VERSION 29
292 CMD_SET_OBJECT_REF = 9,
293 CMD_SET_STRING_REF = 10,
295 CMD_SET_ARRAY_REF = 13,
296 CMD_SET_EVENT_REQUEST = 15,
297 CMD_SET_STACK_FRAME = 16,
298 CMD_SET_APPDOMAIN = 20,
299 CMD_SET_ASSEMBLY = 21,
308 EVENT_KIND_VM_START = 0,
309 EVENT_KIND_VM_DEATH = 1,
310 EVENT_KIND_THREAD_START = 2,
311 EVENT_KIND_THREAD_DEATH = 3,
312 EVENT_KIND_APPDOMAIN_CREATE = 4,
313 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
314 EVENT_KIND_METHOD_ENTRY = 6,
315 EVENT_KIND_METHOD_EXIT = 7,
316 EVENT_KIND_ASSEMBLY_LOAD = 8,
317 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
318 EVENT_KIND_BREAKPOINT = 10,
319 EVENT_KIND_STEP = 11,
320 EVENT_KIND_TYPE_LOAD = 12,
321 EVENT_KIND_EXCEPTION = 13,
322 EVENT_KIND_KEEPALIVE = 14,
323 EVENT_KIND_USER_BREAK = 15,
324 EVENT_KIND_USER_LOG = 16
328 SUSPEND_POLICY_NONE = 0,
329 SUSPEND_POLICY_EVENT_THREAD = 1,
330 SUSPEND_POLICY_ALL = 2
335 ERR_INVALID_OBJECT = 20,
336 ERR_INVALID_FIELDID = 25,
337 ERR_INVALID_FRAMEID = 30,
338 ERR_NOT_IMPLEMENTED = 100,
339 ERR_NOT_SUSPENDED = 101,
340 ERR_INVALID_ARGUMENT = 102,
342 ERR_NO_INVOCATION = 104,
343 ERR_ABSENT_INFORMATION = 105,
344 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
345 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
350 MOD_KIND_THREAD_ONLY = 3,
351 MOD_KIND_LOCATION_ONLY = 7,
352 MOD_KIND_EXCEPTION_ONLY = 8,
354 MOD_KIND_ASSEMBLY_ONLY = 11,
355 MOD_KIND_SOURCE_FILE_ONLY = 12,
356 MOD_KIND_TYPE_NAME_ONLY = 13
371 STEP_FILTER_NONE = 0,
372 STEP_FILTER_STATIC_CTOR = 1,
373 STEP_FILTER_DEBUGGER_HIDDEN = 2,
374 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4
378 TOKEN_TYPE_STRING = 0,
380 TOKEN_TYPE_FIELD = 2,
381 TOKEN_TYPE_METHOD = 3,
382 TOKEN_TYPE_UNKNOWN = 4
386 VALUE_TYPE_ID_NULL = 0xf0,
387 VALUE_TYPE_ID_TYPE = 0xf1
391 FRAME_FLAG_DEBUGGER_INVOKE = 1,
392 FRAME_FLAG_NATIVE_TRANSITION = 2
396 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
397 INVOKE_FLAG_SINGLE_THREADED = 2
401 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
402 } BindingFlagsExtensions;
406 CMD_VM_ALL_THREADS = 2,
411 CMD_VM_INVOKE_METHOD = 7,
412 CMD_VM_SET_PROTOCOL_VERSION = 8,
413 CMD_VM_ABORT_INVOKE = 9,
414 CMD_VM_SET_KEEPALIVE = 10,
415 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
416 CMD_VM_GET_TYPES = 12,
417 CMD_VM_INVOKE_METHODS = 13
421 CMD_THREAD_GET_FRAME_INFO = 1,
422 CMD_THREAD_GET_NAME = 2,
423 CMD_THREAD_GET_STATE = 3,
424 CMD_THREAD_GET_INFO = 4,
425 CMD_THREAD_GET_ID = 5,
426 CMD_THREAD_GET_TID = 6,
427 CMD_THREAD_SET_IP = 7
431 CMD_EVENT_REQUEST_SET = 1,
432 CMD_EVENT_REQUEST_CLEAR = 2,
433 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
441 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
442 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
443 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
444 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
445 CMD_APPDOMAIN_CREATE_STRING = 5,
446 CMD_APPDOMAIN_GET_CORLIB = 6,
447 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
451 CMD_ASSEMBLY_GET_LOCATION = 1,
452 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
453 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
454 CMD_ASSEMBLY_GET_OBJECT = 4,
455 CMD_ASSEMBLY_GET_TYPE = 5,
456 CMD_ASSEMBLY_GET_NAME = 6
460 CMD_MODULE_GET_INFO = 1,
464 CMD_FIELD_GET_INFO = 1,
468 CMD_METHOD_GET_NAME = 1,
469 CMD_METHOD_GET_DECLARING_TYPE = 2,
470 CMD_METHOD_GET_DEBUG_INFO = 3,
471 CMD_METHOD_GET_PARAM_INFO = 4,
472 CMD_METHOD_GET_LOCALS_INFO = 5,
473 CMD_METHOD_GET_INFO = 6,
474 CMD_METHOD_GET_BODY = 7,
475 CMD_METHOD_RESOLVE_TOKEN = 8,
476 CMD_METHOD_GET_CATTRS = 9,
477 CMD_METHOD_MAKE_GENERIC_METHOD = 10
481 CMD_TYPE_GET_INFO = 1,
482 CMD_TYPE_GET_METHODS = 2,
483 CMD_TYPE_GET_FIELDS = 3,
484 CMD_TYPE_GET_VALUES = 4,
485 CMD_TYPE_GET_OBJECT = 5,
486 CMD_TYPE_GET_SOURCE_FILES = 6,
487 CMD_TYPE_SET_VALUES = 7,
488 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
489 CMD_TYPE_GET_PROPERTIES = 9,
490 CMD_TYPE_GET_CATTRS = 10,
491 CMD_TYPE_GET_FIELD_CATTRS = 11,
492 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
493 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
494 CMD_TYPE_GET_VALUES_2 = 14,
495 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
496 CMD_TYPE_GET_INTERFACES = 16,
497 CMD_TYPE_GET_INTERFACE_MAP = 17,
498 CMD_TYPE_IS_INITIALIZED = 18
502 CMD_STACK_FRAME_GET_VALUES = 1,
503 CMD_STACK_FRAME_GET_THIS = 2,
504 CMD_STACK_FRAME_SET_VALUES = 3
508 CMD_ARRAY_REF_GET_LENGTH = 1,
509 CMD_ARRAY_REF_GET_VALUES = 2,
510 CMD_ARRAY_REF_SET_VALUES = 3,
514 CMD_STRING_REF_GET_VALUE = 1,
515 CMD_STRING_REF_GET_LENGTH = 2,
516 CMD_STRING_REF_GET_CHARS = 3
520 CMD_OBJECT_REF_GET_TYPE = 1,
521 CMD_OBJECT_REF_GET_VALUES = 2,
522 CMD_OBJECT_REF_IS_COLLECTED = 3,
523 CMD_OBJECT_REF_GET_ADDRESS = 4,
524 CMD_OBJECT_REF_GET_DOMAIN = 5,
525 CMD_OBJECT_REF_SET_VALUES = 6,
526 CMD_OBJECT_REF_GET_INFO = 7,
532 int count; /* For kind == MOD_KIND_COUNT */
533 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
534 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
535 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
536 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
537 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
538 StepFilter filter; /* For kind == MOD_KIND_STEP */
540 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
549 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
553 * Describes a single step request.
557 MonoInternalThread *thread;
563 MonoMethod *last_method;
565 /* Whenever single stepping is performed using start/stop_single_stepping () */
567 /* The list of breakpoints used to implement step-over */
569 /* The number of frames at the start of a step-over */
574 * Contains additional information for an event
577 /* For EVENT_KIND_EXCEPTION */
579 MonoContext catch_ctx;
581 /* For EVENT_KIND_USER_LOG */
583 char *category, *message;
584 /* For EVENT_KIND_TYPE_LOAD */
588 /* Dummy structure used for the profiler callbacks */
593 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
596 #define get_last_sock_error() WSAGetLastError()
597 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
598 #define MONO_EINTR WSAEINTR
600 #define get_last_sock_error() errno
601 #define MONO_EWOULDBLOCK EWOULDBLOCK
602 #define MONO_EINTR EINTR
605 #define CHECK_PROTOCOL_VERSION(major,minor) \
606 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
612 static AgentConfig agent_config;
615 * Whenever the agent is fully initialized.
616 * When using the onuncaught or onthrow options, only some parts of the agent are
617 * initialized on startup, and the full initialization which includes connection
618 * establishment and the startup of the agent thread is only done in response to
621 static gint32 inited;
623 #ifndef DISABLE_SOCKET_TRANSPORT
625 static int listen_fd;
628 static int packet_id = 0;
630 static int objref_id = 0;
632 static int event_request_id = 0;
634 static int frame_id = 0;
636 static GPtrArray *event_requests;
638 static MonoNativeTlsKey debugger_tls_id;
640 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
642 /* Maps MonoInternalThread -> DebuggerTlsData */
643 static MonoGHashTable *thread_to_tls;
645 /* Maps tid -> MonoInternalThread */
646 static MonoGHashTable *tid_to_thread;
648 /* Maps tid -> MonoThread (not MonoInternalThread) */
649 static MonoGHashTable *tid_to_thread_obj;
651 static gsize debugger_thread_id;
653 static HANDLE debugger_thread_handle;
655 static int log_level;
657 static gboolean embedding;
659 static FILE *log_file;
661 /* Assemblies whose assembly load event has no been sent yet */
662 static GPtrArray *pending_assembly_loads;
664 /* Whenever the debugger thread has exited */
665 static gboolean debugger_thread_exited;
667 /* Cond variable used to wait for debugger_thread_exited becoming true */
668 static mono_cond_t debugger_thread_exited_cond;
670 /* Mutex for the cond var above */
671 static mono_mutex_t debugger_thread_exited_mutex;
673 static DebuggerProfiler debugger_profiler;
675 /* The single step request instance */
676 static SingleStepReq *ss_req = NULL;
677 static gpointer ss_invoke_addr = NULL;
679 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
680 /* Number of single stepping operations in progress */
684 /* The protocol version of the client */
685 static int major_version, minor_version;
687 /* Whenever the variables above are set by the client */
688 static gboolean protocol_version_set;
690 /* A hash table containing all active domains */
691 static GHashTable *domains;
693 /* The number of times the runtime is suspended */
694 static gint32 suspend_count;
696 static void transport_init (void);
697 static void transport_connect (const char *address);
698 static gboolean transport_handshake (void);
699 static void register_transport (DebuggerTransport *trans);
701 static guint32 WINAPI debugger_thread (void *arg);
703 static void runtime_initialized (MonoProfiler *prof);
705 static void runtime_shutdown (MonoProfiler *prof);
707 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
709 static void thread_end (MonoProfiler *prof, uintptr_t tid);
711 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
713 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
715 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
717 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
719 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
721 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
723 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
725 static void emit_assembly_load (gpointer assembly, gpointer user_data);
727 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
729 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
731 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
733 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
735 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
737 static void start_single_stepping (void);
739 static void stop_single_stepping (void);
741 static void suspend_current (void);
743 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
745 static void clear_types_for_assembly (MonoAssembly *assembly);
747 static void clear_breakpoints_for_domain (MonoDomain *domain);
749 static void process_profiler_event (EventKind event, gpointer arg);
751 /* Submodule init/cleanup */
752 static void breakpoints_init (void);
753 static void breakpoints_cleanup (void);
755 static void objrefs_init (void);
756 static void objrefs_cleanup (void);
758 static void ids_init (void);
759 static void ids_cleanup (void);
761 static void suspend_init (void);
763 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
764 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
765 static void ss_destroy (SingleStepReq *req);
767 static void start_debugger_thread (void);
768 static void stop_debugger_thread (void);
770 static void finish_agent_init (gboolean on_startup);
772 static void process_profiler_event (EventKind event, gpointer arg);
774 static void invalidate_frames (DebuggerTlsData *tls);
776 #ifndef DISABLE_SOCKET_TRANSPORT
778 register_socket_transport (void);
782 parse_address (char *address, char **host, int *port)
784 char *pos = strchr (address, ':');
786 if (pos == NULL || pos == address)
789 *host = g_malloc (pos - address + 1);
790 strncpy (*host, address, pos - address);
791 (*host) [pos - address] = '\0';
793 *port = atoi (pos + 1);
801 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
802 fprintf (stderr, "Available options:\n");
803 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
804 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
805 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
806 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
807 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
808 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
809 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
810 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
811 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
812 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
816 parse_flag (const char *option, char *flag)
818 if (!strcmp (flag, "y"))
820 else if (!strcmp (flag, "n"))
823 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
830 mono_debugger_agent_parse_options (char *options)
837 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
838 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
842 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
844 options = g_strdup_printf ("%s,%s", options, extra);
846 agent_config.enabled = TRUE;
847 agent_config.suspend = TRUE;
848 agent_config.server = FALSE;
849 agent_config.defer = FALSE;
850 agent_config.address = NULL;
852 args = g_strsplit (options, ",", -1);
853 for (ptr = args; ptr && *ptr; ptr ++) {
856 if (strncmp (arg, "transport=", 10) == 0) {
857 agent_config.transport = g_strdup (arg + 10);
858 } else if (strncmp (arg, "address=", 8) == 0) {
859 agent_config.address = g_strdup (arg + 8);
860 } else if (strncmp (arg, "loglevel=", 9) == 0) {
861 agent_config.log_level = atoi (arg + 9);
862 } else if (strncmp (arg, "logfile=", 8) == 0) {
863 agent_config.log_file = g_strdup (arg + 8);
864 } else if (strncmp (arg, "suspend=", 8) == 0) {
865 agent_config.suspend = parse_flag ("suspend", arg + 8);
866 } else if (strncmp (arg, "server=", 7) == 0) {
867 agent_config.server = parse_flag ("server", arg + 7);
868 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
869 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
870 } else if (strncmp (arg, "onthrow=", 8) == 0) {
871 /* We support multiple onthrow= options */
872 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
873 } else if (strncmp (arg, "onthrow", 7) == 0) {
874 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
875 } else if (strncmp (arg, "help", 4) == 0) {
878 } else if (strncmp (arg, "timeout=", 8) == 0) {
879 agent_config.timeout = atoi (arg + 8);
880 } else if (strncmp (arg, "launch=", 7) == 0) {
881 agent_config.launch = g_strdup (arg + 7);
882 } else if (strncmp (arg, "embedding=", 10) == 0) {
883 agent_config.embedding = atoi (arg + 10) == 1;
884 } else if (strncmp (arg, "keepalive=", 10) == 0) {
885 agent_config.keepalive = atoi (arg + 10);
886 } else if (strncmp (arg, "setpgid=", 8) == 0) {
887 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
894 if (agent_config.server && !agent_config.suspend) {
895 /* Waiting for deferred attachment */
896 agent_config.defer = TRUE;
897 if (agent_config.address == NULL) {
898 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
902 //agent_config.log_level = 0;
904 if (agent_config.transport == NULL) {
905 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
909 if (agent_config.address == NULL && !agent_config.server) {
910 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
915 if (!strcmp (agent_config.transport, "dt_socket")) {
916 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
917 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
924 mono_debugger_agent_init (void)
926 if (!agent_config.enabled)
931 /* Need to know whenever a thread has acquired the loader mutex */
932 mono_loader_lock_track_ownership (TRUE);
934 event_requests = g_ptr_array_new ();
936 mono_mutex_init (&debugger_thread_exited_mutex);
937 mono_cond_init (&debugger_thread_exited_cond, NULL);
939 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
940 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
941 mono_profiler_install_runtime_initialized (runtime_initialized);
942 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
943 mono_profiler_install_thread (thread_startup, thread_end);
944 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
945 mono_profiler_install_jit_end (jit_end);
946 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
948 mono_native_tls_alloc (&debugger_tls_id, NULL);
950 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
951 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
953 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
954 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
956 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
957 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
959 pending_assembly_loads = g_ptr_array_new ();
960 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
962 log_level = agent_config.log_level;
964 embedding = agent_config.embedding;
967 if (agent_config.log_file) {
968 log_file = fopen (agent_config.log_file, "w+");
970 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
982 mini_get_debug_options ()->gen_seq_points = TRUE;
984 * This is needed because currently we don't handle liveness info.
986 mini_get_debug_options ()->mdb_optimizations = TRUE;
988 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
989 /* This is needed because we can't set local variables in registers yet */
990 mono_disable_optimizations (MONO_OPT_LINEARS);
994 * The stack walk done from thread_interrupt () needs to be signal safe, but it
995 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
996 * safe (#3411). So load AOT info eagerly when the debugger is running as a
999 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1002 if (agent_config.setpgid)
1006 if (!agent_config.onuncaught && !agent_config.onthrow)
1007 finish_agent_init (TRUE);
1011 * finish_agent_init:
1013 * Finish the initialization of the agent. This involves connecting the transport
1014 * and starting the agent thread. This is either done at startup, or
1015 * in response to some event like an unhandled exception.
1018 finish_agent_init (gboolean on_startup)
1022 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1025 if (agent_config.launch) {
1028 // FIXME: Generated address
1029 // FIXME: Races with transport_connect ()
1031 argv [0] = agent_config.launch;
1032 argv [1] = agent_config.transport;
1033 argv [2] = agent_config.address;
1036 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1038 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1043 transport_connect (agent_config.address);
1046 /* Do some which is usually done after sending the VMStart () event */
1047 vm_start_event_sent = TRUE;
1048 start_debugger_thread ();
1053 mono_debugger_agent_cleanup (void)
1058 stop_debugger_thread ();
1060 breakpoints_cleanup ();
1064 mono_mutex_destroy (&debugger_thread_exited_mutex);
1065 mono_cond_destroy (&debugger_thread_exited_cond);
1072 #ifndef DISABLE_SOCKET_TRANSPORT
1077 * recv() + handle incomplete reads and EINTR
1080 socket_transport_recv (void *buf, int len)
1086 static gint32 last_keepalive;
1091 res = recv (fd, (char *) buf + total, len - total, flags);
1094 if (agent_config.keepalive) {
1095 gboolean need_keepalive = FALSE;
1096 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1097 need_keepalive = TRUE;
1098 } else if (res == -1) {
1099 /* This could happen if recv () is interrupted repeatedly */
1100 msecs = mono_msec_ticks ();
1101 if (msecs - last_keepalive >= agent_config.keepalive) {
1102 need_keepalive = TRUE;
1103 last_keepalive = msecs;
1106 if (need_keepalive) {
1107 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1111 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1116 #define HAVE_GETADDRINFO 1
1120 set_keepalive (void)
1125 if (!agent_config.keepalive || !conn_fd)
1128 tv.tv_sec = agent_config.keepalive / 1000;
1129 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1131 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1132 g_assert (result >= 0);
1136 socket_transport_accept (int socket_fd)
1138 conn_fd = accept (socket_fd, NULL, NULL);
1139 if (conn_fd == -1) {
1140 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1142 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1149 socket_transport_send (void *data, int len)
1154 res = send (conn_fd, data, len, 0);
1155 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1163 * socket_transport_connect:
1165 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1168 socket_transport_connect (const char *address)
1170 #ifdef HAVE_GETADDRINFO
1171 struct addrinfo hints;
1172 struct addrinfo *result, *rp;
1174 struct hostent *result;
1176 int sfd = -1, s, res;
1177 char port_string [128];
1181 if (agent_config.address) {
1182 res = parse_address (agent_config.address, &host, &port);
1183 g_assert (res == 0);
1193 sprintf (port_string, "%d", port);
1195 mono_network_init ();
1197 /* Obtain address(es) matching host/port */
1198 #ifdef HAVE_GETADDRINFO
1199 memset (&hints, 0, sizeof (struct addrinfo));
1200 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1201 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1203 hints.ai_protocol = 0; /* Any protocol */
1205 s = getaddrinfo (host, port_string, &hints, &result);
1207 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1211 /* The PS3 doesn't even have _r or hstrerror () */
1212 result = gethostbyname (host);
1214 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1219 if (agent_config.server) {
1220 #ifdef HAVE_GETADDRINFO
1221 /* Wait for a connection */
1223 struct sockaddr_in addr;
1226 /* No address, generate one */
1227 sfd = socket (AF_INET, SOCK_STREAM, 0);
1230 /* This will bind the socket to a random port */
1231 res = listen (sfd, 16);
1233 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1238 addrlen = sizeof (addr);
1239 memset (&addr, 0, sizeof (addr));
1240 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1241 g_assert (res == 0);
1243 host = (char*)"127.0.0.1";
1244 port = ntohs (addr.sin_port);
1246 /* Emit the address to stdout */
1247 /* FIXME: Should print another interface, not localhost */
1248 printf ("%s:%d\n", host, port);
1250 /* Listen on the provided address */
1251 for (rp = result; rp != NULL; rp = rp->ai_next) {
1254 sfd = socket (rp->ai_family, rp->ai_socktype,
1259 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1262 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1266 res = listen (sfd, 16);
1275 * this function is not present on win2000 which we still support, and the
1276 * workaround described here:
1277 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1278 * only works with MSVC.
1280 #ifdef HAVE_GETADDRINFO
1281 freeaddrinfo (result);
1286 if (agent_config.defer)
1289 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1291 if (agent_config.timeout) {
1296 tv.tv_usec = agent_config.timeout * 1000;
1298 FD_SET (sfd, &readfds);
1299 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1301 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1306 conn_fd = socket_transport_accept (sfd);
1310 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1313 #endif /* HAVE_GETADDRINFO */
1315 /* Connect to the specified address */
1316 #ifdef HAVE_GETADDRINFO
1317 /* FIXME: Respect the timeout */
1318 for (rp = result; rp != NULL; rp = rp->ai_next) {
1319 sfd = socket (rp->ai_family, rp->ai_socktype,
1324 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1325 break; /* Success */
1331 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1335 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1337 g_assert_not_reached ();
1338 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1340 g_assert_not_reached ();
1346 /* See the comment above */
1347 #ifdef HAVE_GETADDRINFO
1348 freeaddrinfo (result);
1353 if (!transport_handshake ())
1358 socket_transport_close1 (void)
1360 /* This will interrupt the agent thread */
1361 /* Close the read part only so it can still send back replies */
1362 /* Also shut down the connection listener so that we can exit normally */
1364 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1365 shutdown (conn_fd, SD_BOTH);
1366 shutdown (listen_fd, SD_BOTH);
1367 closesocket (listen_fd);
1369 shutdown (conn_fd, SHUT_RD);
1370 shutdown (listen_fd, SHUT_RDWR);
1376 socket_transport_close2 (void)
1379 shutdown (conn_fd, SD_BOTH);
1381 shutdown (conn_fd, SHUT_RDWR);
1386 register_socket_transport (void)
1388 DebuggerTransport trans;
1390 trans.name = "dt_socket";
1391 trans.connect = socket_transport_connect;
1392 trans.close1 = socket_transport_close1;
1393 trans.close2 = socket_transport_close2;
1394 trans.send = socket_transport_send;
1395 trans.recv = socket_transport_recv;
1397 register_transport (&trans);
1400 #endif /* DISABLE_SOCKET_TRANSPORT */
1406 #define MAX_TRANSPORTS 16
1408 static DebuggerTransport *transport;
1410 static DebuggerTransport transports [MAX_TRANSPORTS];
1411 static int ntransports;
1414 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1417 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1419 register_transport (trans);
1423 register_transport (DebuggerTransport *trans)
1425 g_assert (ntransports < MAX_TRANSPORTS);
1427 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1432 transport_init (void)
1436 #ifndef DISABLE_SOCKET_TRANSPORT
1437 register_socket_transport ();
1440 for (i = 0; i < ntransports; ++i) {
1441 if (!strcmp (agent_config.transport, transports [i].name))
1444 if (i == ntransports) {
1445 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1446 for (i = 0; i < ntransports; ++i)
1447 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1448 fprintf (stderr, "\n");
1451 transport = &transports [i];
1455 transport_connect (const char *address)
1457 transport->connect (address);
1461 transport_close1 (void)
1463 transport->close1 ();
1467 transport_close2 (void)
1469 transport->close2 ();
1473 transport_send (void *buf, int len)
1475 return transport->send (buf, len);
1479 transport_recv (void *buf, int len)
1481 return transport->recv (buf, len);
1485 mono_debugger_agent_transport_handshake (void)
1487 return transport_handshake ();
1491 transport_handshake (void)
1493 char handshake_msg [128];
1497 disconnected = TRUE;
1499 /* Write handshake message */
1500 sprintf (handshake_msg, "DWP-Handshake");
1502 res = transport_send (handshake_msg, strlen (handshake_msg));
1503 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1504 g_assert (res != -1);
1507 res = transport_recv (buf, strlen (handshake_msg));
1508 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1509 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1514 * To support older clients, the client sends its protocol version after connecting
1515 * using a command. Until that is received, default to our protocol version.
1517 major_version = MAJOR_VERSION;
1518 minor_version = MINOR_VERSION;
1519 protocol_version_set = FALSE;
1521 #ifndef DISABLE_SOCKET_TRANSPORT
1522 // FIXME: Move this somewhere else
1524 * Set TCP_NODELAY on the socket so the client receives events/command
1525 * results immediately.
1529 int result = setsockopt (conn_fd,
1534 g_assert (result >= 0);
1540 disconnected = FALSE;
1545 stop_debugger_thread (void)
1550 transport_close1 ();
1553 * Wait for the thread to exit.
1555 * If we continue with the shutdown without waiting for it, then the client might
1556 * not receive an answer to its last command like a resume.
1557 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1560 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1561 if (GetCurrentThreadId () != debugger_thread_id) {
1563 mono_mutex_lock (&debugger_thread_exited_mutex);
1564 if (!debugger_thread_exited) {
1566 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1567 mono_mutex_unlock (&debugger_thread_exited_mutex);
1569 mono_mutex_lock (&debugger_thread_exited_mutex);
1572 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1575 mono_mutex_unlock (&debugger_thread_exited_mutex);
1576 } while (!debugger_thread_exited);
1579 transport_close2 ();
1583 start_debugger_thread (void)
1585 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1586 g_assert (debugger_thread_handle);
1590 * Functions to decode protocol data
1594 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1597 g_assert (*endbuf <= limit);
1602 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1605 g_assert (*endbuf <= limit);
1607 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1610 static inline gint64
1611 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1613 guint32 high = decode_int (buf, &buf, limit);
1614 guint32 low = decode_int (buf, &buf, limit);
1618 return ((((guint64)high) << 32) | ((guint64)low));
1622 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1624 return decode_int (buf, endbuf, limit);
1628 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1630 int len = decode_int (buf, &buf, limit);
1638 s = g_malloc (len + 1);
1641 memcpy (s, buf, len);
1650 * Functions to encode protocol data
1654 guint8 *buf, *p, *end;
1658 buffer_init (Buffer *buf, int size)
1660 buf->buf = g_malloc (size);
1662 buf->end = buf->buf + size;
1666 buffer_make_room (Buffer *buf, int size)
1668 if (buf->end - buf->p < size) {
1669 int new_size = buf->end - buf->buf + size + 32;
1670 guint8 *p = g_realloc (buf->buf, new_size);
1671 size = buf->p - buf->buf;
1674 buf->end = buf->buf + new_size;
1679 buffer_add_byte (Buffer *buf, guint8 val)
1681 buffer_make_room (buf, 1);
1687 buffer_add_short (Buffer *buf, guint32 val)
1689 buffer_make_room (buf, 2);
1690 buf->p [0] = (val >> 8) & 0xff;
1691 buf->p [1] = (val >> 0) & 0xff;
1696 buffer_add_int (Buffer *buf, guint32 val)
1698 buffer_make_room (buf, 4);
1699 buf->p [0] = (val >> 24) & 0xff;
1700 buf->p [1] = (val >> 16) & 0xff;
1701 buf->p [2] = (val >> 8) & 0xff;
1702 buf->p [3] = (val >> 0) & 0xff;
1707 buffer_add_long (Buffer *buf, guint64 l)
1709 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1710 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1714 buffer_add_id (Buffer *buf, int id)
1716 buffer_add_int (buf, (guint64)id);
1720 buffer_add_data (Buffer *buf, guint8 *data, int len)
1722 buffer_make_room (buf, len);
1723 memcpy (buf->p, data, len);
1728 buffer_add_string (Buffer *buf, const char *str)
1733 buffer_add_int (buf, 0);
1736 buffer_add_int (buf, len);
1737 buffer_add_data (buf, (guint8*)str, len);
1742 buffer_free (Buffer *buf)
1748 send_packet (int command_set, int command, Buffer *data)
1754 id = InterlockedIncrement (&packet_id);
1756 len = data->p - data->buf + 11;
1757 buffer_init (&buf, len);
1758 buffer_add_int (&buf, len);
1759 buffer_add_int (&buf, id);
1760 buffer_add_byte (&buf, 0); /* flags */
1761 buffer_add_byte (&buf, command_set);
1762 buffer_add_byte (&buf, command);
1763 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1765 res = transport_send (buf.buf, len);
1773 send_reply_packet (int id, int error, Buffer *data)
1779 len = data->p - data->buf + 11;
1780 buffer_init (&buf, len);
1781 buffer_add_int (&buf, len);
1782 buffer_add_int (&buf, id);
1783 buffer_add_byte (&buf, 0x80); /* flags */
1784 buffer_add_byte (&buf, (error >> 8) & 0xff);
1785 buffer_add_byte (&buf, error);
1786 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1788 res = transport_send (buf.buf, len);
1800 * Represents an object accessible by the debugger client.
1803 /* Unique id used in the wire protocol to refer to objects */
1806 * A weakref gc handle pointing to the object. The gc handle is used to
1807 * detect if the object was garbage collected.
1812 /* Maps objid -> ObjRef */
1813 static GHashTable *objrefs;
1816 free_objref (gpointer value)
1820 mono_gchandle_free (o->handle);
1828 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1832 objrefs_cleanup (void)
1834 g_hash_table_destroy (objrefs);
1838 static GHashTable *obj_to_objref;
1839 static MonoGHashTable *suspended_objs;
1842 * Return an ObjRef for OBJ.
1845 get_objref (MonoObject *obj)
1848 GSList *reflist = NULL, *l;
1854 mono_loader_lock ();
1856 if (!obj_to_objref) {
1857 obj_to_objref = g_hash_table_new (NULL, NULL);
1858 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1859 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1862 if (suspend_count) {
1864 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1866 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1869 /* FIXME: The tables can grow indefinitely */
1871 if (mono_gc_is_moving ()) {
1873 * Objects can move, so use a hash table mapping hash codes to lists of
1874 * ObjRef structures.
1876 hash = mono_object_hash (obj);
1878 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1879 for (l = reflist; l; l = l->next) {
1881 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1882 mono_loader_unlock ();
1887 /* Use a hash table with masked pointers to internalize object references */
1888 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1889 /* ref might refer to a different object with the same addr which was GCd */
1890 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1891 mono_loader_unlock ();
1896 ref = g_new0 (ObjRef, 1);
1897 ref->id = InterlockedIncrement (&objref_id);
1898 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1900 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1902 if (mono_gc_is_moving ()) {
1903 reflist = g_slist_append (reflist, ref);
1904 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1906 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1909 mono_loader_unlock ();
1915 true_pred (gpointer key, gpointer value, gpointer user_data)
1921 clear_suspended_objs (void)
1923 mono_loader_lock ();
1924 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
1925 mono_loader_unlock ();
1929 get_objid (MonoObject *obj)
1931 return get_objref (obj)->id;
1935 * Set OBJ to the object identified by OBJID.
1936 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1940 get_object_allow_null (int objid, MonoObject **obj)
1950 return ERR_INVALID_OBJECT;
1952 mono_loader_lock ();
1954 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1957 *obj = mono_gchandle_get_target (ref->handle);
1958 mono_loader_unlock ();
1960 return ERR_INVALID_OBJECT;
1963 mono_loader_unlock ();
1964 return ERR_INVALID_OBJECT;
1969 get_object (int objid, MonoObject **obj)
1971 int err = get_object_allow_null (objid, obj);
1976 return ERR_INVALID_OBJECT;
1981 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1983 return decode_id (buf, endbuf, limit);
1987 buffer_add_objid (Buffer *buf, MonoObject *o)
1989 buffer_add_id (buf, get_objid (o));
2008 * Represents a runtime structure accessible to the debugger client
2011 /* Unique id used in the wire protocol */
2013 /* Domain of the runtime structure, NULL if the domain was unloaded */
2020 MonoAssembly *assembly;
2021 MonoClassField *field;
2023 MonoProperty *property;
2028 /* Maps runtime structure -> Id */
2029 GHashTable *val_to_id [ID_NUM];
2030 /* Classes whose class load event has been sent */
2031 GHashTable *loaded_classes;
2032 /* Maps MonoClass->GPtrArray of file names */
2033 GHashTable *source_files;
2034 /* Maps source file basename -> GSList of classes */
2035 GHashTable *source_file_to_class;
2036 /* Same with ignore-case */
2037 GHashTable *source_file_to_class_ignorecase;
2041 static GPtrArray *ids [ID_NUM];
2048 for (i = 0; i < ID_NUM; ++i)
2049 ids [i] = g_ptr_array_new ();
2057 for (i = 0; i < ID_NUM; ++i) {
2059 for (j = 0; j < ids [i]->len; ++j)
2060 g_free (g_ptr_array_index (ids [i], j));
2061 g_ptr_array_free (ids [i], TRUE);
2068 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2070 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2072 GHashTableIter iter;
2073 GPtrArray *file_names;
2078 for (i = 0; i < ID_NUM; ++i)
2079 if (info->val_to_id [i])
2080 g_hash_table_destroy (info->val_to_id [i]);
2081 g_hash_table_destroy (info->loaded_classes);
2083 g_hash_table_iter_init (&iter, info->source_files);
2084 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2085 for (i = 0; i < file_names->len; ++i)
2086 g_free (g_ptr_array_index (file_names, i));
2087 g_ptr_array_free (file_names, TRUE);
2090 g_hash_table_iter_init (&iter, info->source_file_to_class);
2091 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2096 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2097 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2105 domain_jit_info (domain)->agent_info = NULL;
2107 /* Clear ids referencing structures in the domain */
2108 for (i = 0; i < ID_NUM; ++i) {
2110 for (j = 0; j < ids [i]->len; ++j) {
2111 Id *id = g_ptr_array_index (ids [i], j);
2112 if (id->domain == domain)
2118 mono_loader_lock ();
2119 g_hash_table_remove (domains, domain);
2120 mono_loader_unlock ();
2123 static AgentDomainInfo*
2124 get_agent_domain_info (MonoDomain *domain)
2126 AgentDomainInfo *info = NULL;
2128 mono_domain_lock (domain);
2130 info = domain_jit_info (domain)->agent_info;
2132 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2133 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2134 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2135 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2136 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2139 mono_domain_unlock (domain);
2145 get_id (MonoDomain *domain, IdType type, gpointer val)
2148 AgentDomainInfo *info;
2153 mono_loader_lock ();
2155 mono_domain_lock (domain);
2157 info = get_agent_domain_info (domain);
2159 if (info->val_to_id [type] == NULL)
2160 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2162 id = g_hash_table_lookup (info->val_to_id [type], val);
2164 mono_domain_unlock (domain);
2165 mono_loader_unlock ();
2169 id = g_new0 (Id, 1);
2171 id->id = ids [type]->len + 1;
2172 id->domain = domain;
2175 g_hash_table_insert (info->val_to_id [type], val, id);
2177 mono_domain_unlock (domain);
2179 g_ptr_array_add (ids [type], id);
2181 mono_loader_unlock ();
2186 static inline gpointer
2187 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2191 int id = decode_id (buf, endbuf, limit);
2200 // FIXME: error handling
2201 mono_loader_lock ();
2202 g_assert (id > 0 && id <= ids [type]->len);
2204 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2205 mono_loader_unlock ();
2207 if (res->domain == NULL) {
2208 DEBUG (0, fprintf (log_file, "ERR_UNLOADED, id=%d, type=%d.\n", id, type));
2209 *err = ERR_UNLOADED;
2214 *domain = res->domain;
2216 return res->data.val;
2220 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2222 buffer_add_id (buf, get_id (domain, type, val));
2225 static inline MonoClass*
2226 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2230 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2231 if (G_UNLIKELY (log_level >= 2) && klass) {
2234 s = mono_type_full_name (&klass->byval_arg);
2235 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2241 static inline MonoAssembly*
2242 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2244 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2247 static inline MonoImage*
2248 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2250 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2253 static inline MonoMethod*
2254 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2258 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2259 if (G_UNLIKELY (log_level >= 2) && m) {
2262 s = mono_method_full_name (m, TRUE);
2263 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2269 static inline MonoClassField*
2270 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2272 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2275 static inline MonoDomain*
2276 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2278 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2281 static inline MonoProperty*
2282 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2284 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2288 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2290 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2291 if (G_UNLIKELY (log_level >= 2) && klass) {
2294 s = mono_type_full_name (&klass->byval_arg);
2295 if (GetCurrentThreadId () == debugger_thread_id)
2296 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2298 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2304 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2306 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2307 if (G_UNLIKELY (log_level >= 2) && method) {
2310 s = mono_method_full_name (method, 1);
2311 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2317 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2319 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2323 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2325 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2329 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2331 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2335 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2337 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2341 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2343 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2346 static void invoke_method (void);
2353 * save_thread_context:
2355 * Set CTX as the current threads context which is used for computing stack traces.
2356 * This function is signal-safe.
2359 save_thread_context (MonoContext *ctx)
2361 DebuggerTlsData *tls;
2363 tls = mono_native_tls_get_value (debugger_tls_id);
2367 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2369 mono_thread_state_init_from_current (&tls->context);
2372 /* Number of threads suspended */
2374 * If this is equal to the size of thread_to_tls, the runtime is considered
2377 static gint32 threads_suspend_count;
2379 static mono_mutex_t suspend_mutex;
2381 /* Cond variable used to wait for suspend_count becoming 0 */
2382 static mono_cond_t suspend_cond;
2384 /* Semaphore used to wait for a thread becoming suspended */
2385 static MonoSemType suspend_sem;
2390 mono_mutex_init (&suspend_mutex);
2391 mono_cond_init (&suspend_cond, NULL);
2392 MONO_SEM_INIT (&suspend_sem, 0);
2397 StackFrameInfo last_frame;
2398 gboolean last_frame_set;
2401 } GetLastFrameUserData;
2404 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2406 GetLastFrameUserData *data = user_data;
2408 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2411 if (!data->last_frame_set) {
2412 /* Store the last frame */
2413 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2414 data->last_frame_set = TRUE;
2417 /* Store the context/lmf for the frame above the last frame */
2418 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2419 data->lmf = info->lmf;
2427 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2428 * INFO is set, process the thread described by INFO.
2429 * This should be signal safe.
2432 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2436 MonoNativeThreadId tid;
2439 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2440 * guarantee the signal handler will be called that many times. Instead of tracking
2441 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2442 * has been requested that hasn't been handled yet, otherwise we can have threads
2443 * refuse to die when VM_EXIT is called
2445 #if defined(__APPLE__)
2446 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2450 * We use interrupt_count to determine whenever this interrupt should be processed
2451 * by us or the normal interrupt processing code in the signal handler.
2452 * There is no race here with notify_thread (), since the signal is sent after
2453 * incrementing interrupt_count.
2455 if (tls->interrupt_count == 0)
2458 InterlockedDecrement (&tls->interrupt_count);
2462 ip = mono_arch_ip_from_context (sigctx);
2464 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2469 tid = mono_thread_info_get_tid (info);
2471 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2473 // FIXME: Races when the thread leaves managed code before hitting a single step
2477 /* Running managed code, will be suspended by the single step code */
2478 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2482 * Running native code, will be suspended when it returns to/enters
2483 * managed code. Treat it as already suspended.
2484 * This might interrupt the code in process_single_step_inner (), we use the
2485 * tls->suspending flag to avoid races when that happens.
2487 if (!tls->suspended && !tls->suspending) {
2489 GetLastFrameUserData data;
2491 // FIXME: printf is not signal safe, but this is only used during
2492 // debugger debugging
2494 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2495 //save_thread_context (&ctx);
2498 /* Already terminated */
2502 * We are in a difficult position: we want to be able to provide stack
2503 * traces for this thread, but we can't use the current ctx+lmf, since
2504 * the thread is still running, so it might return to managed code,
2505 * making these invalid.
2506 * So we start a stack walk and save the first frame, along with the
2507 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2508 * suspended when it returns to managed code, so the parent's ctx should
2511 data.last_frame_set = FALSE;
2513 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2515 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2516 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2517 * since we are not in a JITted method.
2519 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2521 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2523 if (data.last_frame_set) {
2524 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2525 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2527 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2530 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2531 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2532 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2534 tls->async_state.valid = FALSE;
2537 mono_memory_barrier ();
2539 tls->suspended = TRUE;
2540 MONO_SEM_POST (&suspend_sem);
2547 * mono_debugger_agent_thread_interrupt:
2549 * Called by the abort signal handler.
2550 * Should be signal safe.
2553 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2555 DebuggerTlsData *tls;
2560 tls = mono_native_tls_get_value (debugger_tls_id);
2562 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2566 return thread_interrupt (tls, NULL, sigctx, ji);
2570 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2573 mono_debugger_agent_thread_interrupt (NULL, NULL);
2575 #endif /* HOST_WIN32 */
2578 * reset_native_thread_suspend_state:
2580 * Reset the suspended flag and state on native threads
2583 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2585 DebuggerTlsData *tls = value;
2587 if (!tls->really_suspended && tls->suspended) {
2588 tls->suspended = FALSE;
2590 * The thread might still be running if it was executing native code, so the state won't be invalided by
2591 * suspend_current ().
2593 tls->context.valid = FALSE;
2594 tls->async_state.valid = FALSE;
2595 invalidate_frames (tls);
2602 * Notify a thread that it needs to suspend.
2605 notify_thread (gpointer key, gpointer value, gpointer user_data)
2607 MonoInternalThread *thread = key;
2608 DebuggerTlsData *tls = value;
2609 gsize tid = thread->tid;
2612 if (GetCurrentThreadId () == tid || tls->terminated)
2615 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2618 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2619 * guarantee the signal handler will be called that many times. Instead of tracking
2620 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2621 * has been requested that hasn't been handled yet, otherwise we can have threads
2622 * refuse to die when VM_EXIT is called
2624 #if defined(__APPLE__)
2625 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2629 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2630 * of things like breaking waits etc. which we don't want.
2632 InterlockedIncrement (&tls->interrupt_count);
2635 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2637 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2639 if (mono_thread_info_new_interrupt_enabled ()) {
2640 MonoThreadInfo *info;
2643 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2645 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2647 * Attached thread which died without detaching.
2649 tls->terminated = TRUE;
2651 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2653 thread_interrupt (tls, info, NULL, ji);
2655 mono_thread_info_resume (mono_thread_info_get_tid (info));
2658 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2660 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2662 * Attached thread which died without detaching.
2664 tls->terminated = TRUE;
2671 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2673 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2677 if (mono_loader_lock_is_owned_by_self ()) {
2679 * Shortcut for the check in suspend_current (). This speeds up processing
2680 * when executing long running code inside the loader lock, i.e. assembly load
2686 if (debugger_thread_id == GetCurrentThreadId ())
2689 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2690 if (suspend_count - tls->resume_count > 0)
2691 tls->suspending = TRUE;
2693 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2695 if (suspend_count - tls->resume_count == 0) {
2697 * We are executing a single threaded invoke but the single step for
2698 * suspending is still active.
2699 * FIXME: This slows down single threaded invokes.
2701 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2705 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2707 /* Can't suspend in these methods */
2708 method = jinfo_get_method (ji);
2709 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2712 save_thread_context (ctx);
2720 * Increase the suspend count of the VM. While the suspend count is greater
2721 * than 0, runtime threads are suspended at certain points during execution.
2726 mono_loader_lock ();
2728 mono_mutex_lock (&suspend_mutex);
2732 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2734 if (suspend_count == 1) {
2735 // FIXME: Is it safe to call this inside the lock ?
2736 start_single_stepping ();
2737 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2740 mono_mutex_unlock (&suspend_mutex);
2742 if (suspend_count == 1)
2744 * Suspend creation of new threadpool threads, since they cannot run
2746 mono_thread_pool_suspend ();
2748 mono_loader_unlock ();
2754 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2762 g_assert (debugger_thread_id == GetCurrentThreadId ());
2764 mono_loader_lock ();
2766 mono_mutex_lock (&suspend_mutex);
2768 g_assert (suspend_count > 0);
2771 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2773 if (suspend_count == 0) {
2774 // FIXME: Is it safe to call this inside the lock ?
2775 stop_single_stepping ();
2776 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2779 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2780 err = mono_cond_broadcast (&suspend_cond);
2781 g_assert (err == 0);
2783 mono_mutex_unlock (&suspend_mutex);
2784 //g_assert (err == 0);
2786 if (suspend_count == 0)
2787 mono_thread_pool_resume ();
2789 mono_loader_unlock ();
2795 * Resume just one thread.
2798 resume_thread (MonoInternalThread *thread)
2801 DebuggerTlsData *tls;
2803 g_assert (debugger_thread_id == GetCurrentThreadId ());
2805 mono_loader_lock ();
2807 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2810 mono_mutex_lock (&suspend_mutex);
2812 g_assert (suspend_count > 0);
2814 DEBUG(1, fprintf (log_file, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid));
2816 tls->resume_count += suspend_count;
2819 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2820 * but only the one whose resume_count field is > 0 will be resumed.
2822 err = mono_cond_broadcast (&suspend_cond);
2823 g_assert (err == 0);
2825 mono_mutex_unlock (&suspend_mutex);
2826 //g_assert (err == 0);
2828 mono_loader_unlock ();
2832 invalidate_frames (DebuggerTlsData *tls)
2837 tls = mono_native_tls_get_value (debugger_tls_id);
2840 for (i = 0; i < tls->frame_count; ++i) {
2841 if (tls->frames [i]->jit)
2842 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2843 g_free (tls->frames [i]);
2845 g_free (tls->frames);
2846 tls->frame_count = 0;
2853 * Suspend the current thread until the runtime is resumed. If the thread has a
2854 * pending invoke, then the invoke is executed before this function returns.
2857 suspend_current (void)
2860 DebuggerTlsData *tls;
2862 g_assert (debugger_thread_id != GetCurrentThreadId ());
2864 if (mono_loader_lock_is_owned_by_self ()) {
2866 * If we own the loader mutex, can't suspend until we release it, since the
2867 * whole runtime can deadlock otherwise.
2872 tls = mono_native_tls_get_value (debugger_tls_id);
2875 mono_mutex_lock (&suspend_mutex);
2877 tls->suspending = FALSE;
2878 tls->really_suspended = TRUE;
2880 if (!tls->suspended) {
2881 tls->suspended = TRUE;
2882 MONO_SEM_POST (&suspend_sem);
2885 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2887 while (suspend_count - tls->resume_count > 0) {
2889 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2891 mono_mutex_unlock (&suspend_mutex);
2893 mono_mutex_lock (&suspend_mutex);
2899 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2900 g_assert (err == 0);
2904 tls->suspended = FALSE;
2905 tls->really_suspended = FALSE;
2907 threads_suspend_count --;
2909 mono_mutex_unlock (&suspend_mutex);
2911 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2913 if (tls->pending_invoke) {
2914 /* Save the original context */
2915 tls->pending_invoke->has_ctx = TRUE;
2916 tls->pending_invoke->ctx = tls->context.ctx;
2921 /* The frame info becomes invalid after a resume */
2922 tls->context.valid = FALSE;
2923 tls->async_state.valid = FALSE;
2924 invalidate_frames (tls);
2928 count_thread (gpointer key, gpointer value, gpointer user_data)
2930 DebuggerTlsData *tls = value;
2932 if (!tls->suspended && !tls->terminated)
2933 *(int*)user_data = *(int*)user_data + 1;
2937 count_threads_to_wait_for (void)
2941 mono_loader_lock ();
2942 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2943 mono_loader_unlock ();
2951 * Wait until the runtime is completely suspended.
2954 wait_for_suspend (void)
2956 int nthreads, nwait, err;
2957 gboolean waited = FALSE;
2959 // FIXME: Threads starting/stopping ?
2960 mono_loader_lock ();
2961 nthreads = mono_g_hash_table_size (thread_to_tls);
2962 mono_loader_unlock ();
2965 nwait = count_threads_to_wait_for ();
2967 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2968 err = MONO_SEM_WAIT (&suspend_sem);
2969 g_assert (err == 0);
2977 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2983 * Return whenever the runtime is suspended.
2988 return count_threads_to_wait_for () == 0;
2991 static MonoSeqPointInfo*
2992 get_seq_points (MonoDomain *domain, MonoMethod *method)
2994 MonoSeqPointInfo *seq_points;
2996 mono_domain_lock (domain);
2997 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2998 if (!seq_points && method->is_inflated) {
2999 /* generic sharing + aot */
3000 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
3002 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
3004 mono_domain_unlock (domain);
3010 no_seq_points_found (MonoMethod *method)
3013 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3015 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3019 * find_next_seq_point_for_native_offset:
3021 * Find the first sequence point after NATIVE_OFFSET.
3024 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3026 MonoSeqPointInfo *seq_points;
3029 seq_points = get_seq_points (domain, method);
3035 g_assert (seq_points);
3039 for (i = 0; i < seq_points->len; ++i) {
3040 if (seq_points->seq_points [i].native_offset >= native_offset)
3041 return &seq_points->seq_points [i];
3048 * find_prev_seq_point_for_native_offset:
3050 * Find the first sequence point before NATIVE_OFFSET.
3053 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3055 MonoSeqPointInfo *seq_points;
3058 seq_points = get_seq_points (domain, method);
3064 for (i = seq_points->len - 1; i >= 0; --i) {
3065 if (seq_points->seq_points [i].native_offset <= native_offset)
3066 return &seq_points->seq_points [i];
3075 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3076 * should be the location of a sequence point.
3078 static G_GNUC_UNUSED SeqPoint*
3079 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3081 MonoSeqPointInfo *seq_points;
3086 seq_points = get_seq_points (domain, method);
3091 for (i = 0; i < seq_points->len; ++i) {
3092 if (seq_points->seq_points [i].il_offset == il_offset)
3093 return &seq_points->seq_points [i];
3100 DebuggerTlsData *tls;
3102 } ComputeFramesUserData;
3105 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3107 ComputeFramesUserData *ud = user_data;
3109 MonoMethod *method, *actual_method, *api_method;
3113 if (info->type != FRAME_TYPE_MANAGED) {
3114 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3115 /* Mark the last frame as an invoke frame */
3117 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3123 method = jinfo_get_method (info->ji);
3125 method = info->method;
3126 actual_method = info->actual_method;
3127 api_method = method;
3132 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3135 if (info->il_offset == -1) {
3136 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3137 if (ud->frames == NULL) {
3138 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3140 info->il_offset = sp->il_offset;
3142 if (info->il_offset == -1)
3143 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3146 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));
3148 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3149 if (!CHECK_PROTOCOL_VERSION (2, 17))
3150 /* Older clients can't handle this flag */
3152 api_method = mono_marshal_method_from_wrapper (method);
3155 actual_method = api_method;
3156 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3159 frame = g_new0 (StackFrame, 1);
3160 frame->method = method;
3161 frame->actual_method = actual_method;
3162 frame->api_method = api_method;
3163 frame->il_offset = info->il_offset;
3164 frame->native_offset = info->native_offset;
3165 frame->flags = flags;
3166 frame->ji = info->ji;
3167 if (info->reg_locations)
3168 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3171 frame->has_ctx = TRUE;
3173 frame->domain = info->domain;
3175 ud->frames = g_slist_append (ud->frames, frame);
3181 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3183 ComputeFramesUserData *ud = user_data;
3186 * 'tls->filter_ctx' is the location of the throw site.
3188 * mono_walk_stack() will never actually hit the throw site, but unwind
3189 * directly from the filter to the call site; we abort stack unwinding here
3190 * once this happens and resume from the throw site.
3193 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3196 return process_frame (info, ctx, user_data);
3200 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3202 ComputeFramesUserData user_data;
3204 int i, findex, new_frame_count;
3205 StackFrame **new_frames, *f;
3206 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3208 // FIXME: Locking on tls
3209 if (tls->frames && tls->frames_up_to_date)
3212 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3214 user_data.tls = tls;
3215 user_data.frames = NULL;
3216 if (tls->terminated) {
3217 tls->frame_count = 0;
3219 } if (!tls->really_suspended && tls->async_state.valid) {
3220 /* Have to use the state saved by the signal handler */
3221 process_frame (&tls->async_last_frame, NULL, &user_data);
3222 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3223 } else if (tls->filter_state.valid) {
3225 * We are inside an exception filter.
3227 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3229 if (tls->context.valid)
3230 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3232 * After that, we resume unwinding from the location where the exception has been thrown.
3234 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3235 } else if (tls->context.valid) {
3236 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3239 tls->frame_count = 0;
3243 new_frame_count = g_slist_length (user_data.frames);
3244 new_frames = g_new0 (StackFrame*, new_frame_count);
3246 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3250 * Reuse the id for already existing stack frames, so invokes don't invalidate
3251 * the still valid stack frames.
3253 for (i = 0; i < tls->frame_count; ++i) {
3254 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3255 f->id = tls->frames [i]->id;
3260 if (i >= tls->frame_count)
3261 f->id = InterlockedIncrement (&frame_id);
3263 new_frames [findex ++] = f;
3266 g_slist_free (user_data.frames);
3268 invalidate_frames (tls);
3270 tls->frames = new_frames;
3271 tls->frame_count = new_frame_count;
3272 tls->frames_up_to_date = TRUE;
3276 * GHFunc to emit an appdomain creation event
3277 * @param key Don't care
3278 * @param value A loaded appdomain
3279 * @param user_data Don't care
3282 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3284 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3285 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3289 * GHFunc to emit a thread start event
3290 * @param key A thread id
3291 * @param value A thread object
3292 * @param user_data Don't care
3295 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3297 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3298 process_profiler_event (EVENT_KIND_THREAD_START, value);
3302 * GFunc to emit an assembly load event
3303 * @param value A loaded assembly
3304 * @param user_data Don't care
3307 emit_assembly_load (gpointer value, gpointer user_data)
3309 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3313 * GFunc to emit a type load event
3314 * @param value A loaded type
3315 * @param user_data Don't care
3318 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3320 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3324 strdup_tolower (char *s)
3329 for (p = s2; *p; ++p)
3339 * create_event_list:
3341 * Return a list of event request ids matching EVENT, starting from REQS, which
3342 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3344 * We return request ids, instead of requests, to simplify threading, since
3345 * requests could be deleted anytime when the loader lock is not held.
3346 * LOCKING: Assumes the loader lock is held.
3349 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3352 GSList *events = NULL;
3354 *suspend_policy = SUSPEND_POLICY_NONE;
3357 reqs = event_requests;
3362 for (i = 0; i < reqs->len; ++i) {
3363 EventRequest *req = g_ptr_array_index (reqs, i);
3364 if (req->event_kind == event) {
3365 gboolean filtered = FALSE;
3368 for (j = 0; j < req->nmodifiers; ++j) {
3369 Modifier *mod = &req->modifiers [j];
3371 if (mod->kind == MOD_KIND_COUNT) {
3373 if (mod->data.count > 0) {
3374 if (mod->data.count > 0) {
3376 if (mod->data.count == 0)
3380 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3381 if (mod->data.thread != mono_thread_internal_current ())
3383 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3384 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3386 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3388 if (ei->caught && !mod->caught)
3390 if (!ei->caught && !mod->uncaught)
3392 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3394 gboolean found = FALSE;
3395 MonoAssembly **assemblies = mod->data.assemblies;
3398 for (k = 0; assemblies [k]; ++k)
3399 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3404 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3405 gpointer iter = NULL;
3407 MonoDebugSourceInfo *sinfo;
3408 char *source_file, *s;
3409 gboolean found = FALSE;
3411 GPtrArray *source_file_list;
3413 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3414 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3417 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3418 for (i = 0; i < source_file_list->len; ++i) {
3419 sinfo = g_ptr_array_index (source_file_list, i);
3421 * Do a case-insesitive match by converting the file name to
3424 s = strdup_tolower (sinfo->source_file);
3425 if (g_hash_table_lookup (mod->data.source_files, s))
3428 char *s2 = g_path_get_basename (sinfo->source_file);
3429 char *s3 = strdup_tolower (s2);
3431 if (g_hash_table_lookup (mod->data.source_files, s3))
3438 g_ptr_array_free (source_file_list, TRUE);
3443 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3446 s = mono_type_full_name (&ei->klass->byval_arg);
3447 if (!g_hash_table_lookup (mod->data.type_names, s))
3450 } else if (mod->kind == MOD_KIND_STEP) {
3451 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3452 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3453 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3455 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3456 MonoCustomAttrInfo *ainfo;
3457 static MonoClass *klass;
3460 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3463 if (!ji->dbg_hidden_inited) {
3464 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3466 if (mono_custom_attrs_has_attr (ainfo, klass))
3467 ji->dbg_hidden = TRUE;
3468 mono_custom_attrs_free (ainfo);
3470 ji->dbg_hidden_inited = TRUE;
3475 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3476 MonoCustomAttrInfo *ainfo;
3477 static MonoClass *klass;
3480 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3483 if (!ji->dbg_step_through_inited) {
3484 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3486 if (mono_custom_attrs_has_attr (ainfo, klass))
3487 ji->dbg_step_through = TRUE;
3488 mono_custom_attrs_free (ainfo);
3490 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3492 if (mono_custom_attrs_has_attr (ainfo, klass))
3493 ji->dbg_step_through = TRUE;
3494 mono_custom_attrs_free (ainfo);
3496 ji->dbg_step_through_inited = TRUE;
3498 if (ji->dbg_step_through)
3505 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3506 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3511 /* Send a VM START/DEATH event by default */
3512 if (event == EVENT_KIND_VM_START)
3513 events = g_slist_append (events, GINT_TO_POINTER (0));
3514 if (event == EVENT_KIND_VM_DEATH)
3515 events = g_slist_append (events, GINT_TO_POINTER (0));
3520 static G_GNUC_UNUSED const char*
3521 event_to_string (EventKind event)
3524 case EVENT_KIND_VM_START: return "VM_START";
3525 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3526 case EVENT_KIND_THREAD_START: return "THREAD_START";
3527 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3528 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3529 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3530 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3531 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3532 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3533 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3534 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3535 case EVENT_KIND_STEP: return "STEP";
3536 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3537 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3538 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3539 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3540 case EVENT_KIND_USER_LOG: return "USER_LOG";
3542 g_assert_not_reached ();
3550 * Send an event to the client, suspending the vm if needed.
3551 * LOCKING: Since this can suspend the calling thread, no locks should be held
3553 * The EVENTS list is freed by this function.
3556 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3560 MonoDomain *domain = mono_domain_get ();
3561 MonoThread *thread = NULL;
3562 MonoObject *keepalive_obj = NULL;
3563 gboolean send_success = FALSE;
3568 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3572 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3573 // FIXME: We miss those events
3574 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3578 if (vm_death_event_sent) {
3579 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3583 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3584 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3589 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3593 if (event == EVENT_KIND_KEEPALIVE)
3594 suspend_policy = SUSPEND_POLICY_NONE;
3599 if (agent_config.defer) {
3600 /* Make sure the thread id is always set when doing deferred debugging */
3601 if (debugger_thread_id == GetCurrentThreadId ()) {
3602 /* Don't suspend on events from the debugger thread */
3603 suspend_policy = SUSPEND_POLICY_NONE;
3604 thread = mono_thread_get_main ();
3606 else thread = mono_thread_current ();
3608 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3609 // FIXME: Send these with a NULL thread, don't suspend the current thread
3614 nevents = g_slist_length (events);
3615 buffer_init (&buf, 128);
3616 buffer_add_byte (&buf, suspend_policy);
3617 buffer_add_int (&buf, nevents);
3619 for (l = events; l; l = l->next) {
3620 buffer_add_byte (&buf, event); // event kind
3621 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3626 thread = mono_thread_current ();
3628 if (event == EVENT_KIND_VM_START && arg != NULL)
3631 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3634 case EVENT_KIND_THREAD_START:
3635 case EVENT_KIND_THREAD_DEATH:
3637 case EVENT_KIND_APPDOMAIN_CREATE:
3638 case EVENT_KIND_APPDOMAIN_UNLOAD:
3639 buffer_add_domainid (&buf, arg);
3641 case EVENT_KIND_METHOD_ENTRY:
3642 case EVENT_KIND_METHOD_EXIT:
3643 buffer_add_methodid (&buf, domain, arg);
3645 case EVENT_KIND_ASSEMBLY_LOAD:
3646 case EVENT_KIND_ASSEMBLY_UNLOAD:
3647 buffer_add_assemblyid (&buf, domain, arg);
3649 case EVENT_KIND_TYPE_LOAD:
3650 buffer_add_typeid (&buf, domain, arg);
3652 case EVENT_KIND_BREAKPOINT:
3653 case EVENT_KIND_STEP:
3654 buffer_add_methodid (&buf, domain, arg);
3655 buffer_add_long (&buf, il_offset);
3657 case EVENT_KIND_VM_START:
3658 buffer_add_domainid (&buf, mono_get_root_domain ());
3660 case EVENT_KIND_VM_DEATH:
3661 if (CHECK_PROTOCOL_VERSION (2, 27))
3662 buffer_add_int (&buf, mono_environment_exitcode_get ());
3664 case EVENT_KIND_EXCEPTION: {
3665 EventInfo *ei = arg;
3666 buffer_add_objid (&buf, ei->exc);
3668 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3669 * later after the suspension. (#12494).
3671 keepalive_obj = ei->exc;
3674 case EVENT_KIND_USER_BREAK:
3676 case EVENT_KIND_USER_LOG: {
3677 EventInfo *ei = arg;
3678 buffer_add_int (&buf, ei->level);
3679 buffer_add_string (&buf, ei->category ? ei->category : "");
3680 buffer_add_string (&buf, ei->message ? ei->message : "");
3683 case EVENT_KIND_KEEPALIVE:
3684 suspend_policy = SUSPEND_POLICY_NONE;
3687 g_assert_not_reached ();
3691 if (event == EVENT_KIND_VM_START) {
3692 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3693 if (!agent_config.defer)
3694 start_debugger_thread ();
3697 if (event == EVENT_KIND_VM_DEATH) {
3698 vm_death_event_sent = TRUE;
3699 suspend_policy = SUSPEND_POLICY_NONE;
3702 if (mono_runtime_is_shutting_down ())
3703 suspend_policy = SUSPEND_POLICY_NONE;
3705 if (suspend_policy != SUSPEND_POLICY_NONE) {
3707 * Save the thread context and start suspending before sending the packet,
3708 * since we could be receiving the resume request before send_packet ()
3711 save_thread_context (ctx);
3715 /* This will keep this object alive */
3716 get_objref (keepalive_obj);
3719 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3723 g_slist_free (events);
3726 if (!send_success) {
3727 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3731 if (event == EVENT_KIND_VM_START) {
3732 vm_start_event_sent = TRUE;
3735 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3737 switch (suspend_policy) {
3738 case SUSPEND_POLICY_NONE:
3740 case SUSPEND_POLICY_ALL:
3743 case SUSPEND_POLICY_EVENT_THREAD:
3747 g_assert_not_reached ();
3752 process_profiler_event (EventKind event, gpointer arg)
3756 EventInfo ei, *ei_arg = NULL;
3758 if (event == EVENT_KIND_TYPE_LOAD) {
3763 mono_loader_lock ();
3764 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3765 mono_loader_unlock ();
3767 process_event (event, arg, 0, NULL, events, suspend_policy);
3771 runtime_initialized (MonoProfiler *prof)
3773 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3774 if (agent_config.defer)
3775 start_debugger_thread ();
3779 runtime_shutdown (MonoProfiler *prof)
3781 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3783 mono_debugger_agent_cleanup ();
3787 thread_startup (MonoProfiler *prof, uintptr_t tid)
3789 MonoInternalThread *thread = mono_thread_internal_current ();
3790 MonoInternalThread *old_thread;
3791 DebuggerTlsData *tls;
3793 if (tid == debugger_thread_id)
3796 g_assert (thread->tid == tid);
3798 mono_loader_lock ();
3799 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3800 mono_loader_unlock ();
3802 if (thread == old_thread) {
3804 * For some reason, thread_startup () might be called for the same thread
3805 * multiple times (attach ?).
3807 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3811 * thread_end () might not be called for some threads, and the tid could
3814 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3815 mono_loader_lock ();
3816 mono_g_hash_table_remove (thread_to_tls, old_thread);
3817 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3818 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3819 mono_loader_unlock ();
3823 tls = mono_native_tls_get_value (debugger_tls_id);
3825 // FIXME: Free this somewhere
3826 tls = g_new0 (DebuggerTlsData, 1);
3827 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3828 tls->thread = thread;
3829 mono_native_tls_set_value (debugger_tls_id, tls);
3831 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3833 mono_loader_lock ();
3834 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3835 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3836 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3837 mono_loader_unlock ();
3839 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3842 * suspend_vm () could have missed this thread, so wait for a resume.
3848 thread_end (MonoProfiler *prof, uintptr_t tid)
3850 MonoInternalThread *thread;
3851 DebuggerTlsData *tls = NULL;
3853 mono_loader_lock ();
3854 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3856 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3857 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3859 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3860 tls->terminated = TRUE;
3861 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3862 MONO_GC_UNREGISTER_ROOT (tls->thread);
3866 mono_loader_unlock ();
3868 /* We might be called for threads started before we registered the start callback */
3870 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3871 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3876 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3878 mono_loader_lock ();
3879 g_hash_table_insert (domains, domain, domain);
3880 mono_loader_unlock ();
3882 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3886 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3888 clear_breakpoints_for_domain (domain);
3890 mono_loader_lock ();
3891 /* Invalidate each thread's frame stack */
3892 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3893 mono_loader_unlock ();
3895 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3899 * invalidate_each_thread:
3901 * A GHFunc to invalidate frames.
3902 * value must be a DebuggerTlsData*
3905 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3907 invalidate_frames (value);
3911 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3913 /* Sent later in jit_end () */
3914 mono_loader_lock ();
3915 g_ptr_array_add (pending_assembly_loads, assembly);
3916 mono_loader_unlock ();
3920 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3922 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3924 clear_event_requests_for_assembly (assembly);
3925 clear_types_for_assembly (assembly);
3929 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3931 #if defined(HOST_WIN32) && !defined(__GNUC__)
3932 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3934 gpointer stackptr = __builtin_frame_address (1);
3936 MonoInternalThread *thread = mono_thread_internal_current ();
3937 DebuggerTlsData *tls;
3939 mono_loader_lock ();
3941 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3942 /* Could be the debugger thread with assembly/type load hooks */
3944 tls->invoke_addr = stackptr;
3946 mono_loader_unlock ();
3950 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3953 #if defined(HOST_WIN32) && !defined(__GNUC__)
3954 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3956 gpointer stackptr = __builtin_frame_address (1);
3959 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3963 * We need to stop single stepping when exiting a runtime invoke, since if it is
3964 * a step out, it may return to native code, and thus never end.
3966 mono_loader_lock ();
3967 ss_invoke_addr = NULL;
3969 for (i = 0; i < event_requests->len; ++i) {
3970 EventRequest *req = g_ptr_array_index (event_requests, i);
3972 if (req->event_kind == EVENT_KIND_STEP) {
3973 ss_destroy (req->info);
3974 g_ptr_array_remove_index_fast (event_requests, i);
3979 mono_loader_unlock ();
3983 send_type_load (MonoClass *klass)
3985 gboolean type_load = FALSE;
3986 MonoDomain *domain = mono_domain_get ();
3987 AgentDomainInfo *info = NULL;
3989 mono_loader_lock ();
3990 mono_domain_lock (domain);
3992 info = get_agent_domain_info (domain);
3994 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3996 g_hash_table_insert (info->loaded_classes, klass, klass);
3999 mono_domain_unlock (domain);
4000 mono_loader_unlock ();
4002 emit_type_load (klass, klass, NULL);
4006 * Emit load events for all types currently loaded in the domain.
4007 * Takes the loader and domain locks.
4008 * user_data is unused.
4011 send_types_for_domain (MonoDomain *domain, void *user_data)
4013 AgentDomainInfo *info = NULL;
4015 mono_loader_lock ();
4016 mono_domain_lock (domain);
4017 info = get_agent_domain_info (domain);
4019 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4020 mono_domain_unlock (domain);
4021 mono_loader_unlock ();
4025 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4028 * We emit type load events when the first method of the type is JITted,
4029 * since the class load profiler callbacks might be called with the
4030 * loader lock held. They could also occur in the debugger thread.
4031 * Same for assembly load events.
4034 MonoAssembly *assembly = NULL;
4036 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4037 mono_loader_lock ();
4038 if (pending_assembly_loads->len > 0) {
4039 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4040 g_ptr_array_remove_index (pending_assembly_loads, 0);
4042 mono_loader_unlock ();
4045 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4051 send_type_load (method->klass);
4054 add_pending_breakpoints (method, jinfo);
4058 * BREAKPOINTS/SINGLE STEPPING
4062 * Contains information about an inserted breakpoint.
4065 long il_offset, native_offset;
4070 } BreakpointInstance;
4073 * Contains generic information about a breakpoint.
4077 * The method where the breakpoint is placed. Can be NULL in which case it
4078 * is inserted into every method. This is used to implement method entry/
4079 * exit events. Can be a generic method definition, in which case the
4080 * breakpoint is inserted into every instance.
4086 * A list of BreakpointInstance structures describing where the breakpoint
4087 * was inserted. There could be more than one because of
4088 * generics/appdomains/method entry/exit.
4090 GPtrArray *children;
4093 /* List of breakpoints */
4094 static GPtrArray *breakpoints;
4095 /* Maps breakpoint locations to the number of breakpoints at that location */
4096 static GHashTable *bp_locs;
4099 breakpoints_init (void)
4101 breakpoints = g_ptr_array_new ();
4102 bp_locs = g_hash_table_new (NULL, NULL);
4106 * insert_breakpoint:
4108 * Insert the breakpoint described by BP into the method described by
4112 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4115 BreakpointInstance *inst;
4116 SeqPoint *sp = NULL;
4119 mono_error_init (error);
4121 for (i = 0; i < seq_points->len; ++i) {
4122 sp = &seq_points->seq_points [i];
4124 if (sp->il_offset == bp->il_offset)
4128 if (i == seq_points->len) {
4130 * The set of IL offsets with seq points doesn't completely match the
4131 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4133 for (i = 0; i < seq_points->len; ++i) {
4134 sp = &seq_points->seq_points [i];
4136 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4141 if (i == seq_points->len) {
4142 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset, seq_points->len);
4144 for (i = 0; i < seq_points->len; ++i)
4145 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4148 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4149 g_warning ("%s", s);
4153 g_warning ("%s", s);
4159 inst = g_new0 (BreakpointInstance, 1);
4161 inst->native_offset = sp->native_offset;
4162 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4164 inst->domain = domain;
4166 mono_loader_lock ();
4168 g_ptr_array_add (bp->children, inst);
4170 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4171 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4172 mono_loader_unlock ();
4174 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4175 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4176 } else if (count == 0) {
4177 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4178 mono_arch_set_breakpoint (ji, inst->ip);
4184 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (jinfo_get_method (ji), TRUE), (int)sp->il_offset));
4188 remove_breakpoint (BreakpointInstance *inst)
4190 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4192 MonoJitInfo *ji = inst->ji;
4193 guint8 *ip = inst->ip;
4195 mono_loader_lock ();
4196 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4197 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4198 mono_loader_unlock ();
4200 g_assert (count > 0);
4202 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4203 mono_arch_clear_breakpoint (ji, ip);
4210 static inline gboolean
4211 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4217 if (method == bp->method)
4219 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4222 if (bp->method->is_inflated && method->is_inflated) {
4223 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4224 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4226 /* Open generic methods should match closed generic methods of the same class */
4227 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4228 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4229 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4231 /* FIXME: Handle !mvar */
4232 if (t1->type != MONO_TYPE_MVAR)
4243 * add_pending_breakpoints:
4245 * Insert pending breakpoints into the newly JITted method METHOD.
4248 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4251 MonoSeqPointInfo *seq_points;
4253 MonoMethod *jmethod;
4258 domain = mono_domain_get ();
4260 mono_loader_lock ();
4262 for (i = 0; i < breakpoints->len; ++i) {
4263 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4264 gboolean found = FALSE;
4266 if (!bp_matches_method (bp, method))
4269 for (j = 0; j < bp->children->len; ++j) {
4270 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4277 jmethod = jinfo_get_method (ji);
4278 mono_domain_lock (domain);
4279 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4280 if (!seq_points && jmethod->is_inflated)
4281 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4282 mono_domain_unlock (domain);
4284 /* Could be AOT code */
4286 g_assert (seq_points);
4288 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4292 mono_loader_unlock ();
4296 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4302 mono_error_init (error);
4304 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4306 /* Might be AOTed code */
4307 code = mono_aot_get_method (domain, method);
4309 ji = mono_jit_info_table_find (domain, code);
4314 insert_breakpoint (seq_points, domain, ji, bp, error);
4318 clear_breakpoint (MonoBreakpoint *bp);
4323 * Set a breakpoint at IL_OFFSET in METHOD.
4324 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4325 * METHOD can also be a generic method definition, in which case a breakpoint
4326 * is placed in all instances of the method.
4327 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4330 static MonoBreakpoint*
4331 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4334 GHashTableIter iter, iter2;
4337 MonoSeqPointInfo *seq_points;
4340 mono_error_init (error);
4343 // - suspend/resume the vm to prevent code patching problems
4344 // - multiple breakpoints on the same location
4345 // - dynamic methods
4348 bp = g_new0 (MonoBreakpoint, 1);
4349 bp->method = method;
4350 bp->il_offset = il_offset;
4352 bp->children = g_ptr_array_new ();
4354 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));
4356 mono_loader_lock ();
4358 g_hash_table_iter_init (&iter, domains);
4359 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4360 mono_domain_lock (domain);
4362 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4363 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4364 if (bp_matches_method (bp, m))
4365 set_bp_in_method (domain, m, seq_points, bp, error);
4368 mono_domain_unlock (domain);
4371 mono_loader_unlock ();
4373 mono_loader_lock ();
4374 g_ptr_array_add (breakpoints, bp);
4375 mono_loader_unlock ();
4377 if (error && !mono_error_ok (error)) {
4378 clear_breakpoint (bp);
4386 clear_breakpoint (MonoBreakpoint *bp)
4390 // FIXME: locking, races
4391 for (i = 0; i < bp->children->len; ++i) {
4392 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4394 remove_breakpoint (inst);
4399 mono_loader_lock ();
4400 g_ptr_array_remove (breakpoints, bp);
4401 mono_loader_unlock ();
4403 g_ptr_array_free (bp->children, TRUE);
4408 breakpoints_cleanup (void)
4412 mono_loader_lock ();
4414 while (i < event_requests->len) {
4415 EventRequest *req = g_ptr_array_index (event_requests, i);
4417 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4418 clear_breakpoint (req->info);
4419 g_ptr_array_remove_index_fast (event_requests, i);
4426 for (i = 0; i < breakpoints->len; ++i)
4427 g_free (g_ptr_array_index (breakpoints, i));
4429 g_ptr_array_free (breakpoints, TRUE);
4430 g_hash_table_destroy (bp_locs);
4435 mono_loader_unlock ();
4439 * clear_breakpoints_for_domain:
4441 * Clear breakpoint instances which reference DOMAIN.
4444 clear_breakpoints_for_domain (MonoDomain *domain)
4448 /* This could be called after shutdown */
4452 mono_loader_lock ();
4453 for (i = 0; i < breakpoints->len; ++i) {
4454 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4457 while (j < bp->children->len) {
4458 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4460 if (inst->domain == domain) {
4461 remove_breakpoint (inst);
4465 g_ptr_array_remove_index_fast (bp->children, j);
4471 mono_loader_unlock ();
4477 * Return FALSE if single stepping needs to continue.
4480 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4482 MonoDebugMethodInfo *minfo;
4483 MonoDebugSourceLocation *loc = NULL;
4484 gboolean hit = TRUE;
4487 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4489 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4491 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4495 if (req->depth == STEP_DEPTH_OVER && hit) {
4496 if (!tls->context.valid)
4497 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4498 compute_frame_info (tls->thread, tls);
4499 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4500 /* Hit the breakpoint in a recursive call */
4501 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4506 if (req->size != STEP_SIZE_LINE)
4509 /* Have to check whenever a different source line was reached */
4510 method = jinfo_get_method (ji);
4511 minfo = mono_debug_lookup_method (method);
4514 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4516 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4517 /* Have to continue single stepping */
4519 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4521 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4526 ss_req->last_method = method;
4527 ss_req->last_line = loc->row;
4528 mono_debug_free_source_location (loc);
4535 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4537 return bp->method && bp->method->klass->image->assembly == assembly;
4541 process_breakpoint_inner (DebuggerTlsData *tls)
4545 int i, j, suspend_policy;
4546 guint32 native_offset;
4548 BreakpointInstance *inst;
4549 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4550 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4551 EventKind kind = EVENT_KIND_BREAKPOINT;
4552 MonoContext *ctx = &tls->restore_ctx;
4554 MonoSeqPointInfo *info;
4557 // FIXME: Speed this up
4559 ip = MONO_CONTEXT_GET_IP (ctx);
4560 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4562 method = jinfo_get_method (ji);
4564 /* Compute the native offset of the breakpoint from the ip */
4565 native_offset = ip - (guint8*)ji->code_start;
4568 * Skip the instruction causing the breakpoint signal.
4570 mono_arch_skip_breakpoint (ctx, ji);
4572 if (method->wrapper_type || tls->disable_breakpoints)
4575 bp_reqs = g_ptr_array_new ();
4576 ss_reqs = g_ptr_array_new ();
4577 ss_reqs_orig = g_ptr_array_new ();
4579 mono_loader_lock ();
4582 * The ip points to the instruction causing the breakpoint event, which is after
4583 * the offset recorded in the seq point map, so find the prev seq point before ip.
4585 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4587 no_seq_points_found (method);
4590 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), method->name, ip, native_offset, sp ? sp->il_offset : -1));
4593 for (i = 0; i < breakpoints->len; ++i) {
4594 bp = g_ptr_array_index (breakpoints, i);
4599 for (j = 0; j < bp->children->len; ++j) {
4600 inst = g_ptr_array_index (bp->children, j);
4601 if (inst->ji == ji && inst->sp == sp) {
4602 if (bp->req->event_kind == EVENT_KIND_STEP) {
4603 g_ptr_array_add (ss_reqs_orig, bp->req);
4605 g_ptr_array_add (bp_reqs, bp->req);
4610 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4611 /* Maybe a method entry/exit event */
4612 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4613 kind = EVENT_KIND_METHOD_ENTRY;
4614 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4615 kind = EVENT_KIND_METHOD_EXIT;
4618 /* Process single step requests */
4619 for (i = 0; i < ss_reqs_orig->len; ++i) {
4620 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4621 SingleStepReq *ss_req = req->info;
4624 if (mono_thread_internal_current () != ss_req->thread)
4627 hit = ss_update (ss_req, ji, sp, tls, ctx);
4629 g_ptr_array_add (ss_reqs, req);
4631 /* Start single stepping again from the current sequence point */
4632 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4635 if (ss_reqs->len > 0)
4636 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4637 if (bp_reqs->len > 0)
4638 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4639 if (kind != EVENT_KIND_BREAKPOINT)
4640 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4642 mono_loader_unlock ();
4644 g_ptr_array_free (bp_reqs, TRUE);
4645 g_ptr_array_free (ss_reqs, TRUE);
4648 * FIXME: The first event will suspend, so the second will only be sent after the
4652 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4654 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4655 if (enter_leave_events)
4656 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4659 /* Process a breakpoint/single step event after resuming from a signal handler */
4661 process_signal_event (void (*func) (DebuggerTlsData*))
4663 DebuggerTlsData *tls;
4664 MonoContext orig_restore_ctx, ctx;
4666 tls = mono_native_tls_get_value (debugger_tls_id);
4667 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4668 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4669 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4673 /* This is called when resuming from a signal handler, so it shouldn't return */
4674 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4675 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4676 mono_restore_context (&ctx);
4677 g_assert_not_reached ();
4681 process_breakpoint (void)
4683 process_signal_event (process_breakpoint_inner);
4687 resume_from_signal_handler (void *sigctx, void *func)
4689 DebuggerTlsData *tls;
4692 /* Save the original context in TLS */
4693 // FIXME: This might not work on an altstack ?
4694 tls = mono_native_tls_get_value (debugger_tls_id);
4696 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4699 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4700 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4701 // clob:c could be added to op_seq_point.
4703 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4704 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4705 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4706 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4708 MONO_CONTEXT_SET_IP (&ctx, func);
4710 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4712 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4713 mono_ppc_set_func_into_sigctx (sigctx, func);
4718 mono_debugger_agent_breakpoint_hit (void *sigctx)
4721 * We are called from a signal handler, and running code there causes all kinds of
4722 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4723 * So set up the signal context to return to the real breakpoint handler function.
4725 resume_from_signal_handler (sigctx, process_breakpoint);
4729 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4731 if (frame->managed) {
4732 *(MonoContext*)data = *ctx;
4741 * Called by System.Diagnostics.Debugger:Break ().
4744 mono_debugger_agent_user_break (void)
4746 if (agent_config.enabled) {
4751 /* Obtain a context */
4752 MONO_CONTEXT_SET_IP (&ctx, NULL);
4753 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4754 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4756 mono_loader_lock ();
4757 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4758 mono_loader_unlock ();
4760 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4767 ss_depth_to_string (StepDepth depth)
4770 case STEP_DEPTH_OVER:
4772 case STEP_DEPTH_OUT:
4774 case STEP_DEPTH_INTO:
4777 g_assert_not_reached ();
4783 process_single_step_inner (DebuggerTlsData *tls)
4788 int il_offset, suspend_policy;
4791 MonoContext *ctx = &tls->restore_ctx;
4794 MonoSeqPointInfo *info;
4796 ip = MONO_CONTEXT_GET_IP (ctx);
4798 /* Skip the instruction causing the single step */
4799 mono_arch_skip_single_step (ctx);
4801 if (suspend_count > 0) {
4802 process_suspend (tls, ctx);
4807 // FIXME: A suspend race
4810 if (mono_thread_internal_current () != ss_req->thread)
4813 if (log_level > 0) {
4814 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4816 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 (jinfo_get_method (ji), TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4819 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4821 method = jinfo_get_method (ji);
4824 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4829 * Stopping in memset makes half-initialized vtypes visible.
4830 * Stopping in memcpy makes half-copied vtypes visible.
4832 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4836 * The ip points to the instruction causing the single step event, which is before
4837 * the offset recorded in the seq point map, so find the next seq point after ip.
4839 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
4842 il_offset = sp->il_offset;
4844 if (!ss_update (ss_req, ji, sp, tls, ctx))
4847 /* Start single stepping again from the current sequence point */
4848 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4850 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4851 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4852 !strcmp (method->name, ".cctor"))
4855 // FIXME: Has to lock earlier
4857 reqs = g_ptr_array_new ();
4859 mono_loader_lock ();
4861 g_ptr_array_add (reqs, ss_req->req);
4863 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4865 g_ptr_array_free (reqs, TRUE);
4867 mono_loader_unlock ();
4869 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4873 process_single_step (void)
4875 process_signal_event (process_single_step_inner);
4879 * mono_debugger_agent_single_step_event:
4881 * Called from a signal handler to handle a single step event.
4884 mono_debugger_agent_single_step_event (void *sigctx)
4886 /* Resume to process_single_step through the signal context */
4888 // FIXME: Since step out/over is implemented using step in, the step in case should
4889 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4892 if (GetCurrentThreadId () == debugger_thread_id) {
4894 * This could happen despite our best effors when the runtime calls
4895 * assembly/type resolve hooks.
4896 * FIXME: Breakpoints too.
4900 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4901 mono_arch_skip_single_step (&ctx);
4902 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4906 resume_from_signal_handler (sigctx, process_single_step);
4910 debugger_agent_single_step_from_context (MonoContext *ctx)
4912 DebuggerTlsData *tls;
4913 MonoContext orig_restore_ctx;
4915 tls = mono_native_tls_get_value (debugger_tls_id);
4918 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4919 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4920 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4922 process_single_step_inner (tls);
4924 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4925 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4929 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4931 DebuggerTlsData *tls;
4932 MonoContext orig_restore_ctx;
4934 tls = mono_native_tls_get_value (debugger_tls_id);
4936 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4937 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4939 process_breakpoint_inner (tls);
4941 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4942 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4946 * start_single_stepping:
4948 * Turn on single stepping. Can be called multiple times, for example,
4949 * by a single step event request + a suspend.
4952 start_single_stepping (void)
4954 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4955 int val = InterlockedIncrement (&ss_count);
4958 mono_arch_start_single_stepping ();
4960 if (ss_req != NULL && ss_invoke_addr == NULL) {
4961 DebuggerTlsData *tls;
4963 mono_loader_lock ();
4965 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4966 ss_invoke_addr = tls->invoke_addr;
4968 mono_loader_unlock ();
4971 g_assert_not_reached ();
4976 stop_single_stepping (void)
4978 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4979 int val = InterlockedDecrement (&ss_count);
4982 mono_arch_stop_single_stepping ();
4984 ss_invoke_addr = NULL;
4986 g_assert_not_reached ();
4993 * Stop the single stepping operation given by SS_REQ.
4996 ss_stop (SingleStepReq *ss_req)
5001 for (l = ss_req->bps; l; l = l->next) {
5002 clear_breakpoint (l->data);
5004 g_slist_free (ss_req->bps);
5008 if (ss_req->global) {
5009 stop_single_stepping ();
5010 ss_req->global = FALSE;
5017 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5018 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5019 * belong to the same thread as CTX.
5022 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5024 int i, j, frame_index;
5027 gboolean enable_global = FALSE;
5029 /* Stop the previous operation */
5033 * Implement single stepping using breakpoints if possible.
5035 if (step_to_catch) {
5036 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5037 ss_req->bps = g_slist_append (ss_req->bps, bp);
5041 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5042 /* Need parent frames */
5043 if (!tls->context.valid)
5044 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5045 compute_frame_info (tls->thread, tls);
5049 * Find the first sequence point in the current or in a previous frame which
5050 * is not the last in its method.
5052 if (ss_req->depth == STEP_DEPTH_OUT) {
5053 /* Ignore seq points in current method */
5054 while (frame_index < tls->frame_count) {
5055 StackFrame *frame = tls->frames [frame_index];
5057 method = frame->method;
5058 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5060 if (sp && sp->next_len != 0)
5063 // There could be method calls before the next seq point in the caller when using nested calls
5064 //enable_global = TRUE;
5066 if (sp && sp->next_len == 0) {
5068 while (frame_index < tls->frame_count) {
5069 StackFrame *frame = tls->frames [frame_index];
5071 method = frame->method;
5072 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5073 if (sp && sp->next_len != 0)
5081 if (sp && sp->next_len > 0) {
5082 for (i = 0; i < sp->next_len; ++i) {
5083 next_sp = &info->seq_points [sp->next [i]];
5085 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5086 ss_req->bps = g_slist_append (ss_req->bps, bp);
5090 if (ss_req->depth == STEP_DEPTH_OVER) {
5091 if (ss_req->nframes == 0)
5092 ss_req->nframes = tls->frame_count;
5093 /* Need to stop in catch clauses as well */
5094 for (i = 0; i < tls->frame_count; ++i) {
5095 StackFrame *frame = tls->frames [i];
5098 MonoJitInfo *jinfo = frame->ji;
5099 for (j = 0; j < jinfo->num_clauses; ++j) {
5100 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5102 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5104 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5105 ss_req->bps = g_slist_append (ss_req->bps, bp);
5113 if (ss_req->depth == STEP_DEPTH_INTO) {
5114 /* Enable global stepping so we stop at method entry too */
5115 enable_global = TRUE;
5119 * The ctx/frame info computed above will become invalid when we continue.
5121 tls->context.valid = FALSE;
5122 tls->async_state.valid = FALSE;
5123 invalidate_frames (tls);
5126 if (enable_global) {
5127 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5128 ss_req->global = TRUE;
5129 start_single_stepping ();
5130 } else if (!ss_req->bps) {
5131 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5132 ss_req->global = TRUE;
5133 start_single_stepping ();
5135 ss_req->global = FALSE;
5140 * Start single stepping of thread THREAD
5143 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5145 DebuggerTlsData *tls;
5146 MonoSeqPointInfo *info = NULL;
5147 SeqPoint *sp = NULL;
5148 MonoMethod *method = NULL;
5149 MonoDebugMethodInfo *minfo;
5150 gboolean step_to_catch = FALSE;
5152 if (suspend_count == 0)
5153 return ERR_NOT_SUSPENDED;
5155 wait_for_suspend ();
5157 // FIXME: Multiple requests
5159 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5160 return ERR_NOT_IMPLEMENTED;
5163 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5165 ss_req = g_new0 (SingleStepReq, 1);
5167 ss_req->thread = thread;
5168 ss_req->size = size;
5169 ss_req->depth = depth;
5172 mono_loader_lock ();
5173 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5174 mono_loader_unlock ();
5176 g_assert (tls->context.valid);
5177 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5179 if (tls->catch_state.valid) {
5181 StackFrameInfo frame;
5182 MonoContext new_ctx;
5183 MonoLMF *lmf = NULL;
5186 * We are stopped at a throw site. Stepping should go to the catch site.
5189 /* Find the the jit info for the catch context */
5190 res = mono_find_jit_info_ext (tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], thread->jit_data, NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5192 g_assert (frame.type == FRAME_TYPE_MANAGED);
5195 * Find the seq point corresponding to the landing site ip, which is the first seq
5198 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5200 no_seq_points_found (frame.method);
5203 method = frame.method;
5205 step_to_catch = TRUE;
5206 /* This make sure the seq point is not skipped by process_single_step () */
5207 ss_req->last_sp = NULL;
5210 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5213 /* Compute the initial line info */
5214 compute_frame_info (thread, tls);
5216 if (tls->frame_count) {
5217 frame = tls->frames [0];
5219 ss_req->last_method = frame->method;
5220 ss_req->last_line = -1;
5222 minfo = mono_debug_lookup_method (frame->method);
5223 if (minfo && frame->il_offset != -1) {
5224 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5227 ss_req->last_line = loc->row;
5234 if (!step_to_catch) {
5237 compute_frame_info (thread, tls);
5239 if (tls->frame_count) {
5240 frame = tls->frames [0];
5242 if (!method && frame->il_offset != -1) {
5243 /* FIXME: Sort the table and use a binary search */
5244 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5246 no_seq_points_found (frame->method);
5248 method = frame->method;
5253 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5259 ss_destroy (SingleStepReq *req)
5262 g_assert (ss_req == req);
5271 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5274 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5280 if (!agent_config.enabled)
5283 mono_loader_lock ();
5284 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5285 mono_loader_unlock ();
5288 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5289 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5291 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5293 g_free (ei.category);
5294 g_free (ei.message);
5298 mono_debugger_agent_debug_log_is_enabled (void)
5300 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5301 return agent_config.enabled;
5304 #ifdef PLATFORM_ANDROID
5306 mono_debugger_agent_unhandled_exception (MonoException *exc)
5315 memset (&ei, 0, sizeof (EventInfo));
5316 ei.exc = (MonoObject*)exc;
5318 mono_loader_lock ();
5319 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5320 mono_loader_unlock ();
5322 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5327 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5328 MonoContext *catch_ctx)
5330 int i, j, suspend_policy;
5332 MonoJitInfo *ji, *catch_ji;
5334 DebuggerTlsData *tls = NULL;
5336 if (thread_to_tls != NULL) {
5337 MonoInternalThread *thread = mono_thread_internal_current ();
5339 mono_loader_lock ();
5340 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5341 mono_loader_unlock ();
5343 if (tls && tls->abort_requested)
5345 if (tls && tls->disable_breakpoints)
5349 memset (&ei, 0, sizeof (EventInfo));
5351 /* Just-In-Time debugging */
5353 if (agent_config.onuncaught && !inited) {
5354 finish_agent_init (FALSE);
5357 * Send an unsolicited EXCEPTION event with a dummy request id.
5359 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5360 ei.exc = (MonoObject*)exc;
5361 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5364 } else if (agent_config.onthrow && !inited) {
5366 gboolean found = FALSE;
5368 for (l = agent_config.onthrow; l; l = l->next) {
5369 char *ex_type = l->data;
5370 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5372 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5379 finish_agent_init (FALSE);
5382 * Send an unsolicited EXCEPTION event with a dummy request id.
5384 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5385 ei.exc = (MonoObject*)exc;
5386 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5394 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5396 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5400 ei.exc = (MonoObject*)exc;
5401 ei.caught = catch_ctx != NULL;
5403 mono_loader_lock ();
5405 /* Treat exceptions which are caught in non-user code as unhandled */
5406 for (i = 0; i < event_requests->len; ++i) {
5407 EventRequest *req = g_ptr_array_index (event_requests, i);
5408 if (req->event_kind != EVENT_KIND_EXCEPTION)
5411 for (j = 0; j < req->nmodifiers; ++j) {
5412 Modifier *mod = &req->modifiers [j];
5414 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5416 gboolean found = FALSE;
5417 MonoAssembly **assemblies = mod->data.assemblies;
5420 for (k = 0; assemblies [k]; ++k)
5421 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5430 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5431 mono_loader_unlock ();
5433 if (tls && ei.caught && catch_ctx) {
5434 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5435 tls->catch_state.ctx = *catch_ctx;
5436 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5437 tls->catch_state.valid = TRUE;
5440 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5443 tls->catch_state.valid = FALSE;
5447 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5449 DebuggerTlsData *tls;
5454 tls = mono_native_tls_get_value (debugger_tls_id);
5459 * We're about to invoke an exception filter during the first pass of exception handling.
5461 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5462 * 'orig_ctx' is the context where the exception has been thrown.
5465 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5467 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5468 * the call site (line 37) and then continue to Main(), but it would never
5469 * include the throw site (line 32).
5471 * Since exception filters are invoked during the first pass of exception handling,
5472 * the stack frames of the throw site are still intact, so we should include them
5475 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5477 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5478 * but report the location of the 'throw' to the user.
5482 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5486 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5488 DebuggerTlsData *tls;
5493 tls = mono_native_tls_get_value (debugger_tls_id);
5497 tls->filter_state.valid = FALSE;
5501 * buffer_add_value_full:
5503 * Add the encoding of the value at ADDR described by T to the buffer.
5504 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5508 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5514 if (!(*(void**)addr)) {
5515 /* This can happen with compiler generated locals */
5516 //printf ("%s\n", mono_type_full_name (t));
5517 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5520 g_assert (*(void**)addr);
5521 addr = *(void**)addr;
5526 case MONO_TYPE_BOOLEAN:
5529 case MONO_TYPE_CHAR:
5549 case MONO_TYPE_VOID:
5550 buffer_add_byte (buf, t->type);
5552 case MONO_TYPE_BOOLEAN:
5555 buffer_add_byte (buf, t->type);
5556 buffer_add_int (buf, *(gint8*)addr);
5558 case MONO_TYPE_CHAR:
5561 buffer_add_byte (buf, t->type);
5562 buffer_add_int (buf, *(gint16*)addr);
5567 buffer_add_byte (buf, t->type);
5568 buffer_add_int (buf, *(gint32*)addr);
5573 buffer_add_byte (buf, t->type);
5574 buffer_add_long (buf, *(gint64*)addr);
5578 /* Treat it as a vtype */
5580 case MONO_TYPE_PTR: {
5581 gssize val = *(gssize*)addr;
5583 buffer_add_byte (buf, t->type);
5584 buffer_add_long (buf, val);
5588 case MONO_TYPE_STRING:
5589 case MONO_TYPE_SZARRAY:
5590 case MONO_TYPE_OBJECT:
5591 case MONO_TYPE_CLASS:
5592 case MONO_TYPE_ARRAY:
5593 obj = *(MonoObject**)addr;
5596 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5598 if (obj->vtable->klass->valuetype) {
5599 t = &obj->vtable->klass->byval_arg;
5600 addr = mono_object_unbox (obj);
5602 } else if (obj->vtable->klass->rank) {
5603 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5604 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5605 buffer_add_byte (buf, MONO_TYPE_CLASS);
5607 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5609 buffer_add_objid (buf, obj);
5613 case MONO_TYPE_VALUETYPE: {
5617 MonoClass *klass = mono_class_from_mono_type (t);
5619 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5620 buffer_add_byte (buf, klass->enumtype);
5621 buffer_add_typeid (buf, domain, klass);
5625 while ((f = mono_class_get_fields (klass, &iter))) {
5626 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5628 if (mono_field_is_deleted (f))
5632 buffer_add_int (buf, nfields);
5635 while ((f = mono_class_get_fields (klass, &iter))) {
5636 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5638 if (mono_field_is_deleted (f))
5640 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5644 case MONO_TYPE_GENERICINST:
5645 if (mono_type_generic_inst_is_valuetype (t)) {
5657 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5659 buffer_add_value_full (buf, t, addr, domain, FALSE);
5663 obj_is_of_type (MonoObject *obj, MonoType *t)
5665 MonoClass *klass = obj->vtable->klass;
5666 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5667 if (mono_class_is_transparent_proxy (klass)) {
5668 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5669 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5679 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5682 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5688 gpointer iter = NULL;
5692 is_enum = decode_byte (buf, &buf, limit);
5693 /* Enums are sent as a normal vtype */
5695 return ERR_NOT_IMPLEMENTED;
5696 klass = decode_typeid (buf, &buf, limit, &d, &err);
5700 if (t && klass != mono_class_from_mono_type (t)) {
5701 char *name = mono_type_full_name (t);
5702 char *name2 = mono_type_full_name (&klass->byval_arg);
5703 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5706 return ERR_INVALID_ARGUMENT;
5709 nfields = decode_int (buf, &buf, limit);
5710 while ((f = mono_class_get_fields (klass, &iter))) {
5711 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5713 if (mono_field_is_deleted (f))
5715 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5720 g_assert (nfields == 0);
5728 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5732 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5733 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5734 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5735 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5736 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5737 char *name = mono_type_full_name (t);
5738 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5740 return ERR_INVALID_ARGUMENT;
5744 case MONO_TYPE_BOOLEAN:
5745 *(guint8*)addr = decode_int (buf, &buf, limit);
5747 case MONO_TYPE_CHAR:
5748 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5751 *(gint8*)addr = decode_int (buf, &buf, limit);
5754 *(guint8*)addr = decode_int (buf, &buf, limit);
5757 *(gint16*)addr = decode_int (buf, &buf, limit);
5760 *(guint16*)addr = decode_int (buf, &buf, limit);
5763 *(gint32*)addr = decode_int (buf, &buf, limit);
5766 *(guint32*)addr = decode_int (buf, &buf, limit);
5769 *(gint64*)addr = decode_long (buf, &buf, limit);
5772 *(guint64*)addr = decode_long (buf, &buf, limit);
5775 *(guint32*)addr = decode_int (buf, &buf, limit);
5778 *(guint64*)addr = decode_long (buf, &buf, limit);
5781 /* We send these as I8, so we get them back as such */
5782 g_assert (type == MONO_TYPE_I8);
5783 *(gssize*)addr = decode_long (buf, &buf, limit);
5785 case MONO_TYPE_GENERICINST:
5786 if (MONO_TYPE_ISSTRUCT (t)) {
5787 /* The client sends these as a valuetype */
5795 /* We send these as vtypes, so we get them back as such */
5796 g_assert (type == MONO_TYPE_VALUETYPE);
5799 case MONO_TYPE_VALUETYPE:
5800 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5806 if (MONO_TYPE_IS_REFERENCE (t)) {
5807 if (type == MONO_TYPE_OBJECT) {
5808 int objid = decode_objid (buf, &buf, limit);
5812 err = get_object (objid, (MonoObject**)&obj);
5817 if (!obj_is_of_type (obj, t)) {
5818 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5819 return ERR_INVALID_ARGUMENT;
5822 if (obj && obj->vtable->domain != domain)
5823 return ERR_INVALID_ARGUMENT;
5825 mono_gc_wbarrier_generic_store (addr, obj);
5826 } else if (type == VALUE_TYPE_ID_NULL) {
5827 *(MonoObject**)addr = NULL;
5828 } else if (type == MONO_TYPE_VALUETYPE) {
5836 /* This can happen when round-tripping boxed vtypes */
5838 * Obtain vtype class.
5839 * Same as the beginning of the handle_vtype case above.
5842 is_enum = decode_byte (buf, &buf, limit);
5844 return ERR_NOT_IMPLEMENTED;
5845 klass = decode_typeid (buf, &buf, limit, &d, &err);
5849 /* Decode the vtype into a temporary buffer, then box it. */
5850 vtype_buf_size = mono_class_value_size (klass, NULL);
5851 vtype_buf = g_malloc0 (vtype_buf_size);
5852 g_assert (vtype_buf);
5855 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
5860 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
5863 char *name = mono_type_full_name (t);
5864 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5866 return ERR_INVALID_ARGUMENT;
5880 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5883 int type = decode_byte (buf, &buf, limit);
5885 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5886 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5887 guint8 *nullable_buf;
5890 * First try decoding it as a Nullable`1
5892 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5897 * Then try decoding as a primitive value or null.
5899 if (targ->type == type) {
5900 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5901 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5903 g_free (nullable_buf);
5906 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5907 g_free (nullable_buf);
5910 } else if (type == VALUE_TYPE_ID_NULL) {
5911 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5917 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5921 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5925 guint8 *addr, *gaddr;
5928 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5929 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5932 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5933 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5935 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5937 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5938 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5939 addr += (gint32)var->offset;
5941 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5943 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5945 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5948 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5949 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5950 /* Same as regoffset, but with an indirection */
5951 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5952 addr += (gint32)var->offset;
5954 gaddr = *(gpointer*)addr;
5956 buffer_add_value_full (buf, t, gaddr, domain, as_vtype);
5958 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5959 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5960 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5961 MonoGSharedVtMethodRuntimeInfo *info;
5967 g_assert (info_var);
5968 g_assert (locals_var);
5970 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5971 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5972 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5973 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5974 addr += (gint32)info_var->offset;
5975 info = *(gpointer*)addr;
5976 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5977 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5979 g_assert_not_reached ();
5983 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5984 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5985 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5986 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5987 addr += (gint32)locals_var->offset;
5988 locals = *(gpointer*)addr;
5989 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5990 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5992 g_assert_not_reached ();
5996 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5998 buffer_add_value_full (buf, t, addr, domain, as_vtype);
6003 g_assert_not_reached ();
6008 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6012 guint8 *addr, *gaddr;
6014 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6015 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6017 if (MONO_TYPE_IS_REFERENCE (t))
6018 size = sizeof (gpointer);
6020 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6023 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6024 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6026 gboolean is_signed = FALSE;
6029 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6032 // FIXME: Write barriers
6033 mono_gc_memmove_atomic (addr, val, size);
6038 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6043 v = is_signed ? *(gint8*)val : *(guint8*)val;
6046 v = is_signed ? *(gint16*)val : *(guint16*)val;
6049 v = is_signed ? *(gint32*)val : *(guint32*)val;
6052 v = is_signed ? *(gint64*)val : *(guint64*)val;
6055 g_assert_not_reached ();
6058 /* Set value on the stack or in the return ctx */
6059 if (reg_locations [reg]) {
6060 /* Saved on the stack */
6061 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6062 *(reg_locations [reg]) = v;
6065 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6066 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6069 // FIXME: Move these to mono-context.h/c.
6070 mono_arch_context_set_int_reg (ctx, reg, v);
6072 // FIXME: Can't set registers, so we disable linears
6077 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6078 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6079 addr += (gint32)var->offset;
6081 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6084 addr = *(guint8**)addr;
6090 // FIXME: Write barriers
6091 mono_gc_memmove_atomic (addr, val, size);
6093 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6094 /* Same as regoffset, but with an indirection */
6095 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6096 addr += (gint32)var->offset;
6098 gaddr = *(gpointer*)addr;
6100 // FIXME: Write barriers
6101 mono_gc_memmove_atomic (gaddr, val, size);
6103 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6107 g_assert_not_reached ();
6112 clear_event_request (int req_id, int etype)
6116 mono_loader_lock ();
6117 for (i = 0; i < event_requests->len; ++i) {
6118 EventRequest *req = g_ptr_array_index (event_requests, i);
6120 if (req->id == req_id && req->event_kind == etype) {
6121 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6122 clear_breakpoint (req->info);
6123 if (req->event_kind == EVENT_KIND_STEP)
6124 ss_destroy (req->info);
6125 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6126 clear_breakpoint (req->info);
6127 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6128 clear_breakpoint (req->info);
6129 g_ptr_array_remove_index_fast (event_requests, i);
6134 mono_loader_unlock ();
6138 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
6140 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6141 return breakpoint_matches_assembly (req->info, assembly);
6145 for (i = 0; i < req->nmodifiers; ++i) {
6146 Modifier *m = &req->modifiers [i];
6148 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6150 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6151 for (j = 0; m->data.assemblies [j]; ++j)
6152 if (m->data.assemblies [j] == assembly)
6162 * clear_event_requests_for_assembly:
6164 * Clear all events requests which reference ASSEMBLY.
6167 clear_event_requests_for_assembly (MonoAssembly *assembly)
6172 mono_loader_lock ();
6176 for (i = 0; i < event_requests->len; ++i) {
6177 EventRequest *req = g_ptr_array_index (event_requests, i);
6179 if (event_req_matches_assembly (req, assembly)) {
6180 clear_event_request (req->id, req->event_kind);
6186 mono_loader_unlock ();
6190 * type_comes_from_assembly:
6192 * GHRFunc that returns TRUE if klass comes from assembly
6195 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6197 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6201 * clear_types_for_assembly:
6203 * Clears types from loaded_classes for a given assembly
6206 clear_types_for_assembly (MonoAssembly *assembly)
6208 MonoDomain *domain = mono_domain_get ();
6209 AgentDomainInfo *info = NULL;
6211 mono_loader_lock ();
6212 info = get_agent_domain_info (domain);
6213 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6214 mono_loader_unlock ();
6218 add_thread (gpointer key, gpointer value, gpointer user_data)
6220 MonoInternalThread *thread = value;
6221 Buffer *buf = user_data;
6223 buffer_add_objid (buf, (MonoObject*)thread);
6227 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6229 guint8 *end = invoke->endp;
6232 MonoMethodSignature *sig;
6235 MonoObject *this, *res, *exc;
6238 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6241 MonoStopwatch watch;
6243 if (invoke->method) {
6245 * Invoke this method directly, currently only Environment.Exit () is supported.
6248 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>"));
6249 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6250 g_assert_not_reached ();
6253 m = decode_methodid (p, &p, end, &domain, &err);
6256 sig = mono_method_signature (m);
6258 if (m->klass->valuetype)
6259 this_buf = g_alloca (mono_class_instance_size (m->klass));
6261 this_buf = g_alloca (sizeof (MonoObject*));
6262 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6263 /* Should be null */
6264 int type = decode_byte (p, &p, end);
6265 if (type != VALUE_TYPE_ID_NULL) {
6266 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6267 return ERR_INVALID_ARGUMENT;
6269 memset (this_buf, 0, mono_class_instance_size (m->klass));
6271 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6276 if (!m->klass->valuetype)
6277 this = *(MonoObject**)this_buf;
6281 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6283 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6284 return ERR_INVALID_ARGUMENT;
6286 m = mono_object_get_virtual_method (this, m);
6289 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>"));
6291 if (this && this->vtable->domain != domain)
6294 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6295 if (!strcmp (m->name, ".ctor")) {
6296 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6297 return ERR_INVALID_ARGUMENT;
6299 this = mono_object_new (domain, m->klass);
6301 return ERR_INVALID_ARGUMENT;
6305 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6306 return ERR_INVALID_ARGUMENT;
6308 nargs = decode_int (p, &p, end);
6309 if (nargs != sig->param_count)
6310 return ERR_INVALID_ARGUMENT;
6311 /* Use alloca to get gc tracking */
6312 arg_buf = g_alloca (nargs * sizeof (gpointer));
6313 memset (arg_buf, 0, nargs * sizeof (gpointer));
6314 args = g_alloca (nargs * sizeof (gpointer));
6315 for (i = 0; i < nargs; ++i) {
6316 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6317 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6321 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6324 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6325 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6328 args [i] = arg_buf [i];
6335 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6336 tls->disable_breakpoints = TRUE;
6338 tls->disable_breakpoints = FALSE;
6341 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6343 /* FIXME: Move this to arch specific code */
6344 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6345 if (invoke->has_ctx) {
6348 lmf_addr = mono_get_lmf_addr ();
6351 memset (&ext, 0, sizeof (ext));
6352 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6354 ext.debugger_invoke = TRUE;
6355 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6357 mono_set_lmf ((MonoLMF*)&ext);
6361 mono_stopwatch_start (&watch);
6362 if (m->klass->valuetype)
6363 res = mono_runtime_invoke (m, this_buf, args, &exc);
6365 res = mono_runtime_invoke (m, this, args, &exc);
6366 mono_stopwatch_stop (&watch);
6367 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)));
6369 buffer_add_byte (buf, 0);
6370 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6372 buffer_add_byte (buf, 1);
6373 if (sig->ret->type == MONO_TYPE_VOID) {
6374 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6375 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6378 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6379 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6380 buffer_add_value (buf, sig->ret, &res, domain);
6381 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6382 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6383 MonoClass *k = mono_class_from_mono_type (sig->ret);
6384 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6386 g_assert (nullable_buf);
6387 mono_nullable_init (nullable_buf, res, k);
6388 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6391 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6398 tls->disable_breakpoints = FALSE;
6400 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6401 if (invoke->has_ctx)
6402 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6406 // FIXME: byref arguments
6414 * Invoke the method given by tls->pending_invoke in the current thread.
6417 invoke_method (void)
6419 DebuggerTlsData *tls;
6424 MonoContext restore_ctx;
6427 tls = mono_native_tls_get_value (debugger_tls_id);
6431 * Store the `InvokeData *' in `tls->invoke' until we're done with
6432 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6435 mono_loader_lock ();
6437 invoke = tls->pending_invoke;
6439 tls->pending_invoke = NULL;
6441 invoke->last_invoke = tls->invoke;
6442 tls->invoke = invoke;
6444 mono_loader_unlock ();
6446 tls->frames_up_to_date = FALSE;
6452 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6453 buffer_init (&buf, 128);
6456 /* Fail the other invokes as well */
6458 err = do_invoke_method (tls, &buf, invoke, p, &p);
6461 /* Start suspending before sending the reply */
6462 if (mindex == invoke->nmethods - 1) {
6463 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6464 for (i = 0; i < invoke->suspend_count; ++i)
6469 send_reply_packet (id, err, &buf);
6474 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6476 if (invoke->has_ctx)
6477 save_thread_context (&restore_ctx);
6479 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6480 g_assert (tls->resume_count);
6481 tls->resume_count -= invoke->suspend_count;
6484 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6487 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6489 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6490 * after the mono_runtime_invoke() already returned, but it doesn't matter
6491 * because we reset the abort here.
6494 mono_loader_lock ();
6496 if (tls->abort_requested)
6497 mono_thread_internal_reset_abort (tls->thread);
6499 tls->invoke = tls->invoke->last_invoke;
6500 tls->abort_requested = FALSE;
6502 mono_loader_unlock ();
6511 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6513 MonoThread *thread = value;
6514 DebuggerTlsData *tls;
6517 mono_loader_lock ();
6518 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6520 res = tls->really_suspended;
6521 mono_loader_unlock ();
6527 get_source_files_for_type (MonoClass *klass)
6529 gpointer iter = NULL;
6531 MonoDebugSourceInfo *sinfo;
6535 files = g_ptr_array_new ();
6537 while ((method = mono_class_get_methods (klass, &iter))) {
6538 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6539 GPtrArray *source_file_list;
6542 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6543 for (j = 0; j < source_file_list->len; ++j) {
6544 sinfo = g_ptr_array_index (source_file_list, j);
6545 for (i = 0; i < files->len; ++i)
6546 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6548 if (i == files->len)
6549 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6551 g_ptr_array_free (source_file_list, TRUE);
6559 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6562 case CMD_VM_VERSION: {
6563 char *build_info, *version;
6565 build_info = mono_get_runtime_build_info ();
6566 version = g_strdup_printf ("mono %s", build_info);
6568 buffer_add_string (buf, version); /* vm version */
6569 buffer_add_int (buf, MAJOR_VERSION);
6570 buffer_add_int (buf, MINOR_VERSION);
6571 g_free (build_info);
6575 case CMD_VM_SET_PROTOCOL_VERSION: {
6576 major_version = decode_int (p, &p, end);
6577 minor_version = decode_int (p, &p, end);
6578 protocol_version_set = TRUE;
6579 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6582 case CMD_VM_ALL_THREADS: {
6584 mono_loader_lock ();
6585 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6586 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6587 mono_loader_unlock ();
6590 case CMD_VM_SUSPEND:
6592 wait_for_suspend ();
6595 if (suspend_count == 0)
6596 return ERR_NOT_SUSPENDED;
6598 clear_suspended_objs ();
6600 case CMD_VM_DISPOSE:
6601 /* Clear all event requests */
6602 mono_loader_lock ();
6603 while (event_requests->len > 0) {
6604 EventRequest *req = g_ptr_array_index (event_requests, 0);
6606 clear_event_request (req->id, req->event_kind);
6608 mono_loader_unlock ();
6610 while (suspend_count > 0)
6612 disconnected = TRUE;
6613 vm_start_event_sent = FALSE;
6616 MonoInternalThread *thread;
6617 DebuggerTlsData *tls;
6618 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6619 MonoClass *env_class;
6621 MonoMethod *exit_method = NULL;
6625 exit_code = decode_int (p, &p, end);
6627 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6629 /* Have to send a reply before exiting */
6630 send_reply_packet (id, 0, buf);
6632 /* Clear all event requests */
6633 mono_loader_lock ();
6634 while (event_requests->len > 0) {
6635 EventRequest *req = g_ptr_array_index (event_requests, 0);
6637 clear_event_request (req->id, req->event_kind);
6639 mono_loader_unlock ();
6642 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6643 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6644 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6645 * better than doing the shutdown ourselves, since it avoids various races.
6649 wait_for_suspend ();
6651 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6652 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6654 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6657 mono_loader_lock ();
6658 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6659 mono_loader_unlock ();
6661 if (thread && exit_method) {
6662 mono_loader_lock ();
6663 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6664 mono_loader_unlock ();
6666 args = g_new0 (gpointer, 1);
6667 args [0] = g_malloc (sizeof (int));
6668 *(int*)(args [0]) = exit_code;
6670 tls->pending_invoke = g_new0 (InvokeData, 1);
6671 tls->pending_invoke->method = exit_method;
6672 tls->pending_invoke->args = args;
6673 tls->pending_invoke->nmethods = 1;
6675 while (suspend_count > 0)
6679 * No thread found, do it ourselves.
6680 * FIXME: This can race with normal shutdown etc.
6682 while (suspend_count > 0)
6685 if (!mono_runtime_try_shutdown ())
6688 mono_environment_exitcode_set (exit_code);
6690 /* Suspend all managed threads since the runtime is going away */
6691 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6692 mono_thread_suspend_all_other_threads ();
6693 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6694 mono_runtime_quit ();
6695 transport_close2 ();
6696 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6702 case CMD_VM_INVOKE_METHOD:
6703 case CMD_VM_INVOKE_METHODS: {
6704 int objid = decode_objid (p, &p, end);
6706 DebuggerTlsData *tls;
6707 int i, count, err, flags, nmethods;
6709 err = get_object (objid, (MonoObject**)&thread);
6713 flags = decode_int (p, &p, end);
6715 if (command == CMD_VM_INVOKE_METHODS)
6716 nmethods = decode_int (p, &p, end);
6720 // Wait for suspending if it already started
6722 wait_for_suspend ();
6723 if (!is_suspended ())
6724 return ERR_NOT_SUSPENDED;
6726 mono_loader_lock ();
6727 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6728 mono_loader_unlock ();
6731 if (!tls->really_suspended)
6732 /* The thread is still running native code, can't do invokes */
6733 return ERR_NOT_SUSPENDED;
6736 * Store the invoke data into tls, the thread will execute it after it is
6739 if (tls->pending_invoke)
6740 return ERR_NOT_SUSPENDED;
6741 tls->pending_invoke = g_new0 (InvokeData, 1);
6742 tls->pending_invoke->id = id;
6743 tls->pending_invoke->flags = flags;
6744 tls->pending_invoke->p = g_malloc (end - p);
6745 memcpy (tls->pending_invoke->p, p, end - p);
6746 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6747 tls->pending_invoke->suspend_count = suspend_count;
6748 tls->pending_invoke->nmethods = nmethods;
6750 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6751 resume_thread (THREAD_TO_INTERNAL (thread));
6754 count = suspend_count;
6755 for (i = 0; i < count; ++i)
6760 case CMD_VM_ABORT_INVOKE: {
6761 int objid = decode_objid (p, &p, end);
6763 DebuggerTlsData *tls;
6766 err = get_object (objid, (MonoObject**)&thread);
6770 invoke_id = decode_int (p, &p, end);
6772 mono_loader_lock ();
6773 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6776 if (tls->abort_requested) {
6777 mono_loader_unlock ();
6782 * Check whether we're still inside the mono_runtime_invoke() and that it's
6783 * actually the correct invocation.
6785 * Careful, we do not stop the thread that's doing the invocation, so we can't
6786 * inspect its stack. However, invoke_method() also acquires the loader lock
6787 * when it's done, so we're safe here.
6791 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6792 mono_loader_unlock ();
6793 return ERR_NO_INVOCATION;
6796 tls->abort_requested = TRUE;
6798 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6799 mono_loader_unlock ();
6803 case CMD_VM_SET_KEEPALIVE: {
6804 int timeout = decode_int (p, &p, end);
6805 agent_config.keepalive = timeout;
6807 #ifndef DISABLE_SOCKET_TRANSPORT
6814 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6815 GHashTableIter iter, kiter;
6820 char *fname, *basename;
6821 gboolean ignore_case;
6822 GSList *class_list, *l;
6823 GPtrArray *res_classes, *res_domains;
6825 fname = decode_string (p, &p, end);
6826 ignore_case = decode_byte (p, &p, end);
6828 basename = g_path_get_basename (fname);
6830 res_classes = g_ptr_array_new ();
6831 res_domains = g_ptr_array_new ();
6833 mono_loader_lock ();
6834 g_hash_table_iter_init (&iter, domains);
6835 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6836 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6838 /* Update 'source_file_to_class' cache */
6839 g_hash_table_iter_init (&kiter, info->loaded_classes);
6840 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6841 if (!g_hash_table_lookup (info->source_files, klass)) {
6842 files = get_source_files_for_type (klass);
6843 g_hash_table_insert (info->source_files, klass, files);
6845 for (i = 0; i < files->len; ++i) {
6846 char *s = g_ptr_array_index (files, i);
6847 char *s2 = g_path_get_basename (s);
6850 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6852 class_list = g_slist_prepend (class_list, klass);
6853 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6855 class_list = g_slist_prepend (class_list, klass);
6856 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6859 /* The _ignorecase hash contains the lowercase path */
6860 s3 = strdup_tolower (s2);
6861 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6863 class_list = g_slist_prepend (class_list, klass);
6864 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6866 class_list = g_slist_prepend (class_list, klass);
6867 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6879 s = strdup_tolower (basename);
6880 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6883 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6886 for (l = class_list; l; l = l->next) {
6889 g_ptr_array_add (res_classes, klass);
6890 g_ptr_array_add (res_domains, domain);
6893 mono_loader_unlock ();
6898 buffer_add_int (buf, res_classes->len);
6899 for (i = 0; i < res_classes->len; ++i)
6900 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6901 g_ptr_array_free (res_classes, TRUE);
6902 g_ptr_array_free (res_domains, TRUE);
6905 case CMD_VM_GET_TYPES: {
6906 GHashTableIter iter;
6910 gboolean ignore_case;
6911 GPtrArray *res_classes, *res_domains;
6912 MonoTypeNameParse info;
6914 name = decode_string (p, &p, end);
6915 ignore_case = decode_byte (p, &p, end);
6917 if (!mono_reflection_parse_type (name, &info)) {
6919 mono_reflection_free_type_info (&info);
6920 return ERR_INVALID_ARGUMENT;
6923 res_classes = g_ptr_array_new ();
6924 res_domains = g_ptr_array_new ();
6926 mono_loader_lock ();
6927 g_hash_table_iter_init (&iter, domains);
6928 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6930 gboolean type_resolve;
6934 mono_domain_assemblies_lock (domain);
6935 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6939 type_resolve = TRUE;
6940 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6942 g_ptr_array_add (res_classes, mono_type_get_class (t));
6943 g_ptr_array_add (res_domains, domain);
6947 mono_domain_assemblies_unlock (domain);
6949 mono_loader_unlock ();
6952 mono_reflection_free_type_info (&info);
6954 buffer_add_int (buf, res_classes->len);
6955 for (i = 0; i < res_classes->len; ++i)
6956 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6957 g_ptr_array_free (res_classes, TRUE);
6958 g_ptr_array_free (res_domains, TRUE);
6963 return ERR_NOT_IMPLEMENTED;
6970 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6976 case CMD_EVENT_REQUEST_SET: {
6978 int i, event_kind, suspend_policy, nmodifiers, mod;
6981 MonoThread *step_thread;
6982 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6986 event_kind = decode_byte (p, &p, end);
6987 suspend_policy = decode_byte (p, &p, end);
6988 nmodifiers = decode_byte (p, &p, end);
6990 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6991 req->id = InterlockedIncrement (&event_request_id);
6992 req->event_kind = event_kind;
6993 req->suspend_policy = suspend_policy;
6994 req->nmodifiers = nmodifiers;
6997 for (i = 0; i < nmodifiers; ++i) {
6998 mod = decode_byte (p, &p, end);
7000 req->modifiers [i].kind = mod;
7001 if (mod == MOD_KIND_COUNT) {
7002 req->modifiers [i].data.count = decode_int (p, &p, end);
7003 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7004 method = decode_methodid (p, &p, end, &domain, &err);
7007 location = decode_long (p, &p, end);
7008 } else if (mod == MOD_KIND_STEP) {
7009 step_thread_id = decode_id (p, &p, end);
7010 size = decode_int (p, &p, end);
7011 depth = decode_int (p, &p, end);
7012 if (CHECK_PROTOCOL_VERSION (2, 16))
7013 filter = decode_int (p, &p, end);
7014 req->modifiers [i].data.filter = filter;
7015 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7016 /* Treat STEP_THOUGH the same as HIDDEN */
7017 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7018 } else if (mod == MOD_KIND_THREAD_ONLY) {
7019 int id = decode_id (p, &p, end);
7021 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7026 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7027 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7031 req->modifiers [i].caught = decode_byte (p, &p, end);
7032 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7033 if (CHECK_PROTOCOL_VERSION (2, 25))
7034 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7036 req->modifiers [i].subclasses = TRUE;
7037 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : "", req->modifiers [i].subclasses ? ", include-subclasses" : ""));
7039 req->modifiers [i].data.exc_class = exc_class;
7041 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7043 return ERR_INVALID_ARGUMENT;
7046 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7047 int n = decode_int (p, &p, end);
7050 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7051 for (j = 0; j < n; ++j) {
7052 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7054 g_free (req->modifiers [i].data.assemblies);
7058 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7059 int n = decode_int (p, &p, end);
7062 modifier = &req->modifiers [i];
7063 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7064 for (j = 0; j < n; ++j) {
7065 char *s = decode_string (p, &p, end);
7069 s2 = strdup_tolower (s);
7070 g_hash_table_insert (modifier->data.source_files, s2, s2);
7074 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7075 int n = decode_int (p, &p, end);
7078 modifier = &req->modifiers [i];
7079 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7080 for (j = 0; j < n; ++j) {
7081 char *s = decode_string (p, &p, end);
7084 g_hash_table_insert (modifier->data.type_names, s, s);
7088 return ERR_NOT_IMPLEMENTED;
7092 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7095 req->info = set_breakpoint (method, location, req, &error);
7096 if (!mono_error_ok (&error)) {
7098 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7099 mono_error_cleanup (&error);
7100 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7102 } else if (req->event_kind == EVENT_KIND_STEP) {
7103 g_assert (step_thread_id);
7105 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7111 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7116 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7117 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7118 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7119 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7120 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7121 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7123 if (req->nmodifiers) {
7125 return ERR_NOT_IMPLEMENTED;
7129 mono_loader_lock ();
7130 g_ptr_array_add (event_requests, req);
7132 if (agent_config.defer) {
7133 /* Transmit cached data to the client on receipt of the event request */
7134 switch (req->event_kind) {
7135 case EVENT_KIND_APPDOMAIN_CREATE:
7136 /* Emit load events for currently loaded domains */
7137 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7139 case EVENT_KIND_ASSEMBLY_LOAD:
7140 /* Emit load events for currently loaded assemblies */
7141 mono_assembly_foreach (emit_assembly_load, NULL);
7143 case EVENT_KIND_THREAD_START:
7144 /* Emit start events for currently started threads */
7145 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7147 case EVENT_KIND_TYPE_LOAD:
7148 /* Emit type load events for currently loaded types */
7149 mono_domain_foreach (send_types_for_domain, NULL);
7155 mono_loader_unlock ();
7157 buffer_add_int (buf, req->id);
7160 case CMD_EVENT_REQUEST_CLEAR: {
7161 int etype = decode_byte (p, &p, end);
7162 int req_id = decode_int (p, &p, end);
7164 // FIXME: Make a faster mapping from req_id to request
7165 mono_loader_lock ();
7166 clear_event_request (req_id, etype);
7167 mono_loader_unlock ();
7170 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7173 mono_loader_lock ();
7175 while (i < event_requests->len) {
7176 EventRequest *req = g_ptr_array_index (event_requests, i);
7178 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7179 clear_breakpoint (req->info);
7181 g_ptr_array_remove_index_fast (event_requests, i);
7187 mono_loader_unlock ();
7191 return ERR_NOT_IMPLEMENTED;
7198 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7204 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7205 buffer_add_domainid (buf, mono_get_root_domain ());
7208 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7209 domain = decode_domainid (p, &p, end, NULL, &err);
7212 buffer_add_string (buf, domain->friendly_name);
7215 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7220 domain = decode_domainid (p, &p, end, NULL, &err);
7223 mono_loader_lock ();
7225 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7228 buffer_add_int (buf, count);
7229 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7231 buffer_add_assemblyid (buf, domain, ass);
7233 mono_loader_unlock ();
7236 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7237 domain = decode_domainid (p, &p, end, NULL, &err);
7241 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7244 case CMD_APPDOMAIN_GET_CORLIB: {
7245 domain = decode_domainid (p, &p, end, NULL, &err);
7249 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7252 case CMD_APPDOMAIN_CREATE_STRING: {
7256 domain = decode_domainid (p, &p, end, NULL, &err);
7259 s = decode_string (p, &p, end);
7261 o = mono_string_new (domain, s);
7262 buffer_add_objid (buf, (MonoObject*)o);
7265 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7267 MonoDomain *domain2;
7270 domain = decode_domainid (p, &p, end, NULL, &err);
7273 klass = decode_typeid (p, &p, end, &domain2, &err);
7278 g_assert (domain == domain2);
7280 o = mono_object_new (domain, klass);
7282 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7286 buffer_add_objid (buf, o);
7290 return ERR_NOT_IMPLEMENTED;
7297 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7303 ass = decode_assemblyid (p, &p, end, &domain, &err);
7308 case CMD_ASSEMBLY_GET_LOCATION: {
7309 buffer_add_string (buf, mono_image_get_filename (ass->image));
7312 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7316 if (ass->image->dynamic) {
7317 buffer_add_id (buf, 0);
7319 token = mono_image_get_entry_point (ass->image);
7321 buffer_add_id (buf, 0);
7323 m = mono_get_method (ass->image, token, NULL);
7324 buffer_add_methodid (buf, domain, m);
7329 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7330 buffer_add_moduleid (buf, domain, ass->image);
7333 case CMD_ASSEMBLY_GET_OBJECT: {
7334 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7335 buffer_add_objid (buf, o);
7338 case CMD_ASSEMBLY_GET_TYPE: {
7339 char *s = decode_string (p, &p, end);
7340 gboolean ignorecase = decode_byte (p, &p, end);
7341 MonoTypeNameParse info;
7343 gboolean type_resolve, res;
7344 MonoDomain *d = mono_domain_get ();
7346 /* This is needed to be able to find referenced assemblies */
7347 res = mono_domain_set (domain, FALSE);
7350 if (!mono_reflection_parse_type (s, &info)) {
7353 if (info.assembly.name)
7355 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7357 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7358 mono_reflection_free_type_info (&info);
7361 mono_domain_set (d, TRUE);
7365 case CMD_ASSEMBLY_GET_NAME: {
7367 MonoAssembly *mass = ass;
7369 name = g_strdup_printf (
7370 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7372 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7373 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7374 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7375 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7377 buffer_add_string (buf, name);
7382 return ERR_NOT_IMPLEMENTED;
7389 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7395 case CMD_MODULE_GET_INFO: {
7396 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7399 basename = g_path_get_basename (image->name);
7400 buffer_add_string (buf, basename); // name
7401 buffer_add_string (buf, image->module_name); // scopename
7402 buffer_add_string (buf, image->name); // fqname
7403 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7404 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7409 return ERR_NOT_IMPLEMENTED;
7416 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7422 case CMD_FIELD_GET_INFO: {
7423 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7425 buffer_add_string (buf, f->name);
7426 buffer_add_typeid (buf, domain, f->parent);
7427 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7428 buffer_add_int (buf, f->type->attrs);
7432 return ERR_NOT_IMPLEMENTED;
7439 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7441 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7442 /* Special case these so the client doesn't have to handle Type objects */
7444 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7445 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7446 } else if (MONO_TYPE_IS_REFERENCE (t))
7447 buffer_add_value (buf, t, &val, domain);
7449 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7453 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7459 buffer_add_int (buf, 0);
7463 for (i = 0; i < cinfo->num_attrs; ++i) {
7464 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7467 buffer_add_int (buf, nattrs);
7469 for (i = 0; i < cinfo->num_attrs; ++i) {
7470 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7471 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7472 MonoArray *typed_args, *named_args;
7474 CattrNamedArg *arginfo = NULL;
7477 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7478 g_assert (mono_error_ok (&error));
7480 buffer_add_methodid (buf, domain, attr->ctor);
7484 buffer_add_int (buf, mono_array_length (typed_args));
7485 for (j = 0; j < mono_array_length (typed_args); ++j) {
7486 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7488 t = mono_method_signature (attr->ctor)->params [j];
7490 buffer_add_cattr_arg (buf, t, domain, val);
7493 buffer_add_int (buf, 0);
7498 buffer_add_int (buf, mono_array_length (named_args));
7500 for (j = 0; j < mono_array_length (named_args); ++j) {
7501 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7503 if (arginfo [j].prop) {
7504 buffer_add_byte (buf, 0x54);
7505 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7506 } else if (arginfo [j].field) {
7507 buffer_add_byte (buf, 0x53);
7508 buffer_add_fieldid (buf, domain, arginfo [j].field);
7510 g_assert_not_reached ();
7513 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7516 buffer_add_int (buf, 0);
7523 /* FIXME: Code duplication with icall.c */
7525 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7530 mono_class_setup_interfaces (klass, error);
7531 if (!mono_error_ok (error))
7534 for (i = 0; i < klass->interface_count; i++) {
7535 ic = klass->interfaces [i];
7536 g_hash_table_insert (ifaces, ic, ic);
7538 collect_interfaces (ic, ifaces, error);
7539 if (!mono_error_ok (error))
7545 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7555 case CMD_TYPE_GET_INFO: {
7556 buffer_add_string (buf, klass->name_space);
7557 buffer_add_string (buf, klass->name);
7559 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7560 buffer_add_string (buf, name);
7562 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7563 buffer_add_moduleid (buf, domain, klass->image);
7564 buffer_add_typeid (buf, domain, klass->parent);
7565 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7566 buffer_add_typeid (buf, domain, klass->element_class);
7568 buffer_add_id (buf, 0);
7569 buffer_add_int (buf, klass->type_token);
7570 buffer_add_byte (buf, klass->rank);
7571 buffer_add_int (buf, klass->flags);
7573 type = &klass->byval_arg;
7574 // FIXME: Can't decide whenever a class represents a byref type
7577 if (type->type == MONO_TYPE_PTR)
7579 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7581 if (type->type == MONO_TYPE_VALUETYPE)
7583 if (klass->enumtype)
7585 if (klass->generic_container)
7587 if (klass->generic_container || klass->generic_class)
7589 buffer_add_byte (buf, b);
7592 while ((nested = mono_class_get_nested_types (klass, &iter)))
7594 buffer_add_int (buf, nnested);
7596 while ((nested = mono_class_get_nested_types (klass, &iter)))
7597 buffer_add_typeid (buf, domain, nested);
7598 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7599 if (klass->generic_container)
7600 buffer_add_typeid (buf, domain, klass);
7601 else if (klass->generic_class)
7602 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7604 buffer_add_id (buf, 0);
7606 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7609 if (klass->generic_class) {
7610 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7612 count = inst->type_argc;
7613 buffer_add_int (buf, count);
7614 for (i = 0; i < count; i++)
7615 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7616 } else if (klass->generic_container) {
7617 MonoGenericContainer *container = klass->generic_container;
7620 count = container->type_argc;
7621 buffer_add_int (buf, count);
7622 for (i = 0; i < count; i++) {
7623 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7624 buffer_add_typeid (buf, domain, pklass);
7627 buffer_add_int (buf, 0);
7632 case CMD_TYPE_GET_METHODS: {
7635 gpointer iter = NULL;
7638 mono_class_setup_methods (klass);
7640 nmethods = mono_class_num_methods (klass);
7642 buffer_add_int (buf, nmethods);
7644 while ((m = mono_class_get_methods (klass, &iter))) {
7645 buffer_add_methodid (buf, domain, m);
7648 g_assert (i == nmethods);
7651 case CMD_TYPE_GET_FIELDS: {
7654 gpointer iter = NULL;
7657 nfields = mono_class_num_fields (klass);
7659 buffer_add_int (buf, nfields);
7661 while ((f = mono_class_get_fields (klass, &iter))) {
7662 buffer_add_fieldid (buf, domain, f);
7663 buffer_add_string (buf, f->name);
7664 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7665 buffer_add_int (buf, f->type->attrs);
7668 g_assert (i == nfields);
7671 case CMD_TYPE_GET_PROPERTIES: {
7674 gpointer iter = NULL;
7677 nprops = mono_class_num_properties (klass);
7679 buffer_add_int (buf, nprops);
7681 while ((p = mono_class_get_properties (klass, &iter))) {
7682 buffer_add_propertyid (buf, domain, p);
7683 buffer_add_string (buf, p->name);
7684 buffer_add_methodid (buf, domain, p->get);
7685 buffer_add_methodid (buf, domain, p->set);
7686 buffer_add_int (buf, p->attrs);
7689 g_assert (i == nprops);
7692 case CMD_TYPE_GET_CATTRS: {
7693 MonoClass *attr_klass;
7694 MonoCustomAttrInfo *cinfo;
7696 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7697 /* attr_klass can be NULL */
7701 cinfo = mono_custom_attrs_from_class (klass);
7703 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7706 case CMD_TYPE_GET_FIELD_CATTRS: {
7707 MonoClass *attr_klass;
7708 MonoCustomAttrInfo *cinfo;
7709 MonoClassField *field;
7711 field = decode_fieldid (p, &p, end, NULL, &err);
7714 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7718 cinfo = mono_custom_attrs_from_field (klass, field);
7720 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7723 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7724 MonoClass *attr_klass;
7725 MonoCustomAttrInfo *cinfo;
7728 prop = decode_propertyid (p, &p, end, NULL, &err);
7731 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7735 cinfo = mono_custom_attrs_from_property (klass, prop);
7737 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7740 case CMD_TYPE_GET_VALUES:
7741 case CMD_TYPE_GET_VALUES_2: {
7748 MonoThread *thread_obj;
7749 MonoInternalThread *thread = NULL;
7750 guint32 special_static_type;
7752 if (command == CMD_TYPE_GET_VALUES_2) {
7753 int objid = decode_objid (p, &p, end);
7756 err = get_object (objid, (MonoObject**)&thread_obj);
7760 thread = THREAD_TO_INTERNAL (thread_obj);
7763 len = decode_int (p, &p, end);
7764 for (i = 0; i < len; ++i) {
7765 f = decode_fieldid (p, &p, end, NULL, &err);
7769 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7770 return ERR_INVALID_FIELDID;
7771 special_static_type = mono_class_field_get_special_static_type (f);
7772 if (special_static_type != SPECIAL_STATIC_NONE) {
7773 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7774 return ERR_INVALID_FIELDID;
7777 /* Check that the field belongs to the object */
7779 for (k = klass; k; k = k->parent) {
7780 if (k == f->parent) {
7786 return ERR_INVALID_FIELDID;
7788 vtable = mono_class_vtable (domain, f->parent);
7789 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7790 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7791 buffer_add_value (buf, f->type, val, domain);
7796 case CMD_TYPE_SET_VALUES: {
7804 len = decode_int (p, &p, end);
7805 for (i = 0; i < len; ++i) {
7806 f = decode_fieldid (p, &p, end, NULL, &err);
7810 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7811 return ERR_INVALID_FIELDID;
7812 if (mono_class_field_is_special_static (f))
7813 return ERR_INVALID_FIELDID;
7815 /* Check that the field belongs to the object */
7817 for (k = klass; k; k = k->parent) {
7818 if (k == f->parent) {
7824 return ERR_INVALID_FIELDID;
7826 // FIXME: Check for literal/const
7828 vtable = mono_class_vtable (domain, f->parent);
7829 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7830 err = decode_value (f->type, domain, val, p, &p, end);
7835 if (MONO_TYPE_IS_REFERENCE (f->type))
7836 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7838 mono_field_static_set_value (vtable, f, val);
7843 case CMD_TYPE_GET_OBJECT: {
7844 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7845 buffer_add_objid (buf, o);
7848 case CMD_TYPE_GET_SOURCE_FILES:
7849 case CMD_TYPE_GET_SOURCE_FILES_2: {
7850 char *source_file, *base;
7854 files = get_source_files_for_type (klass);
7856 buffer_add_int (buf, files->len);
7857 for (i = 0; i < files->len; ++i) {
7858 source_file = g_ptr_array_index (files, i);
7859 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7860 buffer_add_string (buf, source_file);
7862 base = g_path_get_basename (source_file);
7863 buffer_add_string (buf, base);
7866 g_free (source_file);
7868 g_ptr_array_free (files, TRUE);
7871 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7872 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7876 if (mono_class_is_assignable_from (klass, oklass))
7877 buffer_add_byte (buf, 1);
7879 buffer_add_byte (buf, 0);
7882 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7883 char *name = decode_string (p, &p, end);
7884 int i, flags = decode_int (p, &p, end);
7885 MonoException *ex = NULL;
7886 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7889 return ERR_LOADER_ERROR;
7890 buffer_add_int (buf, array->len);
7891 for (i = 0; i < array->len; ++i) {
7892 MonoMethod *method = g_ptr_array_index (array, i);
7893 buffer_add_methodid (buf, domain, method);
7896 g_ptr_array_free (array, TRUE);
7900 case CMD_TYPE_GET_INTERFACES: {
7902 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7904 MonoClass *tclass, *iface;
7905 GHashTableIter iter;
7909 for (parent = tclass; parent; parent = parent->parent) {
7910 mono_class_setup_interfaces (parent, &error);
7911 if (!mono_error_ok (&error))
7912 return ERR_LOADER_ERROR;
7913 collect_interfaces (parent, iface_hash, &error);
7914 if (!mono_error_ok (&error))
7915 return ERR_LOADER_ERROR;
7918 buffer_add_int (buf, g_hash_table_size (iface_hash));
7920 g_hash_table_iter_init (&iter, iface_hash);
7921 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7922 buffer_add_typeid (buf, domain, iface);
7923 g_hash_table_destroy (iface_hash);
7926 case CMD_TYPE_GET_INTERFACE_MAP: {
7927 int tindex, ioffset;
7928 gboolean variance_used;
7930 int len, nmethods, i;
7934 len = decode_int (p, &p, end);
7935 mono_class_setup_vtable (klass);
7937 for (tindex = 0; tindex < len; ++tindex) {
7938 iclass = decode_typeid (p, &p, end, NULL, &err);
7942 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7944 return ERR_INVALID_ARGUMENT;
7946 nmethods = mono_class_num_methods (iclass);
7947 buffer_add_int (buf, nmethods);
7950 while ((method = mono_class_get_methods (iclass, &iter))) {
7951 buffer_add_methodid (buf, domain, method);
7953 for (i = 0; i < nmethods; ++i)
7954 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7958 case CMD_TYPE_IS_INITIALIZED: {
7959 MonoVTable *vtable = mono_class_vtable (domain, klass);
7962 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7964 buffer_add_int (buf, 0);
7968 return ERR_NOT_IMPLEMENTED;
7975 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7978 MonoDomain *old_domain;
7982 klass = decode_typeid (p, &p, end, &domain, &err);
7986 old_domain = mono_domain_get ();
7988 mono_domain_set (domain, TRUE);
7990 err = type_commands_internal (command, klass, domain, p, end, buf);
7992 mono_domain_set (old_domain, TRUE);
7998 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8000 MonoMethodHeader *header;
8004 case CMD_METHOD_GET_NAME: {
8005 buffer_add_string (buf, method->name);
8008 case CMD_METHOD_GET_DECLARING_TYPE: {
8009 buffer_add_typeid (buf, domain, method->klass);
8012 case CMD_METHOD_GET_DEBUG_INFO: {
8013 MonoDebugMethodInfo *minfo;
8015 int i, j, n_il_offsets;
8018 int *column_numbers;
8020 GPtrArray *source_file_list;
8022 header = mono_method_get_header (method);
8024 buffer_add_int (buf, 0);
8025 buffer_add_string (buf, "");
8026 buffer_add_int (buf, 0);
8030 minfo = mono_debug_lookup_method (method);
8032 buffer_add_int (buf, header->code_size);
8033 buffer_add_string (buf, "");
8034 buffer_add_int (buf, 0);
8035 mono_metadata_free_mh (header);
8039 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
8040 buffer_add_int (buf, header->code_size);
8041 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8042 buffer_add_int (buf, source_file_list->len);
8043 for (i = 0; i < source_file_list->len; ++i) {
8044 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8045 buffer_add_string (buf, sinfo->source_file);
8046 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8047 for (j = 0; j < 16; ++j)
8048 buffer_add_byte (buf, sinfo->hash [j]);
8052 buffer_add_string (buf, source_file);
8054 buffer_add_int (buf, n_il_offsets);
8055 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8056 for (i = 0; i < n_il_offsets; ++i) {
8057 const char *srcfile = "";
8059 if (source_files [i] != -1) {
8060 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8061 srcfile = sinfo->source_file;
8063 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8064 buffer_add_int (buf, il_offsets [i]);
8065 buffer_add_int (buf, line_numbers [i]);
8066 if (CHECK_PROTOCOL_VERSION (2, 13))
8067 buffer_add_int (buf, source_files [i]);
8068 if (CHECK_PROTOCOL_VERSION (2, 19))
8069 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8071 g_free (source_file);
8072 g_free (il_offsets);
8073 g_free (line_numbers);
8074 g_free (source_files);
8075 g_ptr_array_free (source_file_list, TRUE);
8076 mono_metadata_free_mh (header);
8079 case CMD_METHOD_GET_PARAM_INFO: {
8080 MonoMethodSignature *sig = mono_method_signature (method);
8084 /* FIXME: mono_class_from_mono_type () and byrefs */
8086 /* FIXME: Use a smaller encoding */
8087 buffer_add_int (buf, sig->call_convention);
8088 buffer_add_int (buf, sig->param_count);
8089 buffer_add_int (buf, sig->generic_param_count);
8090 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8091 for (i = 0; i < sig->param_count; ++i) {
8093 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8096 /* Emit parameter names */
8097 names = g_new (char *, sig->param_count);
8098 mono_method_get_param_names (method, (const char **) names);
8099 for (i = 0; i < sig->param_count; ++i)
8100 buffer_add_string (buf, names [i]);
8105 case CMD_METHOD_GET_LOCALS_INFO: {
8106 int i, j, num_locals;
8107 MonoDebugLocalsInfo *locals;
8109 header = mono_method_get_header (method);
8111 return ERR_INVALID_ARGUMENT;
8113 buffer_add_int (buf, header->num_locals);
8116 for (i = 0; i < header->num_locals; ++i)
8117 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8120 locals = mono_debug_lookup_locals (method);
8122 num_locals = locals->num_locals;
8125 for (i = 0; i < header->num_locals; ++i) {
8126 for (j = 0; j < num_locals; ++j)
8127 if (locals->locals [j].index == i)
8130 buffer_add_string (buf, locals->locals [j].name);
8132 buffer_add_string (buf, "");
8136 for (i = 0; i < header->num_locals; ++i) {
8137 for (j = 0; j < num_locals; ++j)
8138 if (locals->locals [j].index == i)
8140 if (j < num_locals && locals->locals [j].block) {
8141 buffer_add_int (buf, locals->locals [j].block->start_offset);
8142 buffer_add_int (buf, locals->locals [j].block->end_offset);
8144 buffer_add_int (buf, 0);
8145 buffer_add_int (buf, header->code_size);
8148 mono_metadata_free_mh (header);
8151 mono_debug_symfile_free_locals (locals);
8155 case CMD_METHOD_GET_INFO:
8156 buffer_add_int (buf, method->flags);
8157 buffer_add_int (buf, method->iflags);
8158 buffer_add_int (buf, method->token);
8159 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8161 if (method->is_generic)
8163 if (mono_method_signature (method)->generic_param_count)
8165 buffer_add_byte (buf, attrs);
8166 if (method->is_generic || method->is_inflated) {
8169 if (method->is_generic) {
8172 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8174 result = imethod->declaring;
8175 if (imethod->context.class_inst) {
8176 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8177 /*Generic methods gets the context of the GTD.*/
8178 if (mono_class_get_context (klass))
8179 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8183 buffer_add_methodid (buf, domain, result);
8185 buffer_add_id (buf, 0);
8187 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8188 if (mono_method_signature (method)->generic_param_count) {
8191 if (method->is_inflated) {
8192 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8194 count = inst->type_argc;
8195 buffer_add_int (buf, count);
8197 for (i = 0; i < count; i++)
8198 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8200 buffer_add_int (buf, 0);
8202 } else if (method->is_generic) {
8203 MonoGenericContainer *container = mono_method_get_generic_container (method);
8205 count = mono_method_signature (method)->generic_param_count;
8206 buffer_add_int (buf, count);
8207 for (i = 0; i < count; i++) {
8208 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8209 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8210 buffer_add_typeid (buf, domain, pklass);
8213 buffer_add_int (buf, 0);
8216 buffer_add_int (buf, 0);
8221 case CMD_METHOD_GET_BODY: {
8224 header = mono_method_get_header (method);
8226 buffer_add_int (buf, 0);
8228 if (CHECK_PROTOCOL_VERSION (2, 18))
8229 buffer_add_int (buf, 0);
8231 buffer_add_int (buf, header->code_size);
8232 for (i = 0; i < header->code_size; ++i)
8233 buffer_add_byte (buf, header->code [i]);
8235 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8236 buffer_add_int (buf, header->num_clauses);
8237 for (i = 0; i < header->num_clauses; ++i) {
8238 MonoExceptionClause *clause = &header->clauses [i];
8240 buffer_add_int (buf, clause->flags);
8241 buffer_add_int (buf, clause->try_offset);
8242 buffer_add_int (buf, clause->try_len);
8243 buffer_add_int (buf, clause->handler_offset);
8244 buffer_add_int (buf, clause->handler_len);
8245 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8246 buffer_add_typeid (buf, domain, clause->data.catch_class);
8247 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8248 buffer_add_int (buf, clause->data.filter_offset);
8252 mono_metadata_free_mh (header);
8257 case CMD_METHOD_RESOLVE_TOKEN: {
8258 guint32 token = decode_int (p, &p, end);
8261 switch (mono_metadata_token_code (token)) {
8262 case MONO_TOKEN_STRING: {
8266 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8269 s2 = mono_string_to_utf8 (s);
8271 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8272 buffer_add_string (buf, s2);
8278 MonoClass *handle_class;
8280 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8281 val = mono_method_get_wrapper_data (method, token);
8282 handle_class = mono_method_get_wrapper_data (method, token + 1);
8284 if (handle_class == NULL) {
8285 // Can't figure out the token type
8286 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8290 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8294 if (handle_class == mono_defaults.typehandle_class) {
8295 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8296 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8297 buffer_add_typeid (buf, domain, (MonoClass *) val);
8299 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8300 } else if (handle_class == mono_defaults.fieldhandle_class) {
8301 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8302 buffer_add_fieldid (buf, domain, val);
8303 } else if (handle_class == mono_defaults.methodhandle_class) {
8304 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8305 buffer_add_methodid (buf, domain, val);
8306 } else if (handle_class == mono_defaults.string_class) {
8309 s = mono_string_to_utf8 (val);
8310 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8311 buffer_add_string (buf, s);
8314 g_assert_not_reached ();
8321 case CMD_METHOD_GET_CATTRS: {
8322 MonoClass *attr_klass;
8323 MonoCustomAttrInfo *cinfo;
8325 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8326 /* attr_klass can be NULL */
8330 cinfo = mono_custom_attrs_from_method (method);
8332 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8335 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8336 MonoType **type_argv;
8340 MonoGenericInst *ginst;
8341 MonoGenericContext tmp_context;
8342 MonoMethod *inflated;
8344 type_argc = decode_int (p, &p, end);
8345 type_argv = g_new0 (MonoType*, type_argc);
8346 for (i = 0; i < type_argc; ++i) {
8347 klass = decode_typeid (p, &p, end, &d, &err);
8354 return ERR_INVALID_ARGUMENT;
8356 type_argv [i] = &klass->byval_arg;
8358 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8360 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8361 tmp_context.method_inst = ginst;
8363 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8364 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8365 return ERR_INVALID_ARGUMENT;
8366 buffer_add_methodid (buf, domain, inflated);
8370 return ERR_NOT_IMPLEMENTED;
8377 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8380 MonoDomain *old_domain;
8384 method = decode_methodid (p, &p, end, &domain, &err);
8388 old_domain = mono_domain_get ();
8390 mono_domain_set (domain, TRUE);
8392 err = method_commands_internal (command, method, domain, p, end, buf);
8394 mono_domain_set (old_domain, TRUE);
8400 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8402 int objid = decode_objid (p, &p, end);
8404 MonoThread *thread_obj;
8405 MonoInternalThread *thread;
8407 err = get_object (objid, (MonoObject**)&thread_obj);
8411 thread = THREAD_TO_INTERNAL (thread_obj);
8414 case CMD_THREAD_GET_NAME: {
8416 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8419 buffer_add_int (buf, 0);
8424 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8426 buffer_add_int (buf, len);
8427 buffer_add_data (buf, (guint8*)name, len);
8432 case CMD_THREAD_GET_FRAME_INFO: {
8433 DebuggerTlsData *tls;
8434 int i, start_frame, length;
8436 // Wait for suspending if it already started
8437 // FIXME: Races with suspend_count
8438 while (!is_suspended ()) {
8440 wait_for_suspend ();
8444 wait_for_suspend ();
8445 if (!is_suspended ())
8446 return ERR_NOT_SUSPENDED;
8449 start_frame = decode_int (p, &p, end);
8450 length = decode_int (p, &p, end);
8452 if (start_frame != 0 || length != -1)
8453 return ERR_NOT_IMPLEMENTED;
8455 mono_loader_lock ();
8456 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8457 mono_loader_unlock ();
8460 compute_frame_info (thread, tls);
8462 buffer_add_int (buf, tls->frame_count);
8463 for (i = 0; i < tls->frame_count; ++i) {
8464 buffer_add_int (buf, tls->frames [i]->id);
8465 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8466 buffer_add_int (buf, tls->frames [i]->il_offset);
8468 * Instead of passing the frame type directly to the client, we associate
8469 * it with the previous frame using a set of flags. This avoids lots of
8470 * conditional code in the client, since a frame whose type isn't
8471 * FRAME_TYPE_MANAGED has no method, location, etc.
8473 buffer_add_byte (buf, tls->frames [i]->flags);
8478 case CMD_THREAD_GET_STATE:
8479 buffer_add_int (buf, thread->state);
8481 case CMD_THREAD_GET_INFO:
8482 buffer_add_byte (buf, thread->threadpool_thread);
8484 case CMD_THREAD_GET_ID:
8485 buffer_add_long (buf, (guint64)(gsize)thread);
8487 case CMD_THREAD_GET_TID:
8488 buffer_add_long (buf, (guint64)thread->tid);
8490 case CMD_THREAD_SET_IP: {
8491 DebuggerTlsData *tls;
8494 MonoSeqPointInfo *seq_points;
8495 SeqPoint *sp = NULL;
8499 method = decode_methodid (p, &p, end, &domain, &err);
8502 il_offset = decode_long (p, &p, end);
8504 while (!is_suspended ()) {
8506 wait_for_suspend ();
8509 mono_loader_lock ();
8510 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8511 mono_loader_unlock ();
8514 compute_frame_info (thread, tls);
8515 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8516 return ERR_INVALID_ARGUMENT;
8518 seq_points = get_seq_points (domain, method);
8519 g_assert (seq_points);
8521 for (i = 0; i < seq_points->len; ++i) {
8522 sp = &seq_points->seq_points [i];
8524 if (sp->il_offset == il_offset)
8527 if (i == seq_points->len)
8528 return ERR_INVALID_ARGUMENT;
8530 // FIXME: Check that the ip change is safe
8532 DEBUG (1, fprintf (log_file, "[dbg] Setting IP to %s:0x%0x(0x%0x)\n", tls->frames [0]->actual_method->name, (int)sp->il_offset, (int)sp->native_offset));
8533 MONO_CONTEXT_SET_IP (&tls->restore_ctx, (guint8*)tls->frames [0]->ji->code_start + sp->native_offset);
8537 return ERR_NOT_IMPLEMENTED;
8544 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8548 MonoThread *thread_obj;
8549 MonoInternalThread *thread;
8550 int pos, i, len, frame_idx;
8551 DebuggerTlsData *tls;
8553 MonoDebugMethodJitInfo *jit;
8554 MonoDebugVarInfo *var;
8555 MonoMethodSignature *sig;
8557 MonoMethodHeader *header;
8559 objid = decode_objid (p, &p, end);
8560 err = get_object (objid, (MonoObject**)&thread_obj);
8564 thread = THREAD_TO_INTERNAL (thread_obj);
8566 id = decode_id (p, &p, end);
8568 mono_loader_lock ();
8569 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8570 mono_loader_unlock ();
8573 for (i = 0; i < tls->frame_count; ++i) {
8574 if (tls->frames [i]->id == id)
8577 if (i == tls->frame_count)
8578 return ERR_INVALID_FRAMEID;
8581 frame = tls->frames [frame_idx];
8583 if (!frame->has_ctx)
8584 return ERR_ABSENT_INFORMATION;
8587 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8588 if (!frame->jit && frame->api_method->is_inflated)
8589 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8593 /* This could happen for aot images with no jit debug info */
8594 s = mono_method_full_name (frame->api_method, TRUE);
8595 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8597 return ERR_ABSENT_INFORMATION;
8602 sig = mono_method_signature (frame->actual_method);
8604 if (!get_seq_points (frame->domain, frame->actual_method))
8606 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8608 return ERR_ABSENT_INFORMATION;
8611 case CMD_STACK_FRAME_GET_VALUES: {
8612 len = decode_int (p, &p, end);
8613 header = mono_method_get_header (frame->actual_method);
8615 for (i = 0; i < len; ++i) {
8616 pos = decode_int (p, &p, end);
8621 g_assert (pos >= 0 && pos < jit->num_params);
8623 var = &jit->params [pos];
8625 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8627 g_assert (pos >= 0 && pos < jit->num_locals);
8629 var = &jit->locals [pos];
8631 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8634 mono_metadata_free_mh (header);
8637 case CMD_STACK_FRAME_GET_THIS: {
8638 if (frame->api_method->klass->valuetype) {
8639 if (!sig->hasthis) {
8640 MonoObject *p = NULL;
8641 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8643 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8646 if (!sig->hasthis) {
8647 MonoObject *p = NULL;
8648 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8650 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8655 case CMD_STACK_FRAME_SET_VALUES: {
8658 MonoDebugVarInfo *var;
8660 len = decode_int (p, &p, end);
8661 header = mono_method_get_header (frame->actual_method);
8663 for (i = 0; i < len; ++i) {
8664 pos = decode_int (p, &p, end);
8669 g_assert (pos >= 0 && pos < jit->num_params);
8671 t = sig->params [pos];
8672 var = &jit->params [pos];
8674 g_assert (pos >= 0 && pos < jit->num_locals);
8676 t = header->locals [pos];
8677 var = &jit->locals [pos];
8680 if (MONO_TYPE_IS_REFERENCE (t))
8681 val_buf = g_alloca (sizeof (MonoObject*));
8683 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8684 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8688 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8690 mono_metadata_free_mh (header);
8694 return ERR_NOT_IMPLEMENTED;
8701 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8704 int objid, err, index, len, i, esize;
8707 objid = decode_objid (p, &p, end);
8708 err = get_object (objid, (MonoObject**)&arr);
8713 case CMD_ARRAY_REF_GET_LENGTH:
8714 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8716 buffer_add_int (buf, arr->max_length);
8717 buffer_add_int (buf, 0);
8719 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8720 buffer_add_int (buf, arr->bounds [i].length);
8721 buffer_add_int (buf, arr->bounds [i].lower_bound);
8725 case CMD_ARRAY_REF_GET_VALUES:
8726 index = decode_int (p, &p, end);
8727 len = decode_int (p, &p, end);
8729 g_assert (index >= 0 && len >= 0);
8730 // Reordered to avoid integer overflow
8731 g_assert (!(index > arr->max_length - len));
8733 esize = mono_array_element_size (arr->obj.vtable->klass);
8734 for (i = index; i < index + len; ++i) {
8735 elem = (gpointer*)((char*)arr->vector + (i * esize));
8736 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8739 case CMD_ARRAY_REF_SET_VALUES:
8740 index = decode_int (p, &p, end);
8741 len = decode_int (p, &p, end);
8743 g_assert (index >= 0 && len >= 0);
8744 // Reordered to avoid integer overflow
8745 g_assert (!(index > arr->max_length - len));
8747 esize = mono_array_element_size (arr->obj.vtable->klass);
8748 for (i = index; i < index + len; ++i) {
8749 elem = (gpointer*)((char*)arr->vector + (i * esize));
8751 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8755 return ERR_NOT_IMPLEMENTED;
8762 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8767 int i, index, length;
8770 objid = decode_objid (p, &p, end);
8771 err = get_object (objid, (MonoObject**)&str);
8776 case CMD_STRING_REF_GET_VALUE:
8777 s = mono_string_to_utf8 (str);
8778 buffer_add_string (buf, s);
8781 case CMD_STRING_REF_GET_LENGTH:
8782 buffer_add_long (buf, mono_string_length (str));
8784 case CMD_STRING_REF_GET_CHARS:
8785 index = decode_long (p, &p, end);
8786 length = decode_long (p, &p, end);
8787 if (index > mono_string_length (str) - length)
8788 return ERR_INVALID_ARGUMENT;
8789 c = mono_string_chars (str) + index;
8790 for (i = 0; i < length; ++i)
8791 buffer_add_short (buf, c [i]);
8794 return ERR_NOT_IMPLEMENTED;
8801 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8810 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8811 objid = decode_objid (p, &p, end);
8812 err = get_object (objid, &obj);
8814 buffer_add_int (buf, 1);
8816 buffer_add_int (buf, 0);
8820 objid = decode_objid (p, &p, end);
8821 err = get_object (objid, &obj);
8826 case CMD_OBJECT_REF_GET_TYPE:
8827 /* This handles transparent proxies too */
8828 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8830 case CMD_OBJECT_REF_GET_VALUES:
8831 len = decode_int (p, &p, end);
8833 for (i = 0; i < len; ++i) {
8834 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8838 /* Check that the field belongs to the object */
8840 for (k = obj->vtable->klass; k; k = k->parent) {
8841 if (k == f->parent) {
8847 return ERR_INVALID_FIELDID;
8849 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8853 if (mono_class_field_is_special_static (f))
8854 return ERR_INVALID_FIELDID;
8856 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8857 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8858 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8859 mono_field_static_get_value (vtable, f, val);
8860 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8863 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8867 case CMD_OBJECT_REF_SET_VALUES:
8868 len = decode_int (p, &p, end);
8870 for (i = 0; i < len; ++i) {
8871 f = decode_fieldid (p, &p, end, NULL, &err);
8875 /* Check that the field belongs to the object */
8877 for (k = obj->vtable->klass; k; k = k->parent) {
8878 if (k == f->parent) {
8884 return ERR_INVALID_FIELDID;
8886 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8890 if (mono_class_field_is_special_static (f))
8891 return ERR_INVALID_FIELDID;
8893 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8894 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8896 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8897 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8902 mono_field_static_set_value (vtable, f, val);
8905 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8911 case CMD_OBJECT_REF_GET_ADDRESS:
8912 buffer_add_long (buf, (gssize)obj);
8914 case CMD_OBJECT_REF_GET_DOMAIN:
8915 buffer_add_domainid (buf, obj->vtable->domain);
8917 case CMD_OBJECT_REF_GET_INFO:
8918 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8919 buffer_add_domainid (buf, obj->vtable->domain);
8922 return ERR_NOT_IMPLEMENTED;
8929 command_set_to_string (CommandSet command_set)
8931 switch (command_set) {
8934 case CMD_SET_OBJECT_REF:
8935 return "OBJECT_REF";
8936 case CMD_SET_STRING_REF:
8937 return "STRING_REF";
8938 case CMD_SET_THREAD:
8940 case CMD_SET_ARRAY_REF:
8942 case CMD_SET_EVENT_REQUEST:
8943 return "EVENT_REQUEST";
8944 case CMD_SET_STACK_FRAME:
8945 return "STACK_FRAME";
8946 case CMD_SET_APPDOMAIN:
8948 case CMD_SET_ASSEMBLY:
8950 case CMD_SET_METHOD:
8954 case CMD_SET_MODULE:
8965 static const char* vm_cmds_str [] = {
8973 "SET_PROTOCOL_VERSION",
8976 "GET_TYPES_FOR_SOURCE_FILE",
8981 static const char* thread_cmds_str[] = {
8991 static const char* event_cmds_str[] = {
8994 "REQUEST_CLEAR_ALL_BREAKPOINTS"
8997 static const char* appdomain_cmds_str[] = {
8999 "GET_FRIENDLY_NAME",
9001 "GET_ENTRY_ASSEMBLY",
9004 "CREATE_BOXED_VALUE"
9007 static const char* assembly_cmds_str[] = {
9010 "GET_MANIFEST_MODULE",
9016 static const char* module_cmds_str[] = {
9020 static const char* field_cmds_str[] = {
9024 static const char* method_cmds_str[] = {
9026 "GET_DECLARING_TYPE",
9034 "MAKE_GENERIC_METHOD"
9037 static const char* type_cmds_str[] = {
9045 "IS_ASSIGNABLE_FROM",
9049 "GET_PROPERTY_CATTRS",
9050 "GET_SOURCE_FILES_2",
9052 "GET_METHODS_BY_NAME_FLAGS",
9054 "GET_INTERFACE_MAP",
9058 static const char* stack_frame_cmds_str[] = {
9064 static const char* array_cmds_str[] = {
9070 static const char* string_cmds_str[] = {
9076 static const char* object_cmds_str[] = {
9087 cmd_to_string (CommandSet set, int command)
9095 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9097 case CMD_SET_OBJECT_REF:
9098 cmds = object_cmds_str;
9099 cmds_len = G_N_ELEMENTS (object_cmds_str);
9101 case CMD_SET_STRING_REF:
9102 cmds = string_cmds_str;
9103 cmds_len = G_N_ELEMENTS (string_cmds_str);
9105 case CMD_SET_THREAD:
9106 cmds = thread_cmds_str;
9107 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9109 case CMD_SET_ARRAY_REF:
9110 cmds = array_cmds_str;
9111 cmds_len = G_N_ELEMENTS (array_cmds_str);
9113 case CMD_SET_EVENT_REQUEST:
9114 cmds = event_cmds_str;
9115 cmds_len = G_N_ELEMENTS (event_cmds_str);
9117 case CMD_SET_STACK_FRAME:
9118 cmds = stack_frame_cmds_str;
9119 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9121 case CMD_SET_APPDOMAIN:
9122 cmds = appdomain_cmds_str;
9123 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9125 case CMD_SET_ASSEMBLY:
9126 cmds = assembly_cmds_str;
9127 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9129 case CMD_SET_METHOD:
9130 cmds = method_cmds_str;
9131 cmds_len = G_N_ELEMENTS (method_cmds_str);
9134 cmds = type_cmds_str;
9135 cmds_len = G_N_ELEMENTS (type_cmds_str);
9137 case CMD_SET_MODULE:
9138 cmds = module_cmds_str;
9139 cmds_len = G_N_ELEMENTS (module_cmds_str);
9142 cmds = field_cmds_str;
9143 cmds_len = G_N_ELEMENTS (field_cmds_str);
9146 cmds = event_cmds_str;
9147 cmds_len = G_N_ELEMENTS (event_cmds_str);
9152 if (command > 0 && command <= cmds_len)
9153 return cmds [command - 1];
9159 wait_for_attach (void)
9161 #ifndef DISABLE_SOCKET_TRANSPORT
9162 if (listen_fd == -1) {
9163 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9167 /* Block and wait for client connection */
9168 conn_fd = socket_transport_accept (listen_fd);
9169 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9170 if (conn_fd == -1) {
9171 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9175 g_assert_not_reached ();
9179 disconnected = !transport_handshake ();
9181 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9191 * This thread handles communication with the debugger client using a JDWP
9194 static guint32 WINAPI
9195 debugger_thread (void *arg)
9197 int res, len, id, flags, command_set = 0, command = 0;
9198 guint8 header [HEADER_LENGTH];
9199 guint8 *data, *p, *end;
9203 gboolean attach_failed = FALSE;
9205 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9207 debugger_thread_id = GetCurrentThreadId ();
9209 mono_jit_thread_attach (mono_get_root_domain ());
9211 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9213 mono_set_is_debugger_attached (TRUE);
9215 if (agent_config.defer) {
9216 if (!wait_for_attach ()) {
9217 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9218 attach_failed = TRUE; // Don't abort process when we can't listen
9220 /* Send start event to client */
9221 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9225 while (!attach_failed) {
9226 res = transport_recv (header, HEADER_LENGTH);
9228 /* This will break if the socket is closed during shutdown too */
9229 if (res != HEADER_LENGTH) {
9230 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9235 end = header + HEADER_LENGTH;
9237 len = decode_int (p, &p, end);
9238 id = decode_int (p, &p, end);
9239 flags = decode_byte (p, &p, end);
9240 command_set = decode_byte (p, &p, end);
9241 command = decode_byte (p, &p, end);
9243 g_assert (flags == 0);
9246 const char *cmd_str;
9249 cmd_str = cmd_to_string (command_set, command);
9251 sprintf (cmd_num, "%d", command);
9255 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d].\n", command_set_to_string (command_set), cmd_str, id));
9258 data = g_malloc (len - HEADER_LENGTH);
9259 if (len - HEADER_LENGTH > 0)
9261 res = transport_recv (data, len - HEADER_LENGTH);
9262 if (res != len - HEADER_LENGTH) {
9263 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9269 end = data + (len - HEADER_LENGTH);
9271 buffer_init (&buf, 128);
9276 /* Process the request */
9277 switch (command_set) {
9279 err = vm_commands (command, id, p, end, &buf);
9280 if (!err && command == CMD_VM_INVOKE_METHOD)
9281 /* Sent after the invoke is complete */
9284 case CMD_SET_EVENT_REQUEST:
9285 err = event_commands (command, p, end, &buf);
9287 case CMD_SET_APPDOMAIN:
9288 err = domain_commands (command, p, end, &buf);
9290 case CMD_SET_ASSEMBLY:
9291 err = assembly_commands (command, p, end, &buf);
9293 case CMD_SET_MODULE:
9294 err = module_commands (command, p, end, &buf);
9297 err = field_commands (command, p, end, &buf);
9300 err = type_commands (command, p, end, &buf);
9302 case CMD_SET_METHOD:
9303 err = method_commands (command, p, end, &buf);
9305 case CMD_SET_THREAD:
9306 err = thread_commands (command, p, end, &buf);
9308 case CMD_SET_STACK_FRAME:
9309 err = frame_commands (command, p, end, &buf);
9311 case CMD_SET_ARRAY_REF:
9312 err = array_commands (command, p, end, &buf);
9314 case CMD_SET_STRING_REF:
9315 err = string_commands (command, p, end, &buf);
9317 case CMD_SET_OBJECT_REF:
9318 err = object_commands (command, p, end, &buf);
9321 err = ERR_NOT_IMPLEMENTED;
9325 send_reply_packet (id, err, &buf);
9330 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9334 mono_set_is_debugger_attached (FALSE);
9336 mono_mutex_lock (&debugger_thread_exited_mutex);
9337 debugger_thread_exited = TRUE;
9338 mono_cond_signal (&debugger_thread_exited_cond);
9339 mono_mutex_unlock (&debugger_thread_exited_mutex);
9341 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9343 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9344 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9345 start_debugger_thread ();
9351 #else /* DISABLE_DEBUGGER_AGENT */
9354 mono_debugger_agent_parse_options (char *options)
9356 g_error ("This runtime is configured with the debugger agent disabled.");
9360 mono_debugger_agent_init (void)
9365 mono_debugger_agent_breakpoint_hit (void *sigctx)
9370 mono_debugger_agent_single_step_event (void *sigctx)
9375 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9380 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9386 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9387 MonoContext *catch_ctx)
9392 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9397 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9402 mono_debugger_agent_user_break (void)
9408 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9413 mono_debugger_agent_debug_log_is_enabled (void)