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 27
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,
307 EVENT_KIND_VM_START = 0,
308 EVENT_KIND_VM_DEATH = 1,
309 EVENT_KIND_THREAD_START = 2,
310 EVENT_KIND_THREAD_DEATH = 3,
311 EVENT_KIND_APPDOMAIN_CREATE = 4,
312 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
313 EVENT_KIND_METHOD_ENTRY = 6,
314 EVENT_KIND_METHOD_EXIT = 7,
315 EVENT_KIND_ASSEMBLY_LOAD = 8,
316 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
317 EVENT_KIND_BREAKPOINT = 10,
318 EVENT_KIND_STEP = 11,
319 EVENT_KIND_TYPE_LOAD = 12,
320 EVENT_KIND_EXCEPTION = 13,
321 EVENT_KIND_KEEPALIVE = 14,
322 EVENT_KIND_USER_BREAK = 15,
323 EVENT_KIND_USER_LOG = 16
327 SUSPEND_POLICY_NONE = 0,
328 SUSPEND_POLICY_EVENT_THREAD = 1,
329 SUSPEND_POLICY_ALL = 2
334 ERR_INVALID_OBJECT = 20,
335 ERR_INVALID_FIELDID = 25,
336 ERR_INVALID_FRAMEID = 30,
337 ERR_NOT_IMPLEMENTED = 100,
338 ERR_NOT_SUSPENDED = 101,
339 ERR_INVALID_ARGUMENT = 102,
341 ERR_NO_INVOCATION = 104,
342 ERR_ABSENT_INFORMATION = 105,
343 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
344 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
349 MOD_KIND_THREAD_ONLY = 3,
350 MOD_KIND_LOCATION_ONLY = 7,
351 MOD_KIND_EXCEPTION_ONLY = 8,
353 MOD_KIND_ASSEMBLY_ONLY = 11,
354 MOD_KIND_SOURCE_FILE_ONLY = 12,
355 MOD_KIND_TYPE_NAME_ONLY = 13
370 STEP_FILTER_NONE = 0,
371 STEP_FILTER_STATIC_CTOR = 1,
372 STEP_FILTER_DEBUGGER_HIDDEN = 2,
373 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4
377 TOKEN_TYPE_STRING = 0,
379 TOKEN_TYPE_FIELD = 2,
380 TOKEN_TYPE_METHOD = 3,
381 TOKEN_TYPE_UNKNOWN = 4
385 VALUE_TYPE_ID_NULL = 0xf0,
386 VALUE_TYPE_ID_TYPE = 0xf1
390 FRAME_FLAG_DEBUGGER_INVOKE = 1,
391 FRAME_FLAG_NATIVE_TRANSITION = 2
395 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
396 INVOKE_FLAG_SINGLE_THREADED = 2
400 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
401 } BindingFlagsExtensions;
405 CMD_VM_ALL_THREADS = 2,
410 CMD_VM_INVOKE_METHOD = 7,
411 CMD_VM_SET_PROTOCOL_VERSION = 8,
412 CMD_VM_ABORT_INVOKE = 9,
413 CMD_VM_SET_KEEPALIVE = 10,
414 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
415 CMD_VM_GET_TYPES = 12,
416 CMD_VM_INVOKE_METHODS = 13
420 CMD_THREAD_GET_FRAME_INFO = 1,
421 CMD_THREAD_GET_NAME = 2,
422 CMD_THREAD_GET_STATE = 3,
423 CMD_THREAD_GET_INFO = 4,
424 CMD_THREAD_GET_ID = 5,
425 CMD_THREAD_GET_TID = 6
429 CMD_EVENT_REQUEST_SET = 1,
430 CMD_EVENT_REQUEST_CLEAR = 2,
431 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
439 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
440 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
441 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
442 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
443 CMD_APPDOMAIN_CREATE_STRING = 5,
444 CMD_APPDOMAIN_GET_CORLIB = 6,
445 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
449 CMD_ASSEMBLY_GET_LOCATION = 1,
450 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
451 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
452 CMD_ASSEMBLY_GET_OBJECT = 4,
453 CMD_ASSEMBLY_GET_TYPE = 5,
454 CMD_ASSEMBLY_GET_NAME = 6
458 CMD_MODULE_GET_INFO = 1,
462 CMD_METHOD_GET_NAME = 1,
463 CMD_METHOD_GET_DECLARING_TYPE = 2,
464 CMD_METHOD_GET_DEBUG_INFO = 3,
465 CMD_METHOD_GET_PARAM_INFO = 4,
466 CMD_METHOD_GET_LOCALS_INFO = 5,
467 CMD_METHOD_GET_INFO = 6,
468 CMD_METHOD_GET_BODY = 7,
469 CMD_METHOD_RESOLVE_TOKEN = 8,
470 CMD_METHOD_GET_CATTRS = 9,
471 CMD_METHOD_MAKE_GENERIC_METHOD = 10
475 CMD_TYPE_GET_INFO = 1,
476 CMD_TYPE_GET_METHODS = 2,
477 CMD_TYPE_GET_FIELDS = 3,
478 CMD_TYPE_GET_VALUES = 4,
479 CMD_TYPE_GET_OBJECT = 5,
480 CMD_TYPE_GET_SOURCE_FILES = 6,
481 CMD_TYPE_SET_VALUES = 7,
482 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
483 CMD_TYPE_GET_PROPERTIES = 9,
484 CMD_TYPE_GET_CATTRS = 10,
485 CMD_TYPE_GET_FIELD_CATTRS = 11,
486 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
487 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
488 CMD_TYPE_GET_VALUES_2 = 14,
489 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
490 CMD_TYPE_GET_INTERFACES = 16,
491 CMD_TYPE_GET_INTERFACE_MAP = 17,
492 CMD_TYPE_IS_INITIALIZED = 18
496 CMD_STACK_FRAME_GET_VALUES = 1,
497 CMD_STACK_FRAME_GET_THIS = 2,
498 CMD_STACK_FRAME_SET_VALUES = 3
502 CMD_ARRAY_REF_GET_LENGTH = 1,
503 CMD_ARRAY_REF_GET_VALUES = 2,
504 CMD_ARRAY_REF_SET_VALUES = 3,
508 CMD_STRING_REF_GET_VALUE = 1,
509 CMD_STRING_REF_GET_LENGTH = 2,
510 CMD_STRING_REF_GET_CHARS = 3
514 CMD_OBJECT_REF_GET_TYPE = 1,
515 CMD_OBJECT_REF_GET_VALUES = 2,
516 CMD_OBJECT_REF_IS_COLLECTED = 3,
517 CMD_OBJECT_REF_GET_ADDRESS = 4,
518 CMD_OBJECT_REF_GET_DOMAIN = 5,
519 CMD_OBJECT_REF_SET_VALUES = 6,
520 CMD_OBJECT_REF_GET_INFO = 7,
526 int count; /* For kind == MOD_KIND_COUNT */
527 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
528 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
529 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
530 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
531 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
532 StepFilter filter; /* For kind == MOD_KIND_STEP */
534 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
543 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
547 * Describes a single step request.
551 MonoInternalThread *thread;
557 MonoMethod *last_method;
559 /* Whenever single stepping is performed using start/stop_single_stepping () */
561 /* The list of breakpoints used to implement step-over */
563 /* The number of frames at the start of a step-over */
568 * Contains additional information for an event
571 /* For EVENT_KIND_EXCEPTION */
573 MonoContext catch_ctx;
575 /* For EVENT_KIND_USER_LOG */
577 char *category, *message;
578 /* For EVENT_KIND_TYPE_LOAD */
582 /* Dummy structure used for the profiler callbacks */
587 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
590 #define get_last_sock_error() WSAGetLastError()
591 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
592 #define MONO_EINTR WSAEINTR
594 #define get_last_sock_error() errno
595 #define MONO_EWOULDBLOCK EWOULDBLOCK
596 #define MONO_EINTR EINTR
599 #define CHECK_PROTOCOL_VERSION(major,minor) \
600 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
606 static AgentConfig agent_config;
609 * Whenever the agent is fully initialized.
610 * When using the onuncaught or onthrow options, only some parts of the agent are
611 * initialized on startup, and the full initialization which includes connection
612 * establishment and the startup of the agent thread is only done in response to
615 static gint32 inited;
617 #ifndef DISABLE_SOCKET_TRANSPORT
619 static int listen_fd;
622 static int packet_id = 0;
624 static int objref_id = 0;
626 static int event_request_id = 0;
628 static int frame_id = 0;
630 static GPtrArray *event_requests;
632 static MonoNativeTlsKey debugger_tls_id;
634 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
636 /* Maps MonoInternalThread -> DebuggerTlsData */
637 static MonoGHashTable *thread_to_tls;
639 /* Maps tid -> MonoInternalThread */
640 static MonoGHashTable *tid_to_thread;
642 /* Maps tid -> MonoThread (not MonoInternalThread) */
643 static MonoGHashTable *tid_to_thread_obj;
645 static gsize debugger_thread_id;
647 static HANDLE debugger_thread_handle;
649 static int log_level;
651 static gboolean embedding;
653 static FILE *log_file;
655 /* Assemblies whose assembly load event has no been sent yet */
656 static GPtrArray *pending_assembly_loads;
658 /* Whenever the debugger thread has exited */
659 static gboolean debugger_thread_exited;
661 /* Cond variable used to wait for debugger_thread_exited becoming true */
662 static mono_cond_t debugger_thread_exited_cond;
664 /* Mutex for the cond var above */
665 static mono_mutex_t debugger_thread_exited_mutex;
667 static DebuggerProfiler debugger_profiler;
669 /* The single step request instance */
670 static SingleStepReq *ss_req = NULL;
671 static gpointer ss_invoke_addr = NULL;
673 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
674 /* Number of single stepping operations in progress */
678 /* The protocol version of the client */
679 static int major_version, minor_version;
681 /* Whenever the variables above are set by the client */
682 static gboolean protocol_version_set;
684 /* A hash table containing all active domains */
685 static GHashTable *domains;
687 /* The number of times the runtime is suspended */
688 static gint32 suspend_count;
690 static void transport_init (void);
691 static void transport_connect (const char *address);
692 static gboolean transport_handshake (void);
693 static void register_transport (DebuggerTransport *trans);
695 static guint32 WINAPI debugger_thread (void *arg);
697 static void runtime_initialized (MonoProfiler *prof);
699 static void runtime_shutdown (MonoProfiler *prof);
701 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
703 static void thread_end (MonoProfiler *prof, uintptr_t tid);
705 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
707 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
709 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
711 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
713 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
715 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
717 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
719 static void emit_assembly_load (gpointer assembly, gpointer user_data);
721 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
723 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
725 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
727 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
729 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
731 static void start_single_stepping (void);
733 static void stop_single_stepping (void);
735 static void suspend_current (void);
737 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
739 static void clear_types_for_assembly (MonoAssembly *assembly);
741 static void clear_breakpoints_for_domain (MonoDomain *domain);
743 static void process_profiler_event (EventKind event, gpointer arg);
745 /* Submodule init/cleanup */
746 static void breakpoints_init (void);
747 static void breakpoints_cleanup (void);
749 static void objrefs_init (void);
750 static void objrefs_cleanup (void);
752 static void ids_init (void);
753 static void ids_cleanup (void);
755 static void suspend_init (void);
757 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
758 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
759 static void ss_destroy (SingleStepReq *req);
761 static void start_debugger_thread (void);
762 static void stop_debugger_thread (void);
764 static void finish_agent_init (gboolean on_startup);
766 static void process_profiler_event (EventKind event, gpointer arg);
768 static void invalidate_frames (DebuggerTlsData *tls);
770 #ifndef DISABLE_SOCKET_TRANSPORT
772 register_socket_transport (void);
776 parse_address (char *address, char **host, int *port)
778 char *pos = strchr (address, ':');
780 if (pos == NULL || pos == address)
783 *host = g_malloc (pos - address + 1);
784 strncpy (*host, address, pos - address);
785 (*host) [pos - address] = '\0';
787 *port = atoi (pos + 1);
795 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
796 fprintf (stderr, "Available options:\n");
797 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
798 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
799 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
800 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
801 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
802 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
803 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
804 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
805 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
806 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
810 parse_flag (const char *option, char *flag)
812 if (!strcmp (flag, "y"))
814 else if (!strcmp (flag, "n"))
817 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
824 mono_debugger_agent_parse_options (char *options)
831 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
832 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
836 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
838 options = g_strdup_printf ("%s,%s", options, extra);
840 agent_config.enabled = TRUE;
841 agent_config.suspend = TRUE;
842 agent_config.server = FALSE;
843 agent_config.defer = FALSE;
844 agent_config.address = NULL;
846 args = g_strsplit (options, ",", -1);
847 for (ptr = args; ptr && *ptr; ptr ++) {
850 if (strncmp (arg, "transport=", 10) == 0) {
851 agent_config.transport = g_strdup (arg + 10);
852 } else if (strncmp (arg, "address=", 8) == 0) {
853 agent_config.address = g_strdup (arg + 8);
854 } else if (strncmp (arg, "loglevel=", 9) == 0) {
855 agent_config.log_level = atoi (arg + 9);
856 } else if (strncmp (arg, "logfile=", 8) == 0) {
857 agent_config.log_file = g_strdup (arg + 8);
858 } else if (strncmp (arg, "suspend=", 8) == 0) {
859 agent_config.suspend = parse_flag ("suspend", arg + 8);
860 } else if (strncmp (arg, "server=", 7) == 0) {
861 agent_config.server = parse_flag ("server", arg + 7);
862 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
863 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
864 } else if (strncmp (arg, "onthrow=", 8) == 0) {
865 /* We support multiple onthrow= options */
866 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
867 } else if (strncmp (arg, "onthrow", 7) == 0) {
868 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
869 } else if (strncmp (arg, "help", 4) == 0) {
872 } else if (strncmp (arg, "timeout=", 8) == 0) {
873 agent_config.timeout = atoi (arg + 8);
874 } else if (strncmp (arg, "launch=", 7) == 0) {
875 agent_config.launch = g_strdup (arg + 7);
876 } else if (strncmp (arg, "embedding=", 10) == 0) {
877 agent_config.embedding = atoi (arg + 10) == 1;
878 } else if (strncmp (arg, "keepalive=", 10) == 0) {
879 agent_config.keepalive = atoi (arg + 10);
880 } else if (strncmp (arg, "setpgid=", 8) == 0) {
881 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
888 if (agent_config.server && !agent_config.suspend) {
889 /* Waiting for deferred attachment */
890 agent_config.defer = TRUE;
891 if (agent_config.address == NULL) {
892 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
896 //agent_config.log_level = 0;
898 if (agent_config.transport == NULL) {
899 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
903 if (agent_config.address == NULL && !agent_config.server) {
904 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
909 if (!strcmp (agent_config.transport, "dt_socket")) {
910 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
911 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
918 mono_debugger_agent_init (void)
920 if (!agent_config.enabled)
925 /* Need to know whenever a thread has acquired the loader mutex */
926 mono_loader_lock_track_ownership (TRUE);
928 event_requests = g_ptr_array_new ();
930 mono_mutex_init (&debugger_thread_exited_mutex);
931 mono_cond_init (&debugger_thread_exited_cond, NULL);
933 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
934 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
935 mono_profiler_install_runtime_initialized (runtime_initialized);
936 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
937 mono_profiler_install_thread (thread_startup, thread_end);
938 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
939 mono_profiler_install_jit_end (jit_end);
940 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
942 mono_native_tls_alloc (&debugger_tls_id, NULL);
944 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
945 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
947 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
948 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
950 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
951 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
953 pending_assembly_loads = g_ptr_array_new ();
954 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
956 log_level = agent_config.log_level;
958 embedding = agent_config.embedding;
961 if (agent_config.log_file) {
962 log_file = fopen (agent_config.log_file, "w+");
964 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
976 mini_get_debug_options ()->gen_seq_points = TRUE;
978 * This is needed because currently we don't handle liveness info.
980 mini_get_debug_options ()->mdb_optimizations = TRUE;
982 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
983 /* This is needed because we can't set local variables in registers yet */
984 mono_disable_optimizations (MONO_OPT_LINEARS);
988 * The stack walk done from thread_interrupt () needs to be signal safe, but it
989 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
990 * safe (#3411). So load AOT info eagerly when the debugger is running as a
993 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
996 if (agent_config.setpgid)
1000 if (!agent_config.onuncaught && !agent_config.onthrow)
1001 finish_agent_init (TRUE);
1005 * finish_agent_init:
1007 * Finish the initialization of the agent. This involves connecting the transport
1008 * and starting the agent thread. This is either done at startup, or
1009 * in response to some event like an unhandled exception.
1012 finish_agent_init (gboolean on_startup)
1016 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1019 if (agent_config.launch) {
1022 // FIXME: Generated address
1023 // FIXME: Races with transport_connect ()
1025 argv [0] = agent_config.launch;
1026 argv [1] = agent_config.transport;
1027 argv [2] = agent_config.address;
1030 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1032 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1037 transport_connect (agent_config.address);
1040 /* Do some which is usually done after sending the VMStart () event */
1041 vm_start_event_sent = TRUE;
1042 start_debugger_thread ();
1047 mono_debugger_agent_cleanup (void)
1052 stop_debugger_thread ();
1054 breakpoints_cleanup ();
1058 mono_mutex_destroy (&debugger_thread_exited_mutex);
1059 mono_cond_destroy (&debugger_thread_exited_cond);
1066 #ifndef DISABLE_SOCKET_TRANSPORT
1071 * recv() + handle incomplete reads and EINTR
1074 socket_transport_recv (void *buf, int len)
1080 static gint32 last_keepalive;
1085 res = recv (fd, (char *) buf + total, len - total, flags);
1088 if (agent_config.keepalive) {
1089 gboolean need_keepalive = FALSE;
1090 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1091 need_keepalive = TRUE;
1092 } else if (res == -1) {
1093 /* This could happen if recv () is interrupted repeatedly */
1094 msecs = mono_msec_ticks ();
1095 if (msecs - last_keepalive >= agent_config.keepalive) {
1096 need_keepalive = TRUE;
1097 last_keepalive = msecs;
1100 if (need_keepalive) {
1101 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1105 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1110 #define HAVE_GETADDRINFO 1
1114 set_keepalive (void)
1119 if (!agent_config.keepalive || !conn_fd)
1122 tv.tv_sec = agent_config.keepalive / 1000;
1123 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1125 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1126 g_assert (result >= 0);
1130 socket_transport_accept (int socket_fd)
1132 conn_fd = accept (socket_fd, NULL, NULL);
1133 if (conn_fd == -1) {
1134 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1136 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1143 socket_transport_send (void *data, int len)
1148 res = send (conn_fd, data, len, 0);
1149 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1157 * socket_transport_connect:
1159 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1162 socket_transport_connect (const char *address)
1164 #ifdef HAVE_GETADDRINFO
1165 struct addrinfo hints;
1166 struct addrinfo *result, *rp;
1168 struct hostent *result;
1170 int sfd = -1, s, res;
1171 char port_string [128];
1175 if (agent_config.address) {
1176 res = parse_address (agent_config.address, &host, &port);
1177 g_assert (res == 0);
1187 sprintf (port_string, "%d", port);
1189 mono_network_init ();
1191 /* Obtain address(es) matching host/port */
1192 #ifdef HAVE_GETADDRINFO
1193 memset (&hints, 0, sizeof (struct addrinfo));
1194 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1195 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1197 hints.ai_protocol = 0; /* Any protocol */
1199 s = getaddrinfo (host, port_string, &hints, &result);
1201 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1205 /* The PS3 doesn't even have _r or hstrerror () */
1206 result = gethostbyname (host);
1208 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1213 if (agent_config.server) {
1214 #ifdef HAVE_GETADDRINFO
1215 /* Wait for a connection */
1217 struct sockaddr_in addr;
1220 /* No address, generate one */
1221 sfd = socket (AF_INET, SOCK_STREAM, 0);
1224 /* This will bind the socket to a random port */
1225 res = listen (sfd, 16);
1227 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1232 addrlen = sizeof (addr);
1233 memset (&addr, 0, sizeof (addr));
1234 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1235 g_assert (res == 0);
1237 host = (char*)"127.0.0.1";
1238 port = ntohs (addr.sin_port);
1240 /* Emit the address to stdout */
1241 /* FIXME: Should print another interface, not localhost */
1242 printf ("%s:%d\n", host, port);
1244 /* Listen on the provided address */
1245 for (rp = result; rp != NULL; rp = rp->ai_next) {
1248 sfd = socket (rp->ai_family, rp->ai_socktype,
1253 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1256 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1260 res = listen (sfd, 16);
1269 * this function is not present on win2000 which we still support, and the
1270 * workaround described here:
1271 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1272 * only works with MSVC.
1274 #ifdef HAVE_GETADDRINFO
1275 freeaddrinfo (result);
1280 if (agent_config.defer)
1283 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1285 if (agent_config.timeout) {
1290 tv.tv_usec = agent_config.timeout * 1000;
1292 FD_SET (sfd, &readfds);
1293 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1295 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1300 conn_fd = socket_transport_accept (sfd);
1304 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1307 #endif /* HAVE_GETADDRINFO */
1309 /* Connect to the specified address */
1310 #ifdef HAVE_GETADDRINFO
1311 /* FIXME: Respect the timeout */
1312 for (rp = result; rp != NULL; rp = rp->ai_next) {
1313 sfd = socket (rp->ai_family, rp->ai_socktype,
1318 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1319 break; /* Success */
1325 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1329 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1331 g_assert_not_reached ();
1332 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1334 g_assert_not_reached ();
1340 /* See the comment above */
1341 #ifdef HAVE_GETADDRINFO
1342 freeaddrinfo (result);
1347 if (!transport_handshake ())
1352 socket_transport_close1 (void)
1354 /* This will interrupt the agent thread */
1355 /* Close the read part only so it can still send back replies */
1356 /* Also shut down the connection listener so that we can exit normally */
1358 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1359 shutdown (conn_fd, SD_BOTH);
1360 shutdown (listen_fd, SD_BOTH);
1361 closesocket (listen_fd);
1363 shutdown (conn_fd, SHUT_RD);
1364 shutdown (listen_fd, SHUT_RDWR);
1370 socket_transport_close2 (void)
1373 shutdown (conn_fd, SD_BOTH);
1375 shutdown (conn_fd, SHUT_RDWR);
1380 register_socket_transport (void)
1382 DebuggerTransport trans;
1384 trans.name = "dt_socket";
1385 trans.connect = socket_transport_connect;
1386 trans.close1 = socket_transport_close1;
1387 trans.close2 = socket_transport_close2;
1388 trans.send = socket_transport_send;
1389 trans.recv = socket_transport_recv;
1391 register_transport (&trans);
1394 #endif /* DISABLE_SOCKET_TRANSPORT */
1400 #define MAX_TRANSPORTS 16
1402 static DebuggerTransport *transport;
1404 static DebuggerTransport transports [MAX_TRANSPORTS];
1405 static int ntransports;
1408 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1411 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1413 register_transport (trans);
1417 register_transport (DebuggerTransport *trans)
1419 g_assert (ntransports < MAX_TRANSPORTS);
1421 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1426 transport_init (void)
1430 #ifndef DISABLE_SOCKET_TRANSPORT
1431 register_socket_transport ();
1434 for (i = 0; i < ntransports; ++i) {
1435 if (!strcmp (agent_config.transport, transports [i].name))
1438 if (i == ntransports) {
1439 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1440 for (i = 0; i < ntransports; ++i)
1441 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1442 fprintf (stderr, "\n");
1445 transport = &transports [i];
1449 transport_connect (const char *address)
1451 transport->connect (address);
1455 transport_close1 (void)
1457 transport->close1 ();
1461 transport_close2 (void)
1463 transport->close2 ();
1467 transport_send (void *buf, int len)
1469 return transport->send (buf, len);
1473 transport_recv (void *buf, int len)
1475 return transport->recv (buf, len);
1479 mono_debugger_agent_transport_handshake (void)
1481 return transport_handshake ();
1485 transport_handshake (void)
1487 char handshake_msg [128];
1491 disconnected = TRUE;
1493 /* Write handshake message */
1494 sprintf (handshake_msg, "DWP-Handshake");
1496 res = transport_send (handshake_msg, strlen (handshake_msg));
1497 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1498 g_assert (res != -1);
1501 res = transport_recv (buf, strlen (handshake_msg));
1502 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1503 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1508 * To support older clients, the client sends its protocol version after connecting
1509 * using a command. Until that is received, default to our protocol version.
1511 major_version = MAJOR_VERSION;
1512 minor_version = MINOR_VERSION;
1513 protocol_version_set = FALSE;
1515 #ifndef DISABLE_SOCKET_TRANSPORT
1516 // FIXME: Move this somewhere else
1518 * Set TCP_NODELAY on the socket so the client receives events/command
1519 * results immediately.
1523 int result = setsockopt (conn_fd,
1528 g_assert (result >= 0);
1534 disconnected = FALSE;
1539 stop_debugger_thread (void)
1544 transport_close1 ();
1547 * Wait for the thread to exit.
1549 * If we continue with the shutdown without waiting for it, then the client might
1550 * not receive an answer to its last command like a resume.
1551 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1554 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1555 if (GetCurrentThreadId () != debugger_thread_id) {
1557 mono_mutex_lock (&debugger_thread_exited_mutex);
1558 if (!debugger_thread_exited) {
1560 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1561 mono_mutex_unlock (&debugger_thread_exited_mutex);
1563 mono_mutex_lock (&debugger_thread_exited_mutex);
1566 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1569 mono_mutex_unlock (&debugger_thread_exited_mutex);
1570 } while (!debugger_thread_exited);
1573 transport_close2 ();
1577 start_debugger_thread (void)
1579 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1580 g_assert (debugger_thread_handle);
1584 * Functions to decode protocol data
1588 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1591 g_assert (*endbuf <= limit);
1596 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1599 g_assert (*endbuf <= limit);
1601 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1604 static inline gint64
1605 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1607 guint32 high = decode_int (buf, &buf, limit);
1608 guint32 low = decode_int (buf, &buf, limit);
1612 return ((((guint64)high) << 32) | ((guint64)low));
1616 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1618 return decode_int (buf, endbuf, limit);
1622 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1624 int len = decode_int (buf, &buf, limit);
1632 s = g_malloc (len + 1);
1635 memcpy (s, buf, len);
1644 * Functions to encode protocol data
1648 guint8 *buf, *p, *end;
1652 buffer_init (Buffer *buf, int size)
1654 buf->buf = g_malloc (size);
1656 buf->end = buf->buf + size;
1660 buffer_make_room (Buffer *buf, int size)
1662 if (buf->end - buf->p < size) {
1663 int new_size = buf->end - buf->buf + size + 32;
1664 guint8 *p = g_realloc (buf->buf, new_size);
1665 size = buf->p - buf->buf;
1668 buf->end = buf->buf + new_size;
1673 buffer_add_byte (Buffer *buf, guint8 val)
1675 buffer_make_room (buf, 1);
1681 buffer_add_short (Buffer *buf, guint32 val)
1683 buffer_make_room (buf, 2);
1684 buf->p [0] = (val >> 8) & 0xff;
1685 buf->p [1] = (val >> 0) & 0xff;
1690 buffer_add_int (Buffer *buf, guint32 val)
1692 buffer_make_room (buf, 4);
1693 buf->p [0] = (val >> 24) & 0xff;
1694 buf->p [1] = (val >> 16) & 0xff;
1695 buf->p [2] = (val >> 8) & 0xff;
1696 buf->p [3] = (val >> 0) & 0xff;
1701 buffer_add_long (Buffer *buf, guint64 l)
1703 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1704 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1708 buffer_add_id (Buffer *buf, int id)
1710 buffer_add_int (buf, (guint64)id);
1714 buffer_add_data (Buffer *buf, guint8 *data, int len)
1716 buffer_make_room (buf, len);
1717 memcpy (buf->p, data, len);
1722 buffer_add_string (Buffer *buf, const char *str)
1727 buffer_add_int (buf, 0);
1730 buffer_add_int (buf, len);
1731 buffer_add_data (buf, (guint8*)str, len);
1736 buffer_free (Buffer *buf)
1742 send_packet (int command_set, int command, Buffer *data)
1748 id = InterlockedIncrement (&packet_id);
1750 len = data->p - data->buf + 11;
1751 buffer_init (&buf, len);
1752 buffer_add_int (&buf, len);
1753 buffer_add_int (&buf, id);
1754 buffer_add_byte (&buf, 0); /* flags */
1755 buffer_add_byte (&buf, command_set);
1756 buffer_add_byte (&buf, command);
1757 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1759 res = transport_send (buf.buf, len);
1767 send_reply_packet (int id, int error, Buffer *data)
1773 len = data->p - data->buf + 11;
1774 buffer_init (&buf, len);
1775 buffer_add_int (&buf, len);
1776 buffer_add_int (&buf, id);
1777 buffer_add_byte (&buf, 0x80); /* flags */
1778 buffer_add_byte (&buf, (error >> 8) & 0xff);
1779 buffer_add_byte (&buf, error);
1780 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1782 res = transport_send (buf.buf, len);
1794 * Represents an object accessible by the debugger client.
1797 /* Unique id used in the wire protocol to refer to objects */
1800 * A weakref gc handle pointing to the object. The gc handle is used to
1801 * detect if the object was garbage collected.
1806 /* Maps objid -> ObjRef */
1807 static GHashTable *objrefs;
1810 free_objref (gpointer value)
1814 mono_gchandle_free (o->handle);
1822 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1826 objrefs_cleanup (void)
1828 g_hash_table_destroy (objrefs);
1832 static GHashTable *obj_to_objref;
1833 static MonoGHashTable *suspended_objs;
1836 * Return an ObjRef for OBJ.
1839 get_objref (MonoObject *obj)
1842 GSList *reflist = NULL, *l;
1848 mono_loader_lock ();
1850 if (!obj_to_objref) {
1851 obj_to_objref = g_hash_table_new (NULL, NULL);
1852 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1853 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1856 if (suspend_count) {
1858 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1860 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1863 /* FIXME: The tables can grow indefinitely */
1865 if (mono_gc_is_moving ()) {
1867 * Objects can move, so use a hash table mapping hash codes to lists of
1868 * ObjRef structures.
1870 hash = mono_object_hash (obj);
1872 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1873 for (l = reflist; l; l = l->next) {
1875 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1876 mono_loader_unlock ();
1881 /* Use a hash table with masked pointers to internalize object references */
1882 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1883 /* ref might refer to a different object with the same addr which was GCd */
1884 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1885 mono_loader_unlock ();
1890 ref = g_new0 (ObjRef, 1);
1891 ref->id = InterlockedIncrement (&objref_id);
1892 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1894 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1896 if (mono_gc_is_moving ()) {
1897 reflist = g_slist_append (reflist, ref);
1898 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1900 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1903 mono_loader_unlock ();
1909 true_pred (gpointer key, gpointer value, gpointer user_data)
1915 clear_suspended_objs (void)
1917 mono_loader_lock ();
1918 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
1919 mono_loader_unlock ();
1923 get_objid (MonoObject *obj)
1925 return get_objref (obj)->id;
1929 * Set OBJ to the object identified by OBJID.
1930 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1934 get_object_allow_null (int objid, MonoObject **obj)
1944 return ERR_INVALID_OBJECT;
1946 mono_loader_lock ();
1948 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1951 *obj = mono_gchandle_get_target (ref->handle);
1952 mono_loader_unlock ();
1954 return ERR_INVALID_OBJECT;
1957 mono_loader_unlock ();
1958 return ERR_INVALID_OBJECT;
1963 get_object (int objid, MonoObject **obj)
1965 int err = get_object_allow_null (objid, obj);
1970 return ERR_INVALID_OBJECT;
1975 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1977 return decode_id (buf, endbuf, limit);
1981 buffer_add_objid (Buffer *buf, MonoObject *o)
1983 buffer_add_id (buf, get_objid (o));
2002 * Represents a runtime structure accessible to the debugger client
2005 /* Unique id used in the wire protocol */
2007 /* Domain of the runtime structure, NULL if the domain was unloaded */
2014 MonoAssembly *assembly;
2015 MonoClassField *field;
2017 MonoProperty *property;
2022 /* Maps runtime structure -> Id */
2023 GHashTable *val_to_id [ID_NUM];
2024 /* Classes whose class load event has been sent */
2025 GHashTable *loaded_classes;
2026 /* Maps MonoClass->GPtrArray of file names */
2027 GHashTable *source_files;
2028 /* Maps source file basename -> GSList of classes */
2029 GHashTable *source_file_to_class;
2030 /* Same with ignore-case */
2031 GHashTable *source_file_to_class_ignorecase;
2035 static GPtrArray *ids [ID_NUM];
2042 for (i = 0; i < ID_NUM; ++i)
2043 ids [i] = g_ptr_array_new ();
2051 for (i = 0; i < ID_NUM; ++i) {
2053 for (j = 0; j < ids [i]->len; ++j)
2054 g_free (g_ptr_array_index (ids [i], j));
2055 g_ptr_array_free (ids [i], TRUE);
2062 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2064 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2066 GHashTableIter iter;
2067 GPtrArray *file_names;
2072 for (i = 0; i < ID_NUM; ++i)
2073 if (info->val_to_id [i])
2074 g_hash_table_destroy (info->val_to_id [i]);
2075 g_hash_table_destroy (info->loaded_classes);
2077 g_hash_table_iter_init (&iter, info->source_files);
2078 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2079 for (i = 0; i < file_names->len; ++i)
2080 g_free (g_ptr_array_index (file_names, i));
2081 g_ptr_array_free (file_names, TRUE);
2084 g_hash_table_iter_init (&iter, info->source_file_to_class);
2085 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2090 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2091 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2099 domain_jit_info (domain)->agent_info = NULL;
2101 /* Clear ids referencing structures in the domain */
2102 for (i = 0; i < ID_NUM; ++i) {
2104 for (j = 0; j < ids [i]->len; ++j) {
2105 Id *id = g_ptr_array_index (ids [i], j);
2106 if (id->domain == domain)
2112 mono_loader_lock ();
2113 g_hash_table_remove (domains, domain);
2114 mono_loader_unlock ();
2117 static AgentDomainInfo*
2118 get_agent_domain_info (MonoDomain *domain)
2120 AgentDomainInfo *info = NULL;
2122 mono_domain_lock (domain);
2124 info = domain_jit_info (domain)->agent_info;
2126 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2127 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2128 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2129 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2130 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2133 mono_domain_unlock (domain);
2139 get_id (MonoDomain *domain, IdType type, gpointer val)
2142 AgentDomainInfo *info;
2147 mono_loader_lock ();
2149 mono_domain_lock (domain);
2151 info = get_agent_domain_info (domain);
2153 if (info->val_to_id [type] == NULL)
2154 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2156 id = g_hash_table_lookup (info->val_to_id [type], val);
2158 mono_domain_unlock (domain);
2159 mono_loader_unlock ();
2163 id = g_new0 (Id, 1);
2165 id->id = ids [type]->len + 1;
2166 id->domain = domain;
2169 g_hash_table_insert (info->val_to_id [type], val, id);
2171 mono_domain_unlock (domain);
2173 g_ptr_array_add (ids [type], id);
2175 mono_loader_unlock ();
2180 static inline gpointer
2181 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2185 int id = decode_id (buf, endbuf, limit);
2194 // FIXME: error handling
2195 mono_loader_lock ();
2196 g_assert (id > 0 && id <= ids [type]->len);
2198 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2199 mono_loader_unlock ();
2201 if (res->domain == NULL) {
2202 DEBUG (0, fprintf (log_file, "ERR_UNLOADED, id=%d, type=%d.\n", id, type));
2203 *err = ERR_UNLOADED;
2208 *domain = res->domain;
2210 return res->data.val;
2214 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2216 buffer_add_id (buf, get_id (domain, type, val));
2219 static inline MonoClass*
2220 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2224 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2225 if (G_UNLIKELY (log_level >= 2) && klass) {
2228 s = mono_type_full_name (&klass->byval_arg);
2229 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2235 static inline MonoAssembly*
2236 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2238 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2241 static inline MonoImage*
2242 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2244 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2247 static inline MonoMethod*
2248 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2252 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2253 if (G_UNLIKELY (log_level >= 2) && m) {
2256 s = mono_method_full_name (m, TRUE);
2257 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2263 static inline MonoClassField*
2264 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2266 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2269 static inline MonoDomain*
2270 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2272 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2275 static inline MonoProperty*
2276 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2278 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2282 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2284 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2285 if (G_UNLIKELY (log_level >= 2) && klass) {
2288 s = mono_type_full_name (&klass->byval_arg);
2289 if (GetCurrentThreadId () == debugger_thread_id)
2290 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2292 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2298 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2300 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2301 if (G_UNLIKELY (log_level >= 2) && method) {
2304 s = mono_method_full_name (method, 1);
2305 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2311 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2313 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2317 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2319 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2323 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2325 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2329 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2331 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2335 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2337 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2340 static void invoke_method (void);
2347 * save_thread_context:
2349 * Set CTX as the current threads context which is used for computing stack traces.
2350 * This function is signal-safe.
2353 save_thread_context (MonoContext *ctx)
2355 DebuggerTlsData *tls;
2357 tls = mono_native_tls_get_value (debugger_tls_id);
2361 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2363 mono_thread_state_init_from_current (&tls->context);
2366 /* Number of threads suspended */
2368 * If this is equal to the size of thread_to_tls, the runtime is considered
2371 static gint32 threads_suspend_count;
2373 static mono_mutex_t suspend_mutex;
2375 /* Cond variable used to wait for suspend_count becoming 0 */
2376 static mono_cond_t suspend_cond;
2378 /* Semaphore used to wait for a thread becoming suspended */
2379 static MonoSemType suspend_sem;
2384 mono_mutex_init (&suspend_mutex);
2385 mono_cond_init (&suspend_cond, NULL);
2386 MONO_SEM_INIT (&suspend_sem, 0);
2391 StackFrameInfo last_frame;
2392 gboolean last_frame_set;
2395 } GetLastFrameUserData;
2398 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2400 GetLastFrameUserData *data = user_data;
2402 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2405 if (!data->last_frame_set) {
2406 /* Store the last frame */
2407 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2408 data->last_frame_set = TRUE;
2411 /* Store the context/lmf for the frame above the last frame */
2412 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2413 data->lmf = info->lmf;
2421 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2422 * INFO is set, process the thread described by INFO.
2423 * This should be signal safe.
2426 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2430 MonoNativeThreadId tid;
2433 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2434 * guarantee the signal handler will be called that many times. Instead of tracking
2435 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2436 * has been requested that hasn't been handled yet, otherwise we can have threads
2437 * refuse to die when VM_EXIT is called
2439 #if defined(__APPLE__)
2440 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2444 * We use interrupt_count to determine whenever this interrupt should be processed
2445 * by us or the normal interrupt processing code in the signal handler.
2446 * There is no race here with notify_thread (), since the signal is sent after
2447 * incrementing interrupt_count.
2449 if (tls->interrupt_count == 0)
2452 InterlockedDecrement (&tls->interrupt_count);
2456 ip = mono_arch_ip_from_context (sigctx);
2458 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2463 tid = mono_thread_info_get_tid (info);
2465 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2467 // FIXME: Races when the thread leaves managed code before hitting a single step
2471 /* Running managed code, will be suspended by the single step code */
2472 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2476 * Running native code, will be suspended when it returns to/enters
2477 * managed code. Treat it as already suspended.
2478 * This might interrupt the code in process_single_step_inner (), we use the
2479 * tls->suspending flag to avoid races when that happens.
2481 if (!tls->suspended && !tls->suspending) {
2483 GetLastFrameUserData data;
2485 // FIXME: printf is not signal safe, but this is only used during
2486 // debugger debugging
2488 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2489 //save_thread_context (&ctx);
2492 /* Already terminated */
2496 * We are in a difficult position: we want to be able to provide stack
2497 * traces for this thread, but we can't use the current ctx+lmf, since
2498 * the thread is still running, so it might return to managed code,
2499 * making these invalid.
2500 * So we start a stack walk and save the first frame, along with the
2501 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2502 * suspended when it returns to managed code, so the parent's ctx should
2505 data.last_frame_set = FALSE;
2507 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2509 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2510 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2511 * since we are not in a JITted method.
2513 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2515 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2517 if (data.last_frame_set) {
2518 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2519 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2521 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2524 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2525 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2526 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2528 tls->async_state.valid = FALSE;
2531 mono_memory_barrier ();
2533 tls->suspended = TRUE;
2534 MONO_SEM_POST (&suspend_sem);
2541 * mono_debugger_agent_thread_interrupt:
2543 * Called by the abort signal handler.
2544 * Should be signal safe.
2547 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2549 DebuggerTlsData *tls;
2554 tls = mono_native_tls_get_value (debugger_tls_id);
2556 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2560 return thread_interrupt (tls, NULL, sigctx, ji);
2564 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2567 mono_debugger_agent_thread_interrupt (NULL, NULL);
2569 #endif /* HOST_WIN32 */
2572 * reset_native_thread_suspend_state:
2574 * Reset the suspended flag and state on native threads
2577 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2579 DebuggerTlsData *tls = value;
2581 if (!tls->really_suspended && tls->suspended) {
2582 tls->suspended = FALSE;
2584 * The thread might still be running if it was executing native code, so the state won't be invalided by
2585 * suspend_current ().
2587 tls->context.valid = FALSE;
2588 tls->async_state.valid = FALSE;
2589 invalidate_frames (tls);
2596 * Notify a thread that it needs to suspend.
2599 notify_thread (gpointer key, gpointer value, gpointer user_data)
2601 MonoInternalThread *thread = key;
2602 DebuggerTlsData *tls = value;
2603 gsize tid = thread->tid;
2606 if (GetCurrentThreadId () == tid || tls->terminated)
2609 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2612 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2613 * guarantee the signal handler will be called that many times. Instead of tracking
2614 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2615 * has been requested that hasn't been handled yet, otherwise we can have threads
2616 * refuse to die when VM_EXIT is called
2618 #if defined(__APPLE__)
2619 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2623 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2624 * of things like breaking waits etc. which we don't want.
2626 InterlockedIncrement (&tls->interrupt_count);
2629 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2631 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2633 if (mono_thread_info_new_interrupt_enabled ()) {
2634 MonoThreadInfo *info;
2637 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2639 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2641 * Attached thread which died without detaching.
2643 tls->terminated = TRUE;
2645 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2647 thread_interrupt (tls, info, NULL, ji);
2649 mono_thread_info_resume (mono_thread_info_get_tid (info));
2652 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2654 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2656 * Attached thread which died without detaching.
2658 tls->terminated = TRUE;
2665 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2667 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2671 if (mono_loader_lock_is_owned_by_self ()) {
2673 * Shortcut for the check in suspend_current (). This speeds up processing
2674 * when executing long running code inside the loader lock, i.e. assembly load
2680 if (debugger_thread_id == GetCurrentThreadId ())
2683 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2684 if (suspend_count - tls->resume_count > 0)
2685 tls->suspending = TRUE;
2687 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2689 if (suspend_count - tls->resume_count == 0) {
2691 * We are executing a single threaded invoke but the single step for
2692 * suspending is still active.
2693 * FIXME: This slows down single threaded invokes.
2695 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2699 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2701 /* Can't suspend in these methods */
2702 method = jinfo_get_method (ji);
2703 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2706 save_thread_context (ctx);
2714 * Increase the suspend count of the VM. While the suspend count is greater
2715 * than 0, runtime threads are suspended at certain points during execution.
2720 mono_loader_lock ();
2722 mono_mutex_lock (&suspend_mutex);
2726 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2728 if (suspend_count == 1) {
2729 // FIXME: Is it safe to call this inside the lock ?
2730 start_single_stepping ();
2731 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2734 mono_mutex_unlock (&suspend_mutex);
2736 if (suspend_count == 1)
2738 * Suspend creation of new threadpool threads, since they cannot run
2740 mono_thread_pool_suspend ();
2742 mono_loader_unlock ();
2748 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2756 g_assert (debugger_thread_id == GetCurrentThreadId ());
2758 mono_loader_lock ();
2760 mono_mutex_lock (&suspend_mutex);
2762 g_assert (suspend_count > 0);
2765 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2767 if (suspend_count == 0) {
2768 // FIXME: Is it safe to call this inside the lock ?
2769 stop_single_stepping ();
2770 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2773 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2774 err = mono_cond_broadcast (&suspend_cond);
2775 g_assert (err == 0);
2777 mono_mutex_unlock (&suspend_mutex);
2778 //g_assert (err == 0);
2780 if (suspend_count == 0)
2781 mono_thread_pool_resume ();
2783 mono_loader_unlock ();
2789 * Resume just one thread.
2792 resume_thread (MonoInternalThread *thread)
2795 DebuggerTlsData *tls;
2797 g_assert (debugger_thread_id == GetCurrentThreadId ());
2799 mono_loader_lock ();
2801 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2804 mono_mutex_lock (&suspend_mutex);
2806 g_assert (suspend_count > 0);
2808 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2810 tls->resume_count += suspend_count;
2813 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2814 * but only the one whose resume_count field is > 0 will be resumed.
2816 err = mono_cond_broadcast (&suspend_cond);
2817 g_assert (err == 0);
2819 mono_mutex_unlock (&suspend_mutex);
2820 //g_assert (err == 0);
2822 mono_loader_unlock ();
2826 invalidate_frames (DebuggerTlsData *tls)
2831 tls = mono_native_tls_get_value (debugger_tls_id);
2834 for (i = 0; i < tls->frame_count; ++i) {
2835 if (tls->frames [i]->jit)
2836 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2837 g_free (tls->frames [i]);
2839 g_free (tls->frames);
2840 tls->frame_count = 0;
2847 * Suspend the current thread until the runtime is resumed. If the thread has a
2848 * pending invoke, then the invoke is executed before this function returns.
2851 suspend_current (void)
2854 DebuggerTlsData *tls;
2856 g_assert (debugger_thread_id != GetCurrentThreadId ());
2858 if (mono_loader_lock_is_owned_by_self ()) {
2860 * If we own the loader mutex, can't suspend until we release it, since the
2861 * whole runtime can deadlock otherwise.
2866 tls = mono_native_tls_get_value (debugger_tls_id);
2869 mono_mutex_lock (&suspend_mutex);
2871 tls->suspending = FALSE;
2872 tls->really_suspended = TRUE;
2874 if (!tls->suspended) {
2875 tls->suspended = TRUE;
2876 MONO_SEM_POST (&suspend_sem);
2879 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2881 while (suspend_count - tls->resume_count > 0) {
2883 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2885 mono_mutex_unlock (&suspend_mutex);
2887 mono_mutex_lock (&suspend_mutex);
2893 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2894 g_assert (err == 0);
2898 tls->suspended = FALSE;
2899 tls->really_suspended = FALSE;
2901 threads_suspend_count --;
2903 mono_mutex_unlock (&suspend_mutex);
2905 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2907 if (tls->pending_invoke) {
2908 /* Save the original context */
2909 tls->pending_invoke->has_ctx = TRUE;
2910 tls->pending_invoke->ctx = tls->context.ctx;
2915 /* The frame info becomes invalid after a resume */
2916 tls->context.valid = FALSE;
2917 tls->async_state.valid = FALSE;
2918 invalidate_frames (tls);
2922 count_thread (gpointer key, gpointer value, gpointer user_data)
2924 DebuggerTlsData *tls = value;
2926 if (!tls->suspended && !tls->terminated)
2927 *(int*)user_data = *(int*)user_data + 1;
2931 count_threads_to_wait_for (void)
2935 mono_loader_lock ();
2936 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2937 mono_loader_unlock ();
2945 * Wait until the runtime is completely suspended.
2948 wait_for_suspend (void)
2950 int nthreads, nwait, err;
2951 gboolean waited = FALSE;
2953 // FIXME: Threads starting/stopping ?
2954 mono_loader_lock ();
2955 nthreads = mono_g_hash_table_size (thread_to_tls);
2956 mono_loader_unlock ();
2959 nwait = count_threads_to_wait_for ();
2961 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2962 err = MONO_SEM_WAIT (&suspend_sem);
2963 g_assert (err == 0);
2971 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2977 * Return whenever the runtime is suspended.
2982 return count_threads_to_wait_for () == 0;
2985 static MonoSeqPointInfo*
2986 get_seq_points (MonoDomain *domain, MonoMethod *method)
2988 MonoSeqPointInfo *seq_points;
2990 mono_domain_lock (domain);
2991 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2992 if (!seq_points && method->is_inflated) {
2993 /* generic sharing + aot */
2994 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2996 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2998 mono_domain_unlock (domain);
3004 no_seq_points_found (MonoMethod *method)
3007 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3009 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3013 * find_next_seq_point_for_native_offset:
3015 * Find the first sequence point after NATIVE_OFFSET.
3018 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3020 MonoSeqPointInfo *seq_points;
3023 seq_points = get_seq_points (domain, method);
3029 g_assert (seq_points);
3033 for (i = 0; i < seq_points->len; ++i) {
3034 if (seq_points->seq_points [i].native_offset >= native_offset)
3035 return &seq_points->seq_points [i];
3042 * find_prev_seq_point_for_native_offset:
3044 * Find the first sequence point before NATIVE_OFFSET.
3047 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3049 MonoSeqPointInfo *seq_points;
3052 seq_points = get_seq_points (domain, method);
3058 for (i = seq_points->len - 1; i >= 0; --i) {
3059 if (seq_points->seq_points [i].native_offset <= native_offset)
3060 return &seq_points->seq_points [i];
3069 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3070 * should be the location of a sequence point.
3072 static G_GNUC_UNUSED SeqPoint*
3073 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3075 MonoSeqPointInfo *seq_points;
3080 seq_points = get_seq_points (domain, method);
3085 for (i = 0; i < seq_points->len; ++i) {
3086 if (seq_points->seq_points [i].il_offset == il_offset)
3087 return &seq_points->seq_points [i];
3094 DebuggerTlsData *tls;
3096 } ComputeFramesUserData;
3099 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3101 ComputeFramesUserData *ud = user_data;
3103 MonoMethod *method, *actual_method, *api_method;
3107 if (info->type != FRAME_TYPE_MANAGED) {
3108 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3109 /* Mark the last frame as an invoke frame */
3111 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3117 method = jinfo_get_method (info->ji);
3119 method = info->method;
3120 actual_method = info->actual_method;
3121 api_method = method;
3126 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3129 if (info->il_offset == -1) {
3130 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3131 if (ud->frames == NULL) {
3132 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3134 info->il_offset = sp->il_offset;
3136 if (info->il_offset == -1)
3137 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3140 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));
3142 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3143 if (!CHECK_PROTOCOL_VERSION (2, 17))
3144 /* Older clients can't handle this flag */
3146 api_method = mono_marshal_method_from_wrapper (method);
3149 actual_method = api_method;
3150 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3153 frame = g_new0 (StackFrame, 1);
3154 frame->method = method;
3155 frame->actual_method = actual_method;
3156 frame->api_method = api_method;
3157 frame->il_offset = info->il_offset;
3158 frame->native_offset = info->native_offset;
3159 frame->flags = flags;
3160 frame->ji = info->ji;
3161 if (info->reg_locations)
3162 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3165 frame->has_ctx = TRUE;
3167 frame->domain = info->domain;
3169 ud->frames = g_slist_append (ud->frames, frame);
3175 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3177 ComputeFramesUserData *ud = user_data;
3180 * 'tls->filter_ctx' is the location of the throw site.
3182 * mono_walk_stack() will never actually hit the throw site, but unwind
3183 * directly from the filter to the call site; we abort stack unwinding here
3184 * once this happens and resume from the throw site.
3187 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3190 return process_frame (info, ctx, user_data);
3194 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3196 ComputeFramesUserData user_data;
3198 int i, findex, new_frame_count;
3199 StackFrame **new_frames, *f;
3200 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3202 // FIXME: Locking on tls
3203 if (tls->frames && tls->frames_up_to_date)
3206 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3208 user_data.tls = tls;
3209 user_data.frames = NULL;
3210 if (tls->terminated) {
3211 tls->frame_count = 0;
3213 } if (!tls->really_suspended && tls->async_state.valid) {
3214 /* Have to use the state saved by the signal handler */
3215 process_frame (&tls->async_last_frame, NULL, &user_data);
3216 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3217 } else if (tls->filter_state.valid) {
3219 * We are inside an exception filter.
3221 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3223 if (tls->context.valid)
3224 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3226 * After that, we resume unwinding from the location where the exception has been thrown.
3228 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3229 } else if (tls->context.valid) {
3230 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3233 tls->frame_count = 0;
3237 new_frame_count = g_slist_length (user_data.frames);
3238 new_frames = g_new0 (StackFrame*, new_frame_count);
3240 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3244 * Reuse the id for already existing stack frames, so invokes don't invalidate
3245 * the still valid stack frames.
3247 for (i = 0; i < tls->frame_count; ++i) {
3248 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3249 f->id = tls->frames [i]->id;
3254 if (i >= tls->frame_count)
3255 f->id = InterlockedIncrement (&frame_id);
3257 new_frames [findex ++] = f;
3260 g_slist_free (user_data.frames);
3262 invalidate_frames (tls);
3264 tls->frames = new_frames;
3265 tls->frame_count = new_frame_count;
3266 tls->frames_up_to_date = TRUE;
3270 * GHFunc to emit an appdomain creation event
3271 * @param key Don't care
3272 * @param value A loaded appdomain
3273 * @param user_data Don't care
3276 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3278 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3279 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3283 * GHFunc to emit a thread start event
3284 * @param key A thread id
3285 * @param value A thread object
3286 * @param user_data Don't care
3289 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3291 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3292 process_profiler_event (EVENT_KIND_THREAD_START, value);
3296 * GFunc to emit an assembly load event
3297 * @param value A loaded assembly
3298 * @param user_data Don't care
3301 emit_assembly_load (gpointer value, gpointer user_data)
3303 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3307 * GFunc to emit a type load event
3308 * @param value A loaded type
3309 * @param user_data Don't care
3312 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3314 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3318 strdup_tolower (char *s)
3323 for (p = s2; *p; ++p)
3333 * create_event_list:
3335 * Return a list of event request ids matching EVENT, starting from REQS, which
3336 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3338 * We return request ids, instead of requests, to simplify threading, since
3339 * requests could be deleted anytime when the loader lock is not held.
3340 * LOCKING: Assumes the loader lock is held.
3343 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3346 GSList *events = NULL;
3348 *suspend_policy = SUSPEND_POLICY_NONE;
3351 reqs = event_requests;
3356 for (i = 0; i < reqs->len; ++i) {
3357 EventRequest *req = g_ptr_array_index (reqs, i);
3358 if (req->event_kind == event) {
3359 gboolean filtered = FALSE;
3362 for (j = 0; j < req->nmodifiers; ++j) {
3363 Modifier *mod = &req->modifiers [j];
3365 if (mod->kind == MOD_KIND_COUNT) {
3367 if (mod->data.count > 0) {
3368 if (mod->data.count > 0) {
3370 if (mod->data.count == 0)
3374 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3375 if (mod->data.thread != mono_thread_internal_current ())
3377 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3378 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3380 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3382 if (ei->caught && !mod->caught)
3384 if (!ei->caught && !mod->uncaught)
3386 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3388 gboolean found = FALSE;
3389 MonoAssembly **assemblies = mod->data.assemblies;
3392 for (k = 0; assemblies [k]; ++k)
3393 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3398 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3399 gpointer iter = NULL;
3401 MonoDebugSourceInfo *sinfo;
3402 char *source_file, *s;
3403 gboolean found = FALSE;
3405 GPtrArray *source_file_list;
3407 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3408 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3411 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3412 for (i = 0; i < source_file_list->len; ++i) {
3413 sinfo = g_ptr_array_index (source_file_list, i);
3415 * Do a case-insesitive match by converting the file name to
3418 s = strdup_tolower (sinfo->source_file);
3419 if (g_hash_table_lookup (mod->data.source_files, s))
3422 char *s2 = g_path_get_basename (sinfo->source_file);
3423 char *s3 = strdup_tolower (s2);
3425 if (g_hash_table_lookup (mod->data.source_files, s3))
3432 g_ptr_array_free (source_file_list, TRUE);
3437 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3440 s = mono_type_full_name (&ei->klass->byval_arg);
3441 if (!g_hash_table_lookup (mod->data.type_names, s))
3444 } else if (mod->kind == MOD_KIND_STEP) {
3445 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3446 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3447 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3449 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3450 MonoCustomAttrInfo *ainfo;
3451 static MonoClass *klass;
3454 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3457 if (!ji->dbg_hidden_inited) {
3458 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3460 if (mono_custom_attrs_has_attr (ainfo, klass))
3461 ji->dbg_hidden = TRUE;
3462 mono_custom_attrs_free (ainfo);
3464 ji->dbg_hidden_inited = TRUE;
3469 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3470 MonoCustomAttrInfo *ainfo;
3471 static MonoClass *klass;
3474 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3477 if (!ji->dbg_step_through_inited) {
3478 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3480 if (mono_custom_attrs_has_attr (ainfo, klass))
3481 ji->dbg_step_through = TRUE;
3482 mono_custom_attrs_free (ainfo);
3484 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3486 if (mono_custom_attrs_has_attr (ainfo, klass))
3487 ji->dbg_step_through = TRUE;
3488 mono_custom_attrs_free (ainfo);
3490 ji->dbg_step_through_inited = TRUE;
3492 if (ji->dbg_step_through)
3499 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3500 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3505 /* Send a VM START/DEATH event by default */
3506 if (event == EVENT_KIND_VM_START)
3507 events = g_slist_append (events, GINT_TO_POINTER (0));
3508 if (event == EVENT_KIND_VM_DEATH)
3509 events = g_slist_append (events, GINT_TO_POINTER (0));
3514 static G_GNUC_UNUSED const char*
3515 event_to_string (EventKind event)
3518 case EVENT_KIND_VM_START: return "VM_START";
3519 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3520 case EVENT_KIND_THREAD_START: return "THREAD_START";
3521 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3522 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3523 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3524 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3525 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3526 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3527 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3528 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3529 case EVENT_KIND_STEP: return "STEP";
3530 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3531 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3532 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3533 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3534 case EVENT_KIND_USER_LOG: return "USER_LOG";
3536 g_assert_not_reached ();
3544 * Send an event to the client, suspending the vm if needed.
3545 * LOCKING: Since this can suspend the calling thread, no locks should be held
3547 * The EVENTS list is freed by this function.
3550 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3554 MonoDomain *domain = mono_domain_get ();
3555 MonoThread *thread = NULL;
3556 MonoObject *keepalive_obj = NULL;
3557 gboolean send_success = FALSE;
3562 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3566 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3567 // FIXME: We miss those events
3568 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3572 if (vm_death_event_sent) {
3573 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3577 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3578 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3583 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3587 if (event == EVENT_KIND_KEEPALIVE)
3588 suspend_policy = SUSPEND_POLICY_NONE;
3593 if (agent_config.defer) {
3594 /* Make sure the thread id is always set when doing deferred debugging */
3595 if (debugger_thread_id == GetCurrentThreadId ()) {
3596 /* Don't suspend on events from the debugger thread */
3597 suspend_policy = SUSPEND_POLICY_NONE;
3598 thread = mono_thread_get_main ();
3600 else thread = mono_thread_current ();
3602 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3603 // FIXME: Send these with a NULL thread, don't suspend the current thread
3608 nevents = g_slist_length (events);
3609 buffer_init (&buf, 128);
3610 buffer_add_byte (&buf, suspend_policy);
3611 buffer_add_int (&buf, nevents);
3613 for (l = events; l; l = l->next) {
3614 buffer_add_byte (&buf, event); // event kind
3615 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3620 thread = mono_thread_current ();
3622 if (event == EVENT_KIND_VM_START && arg != NULL)
3625 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3628 case EVENT_KIND_THREAD_START:
3629 case EVENT_KIND_THREAD_DEATH:
3631 case EVENT_KIND_APPDOMAIN_CREATE:
3632 case EVENT_KIND_APPDOMAIN_UNLOAD:
3633 buffer_add_domainid (&buf, arg);
3635 case EVENT_KIND_METHOD_ENTRY:
3636 case EVENT_KIND_METHOD_EXIT:
3637 buffer_add_methodid (&buf, domain, arg);
3639 case EVENT_KIND_ASSEMBLY_LOAD:
3640 case EVENT_KIND_ASSEMBLY_UNLOAD:
3641 buffer_add_assemblyid (&buf, domain, arg);
3643 case EVENT_KIND_TYPE_LOAD:
3644 buffer_add_typeid (&buf, domain, arg);
3646 case EVENT_KIND_BREAKPOINT:
3647 case EVENT_KIND_STEP:
3648 buffer_add_methodid (&buf, domain, arg);
3649 buffer_add_long (&buf, il_offset);
3651 case EVENT_KIND_VM_START:
3652 buffer_add_domainid (&buf, mono_get_root_domain ());
3654 case EVENT_KIND_VM_DEATH:
3655 if (CHECK_PROTOCOL_VERSION (2, 27))
3656 buffer_add_int (&buf, mono_environment_exitcode_get ());
3658 case EVENT_KIND_EXCEPTION: {
3659 EventInfo *ei = arg;
3660 buffer_add_objid (&buf, ei->exc);
3662 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3663 * later after the suspension. (#12494).
3665 keepalive_obj = ei->exc;
3668 case EVENT_KIND_USER_BREAK:
3670 case EVENT_KIND_USER_LOG: {
3671 EventInfo *ei = arg;
3672 buffer_add_int (&buf, ei->level);
3673 buffer_add_string (&buf, ei->category ? ei->category : "");
3674 buffer_add_string (&buf, ei->message ? ei->message : "");
3677 case EVENT_KIND_KEEPALIVE:
3678 suspend_policy = SUSPEND_POLICY_NONE;
3681 g_assert_not_reached ();
3685 if (event == EVENT_KIND_VM_START) {
3686 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3687 if (!agent_config.defer)
3688 start_debugger_thread ();
3691 if (event == EVENT_KIND_VM_DEATH) {
3692 vm_death_event_sent = TRUE;
3693 suspend_policy = SUSPEND_POLICY_NONE;
3696 if (mono_runtime_is_shutting_down ())
3697 suspend_policy = SUSPEND_POLICY_NONE;
3699 if (suspend_policy != SUSPEND_POLICY_NONE) {
3701 * Save the thread context and start suspending before sending the packet,
3702 * since we could be receiving the resume request before send_packet ()
3705 save_thread_context (ctx);
3709 /* This will keep this object alive */
3710 get_objref (keepalive_obj);
3713 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3717 g_slist_free (events);
3720 if (!send_success) {
3721 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3725 if (event == EVENT_KIND_VM_START) {
3726 vm_start_event_sent = TRUE;
3729 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3731 switch (suspend_policy) {
3732 case SUSPEND_POLICY_NONE:
3734 case SUSPEND_POLICY_ALL:
3737 case SUSPEND_POLICY_EVENT_THREAD:
3741 g_assert_not_reached ();
3746 process_profiler_event (EventKind event, gpointer arg)
3750 EventInfo ei, *ei_arg = NULL;
3752 if (event == EVENT_KIND_TYPE_LOAD) {
3757 mono_loader_lock ();
3758 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3759 mono_loader_unlock ();
3761 process_event (event, arg, 0, NULL, events, suspend_policy);
3765 runtime_initialized (MonoProfiler *prof)
3767 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3768 if (agent_config.defer)
3769 start_debugger_thread ();
3773 runtime_shutdown (MonoProfiler *prof)
3775 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3777 mono_debugger_agent_cleanup ();
3781 thread_startup (MonoProfiler *prof, uintptr_t tid)
3783 MonoInternalThread *thread = mono_thread_internal_current ();
3784 MonoInternalThread *old_thread;
3785 DebuggerTlsData *tls;
3787 if (tid == debugger_thread_id)
3790 g_assert (thread->tid == tid);
3792 mono_loader_lock ();
3793 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3794 mono_loader_unlock ();
3796 if (thread == old_thread) {
3798 * For some reason, thread_startup () might be called for the same thread
3799 * multiple times (attach ?).
3801 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3805 * thread_end () might not be called for some threads, and the tid could
3808 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3809 mono_loader_lock ();
3810 mono_g_hash_table_remove (thread_to_tls, old_thread);
3811 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3812 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3813 mono_loader_unlock ();
3817 tls = mono_native_tls_get_value (debugger_tls_id);
3819 // FIXME: Free this somewhere
3820 tls = g_new0 (DebuggerTlsData, 1);
3821 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3822 tls->thread = thread;
3823 mono_native_tls_set_value (debugger_tls_id, tls);
3825 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3827 mono_loader_lock ();
3828 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3829 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3830 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3831 mono_loader_unlock ();
3833 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3836 * suspend_vm () could have missed this thread, so wait for a resume.
3842 thread_end (MonoProfiler *prof, uintptr_t tid)
3844 MonoInternalThread *thread;
3845 DebuggerTlsData *tls = NULL;
3847 mono_loader_lock ();
3848 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3850 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3851 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3853 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3854 tls->terminated = TRUE;
3855 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3856 MONO_GC_UNREGISTER_ROOT (tls->thread);
3860 mono_loader_unlock ();
3862 /* We might be called for threads started before we registered the start callback */
3864 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3865 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3870 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3872 mono_loader_lock ();
3873 g_hash_table_insert (domains, domain, domain);
3874 mono_loader_unlock ();
3876 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3880 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3882 clear_breakpoints_for_domain (domain);
3884 mono_loader_lock ();
3885 /* Invalidate each thread's frame stack */
3886 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3887 mono_loader_unlock ();
3889 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3893 * invalidate_each_thread:
3895 * A GHFunc to invalidate frames.
3896 * value must be a DebuggerTlsData*
3899 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3901 invalidate_frames (value);
3905 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3907 /* Sent later in jit_end () */
3908 mono_loader_lock ();
3909 g_ptr_array_add (pending_assembly_loads, assembly);
3910 mono_loader_unlock ();
3914 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3916 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3918 clear_event_requests_for_assembly (assembly);
3919 clear_types_for_assembly (assembly);
3923 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3925 #if defined(HOST_WIN32) && !defined(__GNUC__)
3926 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3928 gpointer stackptr = __builtin_frame_address (1);
3930 MonoInternalThread *thread = mono_thread_internal_current ();
3931 DebuggerTlsData *tls;
3933 mono_loader_lock ();
3935 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3936 /* Could be the debugger thread with assembly/type load hooks */
3938 tls->invoke_addr = stackptr;
3940 mono_loader_unlock ();
3944 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3947 #if defined(HOST_WIN32) && !defined(__GNUC__)
3948 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3950 gpointer stackptr = __builtin_frame_address (1);
3953 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3957 * We need to stop single stepping when exiting a runtime invoke, since if it is
3958 * a step out, it may return to native code, and thus never end.
3960 mono_loader_lock ();
3961 ss_invoke_addr = NULL;
3963 for (i = 0; i < event_requests->len; ++i) {
3964 EventRequest *req = g_ptr_array_index (event_requests, i);
3966 if (req->event_kind == EVENT_KIND_STEP) {
3967 ss_destroy (req->info);
3968 g_ptr_array_remove_index_fast (event_requests, i);
3973 mono_loader_unlock ();
3977 send_type_load (MonoClass *klass)
3979 gboolean type_load = FALSE;
3980 MonoDomain *domain = mono_domain_get ();
3981 AgentDomainInfo *info = NULL;
3983 mono_loader_lock ();
3984 mono_domain_lock (domain);
3986 info = get_agent_domain_info (domain);
3988 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3990 g_hash_table_insert (info->loaded_classes, klass, klass);
3993 mono_domain_unlock (domain);
3994 mono_loader_unlock ();
3996 emit_type_load (klass, klass, NULL);
4000 * Emit load events for all types currently loaded in the domain.
4001 * Takes the loader and domain locks.
4002 * user_data is unused.
4005 send_types_for_domain (MonoDomain *domain, void *user_data)
4007 AgentDomainInfo *info = NULL;
4009 mono_loader_lock ();
4010 mono_domain_lock (domain);
4011 info = get_agent_domain_info (domain);
4013 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4014 mono_domain_unlock (domain);
4015 mono_loader_unlock ();
4019 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4022 * We emit type load events when the first method of the type is JITted,
4023 * since the class load profiler callbacks might be called with the
4024 * loader lock held. They could also occur in the debugger thread.
4025 * Same for assembly load events.
4028 MonoAssembly *assembly = NULL;
4030 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4031 mono_loader_lock ();
4032 if (pending_assembly_loads->len > 0) {
4033 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4034 g_ptr_array_remove_index (pending_assembly_loads, 0);
4036 mono_loader_unlock ();
4039 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4045 send_type_load (method->klass);
4048 add_pending_breakpoints (method, jinfo);
4052 * BREAKPOINTS/SINGLE STEPPING
4056 * Contains information about an inserted breakpoint.
4059 long il_offset, native_offset;
4064 } BreakpointInstance;
4067 * Contains generic information about a breakpoint.
4071 * The method where the breakpoint is placed. Can be NULL in which case it
4072 * is inserted into every method. This is used to implement method entry/
4073 * exit events. Can be a generic method definition, in which case the
4074 * breakpoint is inserted into every instance.
4080 * A list of BreakpointInstance structures describing where the breakpoint
4081 * was inserted. There could be more than one because of
4082 * generics/appdomains/method entry/exit.
4084 GPtrArray *children;
4087 /* List of breakpoints */
4088 static GPtrArray *breakpoints;
4089 /* Maps breakpoint locations to the number of breakpoints at that location */
4090 static GHashTable *bp_locs;
4093 breakpoints_init (void)
4095 breakpoints = g_ptr_array_new ();
4096 bp_locs = g_hash_table_new (NULL, NULL);
4100 * insert_breakpoint:
4102 * Insert the breakpoint described by BP into the method described by
4106 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4109 BreakpointInstance *inst;
4110 SeqPoint *sp = NULL;
4113 mono_error_init (error);
4115 for (i = 0; i < seq_points->len; ++i) {
4116 sp = &seq_points->seq_points [i];
4118 if (sp->il_offset == bp->il_offset)
4122 if (i == seq_points->len) {
4124 * The set of IL offsets with seq points doesn't completely match the
4125 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4127 for (i = 0; i < seq_points->len; ++i) {
4128 sp = &seq_points->seq_points [i];
4130 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4135 if (i == seq_points->len) {
4136 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);
4138 for (i = 0; i < seq_points->len; ++i)
4139 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4142 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4143 g_warning ("%s", s);
4147 g_warning ("%s", s);
4153 inst = g_new0 (BreakpointInstance, 1);
4155 inst->native_offset = sp->native_offset;
4156 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4158 inst->domain = domain;
4160 mono_loader_lock ();
4162 g_ptr_array_add (bp->children, inst);
4164 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4165 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4166 mono_loader_unlock ();
4168 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4169 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4170 } else if (count == 0) {
4171 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4172 mono_arch_set_breakpoint (ji, inst->ip);
4178 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));
4182 remove_breakpoint (BreakpointInstance *inst)
4184 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4186 MonoJitInfo *ji = inst->ji;
4187 guint8 *ip = inst->ip;
4189 mono_loader_lock ();
4190 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4191 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4192 mono_loader_unlock ();
4194 g_assert (count > 0);
4196 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4197 mono_arch_clear_breakpoint (ji, ip);
4204 static inline gboolean
4205 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4211 if (method == bp->method)
4213 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4216 if (bp->method->is_inflated && method->is_inflated) {
4217 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4218 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4220 /* Open generic methods should match closed generic methods of the same class */
4221 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4222 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4223 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4225 /* FIXME: Handle !mvar */
4226 if (t1->type != MONO_TYPE_MVAR)
4237 * add_pending_breakpoints:
4239 * Insert pending breakpoints into the newly JITted method METHOD.
4242 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4245 MonoSeqPointInfo *seq_points;
4247 MonoMethod *jmethod;
4252 domain = mono_domain_get ();
4254 mono_loader_lock ();
4256 for (i = 0; i < breakpoints->len; ++i) {
4257 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4258 gboolean found = FALSE;
4260 if (!bp_matches_method (bp, method))
4263 for (j = 0; j < bp->children->len; ++j) {
4264 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4271 jmethod = jinfo_get_method (ji);
4272 mono_domain_lock (domain);
4273 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4274 if (!seq_points && jmethod->is_inflated)
4275 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4276 mono_domain_unlock (domain);
4278 /* Could be AOT code */
4280 g_assert (seq_points);
4282 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4286 mono_loader_unlock ();
4290 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4296 mono_error_init (error);
4298 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4300 /* Might be AOTed code */
4301 code = mono_aot_get_method (domain, method);
4303 ji = mono_jit_info_table_find (domain, code);
4308 insert_breakpoint (seq_points, domain, ji, bp, error);
4312 clear_breakpoint (MonoBreakpoint *bp);
4317 * Set a breakpoint at IL_OFFSET in METHOD.
4318 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4319 * METHOD can also be a generic method definition, in which case a breakpoint
4320 * is placed in all instances of the method.
4321 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4324 static MonoBreakpoint*
4325 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4328 GHashTableIter iter, iter2;
4331 MonoSeqPointInfo *seq_points;
4334 mono_error_init (error);
4337 // - suspend/resume the vm to prevent code patching problems
4338 // - multiple breakpoints on the same location
4339 // - dynamic methods
4342 bp = g_new0 (MonoBreakpoint, 1);
4343 bp->method = method;
4344 bp->il_offset = il_offset;
4346 bp->children = g_ptr_array_new ();
4348 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));
4350 mono_loader_lock ();
4352 g_hash_table_iter_init (&iter, domains);
4353 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4354 mono_domain_lock (domain);
4356 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4357 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4358 if (bp_matches_method (bp, m))
4359 set_bp_in_method (domain, m, seq_points, bp, error);
4362 mono_domain_unlock (domain);
4365 mono_loader_unlock ();
4367 mono_loader_lock ();
4368 g_ptr_array_add (breakpoints, bp);
4369 mono_loader_unlock ();
4371 if (error && !mono_error_ok (error)) {
4372 clear_breakpoint (bp);
4380 clear_breakpoint (MonoBreakpoint *bp)
4384 // FIXME: locking, races
4385 for (i = 0; i < bp->children->len; ++i) {
4386 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4388 remove_breakpoint (inst);
4393 mono_loader_lock ();
4394 g_ptr_array_remove (breakpoints, bp);
4395 mono_loader_unlock ();
4397 g_ptr_array_free (bp->children, TRUE);
4402 breakpoints_cleanup (void)
4406 mono_loader_lock ();
4408 while (i < event_requests->len) {
4409 EventRequest *req = g_ptr_array_index (event_requests, i);
4411 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4412 clear_breakpoint (req->info);
4413 g_ptr_array_remove_index_fast (event_requests, i);
4420 for (i = 0; i < breakpoints->len; ++i)
4421 g_free (g_ptr_array_index (breakpoints, i));
4423 g_ptr_array_free (breakpoints, TRUE);
4424 g_hash_table_destroy (bp_locs);
4429 mono_loader_unlock ();
4433 * clear_breakpoints_for_domain:
4435 * Clear breakpoint instances which reference DOMAIN.
4438 clear_breakpoints_for_domain (MonoDomain *domain)
4442 /* This could be called after shutdown */
4446 mono_loader_lock ();
4447 for (i = 0; i < breakpoints->len; ++i) {
4448 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4451 while (j < bp->children->len) {
4452 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4454 if (inst->domain == domain) {
4455 remove_breakpoint (inst);
4459 g_ptr_array_remove_index_fast (bp->children, j);
4465 mono_loader_unlock ();
4471 * Return FALSE if single stepping needs to continue.
4474 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4476 MonoDebugMethodInfo *minfo;
4477 MonoDebugSourceLocation *loc = NULL;
4478 gboolean hit = TRUE;
4481 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4483 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4485 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4489 if (req->depth == STEP_DEPTH_OVER && hit) {
4490 if (!tls->context.valid)
4491 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4492 compute_frame_info (tls->thread, tls);
4493 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4494 /* Hit the breakpoint in a recursive call */
4495 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4500 if (req->size != STEP_SIZE_LINE)
4503 /* Have to check whenever a different source line was reached */
4504 method = jinfo_get_method (ji);
4505 minfo = mono_debug_lookup_method (method);
4508 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4510 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4511 /* Have to continue single stepping */
4513 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4515 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4520 ss_req->last_method = method;
4521 ss_req->last_line = loc->row;
4522 mono_debug_free_source_location (loc);
4529 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4531 return bp->method && bp->method->klass->image->assembly == assembly;
4535 process_breakpoint_inner (DebuggerTlsData *tls)
4539 int i, j, suspend_policy;
4540 guint32 native_offset;
4542 BreakpointInstance *inst;
4543 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4544 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4545 EventKind kind = EVENT_KIND_BREAKPOINT;
4546 MonoContext *ctx = &tls->restore_ctx;
4548 MonoSeqPointInfo *info;
4551 // FIXME: Speed this up
4553 ip = MONO_CONTEXT_GET_IP (ctx);
4554 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4556 method = jinfo_get_method (ji);
4558 /* Compute the native offset of the breakpoint from the ip */
4559 native_offset = ip - (guint8*)ji->code_start;
4562 * Skip the instruction causing the breakpoint signal.
4564 mono_arch_skip_breakpoint (ctx, ji);
4566 if (method->wrapper_type || tls->disable_breakpoints)
4569 bp_reqs = g_ptr_array_new ();
4570 ss_reqs = g_ptr_array_new ();
4571 ss_reqs_orig = g_ptr_array_new ();
4573 mono_loader_lock ();
4576 * The ip points to the instruction causing the breakpoint event, which is after
4577 * the offset recorded in the seq point map, so find the prev seq point before ip.
4579 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4581 no_seq_points_found (method);
4584 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));
4587 for (i = 0; i < breakpoints->len; ++i) {
4588 bp = g_ptr_array_index (breakpoints, i);
4593 for (j = 0; j < bp->children->len; ++j) {
4594 inst = g_ptr_array_index (bp->children, j);
4595 if (inst->ji == ji && inst->sp == sp) {
4596 if (bp->req->event_kind == EVENT_KIND_STEP) {
4597 g_ptr_array_add (ss_reqs_orig, bp->req);
4599 g_ptr_array_add (bp_reqs, bp->req);
4604 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4605 /* Maybe a method entry/exit event */
4606 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4607 kind = EVENT_KIND_METHOD_ENTRY;
4608 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4609 kind = EVENT_KIND_METHOD_EXIT;
4612 /* Process single step requests */
4613 for (i = 0; i < ss_reqs_orig->len; ++i) {
4614 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4615 SingleStepReq *ss_req = req->info;
4618 if (mono_thread_internal_current () != ss_req->thread)
4621 hit = ss_update (ss_req, ji, sp, tls, ctx);
4623 g_ptr_array_add (ss_reqs, req);
4625 /* Start single stepping again from the current sequence point */
4626 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4629 if (ss_reqs->len > 0)
4630 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4631 if (bp_reqs->len > 0)
4632 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4633 if (kind != EVENT_KIND_BREAKPOINT)
4634 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4636 mono_loader_unlock ();
4638 g_ptr_array_free (bp_reqs, TRUE);
4639 g_ptr_array_free (ss_reqs, TRUE);
4642 * FIXME: The first event will suspend, so the second will only be sent after the
4646 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4648 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4649 if (enter_leave_events)
4650 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4653 /* Process a breakpoint/single step event after resuming from a signal handler */
4655 process_signal_event (void (*func) (DebuggerTlsData*))
4657 DebuggerTlsData *tls;
4658 MonoContext orig_restore_ctx, ctx;
4660 tls = mono_native_tls_get_value (debugger_tls_id);
4661 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4662 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4663 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4667 /* This is called when resuming from a signal handler, so it shouldn't return */
4668 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4669 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4670 mono_restore_context (&ctx);
4671 g_assert_not_reached ();
4675 process_breakpoint (void)
4677 process_signal_event (process_breakpoint_inner);
4681 resume_from_signal_handler (void *sigctx, void *func)
4683 DebuggerTlsData *tls;
4686 /* Save the original context in TLS */
4687 // FIXME: This might not work on an altstack ?
4688 tls = mono_native_tls_get_value (debugger_tls_id);
4690 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4693 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4694 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4695 // clob:c could be added to op_seq_point.
4697 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4698 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4699 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4700 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4702 MONO_CONTEXT_SET_IP (&ctx, func);
4704 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4706 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4707 mono_ppc_set_func_into_sigctx (sigctx, func);
4712 mono_debugger_agent_breakpoint_hit (void *sigctx)
4715 * We are called from a signal handler, and running code there causes all kinds of
4716 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4717 * So set up the signal context to return to the real breakpoint handler function.
4719 resume_from_signal_handler (sigctx, process_breakpoint);
4723 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4725 if (frame->managed) {
4726 *(MonoContext*)data = *ctx;
4735 * Called by System.Diagnostics.Debugger:Break ().
4738 mono_debugger_agent_user_break (void)
4740 if (agent_config.enabled) {
4745 /* Obtain a context */
4746 MONO_CONTEXT_SET_IP (&ctx, NULL);
4747 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4748 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4750 mono_loader_lock ();
4751 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4752 mono_loader_unlock ();
4754 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4761 ss_depth_to_string (StepDepth depth)
4764 case STEP_DEPTH_OVER:
4766 case STEP_DEPTH_OUT:
4768 case STEP_DEPTH_INTO:
4771 g_assert_not_reached ();
4777 process_single_step_inner (DebuggerTlsData *tls)
4782 int il_offset, suspend_policy;
4785 MonoContext *ctx = &tls->restore_ctx;
4788 MonoSeqPointInfo *info;
4790 ip = MONO_CONTEXT_GET_IP (ctx);
4792 /* Skip the instruction causing the single step */
4793 mono_arch_skip_single_step (ctx);
4795 if (suspend_count > 0) {
4796 process_suspend (tls, ctx);
4801 // FIXME: A suspend race
4804 if (mono_thread_internal_current () != ss_req->thread)
4807 if (log_level > 0) {
4808 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4810 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));
4813 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4815 method = jinfo_get_method (ji);
4818 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4823 * Stopping in memset makes half-initialized vtypes visible.
4824 * Stopping in memcpy makes half-copied vtypes visible.
4826 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4830 * The ip points to the instruction causing the single step event, which is before
4831 * the offset recorded in the seq point map, so find the next seq point after ip.
4833 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
4836 il_offset = sp->il_offset;
4838 if (!ss_update (ss_req, ji, sp, tls, ctx))
4841 /* Start single stepping again from the current sequence point */
4842 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4844 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4845 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4846 !strcmp (method->name, ".cctor"))
4849 // FIXME: Has to lock earlier
4851 reqs = g_ptr_array_new ();
4853 mono_loader_lock ();
4855 g_ptr_array_add (reqs, ss_req->req);
4857 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4859 g_ptr_array_free (reqs, TRUE);
4861 mono_loader_unlock ();
4863 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4867 process_single_step (void)
4869 process_signal_event (process_single_step_inner);
4873 * mono_debugger_agent_single_step_event:
4875 * Called from a signal handler to handle a single step event.
4878 mono_debugger_agent_single_step_event (void *sigctx)
4880 /* Resume to process_single_step through the signal context */
4882 // FIXME: Since step out/over is implemented using step in, the step in case should
4883 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4886 if (GetCurrentThreadId () == debugger_thread_id) {
4888 * This could happen despite our best effors when the runtime calls
4889 * assembly/type resolve hooks.
4890 * FIXME: Breakpoints too.
4894 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4895 mono_arch_skip_single_step (&ctx);
4896 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4900 resume_from_signal_handler (sigctx, process_single_step);
4904 debugger_agent_single_step_from_context (MonoContext *ctx)
4906 DebuggerTlsData *tls;
4907 MonoContext orig_restore_ctx;
4909 tls = mono_native_tls_get_value (debugger_tls_id);
4912 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4913 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4914 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4916 process_single_step_inner (tls);
4918 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4919 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4923 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4925 DebuggerTlsData *tls;
4926 MonoContext orig_restore_ctx;
4928 tls = mono_native_tls_get_value (debugger_tls_id);
4930 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4931 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4933 process_breakpoint_inner (tls);
4935 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4936 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4940 * start_single_stepping:
4942 * Turn on single stepping. Can be called multiple times, for example,
4943 * by a single step event request + a suspend.
4946 start_single_stepping (void)
4948 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4949 int val = InterlockedIncrement (&ss_count);
4952 mono_arch_start_single_stepping ();
4954 if (ss_req != NULL && ss_invoke_addr == NULL) {
4955 DebuggerTlsData *tls;
4957 mono_loader_lock ();
4959 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4960 ss_invoke_addr = tls->invoke_addr;
4962 mono_loader_unlock ();
4965 g_assert_not_reached ();
4970 stop_single_stepping (void)
4972 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4973 int val = InterlockedDecrement (&ss_count);
4976 mono_arch_stop_single_stepping ();
4978 ss_invoke_addr = NULL;
4980 g_assert_not_reached ();
4987 * Stop the single stepping operation given by SS_REQ.
4990 ss_stop (SingleStepReq *ss_req)
4995 for (l = ss_req->bps; l; l = l->next) {
4996 clear_breakpoint (l->data);
4998 g_slist_free (ss_req->bps);
5002 if (ss_req->global) {
5003 stop_single_stepping ();
5004 ss_req->global = FALSE;
5011 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5012 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5013 * belong to the same thread as CTX.
5016 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5018 int i, j, frame_index;
5021 gboolean enable_global = FALSE;
5023 /* Stop the previous operation */
5027 * Implement single stepping using breakpoints if possible.
5029 if (step_to_catch) {
5030 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5031 ss_req->bps = g_slist_append (ss_req->bps, bp);
5035 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5036 /* Need parent frames */
5037 if (!tls->context.valid)
5038 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5039 compute_frame_info (tls->thread, tls);
5043 * Find the first sequence point in the current or in a previous frame which
5044 * is not the last in its method.
5046 if (ss_req->depth == STEP_DEPTH_OUT) {
5047 /* Ignore seq points in current method */
5048 while (frame_index < tls->frame_count) {
5049 StackFrame *frame = tls->frames [frame_index];
5051 method = frame->method;
5052 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5054 if (sp && sp->next_len != 0)
5057 // There could be method calls before the next seq point in the caller when using nested calls
5058 //enable_global = TRUE;
5060 if (sp && sp->next_len == 0) {
5062 while (frame_index < tls->frame_count) {
5063 StackFrame *frame = tls->frames [frame_index];
5065 method = frame->method;
5066 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5067 if (sp && sp->next_len != 0)
5075 if (sp && sp->next_len > 0) {
5076 for (i = 0; i < sp->next_len; ++i) {
5077 next_sp = &info->seq_points [sp->next [i]];
5079 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5080 ss_req->bps = g_slist_append (ss_req->bps, bp);
5084 if (ss_req->depth == STEP_DEPTH_OVER) {
5085 if (ss_req->nframes == 0)
5086 ss_req->nframes = tls->frame_count;
5087 /* Need to stop in catch clauses as well */
5088 for (i = 0; i < tls->frame_count; ++i) {
5089 StackFrame *frame = tls->frames [i];
5092 MonoJitInfo *jinfo = frame->ji;
5093 for (j = 0; j < jinfo->num_clauses; ++j) {
5094 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5096 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5098 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5099 ss_req->bps = g_slist_append (ss_req->bps, bp);
5107 if (ss_req->depth == STEP_DEPTH_INTO) {
5108 /* Enable global stepping so we stop at method entry too */
5109 enable_global = TRUE;
5113 * The ctx/frame info computed above will become invalid when we continue.
5115 tls->context.valid = FALSE;
5116 tls->async_state.valid = FALSE;
5117 invalidate_frames (tls);
5120 if (enable_global) {
5121 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5122 ss_req->global = TRUE;
5123 start_single_stepping ();
5124 } else if (!ss_req->bps) {
5125 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5126 ss_req->global = TRUE;
5127 start_single_stepping ();
5129 ss_req->global = FALSE;
5134 * Start single stepping of thread THREAD
5137 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5139 DebuggerTlsData *tls;
5140 MonoSeqPointInfo *info = NULL;
5141 SeqPoint *sp = NULL;
5142 MonoMethod *method = NULL;
5143 MonoDebugMethodInfo *minfo;
5144 gboolean step_to_catch = FALSE;
5146 if (suspend_count == 0)
5147 return ERR_NOT_SUSPENDED;
5149 wait_for_suspend ();
5151 // FIXME: Multiple requests
5153 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5154 return ERR_NOT_IMPLEMENTED;
5157 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5159 ss_req = g_new0 (SingleStepReq, 1);
5161 ss_req->thread = thread;
5162 ss_req->size = size;
5163 ss_req->depth = depth;
5166 mono_loader_lock ();
5167 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5168 mono_loader_unlock ();
5170 g_assert (tls->context.valid);
5171 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5173 if (tls->catch_state.valid) {
5175 StackFrameInfo frame;
5176 MonoContext new_ctx;
5177 MonoLMF *lmf = NULL;
5180 * We are stopped at a throw site. Stepping should go to the catch site.
5183 /* Find the the jit info for the catch context */
5184 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);
5186 g_assert (frame.type == FRAME_TYPE_MANAGED);
5189 * Find the seq point corresponding to the landing site ip, which is the first seq
5192 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5194 no_seq_points_found (frame.method);
5197 method = frame.method;
5199 step_to_catch = TRUE;
5200 /* This make sure the seq point is not skipped by process_single_step () */
5201 ss_req->last_sp = NULL;
5204 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5207 /* Compute the initial line info */
5208 compute_frame_info (thread, tls);
5210 if (tls->frame_count) {
5211 frame = tls->frames [0];
5213 ss_req->last_method = frame->method;
5214 ss_req->last_line = -1;
5216 minfo = mono_debug_lookup_method (frame->method);
5217 if (minfo && frame->il_offset != -1) {
5218 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5221 ss_req->last_line = loc->row;
5228 if (!step_to_catch) {
5231 compute_frame_info (thread, tls);
5233 if (tls->frame_count) {
5234 frame = tls->frames [0];
5236 if (!method && frame->il_offset != -1) {
5237 /* FIXME: Sort the table and use a binary search */
5238 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5240 no_seq_points_found (frame->method);
5242 method = frame->method;
5247 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5253 ss_destroy (SingleStepReq *req)
5256 g_assert (ss_req == req);
5265 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5268 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5274 if (!agent_config.enabled)
5277 mono_loader_lock ();
5278 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5279 mono_loader_unlock ();
5282 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5283 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5285 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5287 g_free (ei.category);
5288 g_free (ei.message);
5292 mono_debugger_agent_debug_log_is_enabled (void)
5294 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5295 return agent_config.enabled;
5298 #ifdef PLATFORM_ANDROID
5300 mono_debugger_agent_unhandled_exception (MonoException *exc)
5309 memset (&ei, 0, sizeof (EventInfo));
5310 ei.exc = (MonoObject*)exc;
5312 mono_loader_lock ();
5313 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5314 mono_loader_unlock ();
5316 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5321 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5322 MonoContext *catch_ctx)
5324 int i, j, suspend_policy;
5326 MonoJitInfo *ji, *catch_ji;
5328 DebuggerTlsData *tls = NULL;
5330 if (thread_to_tls != NULL) {
5331 MonoInternalThread *thread = mono_thread_internal_current ();
5333 mono_loader_lock ();
5334 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5335 mono_loader_unlock ();
5337 if (tls && tls->abort_requested)
5339 if (tls && tls->disable_breakpoints)
5343 memset (&ei, 0, sizeof (EventInfo));
5345 /* Just-In-Time debugging */
5347 if (agent_config.onuncaught && !inited) {
5348 finish_agent_init (FALSE);
5351 * Send an unsolicited EXCEPTION event with a dummy request id.
5353 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5354 ei.exc = (MonoObject*)exc;
5355 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5358 } else if (agent_config.onthrow && !inited) {
5360 gboolean found = FALSE;
5362 for (l = agent_config.onthrow; l; l = l->next) {
5363 char *ex_type = l->data;
5364 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5366 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5373 finish_agent_init (FALSE);
5376 * Send an unsolicited EXCEPTION event with a dummy request id.
5378 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5379 ei.exc = (MonoObject*)exc;
5380 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5388 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5390 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5394 ei.exc = (MonoObject*)exc;
5395 ei.caught = catch_ctx != NULL;
5397 mono_loader_lock ();
5399 /* Treat exceptions which are caught in non-user code as unhandled */
5400 for (i = 0; i < event_requests->len; ++i) {
5401 EventRequest *req = g_ptr_array_index (event_requests, i);
5402 if (req->event_kind != EVENT_KIND_EXCEPTION)
5405 for (j = 0; j < req->nmodifiers; ++j) {
5406 Modifier *mod = &req->modifiers [j];
5408 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5410 gboolean found = FALSE;
5411 MonoAssembly **assemblies = mod->data.assemblies;
5414 for (k = 0; assemblies [k]; ++k)
5415 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5424 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5425 mono_loader_unlock ();
5427 if (tls && ei.caught && catch_ctx) {
5428 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5429 tls->catch_state.ctx = *catch_ctx;
5430 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5431 tls->catch_state.valid = TRUE;
5434 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5437 tls->catch_state.valid = FALSE;
5441 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5443 DebuggerTlsData *tls;
5448 tls = mono_native_tls_get_value (debugger_tls_id);
5453 * We're about to invoke an exception filter during the first pass of exception handling.
5455 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5456 * 'orig_ctx' is the context where the exception has been thrown.
5459 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5461 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5462 * the call site (line 37) and then continue to Main(), but it would never
5463 * include the throw site (line 32).
5465 * Since exception filters are invoked during the first pass of exception handling,
5466 * the stack frames of the throw site are still intact, so we should include them
5469 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5471 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5472 * but report the location of the 'throw' to the user.
5476 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5480 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5482 DebuggerTlsData *tls;
5487 tls = mono_native_tls_get_value (debugger_tls_id);
5491 tls->filter_state.valid = FALSE;
5495 * buffer_add_value_full:
5497 * Add the encoding of the value at ADDR described by T to the buffer.
5498 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5502 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5508 if (!(*(void**)addr)) {
5509 /* This can happen with compiler generated locals */
5510 //printf ("%s\n", mono_type_full_name (t));
5511 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5514 g_assert (*(void**)addr);
5515 addr = *(void**)addr;
5520 case MONO_TYPE_BOOLEAN:
5523 case MONO_TYPE_CHAR:
5543 case MONO_TYPE_VOID:
5544 buffer_add_byte (buf, t->type);
5546 case MONO_TYPE_BOOLEAN:
5549 buffer_add_byte (buf, t->type);
5550 buffer_add_int (buf, *(gint8*)addr);
5552 case MONO_TYPE_CHAR:
5555 buffer_add_byte (buf, t->type);
5556 buffer_add_int (buf, *(gint16*)addr);
5561 buffer_add_byte (buf, t->type);
5562 buffer_add_int (buf, *(gint32*)addr);
5567 buffer_add_byte (buf, t->type);
5568 buffer_add_long (buf, *(gint64*)addr);
5572 /* Treat it as a vtype */
5574 case MONO_TYPE_PTR: {
5575 gssize val = *(gssize*)addr;
5577 buffer_add_byte (buf, t->type);
5578 buffer_add_long (buf, val);
5582 case MONO_TYPE_STRING:
5583 case MONO_TYPE_SZARRAY:
5584 case MONO_TYPE_OBJECT:
5585 case MONO_TYPE_CLASS:
5586 case MONO_TYPE_ARRAY:
5587 obj = *(MonoObject**)addr;
5590 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5592 if (obj->vtable->klass->valuetype) {
5593 t = &obj->vtable->klass->byval_arg;
5594 addr = mono_object_unbox (obj);
5596 } else if (obj->vtable->klass->rank) {
5597 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5598 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5599 buffer_add_byte (buf, MONO_TYPE_CLASS);
5601 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5603 buffer_add_objid (buf, obj);
5607 case MONO_TYPE_VALUETYPE: {
5611 MonoClass *klass = mono_class_from_mono_type (t);
5613 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5614 buffer_add_byte (buf, klass->enumtype);
5615 buffer_add_typeid (buf, domain, klass);
5619 while ((f = mono_class_get_fields (klass, &iter))) {
5620 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5622 if (mono_field_is_deleted (f))
5626 buffer_add_int (buf, nfields);
5629 while ((f = mono_class_get_fields (klass, &iter))) {
5630 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5632 if (mono_field_is_deleted (f))
5634 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5638 case MONO_TYPE_GENERICINST:
5639 if (mono_type_generic_inst_is_valuetype (t)) {
5651 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5653 buffer_add_value_full (buf, t, addr, domain, FALSE);
5657 obj_is_of_type (MonoObject *obj, MonoType *t)
5659 MonoClass *klass = obj->vtable->klass;
5660 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5661 if (mono_class_is_transparent_proxy (klass)) {
5662 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5663 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5673 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5676 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5682 gpointer iter = NULL;
5686 is_enum = decode_byte (buf, &buf, limit);
5687 /* Enums are sent as a normal vtype */
5689 return ERR_NOT_IMPLEMENTED;
5690 klass = decode_typeid (buf, &buf, limit, &d, &err);
5694 if (t && klass != mono_class_from_mono_type (t)) {
5695 char *name = mono_type_full_name (t);
5696 char *name2 = mono_type_full_name (&klass->byval_arg);
5697 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5700 return ERR_INVALID_ARGUMENT;
5703 nfields = decode_int (buf, &buf, limit);
5704 while ((f = mono_class_get_fields (klass, &iter))) {
5705 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5707 if (mono_field_is_deleted (f))
5709 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5714 g_assert (nfields == 0);
5722 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5726 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5727 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5728 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5729 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5730 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5731 char *name = mono_type_full_name (t);
5732 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5734 return ERR_INVALID_ARGUMENT;
5738 case MONO_TYPE_BOOLEAN:
5739 *(guint8*)addr = decode_int (buf, &buf, limit);
5741 case MONO_TYPE_CHAR:
5742 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5745 *(gint8*)addr = decode_int (buf, &buf, limit);
5748 *(guint8*)addr = decode_int (buf, &buf, limit);
5751 *(gint16*)addr = decode_int (buf, &buf, limit);
5754 *(guint16*)addr = decode_int (buf, &buf, limit);
5757 *(gint32*)addr = decode_int (buf, &buf, limit);
5760 *(guint32*)addr = decode_int (buf, &buf, limit);
5763 *(gint64*)addr = decode_long (buf, &buf, limit);
5766 *(guint64*)addr = decode_long (buf, &buf, limit);
5769 *(guint32*)addr = decode_int (buf, &buf, limit);
5772 *(guint64*)addr = decode_long (buf, &buf, limit);
5775 /* We send these as I8, so we get them back as such */
5776 g_assert (type == MONO_TYPE_I8);
5777 *(gssize*)addr = decode_long (buf, &buf, limit);
5779 case MONO_TYPE_GENERICINST:
5780 if (MONO_TYPE_ISSTRUCT (t)) {
5781 /* The client sends these as a valuetype */
5789 /* We send these as vtypes, so we get them back as such */
5790 g_assert (type == MONO_TYPE_VALUETYPE);
5793 case MONO_TYPE_VALUETYPE:
5794 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5800 if (MONO_TYPE_IS_REFERENCE (t)) {
5801 if (type == MONO_TYPE_OBJECT) {
5802 int objid = decode_objid (buf, &buf, limit);
5806 err = get_object (objid, (MonoObject**)&obj);
5811 if (!obj_is_of_type (obj, t)) {
5812 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5813 return ERR_INVALID_ARGUMENT;
5816 if (obj && obj->vtable->domain != domain)
5817 return ERR_INVALID_ARGUMENT;
5819 mono_gc_wbarrier_generic_store (addr, obj);
5820 } else if (type == VALUE_TYPE_ID_NULL) {
5821 *(MonoObject**)addr = NULL;
5822 } else if (type == MONO_TYPE_VALUETYPE) {
5830 /* This can happen when round-tripping boxed vtypes */
5832 * Obtain vtype class.
5833 * Same as the beginning of the handle_vtype case above.
5836 is_enum = decode_byte (buf, &buf, limit);
5838 return ERR_NOT_IMPLEMENTED;
5839 klass = decode_typeid (buf, &buf, limit, &d, &err);
5843 /* Decode the vtype into a temporary buffer, then box it. */
5844 vtype_buf_size = mono_class_value_size (klass, NULL);
5845 vtype_buf = g_malloc0 (vtype_buf_size);
5846 g_assert (vtype_buf);
5849 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
5854 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
5857 char *name = mono_type_full_name (t);
5858 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5860 return ERR_INVALID_ARGUMENT;
5874 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5877 int type = decode_byte (buf, &buf, limit);
5879 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5880 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5881 guint8 *nullable_buf;
5884 * First try decoding it as a Nullable`1
5886 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5891 * Then try decoding as a primitive value or null.
5893 if (targ->type == type) {
5894 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5895 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5897 g_free (nullable_buf);
5900 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5901 g_free (nullable_buf);
5904 } else if (type == VALUE_TYPE_ID_NULL) {
5905 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5911 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5915 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5919 guint8 *addr, *gaddr;
5922 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5923 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5926 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5927 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5929 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5931 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5932 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5933 addr += (gint32)var->offset;
5935 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5937 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5939 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5942 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5943 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5944 /* Same as regoffset, but with an indirection */
5945 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5946 addr += (gint32)var->offset;
5948 gaddr = *(gpointer*)addr;
5950 buffer_add_value_full (buf, t, gaddr, domain, as_vtype);
5952 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5953 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5954 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5955 MonoGSharedVtMethodRuntimeInfo *info;
5961 g_assert (info_var);
5962 g_assert (locals_var);
5964 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5965 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5966 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5967 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5968 addr += (gint32)info_var->offset;
5969 info = *(gpointer*)addr;
5970 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5971 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5973 g_assert_not_reached ();
5977 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5978 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5979 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5980 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5981 addr += (gint32)locals_var->offset;
5982 locals = *(gpointer*)addr;
5983 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5984 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5986 g_assert_not_reached ();
5990 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5992 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5997 g_assert_not_reached ();
6002 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6006 guint8 *addr, *gaddr;
6008 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6009 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6011 if (MONO_TYPE_IS_REFERENCE (t))
6012 size = sizeof (gpointer);
6014 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6017 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6018 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6020 gboolean is_signed = FALSE;
6023 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6026 // FIXME: Write barriers
6027 mono_gc_memmove_atomic (addr, val, size);
6032 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6037 v = is_signed ? *(gint8*)val : *(guint8*)val;
6040 v = is_signed ? *(gint16*)val : *(guint16*)val;
6043 v = is_signed ? *(gint32*)val : *(guint32*)val;
6046 v = is_signed ? *(gint64*)val : *(guint64*)val;
6049 g_assert_not_reached ();
6052 /* Set value on the stack or in the return ctx */
6053 if (reg_locations [reg]) {
6054 /* Saved on the stack */
6055 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6056 *(reg_locations [reg]) = v;
6059 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6060 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6063 // FIXME: Move these to mono-context.h/c.
6064 mono_arch_context_set_int_reg (ctx, reg, v);
6066 // FIXME: Can't set registers, so we disable linears
6071 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6072 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6073 addr += (gint32)var->offset;
6075 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6078 addr = *(guint8**)addr;
6084 // FIXME: Write barriers
6085 mono_gc_memmove_atomic (addr, val, size);
6087 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6088 /* Same as regoffset, but with an indirection */
6089 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6090 addr += (gint32)var->offset;
6092 gaddr = *(gpointer*)addr;
6094 // FIXME: Write barriers
6095 mono_gc_memmove_atomic (gaddr, val, size);
6097 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6101 g_assert_not_reached ();
6106 clear_event_request (int req_id, int etype)
6110 mono_loader_lock ();
6111 for (i = 0; i < event_requests->len; ++i) {
6112 EventRequest *req = g_ptr_array_index (event_requests, i);
6114 if (req->id == req_id && req->event_kind == etype) {
6115 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6116 clear_breakpoint (req->info);
6117 if (req->event_kind == EVENT_KIND_STEP)
6118 ss_destroy (req->info);
6119 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6120 clear_breakpoint (req->info);
6121 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6122 clear_breakpoint (req->info);
6123 g_ptr_array_remove_index_fast (event_requests, i);
6128 mono_loader_unlock ();
6132 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
6134 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6135 return breakpoint_matches_assembly (req->info, assembly);
6139 for (i = 0; i < req->nmodifiers; ++i) {
6140 Modifier *m = &req->modifiers [i];
6142 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6144 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6145 for (j = 0; m->data.assemblies [j]; ++j)
6146 if (m->data.assemblies [j] == assembly)
6156 * clear_event_requests_for_assembly:
6158 * Clear all events requests which reference ASSEMBLY.
6161 clear_event_requests_for_assembly (MonoAssembly *assembly)
6166 mono_loader_lock ();
6170 for (i = 0; i < event_requests->len; ++i) {
6171 EventRequest *req = g_ptr_array_index (event_requests, i);
6173 if (event_req_matches_assembly (req, assembly)) {
6174 clear_event_request (req->id, req->event_kind);
6180 mono_loader_unlock ();
6184 * type_comes_from_assembly:
6186 * GHRFunc that returns TRUE if klass comes from assembly
6189 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6191 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6195 * clear_types_for_assembly:
6197 * Clears types from loaded_classes for a given assembly
6200 clear_types_for_assembly (MonoAssembly *assembly)
6202 MonoDomain *domain = mono_domain_get ();
6203 AgentDomainInfo *info = NULL;
6205 mono_loader_lock ();
6206 info = get_agent_domain_info (domain);
6207 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6208 mono_loader_unlock ();
6212 add_thread (gpointer key, gpointer value, gpointer user_data)
6214 MonoInternalThread *thread = value;
6215 Buffer *buf = user_data;
6217 buffer_add_objid (buf, (MonoObject*)thread);
6221 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6223 guint8 *end = invoke->endp;
6226 MonoMethodSignature *sig;
6229 MonoObject *this, *res, *exc;
6232 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6235 MonoStopwatch watch;
6237 if (invoke->method) {
6239 * Invoke this method directly, currently only Environment.Exit () is supported.
6242 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>"));
6243 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6244 g_assert_not_reached ();
6247 m = decode_methodid (p, &p, end, &domain, &err);
6250 sig = mono_method_signature (m);
6252 if (m->klass->valuetype)
6253 this_buf = g_alloca (mono_class_instance_size (m->klass));
6255 this_buf = g_alloca (sizeof (MonoObject*));
6256 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6257 /* Should be null */
6258 int type = decode_byte (p, &p, end);
6259 if (type != VALUE_TYPE_ID_NULL) {
6260 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6261 return ERR_INVALID_ARGUMENT;
6263 memset (this_buf, 0, mono_class_instance_size (m->klass));
6265 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6270 if (!m->klass->valuetype)
6271 this = *(MonoObject**)this_buf;
6275 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6277 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6278 return ERR_INVALID_ARGUMENT;
6280 m = mono_object_get_virtual_method (this, m);
6283 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>"));
6285 if (this && this->vtable->domain != domain)
6288 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6289 if (!strcmp (m->name, ".ctor")) {
6290 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6291 return ERR_INVALID_ARGUMENT;
6293 this = mono_object_new (domain, m->klass);
6295 return ERR_INVALID_ARGUMENT;
6299 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6300 return ERR_INVALID_ARGUMENT;
6302 nargs = decode_int (p, &p, end);
6303 if (nargs != sig->param_count)
6304 return ERR_INVALID_ARGUMENT;
6305 /* Use alloca to get gc tracking */
6306 arg_buf = g_alloca (nargs * sizeof (gpointer));
6307 memset (arg_buf, 0, nargs * sizeof (gpointer));
6308 args = g_alloca (nargs * sizeof (gpointer));
6309 for (i = 0; i < nargs; ++i) {
6310 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6311 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6315 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6318 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6319 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6322 args [i] = arg_buf [i];
6329 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6330 tls->disable_breakpoints = TRUE;
6332 tls->disable_breakpoints = FALSE;
6335 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6337 /* FIXME: Move this to arch specific code */
6338 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6339 if (invoke->has_ctx) {
6342 lmf_addr = mono_get_lmf_addr ();
6345 memset (&ext, 0, sizeof (ext));
6346 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6348 ext.debugger_invoke = TRUE;
6349 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6351 mono_set_lmf ((MonoLMF*)&ext);
6355 mono_stopwatch_start (&watch);
6356 if (m->klass->valuetype)
6357 res = mono_runtime_invoke (m, this_buf, args, &exc);
6359 res = mono_runtime_invoke (m, this, args, &exc);
6360 mono_stopwatch_stop (&watch);
6361 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)));
6363 buffer_add_byte (buf, 0);
6364 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6366 buffer_add_byte (buf, 1);
6367 if (sig->ret->type == MONO_TYPE_VOID) {
6368 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6369 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6372 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6373 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6374 buffer_add_value (buf, sig->ret, &res, domain);
6375 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6376 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6377 MonoClass *k = mono_class_from_mono_type (sig->ret);
6378 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6380 g_assert (nullable_buf);
6381 mono_nullable_init (nullable_buf, res, k);
6382 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6385 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6392 tls->disable_breakpoints = FALSE;
6394 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6395 if (invoke->has_ctx)
6396 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6400 // FIXME: byref arguments
6408 * Invoke the method given by tls->pending_invoke in the current thread.
6411 invoke_method (void)
6413 DebuggerTlsData *tls;
6418 MonoContext restore_ctx;
6421 tls = mono_native_tls_get_value (debugger_tls_id);
6425 * Store the `InvokeData *' in `tls->invoke' until we're done with
6426 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6429 mono_loader_lock ();
6431 invoke = tls->pending_invoke;
6433 tls->pending_invoke = NULL;
6435 invoke->last_invoke = tls->invoke;
6436 tls->invoke = invoke;
6438 mono_loader_unlock ();
6440 tls->frames_up_to_date = FALSE;
6446 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6447 buffer_init (&buf, 128);
6450 /* Fail the other invokes as well */
6452 err = do_invoke_method (tls, &buf, invoke, p, &p);
6455 /* Start suspending before sending the reply */
6456 if (mindex == invoke->nmethods - 1) {
6457 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6458 for (i = 0; i < invoke->suspend_count; ++i)
6463 send_reply_packet (id, err, &buf);
6468 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6470 if (invoke->has_ctx)
6471 save_thread_context (&restore_ctx);
6473 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6474 g_assert (tls->resume_count);
6475 tls->resume_count -= invoke->suspend_count;
6478 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6481 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6483 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6484 * after the mono_runtime_invoke() already returned, but it doesn't matter
6485 * because we reset the abort here.
6488 mono_loader_lock ();
6490 if (tls->abort_requested)
6491 mono_thread_internal_reset_abort (tls->thread);
6493 tls->invoke = tls->invoke->last_invoke;
6494 tls->abort_requested = FALSE;
6496 mono_loader_unlock ();
6505 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6507 MonoThread *thread = value;
6508 DebuggerTlsData *tls;
6511 mono_loader_lock ();
6512 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6514 res = tls->really_suspended;
6515 mono_loader_unlock ();
6521 get_source_files_for_type (MonoClass *klass)
6523 gpointer iter = NULL;
6525 MonoDebugSourceInfo *sinfo;
6529 files = g_ptr_array_new ();
6531 while ((method = mono_class_get_methods (klass, &iter))) {
6532 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6533 GPtrArray *source_file_list;
6536 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6537 for (j = 0; j < source_file_list->len; ++j) {
6538 sinfo = g_ptr_array_index (source_file_list, j);
6539 for (i = 0; i < files->len; ++i)
6540 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6542 if (i == files->len)
6543 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6545 g_ptr_array_free (source_file_list, TRUE);
6553 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6556 case CMD_VM_VERSION: {
6557 char *build_info, *version;
6559 build_info = mono_get_runtime_build_info ();
6560 version = g_strdup_printf ("mono %s", build_info);
6562 buffer_add_string (buf, version); /* vm version */
6563 buffer_add_int (buf, MAJOR_VERSION);
6564 buffer_add_int (buf, MINOR_VERSION);
6565 g_free (build_info);
6569 case CMD_VM_SET_PROTOCOL_VERSION: {
6570 major_version = decode_int (p, &p, end);
6571 minor_version = decode_int (p, &p, end);
6572 protocol_version_set = TRUE;
6573 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6576 case CMD_VM_ALL_THREADS: {
6578 mono_loader_lock ();
6579 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6580 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6581 mono_loader_unlock ();
6584 case CMD_VM_SUSPEND:
6586 wait_for_suspend ();
6589 if (suspend_count == 0)
6590 return ERR_NOT_SUSPENDED;
6592 clear_suspended_objs ();
6594 case CMD_VM_DISPOSE:
6595 /* Clear all event requests */
6596 mono_loader_lock ();
6597 while (event_requests->len > 0) {
6598 EventRequest *req = g_ptr_array_index (event_requests, 0);
6600 clear_event_request (req->id, req->event_kind);
6602 mono_loader_unlock ();
6604 while (suspend_count > 0)
6606 disconnected = TRUE;
6607 vm_start_event_sent = FALSE;
6610 MonoInternalThread *thread;
6611 DebuggerTlsData *tls;
6612 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6613 MonoClass *env_class;
6615 MonoMethod *exit_method = NULL;
6619 exit_code = decode_int (p, &p, end);
6621 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6623 /* Have to send a reply before exiting */
6624 send_reply_packet (id, 0, buf);
6626 /* Clear all event requests */
6627 mono_loader_lock ();
6628 while (event_requests->len > 0) {
6629 EventRequest *req = g_ptr_array_index (event_requests, 0);
6631 clear_event_request (req->id, req->event_kind);
6633 mono_loader_unlock ();
6636 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6637 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6638 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6639 * better than doing the shutdown ourselves, since it avoids various races.
6643 wait_for_suspend ();
6645 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6646 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6648 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6651 mono_loader_lock ();
6652 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6653 mono_loader_unlock ();
6655 if (thread && exit_method) {
6656 mono_loader_lock ();
6657 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6658 mono_loader_unlock ();
6660 args = g_new0 (gpointer, 1);
6661 args [0] = g_malloc (sizeof (int));
6662 *(int*)(args [0]) = exit_code;
6664 tls->pending_invoke = g_new0 (InvokeData, 1);
6665 tls->pending_invoke->method = exit_method;
6666 tls->pending_invoke->args = args;
6667 tls->pending_invoke->nmethods = 1;
6669 while (suspend_count > 0)
6673 * No thread found, do it ourselves.
6674 * FIXME: This can race with normal shutdown etc.
6676 while (suspend_count > 0)
6679 if (!mono_runtime_try_shutdown ())
6682 mono_environment_exitcode_set (exit_code);
6684 /* Suspend all managed threads since the runtime is going away */
6685 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6686 mono_thread_suspend_all_other_threads ();
6687 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6688 mono_runtime_quit ();
6689 transport_close2 ();
6690 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6696 case CMD_VM_INVOKE_METHOD:
6697 case CMD_VM_INVOKE_METHODS: {
6698 int objid = decode_objid (p, &p, end);
6700 DebuggerTlsData *tls;
6701 int i, count, err, flags, nmethods;
6703 err = get_object (objid, (MonoObject**)&thread);
6707 flags = decode_int (p, &p, end);
6709 if (command == CMD_VM_INVOKE_METHODS)
6710 nmethods = decode_int (p, &p, end);
6714 // Wait for suspending if it already started
6716 wait_for_suspend ();
6717 if (!is_suspended ())
6718 return ERR_NOT_SUSPENDED;
6720 mono_loader_lock ();
6721 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6722 mono_loader_unlock ();
6725 if (!tls->really_suspended)
6726 /* The thread is still running native code, can't do invokes */
6727 return ERR_NOT_SUSPENDED;
6730 * Store the invoke data into tls, the thread will execute it after it is
6733 if (tls->pending_invoke)
6734 return ERR_NOT_SUSPENDED;
6735 tls->pending_invoke = g_new0 (InvokeData, 1);
6736 tls->pending_invoke->id = id;
6737 tls->pending_invoke->flags = flags;
6738 tls->pending_invoke->p = g_malloc (end - p);
6739 memcpy (tls->pending_invoke->p, p, end - p);
6740 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6741 tls->pending_invoke->suspend_count = suspend_count;
6742 tls->pending_invoke->nmethods = nmethods;
6744 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6745 resume_thread (THREAD_TO_INTERNAL (thread));
6748 count = suspend_count;
6749 for (i = 0; i < count; ++i)
6754 case CMD_VM_ABORT_INVOKE: {
6755 int objid = decode_objid (p, &p, end);
6757 DebuggerTlsData *tls;
6760 err = get_object (objid, (MonoObject**)&thread);
6764 invoke_id = decode_int (p, &p, end);
6766 mono_loader_lock ();
6767 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6770 if (tls->abort_requested) {
6771 mono_loader_unlock ();
6776 * Check whether we're still inside the mono_runtime_invoke() and that it's
6777 * actually the correct invocation.
6779 * Careful, we do not stop the thread that's doing the invocation, so we can't
6780 * inspect its stack. However, invoke_method() also acquires the loader lock
6781 * when it's done, so we're safe here.
6785 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6786 mono_loader_unlock ();
6787 return ERR_NO_INVOCATION;
6790 tls->abort_requested = TRUE;
6792 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6793 mono_loader_unlock ();
6797 case CMD_VM_SET_KEEPALIVE: {
6798 int timeout = decode_int (p, &p, end);
6799 agent_config.keepalive = timeout;
6801 #ifndef DISABLE_SOCKET_TRANSPORT
6808 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6809 GHashTableIter iter, kiter;
6814 char *fname, *basename;
6815 gboolean ignore_case;
6816 GSList *class_list, *l;
6817 GPtrArray *res_classes, *res_domains;
6819 fname = decode_string (p, &p, end);
6820 ignore_case = decode_byte (p, &p, end);
6822 basename = g_path_get_basename (fname);
6824 res_classes = g_ptr_array_new ();
6825 res_domains = g_ptr_array_new ();
6827 mono_loader_lock ();
6828 g_hash_table_iter_init (&iter, domains);
6829 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6830 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6832 /* Update 'source_file_to_class' cache */
6833 g_hash_table_iter_init (&kiter, info->loaded_classes);
6834 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6835 if (!g_hash_table_lookup (info->source_files, klass)) {
6836 files = get_source_files_for_type (klass);
6837 g_hash_table_insert (info->source_files, klass, files);
6839 for (i = 0; i < files->len; ++i) {
6840 char *s = g_ptr_array_index (files, i);
6841 char *s2 = g_path_get_basename (s);
6844 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6846 class_list = g_slist_prepend (class_list, klass);
6847 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6849 class_list = g_slist_prepend (class_list, klass);
6850 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6853 /* The _ignorecase hash contains the lowercase path */
6854 s3 = strdup_tolower (s2);
6855 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6857 class_list = g_slist_prepend (class_list, klass);
6858 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6860 class_list = g_slist_prepend (class_list, klass);
6861 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6873 s = strdup_tolower (basename);
6874 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6877 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6880 for (l = class_list; l; l = l->next) {
6883 g_ptr_array_add (res_classes, klass);
6884 g_ptr_array_add (res_domains, domain);
6887 mono_loader_unlock ();
6892 buffer_add_int (buf, res_classes->len);
6893 for (i = 0; i < res_classes->len; ++i)
6894 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6895 g_ptr_array_free (res_classes, TRUE);
6896 g_ptr_array_free (res_domains, TRUE);
6899 case CMD_VM_GET_TYPES: {
6900 GHashTableIter iter;
6904 gboolean ignore_case;
6905 GPtrArray *res_classes, *res_domains;
6906 MonoTypeNameParse info;
6908 name = decode_string (p, &p, end);
6909 ignore_case = decode_byte (p, &p, end);
6911 if (!mono_reflection_parse_type (name, &info)) {
6913 mono_reflection_free_type_info (&info);
6914 return ERR_INVALID_ARGUMENT;
6917 res_classes = g_ptr_array_new ();
6918 res_domains = g_ptr_array_new ();
6920 mono_loader_lock ();
6921 g_hash_table_iter_init (&iter, domains);
6922 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6924 gboolean type_resolve;
6928 mono_domain_assemblies_lock (domain);
6929 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6933 type_resolve = TRUE;
6934 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6936 g_ptr_array_add (res_classes, mono_type_get_class (t));
6937 g_ptr_array_add (res_domains, domain);
6941 mono_domain_assemblies_unlock (domain);
6943 mono_loader_unlock ();
6946 mono_reflection_free_type_info (&info);
6948 buffer_add_int (buf, res_classes->len);
6949 for (i = 0; i < res_classes->len; ++i)
6950 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6951 g_ptr_array_free (res_classes, TRUE);
6952 g_ptr_array_free (res_domains, TRUE);
6957 return ERR_NOT_IMPLEMENTED;
6964 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6970 case CMD_EVENT_REQUEST_SET: {
6972 int i, event_kind, suspend_policy, nmodifiers, mod;
6975 MonoThread *step_thread;
6976 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6980 event_kind = decode_byte (p, &p, end);
6981 suspend_policy = decode_byte (p, &p, end);
6982 nmodifiers = decode_byte (p, &p, end);
6984 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6985 req->id = InterlockedIncrement (&event_request_id);
6986 req->event_kind = event_kind;
6987 req->suspend_policy = suspend_policy;
6988 req->nmodifiers = nmodifiers;
6991 for (i = 0; i < nmodifiers; ++i) {
6992 mod = decode_byte (p, &p, end);
6994 req->modifiers [i].kind = mod;
6995 if (mod == MOD_KIND_COUNT) {
6996 req->modifiers [i].data.count = decode_int (p, &p, end);
6997 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6998 method = decode_methodid (p, &p, end, &domain, &err);
7001 location = decode_long (p, &p, end);
7002 } else if (mod == MOD_KIND_STEP) {
7003 step_thread_id = decode_id (p, &p, end);
7004 size = decode_int (p, &p, end);
7005 depth = decode_int (p, &p, end);
7006 if (CHECK_PROTOCOL_VERSION (2, 16))
7007 filter = decode_int (p, &p, end);
7008 req->modifiers [i].data.filter = filter;
7009 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7010 /* Treat STEP_THOUGH the same as HIDDEN */
7011 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7012 } else if (mod == MOD_KIND_THREAD_ONLY) {
7013 int id = decode_id (p, &p, end);
7015 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7020 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7021 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7025 req->modifiers [i].caught = decode_byte (p, &p, end);
7026 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7027 if (CHECK_PROTOCOL_VERSION (2, 25))
7028 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7030 req->modifiers [i].subclasses = TRUE;
7031 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" : ""));
7033 req->modifiers [i].data.exc_class = exc_class;
7035 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7037 return ERR_INVALID_ARGUMENT;
7040 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7041 int n = decode_int (p, &p, end);
7044 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7045 for (j = 0; j < n; ++j) {
7046 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7048 g_free (req->modifiers [i].data.assemblies);
7052 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7053 int n = decode_int (p, &p, end);
7056 modifier = &req->modifiers [i];
7057 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7058 for (j = 0; j < n; ++j) {
7059 char *s = decode_string (p, &p, end);
7063 s2 = strdup_tolower (s);
7064 g_hash_table_insert (modifier->data.source_files, s2, s2);
7068 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7069 int n = decode_int (p, &p, end);
7072 modifier = &req->modifiers [i];
7073 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7074 for (j = 0; j < n; ++j) {
7075 char *s = decode_string (p, &p, end);
7078 g_hash_table_insert (modifier->data.type_names, s, s);
7082 return ERR_NOT_IMPLEMENTED;
7086 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7089 req->info = set_breakpoint (method, location, req, &error);
7090 if (!mono_error_ok (&error)) {
7092 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7093 mono_error_cleanup (&error);
7094 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7096 } else if (req->event_kind == EVENT_KIND_STEP) {
7097 g_assert (step_thread_id);
7099 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7105 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7110 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7111 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7112 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7113 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7114 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7115 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7117 if (req->nmodifiers) {
7119 return ERR_NOT_IMPLEMENTED;
7123 mono_loader_lock ();
7124 g_ptr_array_add (event_requests, req);
7126 if (agent_config.defer) {
7127 /* Transmit cached data to the client on receipt of the event request */
7128 switch (req->event_kind) {
7129 case EVENT_KIND_APPDOMAIN_CREATE:
7130 /* Emit load events for currently loaded domains */
7131 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7133 case EVENT_KIND_ASSEMBLY_LOAD:
7134 /* Emit load events for currently loaded assemblies */
7135 mono_assembly_foreach (emit_assembly_load, NULL);
7137 case EVENT_KIND_THREAD_START:
7138 /* Emit start events for currently started threads */
7139 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7141 case EVENT_KIND_TYPE_LOAD:
7142 /* Emit type load events for currently loaded types */
7143 mono_domain_foreach (send_types_for_domain, NULL);
7149 mono_loader_unlock ();
7151 buffer_add_int (buf, req->id);
7154 case CMD_EVENT_REQUEST_CLEAR: {
7155 int etype = decode_byte (p, &p, end);
7156 int req_id = decode_int (p, &p, end);
7158 // FIXME: Make a faster mapping from req_id to request
7159 mono_loader_lock ();
7160 clear_event_request (req_id, etype);
7161 mono_loader_unlock ();
7164 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7167 mono_loader_lock ();
7169 while (i < event_requests->len) {
7170 EventRequest *req = g_ptr_array_index (event_requests, i);
7172 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7173 clear_breakpoint (req->info);
7175 g_ptr_array_remove_index_fast (event_requests, i);
7181 mono_loader_unlock ();
7185 return ERR_NOT_IMPLEMENTED;
7192 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7198 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7199 buffer_add_domainid (buf, mono_get_root_domain ());
7202 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7203 domain = decode_domainid (p, &p, end, NULL, &err);
7206 buffer_add_string (buf, domain->friendly_name);
7209 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7214 domain = decode_domainid (p, &p, end, NULL, &err);
7217 mono_loader_lock ();
7219 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7222 buffer_add_int (buf, count);
7223 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7225 buffer_add_assemblyid (buf, domain, ass);
7227 mono_loader_unlock ();
7230 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7231 domain = decode_domainid (p, &p, end, NULL, &err);
7235 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7238 case CMD_APPDOMAIN_GET_CORLIB: {
7239 domain = decode_domainid (p, &p, end, NULL, &err);
7243 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7246 case CMD_APPDOMAIN_CREATE_STRING: {
7250 domain = decode_domainid (p, &p, end, NULL, &err);
7253 s = decode_string (p, &p, end);
7255 o = mono_string_new (domain, s);
7256 buffer_add_objid (buf, (MonoObject*)o);
7259 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7261 MonoDomain *domain2;
7264 domain = decode_domainid (p, &p, end, NULL, &err);
7267 klass = decode_typeid (p, &p, end, &domain2, &err);
7272 g_assert (domain == domain2);
7274 o = mono_object_new (domain, klass);
7276 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7280 buffer_add_objid (buf, o);
7284 return ERR_NOT_IMPLEMENTED;
7291 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7297 ass = decode_assemblyid (p, &p, end, &domain, &err);
7302 case CMD_ASSEMBLY_GET_LOCATION: {
7303 buffer_add_string (buf, mono_image_get_filename (ass->image));
7306 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7310 if (ass->image->dynamic) {
7311 buffer_add_id (buf, 0);
7313 token = mono_image_get_entry_point (ass->image);
7315 buffer_add_id (buf, 0);
7317 m = mono_get_method (ass->image, token, NULL);
7318 buffer_add_methodid (buf, domain, m);
7323 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7324 buffer_add_moduleid (buf, domain, ass->image);
7327 case CMD_ASSEMBLY_GET_OBJECT: {
7328 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7329 buffer_add_objid (buf, o);
7332 case CMD_ASSEMBLY_GET_TYPE: {
7333 char *s = decode_string (p, &p, end);
7334 gboolean ignorecase = decode_byte (p, &p, end);
7335 MonoTypeNameParse info;
7337 gboolean type_resolve, res;
7338 MonoDomain *d = mono_domain_get ();
7340 /* This is needed to be able to find referenced assemblies */
7341 res = mono_domain_set (domain, FALSE);
7344 if (!mono_reflection_parse_type (s, &info)) {
7347 if (info.assembly.name)
7349 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7351 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7352 mono_reflection_free_type_info (&info);
7355 mono_domain_set (d, TRUE);
7359 case CMD_ASSEMBLY_GET_NAME: {
7361 MonoAssembly *mass = ass;
7363 name = g_strdup_printf (
7364 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7366 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7367 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7368 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7369 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7371 buffer_add_string (buf, name);
7376 return ERR_NOT_IMPLEMENTED;
7383 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7389 case CMD_MODULE_GET_INFO: {
7390 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7393 basename = g_path_get_basename (image->name);
7394 buffer_add_string (buf, basename); // name
7395 buffer_add_string (buf, image->module_name); // scopename
7396 buffer_add_string (buf, image->name); // fqname
7397 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7398 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7403 return ERR_NOT_IMPLEMENTED;
7410 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7412 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7413 /* Special case these so the client doesn't have to handle Type objects */
7415 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7416 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7417 } else if (MONO_TYPE_IS_REFERENCE (t))
7418 buffer_add_value (buf, t, &val, domain);
7420 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7424 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7430 buffer_add_int (buf, 0);
7434 for (i = 0; i < cinfo->num_attrs; ++i) {
7435 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7438 buffer_add_int (buf, nattrs);
7440 for (i = 0; i < cinfo->num_attrs; ++i) {
7441 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7442 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7443 MonoArray *typed_args, *named_args;
7445 CattrNamedArg *arginfo = NULL;
7448 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7449 g_assert (mono_error_ok (&error));
7451 buffer_add_methodid (buf, domain, attr->ctor);
7455 buffer_add_int (buf, mono_array_length (typed_args));
7456 for (j = 0; j < mono_array_length (typed_args); ++j) {
7457 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7459 t = mono_method_signature (attr->ctor)->params [j];
7461 buffer_add_cattr_arg (buf, t, domain, val);
7464 buffer_add_int (buf, 0);
7469 buffer_add_int (buf, mono_array_length (named_args));
7471 for (j = 0; j < mono_array_length (named_args); ++j) {
7472 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7474 if (arginfo [j].prop) {
7475 buffer_add_byte (buf, 0x54);
7476 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7477 } else if (arginfo [j].field) {
7478 buffer_add_byte (buf, 0x53);
7479 buffer_add_fieldid (buf, domain, arginfo [j].field);
7481 g_assert_not_reached ();
7484 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7487 buffer_add_int (buf, 0);
7494 /* FIXME: Code duplication with icall.c */
7496 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7501 mono_class_setup_interfaces (klass, error);
7502 if (!mono_error_ok (error))
7505 for (i = 0; i < klass->interface_count; i++) {
7506 ic = klass->interfaces [i];
7507 g_hash_table_insert (ifaces, ic, ic);
7509 collect_interfaces (ic, ifaces, error);
7510 if (!mono_error_ok (error))
7516 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7526 case CMD_TYPE_GET_INFO: {
7527 buffer_add_string (buf, klass->name_space);
7528 buffer_add_string (buf, klass->name);
7530 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7531 buffer_add_string (buf, name);
7533 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7534 buffer_add_moduleid (buf, domain, klass->image);
7535 buffer_add_typeid (buf, domain, klass->parent);
7536 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7537 buffer_add_typeid (buf, domain, klass->element_class);
7539 buffer_add_id (buf, 0);
7540 buffer_add_int (buf, klass->type_token);
7541 buffer_add_byte (buf, klass->rank);
7542 buffer_add_int (buf, klass->flags);
7544 type = &klass->byval_arg;
7545 // FIXME: Can't decide whenever a class represents a byref type
7548 if (type->type == MONO_TYPE_PTR)
7550 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7552 if (type->type == MONO_TYPE_VALUETYPE)
7554 if (klass->enumtype)
7556 if (klass->generic_container)
7558 if (klass->generic_container || klass->generic_class)
7560 buffer_add_byte (buf, b);
7563 while ((nested = mono_class_get_nested_types (klass, &iter)))
7565 buffer_add_int (buf, nnested);
7567 while ((nested = mono_class_get_nested_types (klass, &iter)))
7568 buffer_add_typeid (buf, domain, nested);
7569 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7570 if (klass->generic_container)
7571 buffer_add_typeid (buf, domain, klass);
7572 else if (klass->generic_class)
7573 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7575 buffer_add_id (buf, 0);
7577 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7580 if (klass->generic_class) {
7581 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7583 count = inst->type_argc;
7584 buffer_add_int (buf, count);
7585 for (i = 0; i < count; i++)
7586 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7587 } else if (klass->generic_container) {
7588 MonoGenericContainer *container = klass->generic_container;
7591 count = container->type_argc;
7592 buffer_add_int (buf, count);
7593 for (i = 0; i < count; i++) {
7594 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7595 buffer_add_typeid (buf, domain, pklass);
7598 buffer_add_int (buf, 0);
7603 case CMD_TYPE_GET_METHODS: {
7606 gpointer iter = NULL;
7609 mono_class_setup_methods (klass);
7611 nmethods = mono_class_num_methods (klass);
7613 buffer_add_int (buf, nmethods);
7615 while ((m = mono_class_get_methods (klass, &iter))) {
7616 buffer_add_methodid (buf, domain, m);
7619 g_assert (i == nmethods);
7622 case CMD_TYPE_GET_FIELDS: {
7625 gpointer iter = NULL;
7628 nfields = mono_class_num_fields (klass);
7630 buffer_add_int (buf, nfields);
7632 while ((f = mono_class_get_fields (klass, &iter))) {
7633 buffer_add_fieldid (buf, domain, f);
7634 buffer_add_string (buf, f->name);
7635 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7636 buffer_add_int (buf, f->type->attrs);
7639 g_assert (i == nfields);
7642 case CMD_TYPE_GET_PROPERTIES: {
7645 gpointer iter = NULL;
7648 nprops = mono_class_num_properties (klass);
7650 buffer_add_int (buf, nprops);
7652 while ((p = mono_class_get_properties (klass, &iter))) {
7653 buffer_add_propertyid (buf, domain, p);
7654 buffer_add_string (buf, p->name);
7655 buffer_add_methodid (buf, domain, p->get);
7656 buffer_add_methodid (buf, domain, p->set);
7657 buffer_add_int (buf, p->attrs);
7660 g_assert (i == nprops);
7663 case CMD_TYPE_GET_CATTRS: {
7664 MonoClass *attr_klass;
7665 MonoCustomAttrInfo *cinfo;
7667 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7668 /* attr_klass can be NULL */
7672 cinfo = mono_custom_attrs_from_class (klass);
7674 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7677 case CMD_TYPE_GET_FIELD_CATTRS: {
7678 MonoClass *attr_klass;
7679 MonoCustomAttrInfo *cinfo;
7680 MonoClassField *field;
7682 field = decode_fieldid (p, &p, end, NULL, &err);
7685 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7689 cinfo = mono_custom_attrs_from_field (klass, field);
7691 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7694 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7695 MonoClass *attr_klass;
7696 MonoCustomAttrInfo *cinfo;
7699 prop = decode_propertyid (p, &p, end, NULL, &err);
7702 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7706 cinfo = mono_custom_attrs_from_property (klass, prop);
7708 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7711 case CMD_TYPE_GET_VALUES:
7712 case CMD_TYPE_GET_VALUES_2: {
7719 MonoThread *thread_obj;
7720 MonoInternalThread *thread = NULL;
7721 guint32 special_static_type;
7723 if (command == CMD_TYPE_GET_VALUES_2) {
7724 int objid = decode_objid (p, &p, end);
7727 err = get_object (objid, (MonoObject**)&thread_obj);
7731 thread = THREAD_TO_INTERNAL (thread_obj);
7734 len = decode_int (p, &p, end);
7735 for (i = 0; i < len; ++i) {
7736 f = decode_fieldid (p, &p, end, NULL, &err);
7740 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7741 return ERR_INVALID_FIELDID;
7742 special_static_type = mono_class_field_get_special_static_type (f);
7743 if (special_static_type != SPECIAL_STATIC_NONE) {
7744 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7745 return ERR_INVALID_FIELDID;
7748 /* Check that the field belongs to the object */
7750 for (k = klass; k; k = k->parent) {
7751 if (k == f->parent) {
7757 return ERR_INVALID_FIELDID;
7759 vtable = mono_class_vtable (domain, f->parent);
7760 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7761 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7762 buffer_add_value (buf, f->type, val, domain);
7767 case CMD_TYPE_SET_VALUES: {
7775 len = decode_int (p, &p, end);
7776 for (i = 0; i < len; ++i) {
7777 f = decode_fieldid (p, &p, end, NULL, &err);
7781 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7782 return ERR_INVALID_FIELDID;
7783 if (mono_class_field_is_special_static (f))
7784 return ERR_INVALID_FIELDID;
7786 /* Check that the field belongs to the object */
7788 for (k = klass; k; k = k->parent) {
7789 if (k == f->parent) {
7795 return ERR_INVALID_FIELDID;
7797 // FIXME: Check for literal/const
7799 vtable = mono_class_vtable (domain, f->parent);
7800 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7801 err = decode_value (f->type, domain, val, p, &p, end);
7806 if (MONO_TYPE_IS_REFERENCE (f->type))
7807 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7809 mono_field_static_set_value (vtable, f, val);
7814 case CMD_TYPE_GET_OBJECT: {
7815 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7816 buffer_add_objid (buf, o);
7819 case CMD_TYPE_GET_SOURCE_FILES:
7820 case CMD_TYPE_GET_SOURCE_FILES_2: {
7821 char *source_file, *base;
7825 files = get_source_files_for_type (klass);
7827 buffer_add_int (buf, files->len);
7828 for (i = 0; i < files->len; ++i) {
7829 source_file = g_ptr_array_index (files, i);
7830 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7831 buffer_add_string (buf, source_file);
7833 base = g_path_get_basename (source_file);
7834 buffer_add_string (buf, base);
7837 g_free (source_file);
7839 g_ptr_array_free (files, TRUE);
7842 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7843 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7847 if (mono_class_is_assignable_from (klass, oklass))
7848 buffer_add_byte (buf, 1);
7850 buffer_add_byte (buf, 0);
7853 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7854 char *name = decode_string (p, &p, end);
7855 int i, flags = decode_int (p, &p, end);
7856 MonoException *ex = NULL;
7857 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7860 return ERR_LOADER_ERROR;
7861 buffer_add_int (buf, array->len);
7862 for (i = 0; i < array->len; ++i) {
7863 MonoMethod *method = g_ptr_array_index (array, i);
7864 buffer_add_methodid (buf, domain, method);
7867 g_ptr_array_free (array, TRUE);
7871 case CMD_TYPE_GET_INTERFACES: {
7873 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7875 MonoClass *tclass, *iface;
7876 GHashTableIter iter;
7880 for (parent = tclass; parent; parent = parent->parent) {
7881 mono_class_setup_interfaces (parent, &error);
7882 if (!mono_error_ok (&error))
7883 return ERR_LOADER_ERROR;
7884 collect_interfaces (parent, iface_hash, &error);
7885 if (!mono_error_ok (&error))
7886 return ERR_LOADER_ERROR;
7889 buffer_add_int (buf, g_hash_table_size (iface_hash));
7891 g_hash_table_iter_init (&iter, iface_hash);
7892 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7893 buffer_add_typeid (buf, domain, iface);
7894 g_hash_table_destroy (iface_hash);
7897 case CMD_TYPE_GET_INTERFACE_MAP: {
7898 int tindex, ioffset;
7899 gboolean variance_used;
7901 int len, nmethods, i;
7905 len = decode_int (p, &p, end);
7906 mono_class_setup_vtable (klass);
7908 for (tindex = 0; tindex < len; ++tindex) {
7909 iclass = decode_typeid (p, &p, end, NULL, &err);
7913 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7915 return ERR_INVALID_ARGUMENT;
7917 nmethods = mono_class_num_methods (iclass);
7918 buffer_add_int (buf, nmethods);
7921 while ((method = mono_class_get_methods (iclass, &iter))) {
7922 buffer_add_methodid (buf, domain, method);
7924 for (i = 0; i < nmethods; ++i)
7925 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7929 case CMD_TYPE_IS_INITIALIZED: {
7930 MonoVTable *vtable = mono_class_vtable (domain, klass);
7933 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7935 buffer_add_int (buf, 0);
7939 return ERR_NOT_IMPLEMENTED;
7946 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7949 MonoDomain *old_domain;
7953 klass = decode_typeid (p, &p, end, &domain, &err);
7957 old_domain = mono_domain_get ();
7959 mono_domain_set (domain, TRUE);
7961 err = type_commands_internal (command, klass, domain, p, end, buf);
7963 mono_domain_set (old_domain, TRUE);
7969 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7971 MonoMethodHeader *header;
7975 case CMD_METHOD_GET_NAME: {
7976 buffer_add_string (buf, method->name);
7979 case CMD_METHOD_GET_DECLARING_TYPE: {
7980 buffer_add_typeid (buf, domain, method->klass);
7983 case CMD_METHOD_GET_DEBUG_INFO: {
7984 MonoDebugMethodInfo *minfo;
7986 int i, j, n_il_offsets;
7989 int *column_numbers;
7991 GPtrArray *source_file_list;
7993 header = mono_method_get_header (method);
7995 buffer_add_int (buf, 0);
7996 buffer_add_string (buf, "");
7997 buffer_add_int (buf, 0);
8001 minfo = mono_debug_lookup_method (method);
8003 buffer_add_int (buf, header->code_size);
8004 buffer_add_string (buf, "");
8005 buffer_add_int (buf, 0);
8006 mono_metadata_free_mh (header);
8010 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
8011 buffer_add_int (buf, header->code_size);
8012 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8013 buffer_add_int (buf, source_file_list->len);
8014 for (i = 0; i < source_file_list->len; ++i) {
8015 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8016 buffer_add_string (buf, sinfo->source_file);
8017 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8018 for (j = 0; j < 16; ++j)
8019 buffer_add_byte (buf, sinfo->hash [j]);
8023 buffer_add_string (buf, source_file);
8025 buffer_add_int (buf, n_il_offsets);
8026 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8027 for (i = 0; i < n_il_offsets; ++i) {
8028 const char *srcfile = "";
8030 if (source_files [i] != -1) {
8031 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8032 srcfile = sinfo->source_file;
8034 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8035 buffer_add_int (buf, il_offsets [i]);
8036 buffer_add_int (buf, line_numbers [i]);
8037 if (CHECK_PROTOCOL_VERSION (2, 13))
8038 buffer_add_int (buf, source_files [i]);
8039 if (CHECK_PROTOCOL_VERSION (2, 19))
8040 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8042 g_free (source_file);
8043 g_free (il_offsets);
8044 g_free (line_numbers);
8045 g_free (source_files);
8046 g_ptr_array_free (source_file_list, TRUE);
8047 mono_metadata_free_mh (header);
8050 case CMD_METHOD_GET_PARAM_INFO: {
8051 MonoMethodSignature *sig = mono_method_signature (method);
8055 /* FIXME: mono_class_from_mono_type () and byrefs */
8057 /* FIXME: Use a smaller encoding */
8058 buffer_add_int (buf, sig->call_convention);
8059 buffer_add_int (buf, sig->param_count);
8060 buffer_add_int (buf, sig->generic_param_count);
8061 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8062 for (i = 0; i < sig->param_count; ++i) {
8064 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8067 /* Emit parameter names */
8068 names = g_new (char *, sig->param_count);
8069 mono_method_get_param_names (method, (const char **) names);
8070 for (i = 0; i < sig->param_count; ++i)
8071 buffer_add_string (buf, names [i]);
8076 case CMD_METHOD_GET_LOCALS_INFO: {
8077 int i, j, num_locals;
8078 MonoDebugLocalsInfo *locals;
8080 header = mono_method_get_header (method);
8082 return ERR_INVALID_ARGUMENT;
8084 buffer_add_int (buf, header->num_locals);
8087 for (i = 0; i < header->num_locals; ++i)
8088 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8091 locals = mono_debug_lookup_locals (method);
8093 num_locals = locals->num_locals;
8096 for (i = 0; i < header->num_locals; ++i) {
8097 for (j = 0; j < num_locals; ++j)
8098 if (locals->locals [j].index == i)
8101 buffer_add_string (buf, locals->locals [j].name);
8103 buffer_add_string (buf, "");
8107 for (i = 0; i < header->num_locals; ++i) {
8108 for (j = 0; j < num_locals; ++j)
8109 if (locals->locals [j].index == i)
8111 if (j < num_locals && locals->locals [j].block) {
8112 buffer_add_int (buf, locals->locals [j].block->start_offset);
8113 buffer_add_int (buf, locals->locals [j].block->end_offset);
8115 buffer_add_int (buf, 0);
8116 buffer_add_int (buf, header->code_size);
8119 mono_metadata_free_mh (header);
8122 mono_debug_symfile_free_locals (locals);
8126 case CMD_METHOD_GET_INFO:
8127 buffer_add_int (buf, method->flags);
8128 buffer_add_int (buf, method->iflags);
8129 buffer_add_int (buf, method->token);
8130 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8132 if (method->is_generic)
8134 if (mono_method_signature (method)->generic_param_count)
8136 buffer_add_byte (buf, attrs);
8137 if (method->is_generic || method->is_inflated) {
8140 if (method->is_generic) {
8143 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8145 result = imethod->declaring;
8146 if (imethod->context.class_inst) {
8147 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8148 /*Generic methods gets the context of the GTD.*/
8149 if (mono_class_get_context (klass))
8150 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8154 buffer_add_methodid (buf, domain, result);
8156 buffer_add_id (buf, 0);
8158 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8159 if (mono_method_signature (method)->generic_param_count) {
8162 if (method->is_inflated) {
8163 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8165 count = inst->type_argc;
8166 buffer_add_int (buf, count);
8168 for (i = 0; i < count; i++)
8169 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8171 buffer_add_int (buf, 0);
8173 } else if (method->is_generic) {
8174 MonoGenericContainer *container = mono_method_get_generic_container (method);
8176 count = mono_method_signature (method)->generic_param_count;
8177 buffer_add_int (buf, count);
8178 for (i = 0; i < count; i++) {
8179 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8180 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8181 buffer_add_typeid (buf, domain, pklass);
8184 buffer_add_int (buf, 0);
8187 buffer_add_int (buf, 0);
8192 case CMD_METHOD_GET_BODY: {
8195 header = mono_method_get_header (method);
8197 buffer_add_int (buf, 0);
8199 if (CHECK_PROTOCOL_VERSION (2, 18))
8200 buffer_add_int (buf, 0);
8202 buffer_add_int (buf, header->code_size);
8203 for (i = 0; i < header->code_size; ++i)
8204 buffer_add_byte (buf, header->code [i]);
8206 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8207 buffer_add_int (buf, header->num_clauses);
8208 for (i = 0; i < header->num_clauses; ++i) {
8209 MonoExceptionClause *clause = &header->clauses [i];
8211 buffer_add_int (buf, clause->flags);
8212 buffer_add_int (buf, clause->try_offset);
8213 buffer_add_int (buf, clause->try_len);
8214 buffer_add_int (buf, clause->handler_offset);
8215 buffer_add_int (buf, clause->handler_len);
8216 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8217 buffer_add_typeid (buf, domain, clause->data.catch_class);
8218 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8219 buffer_add_int (buf, clause->data.filter_offset);
8223 mono_metadata_free_mh (header);
8228 case CMD_METHOD_RESOLVE_TOKEN: {
8229 guint32 token = decode_int (p, &p, end);
8232 switch (mono_metadata_token_code (token)) {
8233 case MONO_TOKEN_STRING: {
8237 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8240 s2 = mono_string_to_utf8 (s);
8242 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8243 buffer_add_string (buf, s2);
8249 MonoClass *handle_class;
8251 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8252 val = mono_method_get_wrapper_data (method, token);
8253 handle_class = mono_method_get_wrapper_data (method, token + 1);
8255 if (handle_class == NULL) {
8256 // Can't figure out the token type
8257 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8261 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8265 if (handle_class == mono_defaults.typehandle_class) {
8266 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8267 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8268 buffer_add_typeid (buf, domain, (MonoClass *) val);
8270 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8271 } else if (handle_class == mono_defaults.fieldhandle_class) {
8272 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8273 buffer_add_fieldid (buf, domain, val);
8274 } else if (handle_class == mono_defaults.methodhandle_class) {
8275 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8276 buffer_add_methodid (buf, domain, val);
8277 } else if (handle_class == mono_defaults.string_class) {
8280 s = mono_string_to_utf8 (val);
8281 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8282 buffer_add_string (buf, s);
8285 g_assert_not_reached ();
8292 case CMD_METHOD_GET_CATTRS: {
8293 MonoClass *attr_klass;
8294 MonoCustomAttrInfo *cinfo;
8296 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8297 /* attr_klass can be NULL */
8301 cinfo = mono_custom_attrs_from_method (method);
8303 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8306 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8307 MonoType **type_argv;
8311 MonoGenericInst *ginst;
8312 MonoGenericContext tmp_context;
8313 MonoMethod *inflated;
8315 type_argc = decode_int (p, &p, end);
8316 type_argv = g_new0 (MonoType*, type_argc);
8317 for (i = 0; i < type_argc; ++i) {
8318 klass = decode_typeid (p, &p, end, &d, &err);
8325 return ERR_INVALID_ARGUMENT;
8327 type_argv [i] = &klass->byval_arg;
8329 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8331 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8332 tmp_context.method_inst = ginst;
8334 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8335 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8336 return ERR_INVALID_ARGUMENT;
8337 buffer_add_methodid (buf, domain, inflated);
8341 return ERR_NOT_IMPLEMENTED;
8348 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8351 MonoDomain *old_domain;
8355 method = decode_methodid (p, &p, end, &domain, &err);
8359 old_domain = mono_domain_get ();
8361 mono_domain_set (domain, TRUE);
8363 err = method_commands_internal (command, method, domain, p, end, buf);
8365 mono_domain_set (old_domain, TRUE);
8371 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8373 int objid = decode_objid (p, &p, end);
8375 MonoThread *thread_obj;
8376 MonoInternalThread *thread;
8378 err = get_object (objid, (MonoObject**)&thread_obj);
8382 thread = THREAD_TO_INTERNAL (thread_obj);
8385 case CMD_THREAD_GET_NAME: {
8387 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8390 buffer_add_int (buf, 0);
8395 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8397 buffer_add_int (buf, len);
8398 buffer_add_data (buf, (guint8*)name, len);
8403 case CMD_THREAD_GET_FRAME_INFO: {
8404 DebuggerTlsData *tls;
8405 int i, start_frame, length;
8407 // Wait for suspending if it already started
8408 // FIXME: Races with suspend_count
8409 while (!is_suspended ()) {
8411 wait_for_suspend ();
8415 wait_for_suspend ();
8416 if (!is_suspended ())
8417 return ERR_NOT_SUSPENDED;
8420 start_frame = decode_int (p, &p, end);
8421 length = decode_int (p, &p, end);
8423 if (start_frame != 0 || length != -1)
8424 return ERR_NOT_IMPLEMENTED;
8426 mono_loader_lock ();
8427 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8428 mono_loader_unlock ();
8431 compute_frame_info (thread, tls);
8433 buffer_add_int (buf, tls->frame_count);
8434 for (i = 0; i < tls->frame_count; ++i) {
8435 buffer_add_int (buf, tls->frames [i]->id);
8436 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8437 buffer_add_int (buf, tls->frames [i]->il_offset);
8439 * Instead of passing the frame type directly to the client, we associate
8440 * it with the previous frame using a set of flags. This avoids lots of
8441 * conditional code in the client, since a frame whose type isn't
8442 * FRAME_TYPE_MANAGED has no method, location, etc.
8444 buffer_add_byte (buf, tls->frames [i]->flags);
8449 case CMD_THREAD_GET_STATE:
8450 buffer_add_int (buf, thread->state);
8452 case CMD_THREAD_GET_INFO:
8453 buffer_add_byte (buf, thread->threadpool_thread);
8455 case CMD_THREAD_GET_ID:
8456 buffer_add_long (buf, (guint64)(gsize)thread);
8458 case CMD_THREAD_GET_TID:
8459 buffer_add_long (buf, (guint64)thread->tid);
8462 return ERR_NOT_IMPLEMENTED;
8469 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8473 MonoThread *thread_obj;
8474 MonoInternalThread *thread;
8475 int pos, i, len, frame_idx;
8476 DebuggerTlsData *tls;
8478 MonoDebugMethodJitInfo *jit;
8479 MonoDebugVarInfo *var;
8480 MonoMethodSignature *sig;
8482 MonoMethodHeader *header;
8484 objid = decode_objid (p, &p, end);
8485 err = get_object (objid, (MonoObject**)&thread_obj);
8489 thread = THREAD_TO_INTERNAL (thread_obj);
8491 id = decode_id (p, &p, end);
8493 mono_loader_lock ();
8494 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8495 mono_loader_unlock ();
8498 for (i = 0; i < tls->frame_count; ++i) {
8499 if (tls->frames [i]->id == id)
8502 if (i == tls->frame_count)
8503 return ERR_INVALID_FRAMEID;
8506 frame = tls->frames [frame_idx];
8508 if (!frame->has_ctx)
8509 return ERR_ABSENT_INFORMATION;
8512 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8513 if (!frame->jit && frame->api_method->is_inflated)
8514 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8518 /* This could happen for aot images with no jit debug info */
8519 s = mono_method_full_name (frame->api_method, TRUE);
8520 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8522 return ERR_ABSENT_INFORMATION;
8527 sig = mono_method_signature (frame->actual_method);
8529 if (!get_seq_points (frame->domain, frame->actual_method))
8531 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8533 return ERR_ABSENT_INFORMATION;
8536 case CMD_STACK_FRAME_GET_VALUES: {
8537 len = decode_int (p, &p, end);
8538 header = mono_method_get_header (frame->actual_method);
8540 for (i = 0; i < len; ++i) {
8541 pos = decode_int (p, &p, end);
8546 g_assert (pos >= 0 && pos < jit->num_params);
8548 var = &jit->params [pos];
8550 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8552 g_assert (pos >= 0 && pos < jit->num_locals);
8554 var = &jit->locals [pos];
8556 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8559 mono_metadata_free_mh (header);
8562 case CMD_STACK_FRAME_GET_THIS: {
8563 if (frame->api_method->klass->valuetype) {
8564 if (!sig->hasthis) {
8565 MonoObject *p = NULL;
8566 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8568 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8571 if (!sig->hasthis) {
8572 MonoObject *p = NULL;
8573 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8575 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8580 case CMD_STACK_FRAME_SET_VALUES: {
8583 MonoDebugVarInfo *var;
8585 len = decode_int (p, &p, end);
8586 header = mono_method_get_header (frame->actual_method);
8588 for (i = 0; i < len; ++i) {
8589 pos = decode_int (p, &p, end);
8594 g_assert (pos >= 0 && pos < jit->num_params);
8596 t = sig->params [pos];
8597 var = &jit->params [pos];
8599 g_assert (pos >= 0 && pos < jit->num_locals);
8601 t = header->locals [pos];
8602 var = &jit->locals [pos];
8605 if (MONO_TYPE_IS_REFERENCE (t))
8606 val_buf = g_alloca (sizeof (MonoObject*));
8608 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8609 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8613 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8615 mono_metadata_free_mh (header);
8619 return ERR_NOT_IMPLEMENTED;
8626 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8629 int objid, err, index, len, i, esize;
8632 objid = decode_objid (p, &p, end);
8633 err = get_object (objid, (MonoObject**)&arr);
8638 case CMD_ARRAY_REF_GET_LENGTH:
8639 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8641 buffer_add_int (buf, arr->max_length);
8642 buffer_add_int (buf, 0);
8644 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8645 buffer_add_int (buf, arr->bounds [i].length);
8646 buffer_add_int (buf, arr->bounds [i].lower_bound);
8650 case CMD_ARRAY_REF_GET_VALUES:
8651 index = decode_int (p, &p, end);
8652 len = decode_int (p, &p, end);
8654 g_assert (index >= 0 && len >= 0);
8655 // Reordered to avoid integer overflow
8656 g_assert (!(index > arr->max_length - len));
8658 esize = mono_array_element_size (arr->obj.vtable->klass);
8659 for (i = index; i < index + len; ++i) {
8660 elem = (gpointer*)((char*)arr->vector + (i * esize));
8661 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8664 case CMD_ARRAY_REF_SET_VALUES:
8665 index = decode_int (p, &p, end);
8666 len = decode_int (p, &p, end);
8668 g_assert (index >= 0 && len >= 0);
8669 // Reordered to avoid integer overflow
8670 g_assert (!(index > arr->max_length - len));
8672 esize = mono_array_element_size (arr->obj.vtable->klass);
8673 for (i = index; i < index + len; ++i) {
8674 elem = (gpointer*)((char*)arr->vector + (i * esize));
8676 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8680 return ERR_NOT_IMPLEMENTED;
8687 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8692 int i, index, length;
8695 objid = decode_objid (p, &p, end);
8696 err = get_object (objid, (MonoObject**)&str);
8701 case CMD_STRING_REF_GET_VALUE:
8702 s = mono_string_to_utf8 (str);
8703 buffer_add_string (buf, s);
8706 case CMD_STRING_REF_GET_LENGTH:
8707 buffer_add_long (buf, mono_string_length (str));
8709 case CMD_STRING_REF_GET_CHARS:
8710 index = decode_long (p, &p, end);
8711 length = decode_long (p, &p, end);
8712 if (index > mono_string_length (str) - length)
8713 return ERR_INVALID_ARGUMENT;
8714 c = mono_string_chars (str) + index;
8715 for (i = 0; i < length; ++i)
8716 buffer_add_short (buf, c [i]);
8719 return ERR_NOT_IMPLEMENTED;
8726 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8735 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8736 objid = decode_objid (p, &p, end);
8737 err = get_object (objid, &obj);
8739 buffer_add_int (buf, 1);
8741 buffer_add_int (buf, 0);
8745 objid = decode_objid (p, &p, end);
8746 err = get_object (objid, &obj);
8751 case CMD_OBJECT_REF_GET_TYPE:
8752 /* This handles transparent proxies too */
8753 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8755 case CMD_OBJECT_REF_GET_VALUES:
8756 len = decode_int (p, &p, end);
8758 for (i = 0; i < len; ++i) {
8759 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8763 /* Check that the field belongs to the object */
8765 for (k = obj->vtable->klass; k; k = k->parent) {
8766 if (k == f->parent) {
8772 return ERR_INVALID_FIELDID;
8774 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8778 if (mono_class_field_is_special_static (f))
8779 return ERR_INVALID_FIELDID;
8781 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8782 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8783 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8784 mono_field_static_get_value (vtable, f, val);
8785 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8788 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8792 case CMD_OBJECT_REF_SET_VALUES:
8793 len = decode_int (p, &p, end);
8795 for (i = 0; i < len; ++i) {
8796 f = decode_fieldid (p, &p, end, NULL, &err);
8800 /* Check that the field belongs to the object */
8802 for (k = obj->vtable->klass; k; k = k->parent) {
8803 if (k == f->parent) {
8809 return ERR_INVALID_FIELDID;
8811 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8815 if (mono_class_field_is_special_static (f))
8816 return ERR_INVALID_FIELDID;
8818 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8819 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8821 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8822 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8827 mono_field_static_set_value (vtable, f, val);
8830 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8836 case CMD_OBJECT_REF_GET_ADDRESS:
8837 buffer_add_long (buf, (gssize)obj);
8839 case CMD_OBJECT_REF_GET_DOMAIN:
8840 buffer_add_domainid (buf, obj->vtable->domain);
8842 case CMD_OBJECT_REF_GET_INFO:
8843 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8844 buffer_add_domainid (buf, obj->vtable->domain);
8847 return ERR_NOT_IMPLEMENTED;
8854 command_set_to_string (CommandSet command_set)
8856 switch (command_set) {
8859 case CMD_SET_OBJECT_REF:
8860 return "OBJECT_REF";
8861 case CMD_SET_STRING_REF:
8862 return "STRING_REF";
8863 case CMD_SET_THREAD:
8865 case CMD_SET_ARRAY_REF:
8867 case CMD_SET_EVENT_REQUEST:
8868 return "EVENT_REQUEST";
8869 case CMD_SET_STACK_FRAME:
8870 return "STACK_FRAME";
8871 case CMD_SET_APPDOMAIN:
8873 case CMD_SET_ASSEMBLY:
8875 case CMD_SET_METHOD:
8879 case CMD_SET_MODULE:
8888 static const char* vm_cmds_str [] = {
8896 "SET_PROTOCOL_VERSION",
8899 "GET_TYPES_FOR_SOURCE_FILE",
8904 static const char* thread_cmds_str[] = {
8913 static const char* event_cmds_str[] = {
8916 "REQUEST_CLEAR_ALL_BREAKPOINTS"
8919 static const char* appdomain_cmds_str[] = {
8921 "GET_FRIENDLY_NAME",
8923 "GET_ENTRY_ASSEMBLY",
8926 "CREATE_BOXED_VALUE"
8929 static const char* assembly_cmds_str[] = {
8932 "GET_MANIFEST_MODULE",
8938 static const char* module_cmds_str[] = {
8942 static const char* method_cmds_str[] = {
8944 "GET_DECLARING_TYPE",
8952 "MAKE_GENERIC_METHOD"
8955 static const char* type_cmds_str[] = {
8963 "IS_ASSIGNABLE_FROM",
8967 "GET_PROPERTY_CATTRS",
8968 "GET_SOURCE_FILES_2",
8970 "GET_METHODS_BY_NAME_FLAGS",
8972 "GET_INTERFACE_MAP",
8976 static const char* stack_frame_cmds_str[] = {
8982 static const char* array_cmds_str[] = {
8988 static const char* string_cmds_str[] = {
8994 static const char* object_cmds_str[] = {
9005 cmd_to_string (CommandSet set, int command)
9013 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9015 case CMD_SET_OBJECT_REF:
9016 cmds = object_cmds_str;
9017 cmds_len = G_N_ELEMENTS (object_cmds_str);
9019 case CMD_SET_STRING_REF:
9020 cmds = string_cmds_str;
9021 cmds_len = G_N_ELEMENTS (string_cmds_str);
9023 case CMD_SET_THREAD:
9024 cmds = thread_cmds_str;
9025 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9027 case CMD_SET_ARRAY_REF:
9028 cmds = array_cmds_str;
9029 cmds_len = G_N_ELEMENTS (array_cmds_str);
9031 case CMD_SET_EVENT_REQUEST:
9032 cmds = event_cmds_str;
9033 cmds_len = G_N_ELEMENTS (event_cmds_str);
9035 case CMD_SET_STACK_FRAME:
9036 cmds = stack_frame_cmds_str;
9037 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9039 case CMD_SET_APPDOMAIN:
9040 cmds = appdomain_cmds_str;
9041 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9043 case CMD_SET_ASSEMBLY:
9044 cmds = assembly_cmds_str;
9045 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9047 case CMD_SET_METHOD:
9048 cmds = method_cmds_str;
9049 cmds_len = G_N_ELEMENTS (method_cmds_str);
9052 cmds = type_cmds_str;
9053 cmds_len = G_N_ELEMENTS (type_cmds_str);
9055 case CMD_SET_MODULE:
9056 cmds = module_cmds_str;
9057 cmds_len = G_N_ELEMENTS (module_cmds_str);
9060 cmds = event_cmds_str;
9061 cmds_len = G_N_ELEMENTS (event_cmds_str);
9066 if (command > 0 && command <= cmds_len)
9067 return cmds [command - 1];
9073 wait_for_attach (void)
9075 #ifndef DISABLE_SOCKET_TRANSPORT
9076 if (listen_fd == -1) {
9077 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9081 /* Block and wait for client connection */
9082 conn_fd = socket_transport_accept (listen_fd);
9083 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9084 if (conn_fd == -1) {
9085 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9089 g_assert_not_reached ();
9093 disconnected = !transport_handshake ();
9095 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9105 * This thread handles communication with the debugger client using a JDWP
9108 static guint32 WINAPI
9109 debugger_thread (void *arg)
9111 int res, len, id, flags, command_set = 0, command = 0;
9112 guint8 header [HEADER_LENGTH];
9113 guint8 *data, *p, *end;
9117 gboolean attach_failed = FALSE;
9119 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9121 debugger_thread_id = GetCurrentThreadId ();
9123 mono_jit_thread_attach (mono_get_root_domain ());
9125 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9127 mono_set_is_debugger_attached (TRUE);
9129 if (agent_config.defer) {
9130 if (!wait_for_attach ()) {
9131 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9132 attach_failed = TRUE; // Don't abort process when we can't listen
9134 /* Send start event to client */
9135 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9139 while (!attach_failed) {
9140 res = transport_recv (header, HEADER_LENGTH);
9142 /* This will break if the socket is closed during shutdown too */
9143 if (res != HEADER_LENGTH) {
9144 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9149 end = header + HEADER_LENGTH;
9151 len = decode_int (p, &p, end);
9152 id = decode_int (p, &p, end);
9153 flags = decode_byte (p, &p, end);
9154 command_set = decode_byte (p, &p, end);
9155 command = decode_byte (p, &p, end);
9157 g_assert (flags == 0);
9160 const char *cmd_str;
9163 cmd_str = cmd_to_string (command_set, command);
9165 sprintf (cmd_num, "%d", command);
9169 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d].\n", command_set_to_string (command_set), cmd_str, id));
9172 data = g_malloc (len - HEADER_LENGTH);
9173 if (len - HEADER_LENGTH > 0)
9175 res = transport_recv (data, len - HEADER_LENGTH);
9176 if (res != len - HEADER_LENGTH) {
9177 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9183 end = data + (len - HEADER_LENGTH);
9185 buffer_init (&buf, 128);
9190 /* Process the request */
9191 switch (command_set) {
9193 err = vm_commands (command, id, p, end, &buf);
9194 if (!err && command == CMD_VM_INVOKE_METHOD)
9195 /* Sent after the invoke is complete */
9198 case CMD_SET_EVENT_REQUEST:
9199 err = event_commands (command, p, end, &buf);
9201 case CMD_SET_APPDOMAIN:
9202 err = domain_commands (command, p, end, &buf);
9204 case CMD_SET_ASSEMBLY:
9205 err = assembly_commands (command, p, end, &buf);
9207 case CMD_SET_MODULE:
9208 err = module_commands (command, p, end, &buf);
9211 err = type_commands (command, p, end, &buf);
9213 case CMD_SET_METHOD:
9214 err = method_commands (command, p, end, &buf);
9216 case CMD_SET_THREAD:
9217 err = thread_commands (command, p, end, &buf);
9219 case CMD_SET_STACK_FRAME:
9220 err = frame_commands (command, p, end, &buf);
9222 case CMD_SET_ARRAY_REF:
9223 err = array_commands (command, p, end, &buf);
9225 case CMD_SET_STRING_REF:
9226 err = string_commands (command, p, end, &buf);
9228 case CMD_SET_OBJECT_REF:
9229 err = object_commands (command, p, end, &buf);
9232 err = ERR_NOT_IMPLEMENTED;
9236 send_reply_packet (id, err, &buf);
9241 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9245 mono_set_is_debugger_attached (FALSE);
9247 mono_mutex_lock (&debugger_thread_exited_mutex);
9248 debugger_thread_exited = TRUE;
9249 mono_cond_signal (&debugger_thread_exited_cond);
9250 mono_mutex_unlock (&debugger_thread_exited_mutex);
9252 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9254 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9255 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9256 start_debugger_thread ();
9262 #else /* DISABLE_DEBUGGER_AGENT */
9265 mono_debugger_agent_parse_options (char *options)
9267 g_error ("This runtime is configured with the debugger agent disabled.");
9271 mono_debugger_agent_init (void)
9276 mono_debugger_agent_breakpoint_hit (void *sigctx)
9281 mono_debugger_agent_single_step_event (void *sigctx)
9286 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9291 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9297 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9298 MonoContext *catch_ctx)
9303 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9308 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9313 mono_debugger_agent_user_break (void)
9319 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9324 mono_debugger_agent_debug_log_is_enabled (void)