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>
48 #ifdef PLATFORM_ANDROID
50 #include <linux/tcp.h>
51 #include <sys/endian.h>
54 #include <mono/metadata/mono-debug.h>
55 #include <mono/metadata/mono-debug-debugger.h>
56 #include <mono/metadata/debug-mono-symfile.h>
57 #include <mono/metadata/gc-internals.h>
58 #include <mono/metadata/environment.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/metadata/threadpool-ms.h>
61 #include <mono/metadata/socket-io.h>
62 #include <mono/metadata/assembly.h>
63 #include <mono/metadata/runtime.h>
64 #include <mono/metadata/verify-internals.h>
65 #include <mono/metadata/reflection-internals.h>
66 #include <mono/utils/mono-coop-mutex.h>
67 #include <mono/utils/mono-coop-semaphore.h>
68 #include <mono/utils/mono-error-internals.h>
69 #include <mono/utils/mono-stack-unwinding.h>
70 #include <mono/utils/mono-time.h>
71 #include <mono/utils/mono-threads.h>
72 #include <mono/utils/networking.h>
73 #include "debugger-agent.h"
75 #include "seq-points.h"
78 * On iOS we can't use System.Environment.Exit () as it will do the wrong
81 #if !defined (TARGET_IOS)
82 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
86 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
87 #define DISABLE_DEBUGGER_AGENT 1
90 #ifdef DISABLE_SOFT_DEBUG
91 #define DISABLE_DEBUGGER_AGENT 1
94 #ifndef DISABLE_DEBUGGER_AGENT
96 #include <mono/utils/mono-os-mutex.h>
98 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
121 guint32 il_offset, native_offset;
125 * If method is gshared, this is the actual instance, otherwise this is equal to
128 MonoMethod *actual_method;
130 * This is the method which is visible to debugger clients. Same as method,
131 * except for native-to-managed wrappers.
133 MonoMethod *api_method;
135 MonoDebugMethodJitInfo *jit;
138 mgreg_t *reg_locations [MONO_MAX_IREGS];
140 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
141 * the frame can become invalid.
146 typedef struct _InvokeData InvokeData;
154 /* This is the context which needs to be restored after the invoke */
158 * If this is set, invoke this method with the arguments given by ARGS.
162 guint32 suspend_count;
165 InvokeData *last_invoke;
169 MonoThreadUnwindState context;
171 /* This is computed on demand when it is requested using the wire protocol */
172 /* It is freed up when the thread is resumed */
176 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
179 gboolean frames_up_to_date;
181 * Points to data about a pending invoke which needs to be executed after the thread
184 InvokeData *pending_invoke;
186 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
191 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
192 * within a finite amount of time.
196 * Set to TRUE if this thread is suspended in suspend_current ().
198 gboolean really_suspended;
199 /* Used to pass the context to the breakpoint/single step handler */
200 MonoContext handler_ctx;
201 /* Whenever thread_stop () was called for this thread */
204 /* Whenever to disable breakpoints (used during invokes) */
205 gboolean disable_breakpoints;
208 * Number of times this thread has been resumed using resume_thread ().
210 guint32 resume_count;
212 MonoInternalThread *thread;
215 * Information about the frame which transitioned to native code for running
218 StackFrameInfo async_last_frame;
221 * The context where the stack walk can be started for running threads.
223 MonoThreadUnwindState async_state;
226 * The context used for filter clauses
228 MonoThreadUnwindState filter_state;
230 gboolean abort_requested;
233 * The current mono_runtime_invoke_checked invocation.
238 * The context where single stepping should resume while the thread is suspended because
239 * of an EXCEPTION event.
241 MonoThreadUnwindState catch_state;
244 * The context which needs to be restored after handling a single step/breakpoint
245 * event. This is the same as the ctx at step/breakpoint site, but includes changes
246 * to caller saved registers done by set_var ().
248 MonoThreadUnwindState restore_state;
249 /* Frames computed from restore_state */
250 int restore_frame_count;
251 StackFrame **restore_frames;
253 /* The currently unloading appdomain */
254 MonoDomain *domain_unloading;
259 void (*connect) (const char *address);
260 void (*close1) (void);
261 void (*close2) (void);
262 gboolean (*send) (void *buf, int len);
263 int (*recv) (void *buf, int len);
267 * Wire Protocol definitions
270 #define HEADER_LENGTH 11
272 #define MAJOR_VERSION 2
273 #define MINOR_VERSION 42
277 CMD_SET_OBJECT_REF = 9,
278 CMD_SET_STRING_REF = 10,
280 CMD_SET_ARRAY_REF = 13,
281 CMD_SET_EVENT_REQUEST = 15,
282 CMD_SET_STACK_FRAME = 16,
283 CMD_SET_APPDOMAIN = 20,
284 CMD_SET_ASSEMBLY = 21,
293 EVENT_KIND_VM_START = 0,
294 EVENT_KIND_VM_DEATH = 1,
295 EVENT_KIND_THREAD_START = 2,
296 EVENT_KIND_THREAD_DEATH = 3,
297 EVENT_KIND_APPDOMAIN_CREATE = 4,
298 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
299 EVENT_KIND_METHOD_ENTRY = 6,
300 EVENT_KIND_METHOD_EXIT = 7,
301 EVENT_KIND_ASSEMBLY_LOAD = 8,
302 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
303 EVENT_KIND_BREAKPOINT = 10,
304 EVENT_KIND_STEP = 11,
305 EVENT_KIND_TYPE_LOAD = 12,
306 EVENT_KIND_EXCEPTION = 13,
307 EVENT_KIND_KEEPALIVE = 14,
308 EVENT_KIND_USER_BREAK = 15,
309 EVENT_KIND_USER_LOG = 16
313 SUSPEND_POLICY_NONE = 0,
314 SUSPEND_POLICY_EVENT_THREAD = 1,
315 SUSPEND_POLICY_ALL = 2
320 ERR_INVALID_OBJECT = 20,
321 ERR_INVALID_FIELDID = 25,
322 ERR_INVALID_FRAMEID = 30,
323 ERR_NOT_IMPLEMENTED = 100,
324 ERR_NOT_SUSPENDED = 101,
325 ERR_INVALID_ARGUMENT = 102,
327 ERR_NO_INVOCATION = 104,
328 ERR_ABSENT_INFORMATION = 105,
329 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
330 ERR_INVOKE_ABORTED = 107,
331 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
336 MOD_KIND_THREAD_ONLY = 3,
337 MOD_KIND_LOCATION_ONLY = 7,
338 MOD_KIND_EXCEPTION_ONLY = 8,
340 MOD_KIND_ASSEMBLY_ONLY = 11,
341 MOD_KIND_SOURCE_FILE_ONLY = 12,
342 MOD_KIND_TYPE_NAME_ONLY = 13,
358 STEP_FILTER_NONE = 0,
359 STEP_FILTER_STATIC_CTOR = 1,
360 STEP_FILTER_DEBUGGER_HIDDEN = 2,
361 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
362 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
366 TOKEN_TYPE_STRING = 0,
368 TOKEN_TYPE_FIELD = 2,
369 TOKEN_TYPE_METHOD = 3,
370 TOKEN_TYPE_UNKNOWN = 4
374 VALUE_TYPE_ID_NULL = 0xf0,
375 VALUE_TYPE_ID_TYPE = 0xf1,
376 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
380 FRAME_FLAG_DEBUGGER_INVOKE = 1,
381 FRAME_FLAG_NATIVE_TRANSITION = 2
385 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
386 INVOKE_FLAG_SINGLE_THREADED = 2,
387 INVOKE_FLAG_RETURN_OUT_THIS = 4,
388 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
389 INVOKE_FLAG_VIRTUAL = 16
393 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
394 } BindingFlagsExtensions;
398 CMD_VM_ALL_THREADS = 2,
403 CMD_VM_INVOKE_METHOD = 7,
404 CMD_VM_SET_PROTOCOL_VERSION = 8,
405 CMD_VM_ABORT_INVOKE = 9,
406 CMD_VM_SET_KEEPALIVE = 10,
407 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
408 CMD_VM_GET_TYPES = 12,
409 CMD_VM_INVOKE_METHODS = 13,
410 CMD_VM_START_BUFFERING = 14,
411 CMD_VM_STOP_BUFFERING = 15
415 CMD_THREAD_GET_FRAME_INFO = 1,
416 CMD_THREAD_GET_NAME = 2,
417 CMD_THREAD_GET_STATE = 3,
418 CMD_THREAD_GET_INFO = 4,
419 CMD_THREAD_GET_ID = 5,
420 CMD_THREAD_GET_TID = 6,
421 CMD_THREAD_SET_IP = 7
425 CMD_EVENT_REQUEST_SET = 1,
426 CMD_EVENT_REQUEST_CLEAR = 2,
427 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
435 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
436 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
437 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
438 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
439 CMD_APPDOMAIN_CREATE_STRING = 5,
440 CMD_APPDOMAIN_GET_CORLIB = 6,
441 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
445 CMD_ASSEMBLY_GET_LOCATION = 1,
446 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
447 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
448 CMD_ASSEMBLY_GET_OBJECT = 4,
449 CMD_ASSEMBLY_GET_TYPE = 5,
450 CMD_ASSEMBLY_GET_NAME = 6
454 CMD_MODULE_GET_INFO = 1,
458 CMD_FIELD_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,
493 CMD_TYPE_CREATE_INSTANCE = 19
497 CMD_STACK_FRAME_GET_VALUES = 1,
498 CMD_STACK_FRAME_GET_THIS = 2,
499 CMD_STACK_FRAME_SET_VALUES = 3,
500 CMD_STACK_FRAME_GET_DOMAIN = 4,
504 CMD_ARRAY_REF_GET_LENGTH = 1,
505 CMD_ARRAY_REF_GET_VALUES = 2,
506 CMD_ARRAY_REF_SET_VALUES = 3,
510 CMD_STRING_REF_GET_VALUE = 1,
511 CMD_STRING_REF_GET_LENGTH = 2,
512 CMD_STRING_REF_GET_CHARS = 3
516 CMD_OBJECT_REF_GET_TYPE = 1,
517 CMD_OBJECT_REF_GET_VALUES = 2,
518 CMD_OBJECT_REF_IS_COLLECTED = 3,
519 CMD_OBJECT_REF_GET_ADDRESS = 4,
520 CMD_OBJECT_REF_GET_DOMAIN = 5,
521 CMD_OBJECT_REF_SET_VALUES = 6,
522 CMD_OBJECT_REF_GET_INFO = 7,
528 int count; /* For kind == MOD_KIND_COUNT */
529 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
530 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
531 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
532 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
533 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
534 StepFilter filter; /* For kind == MOD_KIND_STEP */
536 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
545 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
549 * Describes a single step request.
553 MonoInternalThread *thread;
559 MonoMethod *start_method;
560 MonoMethod *last_method;
562 /* Whenever single stepping is performed using start/stop_single_stepping () */
564 /* The list of breakpoints used to implement step-over */
566 /* The number of frames at the start of a step-over */
571 * Contains additional information for an event
574 /* For EVENT_KIND_EXCEPTION */
576 MonoContext catch_ctx;
578 /* For EVENT_KIND_USER_LOG */
580 char *category, *message;
581 /* For EVENT_KIND_TYPE_LOAD */
585 /* Dummy structure used for the profiler callbacks */
591 guint8 *buf, *p, *end;
594 typedef struct ReplyPacket {
600 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
602 #ifdef PLATFORM_ANDROID
603 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
605 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
609 #define get_last_sock_error() WSAGetLastError()
610 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
611 #define MONO_EINTR WSAEINTR
613 #define get_last_sock_error() errno
614 #define MONO_EWOULDBLOCK EWOULDBLOCK
615 #define MONO_EINTR EINTR
618 #define CHECK_PROTOCOL_VERSION(major,minor) \
619 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
625 static AgentConfig agent_config;
628 * Whenever the agent is fully initialized.
629 * When using the onuncaught or onthrow options, only some parts of the agent are
630 * initialized on startup, and the full initialization which includes connection
631 * establishment and the startup of the agent thread is only done in response to
634 static gint32 inited;
636 #ifndef DISABLE_SOCKET_TRANSPORT
638 static int listen_fd;
641 static int packet_id = 0;
643 static int objref_id = 0;
645 static int event_request_id = 0;
647 static int frame_id = 0;
649 static GPtrArray *event_requests;
651 static MonoNativeTlsKey debugger_tls_id;
653 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
655 /* Maps MonoInternalThread -> DebuggerTlsData */
656 /* Protected by the loader lock */
657 static MonoGHashTable *thread_to_tls;
659 /* Maps tid -> MonoInternalThread */
660 /* Protected by the loader lock */
661 static MonoGHashTable *tid_to_thread;
663 /* Maps tid -> MonoThread (not MonoInternalThread) */
664 /* Protected by the loader lock */
665 static MonoGHashTable *tid_to_thread_obj;
667 static MonoNativeThreadId debugger_thread_id;
669 static HANDLE debugger_thread_handle;
671 static int log_level;
673 static gboolean embedding;
675 static FILE *log_file;
677 /* Assemblies whose assembly load event has no been sent yet */
678 /* Protected by the dbg lock */
679 static GPtrArray *pending_assembly_loads;
681 /* Whenever the debugger thread has exited */
682 static gboolean debugger_thread_exited;
684 /* Cond variable used to wait for debugger_thread_exited becoming true */
685 static MonoCoopCond debugger_thread_exited_cond;
687 /* Mutex for the cond var above */
688 static MonoCoopMutex debugger_thread_exited_mutex;
690 static DebuggerProfiler debugger_profiler;
692 /* The single step request instance */
693 static SingleStepReq *ss_req;
695 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
696 /* Number of single stepping operations in progress */
700 /* The protocol version of the client */
701 static int major_version, minor_version;
703 /* Whenever the variables above are set by the client */
704 static gboolean protocol_version_set;
706 /* A hash table containing all active domains */
707 /* Protected by the loader lock */
708 static GHashTable *domains;
710 /* The number of times the runtime is suspended */
711 static gint32 suspend_count;
713 /* Whenever to buffer reply messages and send them together */
714 static gboolean buffer_replies;
716 /* Buffered reply packets */
717 static ReplyPacket reply_packets [128];
720 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
721 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
722 static MonoCoopMutex debug_mutex;
724 static void transport_init (void);
725 static void transport_connect (const char *address);
726 static gboolean transport_handshake (void);
727 static void register_transport (DebuggerTransport *trans);
729 static guint32 WINAPI debugger_thread (void *arg);
731 static void runtime_initialized (MonoProfiler *prof);
733 static void runtime_shutdown (MonoProfiler *prof);
735 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
737 static void thread_end (MonoProfiler *prof, uintptr_t tid);
739 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
741 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
743 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
745 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
747 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
749 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
751 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
753 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
755 static void emit_assembly_load (gpointer assembly, gpointer user_data);
757 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
759 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
761 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
763 static void start_single_stepping (void);
765 static void stop_single_stepping (void);
767 static void suspend_current (void);
769 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
771 static void clear_types_for_assembly (MonoAssembly *assembly);
773 static void clear_breakpoints_for_domain (MonoDomain *domain);
775 static void process_profiler_event (EventKind event, gpointer arg);
777 /* Submodule init/cleanup */
778 static void breakpoints_init (void);
779 static void breakpoints_cleanup (void);
781 static void objrefs_init (void);
782 static void objrefs_cleanup (void);
784 static void ids_init (void);
785 static void ids_cleanup (void);
787 static void suspend_init (void);
789 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
790 StackFrame **frames, int nframes);
791 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
792 static void ss_destroy (SingleStepReq *req);
794 static void start_debugger_thread (void);
795 static void stop_debugger_thread (void);
797 static void finish_agent_init (gboolean on_startup);
799 static void process_profiler_event (EventKind event, gpointer arg);
801 static void invalidate_frames (DebuggerTlsData *tls);
803 #ifndef DISABLE_SOCKET_TRANSPORT
805 register_socket_transport (void);
808 static inline gboolean
809 is_debugger_thread (void)
811 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
815 parse_address (char *address, char **host, int *port)
817 char *pos = strchr (address, ':');
819 if (pos == NULL || pos == address)
822 *host = (char *)g_malloc (pos - address + 1);
823 strncpy (*host, address, pos - address);
824 (*host) [pos - address] = '\0';
826 *port = atoi (pos + 1);
834 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
835 fprintf (stderr, "Available options:\n");
836 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
837 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
838 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
839 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
840 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
841 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
842 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
843 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
844 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
845 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
849 parse_flag (const char *option, char *flag)
851 if (!strcmp (flag, "y"))
853 else if (!strcmp (flag, "n"))
856 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
863 mono_debugger_agent_parse_options (char *options)
870 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
871 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
875 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
877 options = g_strdup_printf ("%s,%s", options, extra);
879 agent_config.enabled = TRUE;
880 agent_config.suspend = TRUE;
881 agent_config.server = FALSE;
882 agent_config.defer = FALSE;
883 agent_config.address = NULL;
885 //agent_config.log_level = 10;
887 args = g_strsplit (options, ",", -1);
888 for (ptr = args; ptr && *ptr; ptr ++) {
891 if (strncmp (arg, "transport=", 10) == 0) {
892 agent_config.transport = g_strdup (arg + 10);
893 } else if (strncmp (arg, "address=", 8) == 0) {
894 agent_config.address = g_strdup (arg + 8);
895 } else if (strncmp (arg, "loglevel=", 9) == 0) {
896 agent_config.log_level = atoi (arg + 9);
897 } else if (strncmp (arg, "logfile=", 8) == 0) {
898 agent_config.log_file = g_strdup (arg + 8);
899 } else if (strncmp (arg, "suspend=", 8) == 0) {
900 agent_config.suspend = parse_flag ("suspend", arg + 8);
901 } else if (strncmp (arg, "server=", 7) == 0) {
902 agent_config.server = parse_flag ("server", arg + 7);
903 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
904 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
905 } else if (strncmp (arg, "onthrow=", 8) == 0) {
906 /* We support multiple onthrow= options */
907 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
908 } else if (strncmp (arg, "onthrow", 7) == 0) {
909 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
910 } else if (strncmp (arg, "help", 4) == 0) {
913 } else if (strncmp (arg, "timeout=", 8) == 0) {
914 agent_config.timeout = atoi (arg + 8);
915 } else if (strncmp (arg, "launch=", 7) == 0) {
916 agent_config.launch = g_strdup (arg + 7);
917 } else if (strncmp (arg, "embedding=", 10) == 0) {
918 agent_config.embedding = atoi (arg + 10) == 1;
919 } else if (strncmp (arg, "keepalive=", 10) == 0) {
920 agent_config.keepalive = atoi (arg + 10);
921 } else if (strncmp (arg, "setpgid=", 8) == 0) {
922 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
929 if (agent_config.server && !agent_config.suspend) {
930 /* Waiting for deferred attachment */
931 agent_config.defer = TRUE;
932 if (agent_config.address == NULL) {
933 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
937 //agent_config.log_level = 0;
939 if (agent_config.transport == NULL) {
940 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
944 if (agent_config.address == NULL && !agent_config.server) {
945 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
950 if (!strcmp (agent_config.transport, "dt_socket")) {
951 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
952 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
959 mono_debugger_agent_init (void)
961 mono_coop_mutex_init_recursive (&debug_mutex);
963 if (!agent_config.enabled)
968 /* Need to know whenever a thread has acquired the loader mutex */
969 mono_loader_lock_track_ownership (TRUE);
971 event_requests = g_ptr_array_new ();
973 mono_coop_mutex_init (&debugger_thread_exited_mutex);
974 mono_coop_cond_init (&debugger_thread_exited_cond);
976 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
977 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
978 mono_profiler_install_runtime_initialized (runtime_initialized);
979 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
980 mono_profiler_install_thread (thread_startup, thread_end);
981 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
982 mono_profiler_install_jit_end (jit_end);
984 mono_native_tls_alloc (&debugger_tls_id, NULL);
986 /* Needed by the hash_table_new_type () call below */
987 mono_gc_base_init ();
989 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
990 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
992 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
993 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
995 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
996 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
998 pending_assembly_loads = g_ptr_array_new ();
999 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1001 log_level = agent_config.log_level;
1003 embedding = agent_config.embedding;
1004 disconnected = TRUE;
1006 if (agent_config.log_file) {
1007 log_file = fopen (agent_config.log_file, "w+");
1009 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1018 breakpoints_init ();
1021 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1023 * This is needed because currently we don't handle liveness info.
1025 mini_get_debug_options ()->mdb_optimizations = TRUE;
1027 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1028 /* This is needed because we can't set local variables in registers yet */
1029 mono_disable_optimizations (MONO_OPT_LINEARS);
1033 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1034 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1035 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1038 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1041 if (agent_config.setpgid)
1045 if (!agent_config.onuncaught && !agent_config.onthrow)
1046 finish_agent_init (TRUE);
1050 * finish_agent_init:
1052 * Finish the initialization of the agent. This involves connecting the transport
1053 * and starting the agent thread. This is either done at startup, or
1054 * in response to some event like an unhandled exception.
1057 finish_agent_init (gboolean on_startup)
1061 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1064 if (agent_config.launch) {
1067 // FIXME: Generated address
1068 // FIXME: Races with transport_connect ()
1070 argv [0] = agent_config.launch;
1071 argv [1] = agent_config.transport;
1072 argv [2] = agent_config.address;
1075 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1077 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1082 transport_connect (agent_config.address);
1085 /* Do some which is usually done after sending the VMStart () event */
1086 vm_start_event_sent = TRUE;
1087 start_debugger_thread ();
1092 mono_debugger_agent_cleanup (void)
1097 stop_debugger_thread ();
1099 breakpoints_cleanup ();
1108 #ifndef DISABLE_SOCKET_TRANSPORT
1113 * recv() + handle incomplete reads and EINTR
1116 socket_transport_recv (void *buf, int len)
1122 static gint32 last_keepalive;
1125 MONO_PREPARE_BLOCKING;
1129 res = recv (fd, (char *) buf + total, len - total, flags);
1132 if (agent_config.keepalive) {
1133 gboolean need_keepalive = FALSE;
1134 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1135 need_keepalive = TRUE;
1136 } else if (res == -1) {
1137 /* This could happen if recv () is interrupted repeatedly */
1138 msecs = mono_msec_ticks ();
1139 if (msecs - last_keepalive >= agent_config.keepalive) {
1140 need_keepalive = TRUE;
1141 last_keepalive = msecs;
1144 if (need_keepalive) {
1145 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1149 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1151 MONO_FINISH_BLOCKING;
1157 set_keepalive (void)
1162 if (!agent_config.keepalive || !conn_fd)
1165 tv.tv_sec = agent_config.keepalive / 1000;
1166 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1168 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1169 g_assert (result >= 0);
1173 socket_transport_accept (int socket_fd)
1175 MONO_PREPARE_BLOCKING;
1176 conn_fd = accept (socket_fd, NULL, NULL);
1177 MONO_FINISH_BLOCKING;
1179 if (conn_fd == -1) {
1180 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1182 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1189 socket_transport_send (void *data, int len)
1193 MONO_PREPARE_BLOCKING;
1196 res = send (conn_fd, data, len, 0);
1197 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1199 MONO_FINISH_BLOCKING;
1208 * socket_transport_connect:
1210 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1213 socket_transport_connect (const char *address)
1215 MonoAddressInfo *result;
1216 MonoAddressEntry *rp;
1217 int sfd = -1, s, res;
1221 if (agent_config.address) {
1222 res = parse_address (agent_config.address, &host, &port);
1223 g_assert (res == 0);
1234 mono_network_init ();
1236 /* Obtain address(es) matching host/port */
1237 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1239 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1244 if (agent_config.server) {
1245 /* Wait for a connection */
1247 struct sockaddr_in addr;
1250 /* No address, generate one */
1251 sfd = socket (AF_INET, SOCK_STREAM, 0);
1254 /* This will bind the socket to a random port */
1255 res = listen (sfd, 16);
1257 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1262 addrlen = sizeof (addr);
1263 memset (&addr, 0, sizeof (addr));
1264 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1265 g_assert (res == 0);
1267 host = (char*)"127.0.0.1";
1268 port = ntohs (addr.sin_port);
1270 /* Emit the address to stdout */
1271 /* FIXME: Should print another interface, not localhost */
1272 printf ("%s:%d\n", host, port);
1274 /* Listen on the provided address */
1275 for (rp = result->entries; rp != NULL; rp = rp->next) {
1276 MonoSocketAddress sockaddr;
1280 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1282 sfd = socket (rp->family, rp->socktype,
1287 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1290 res = bind (sfd, &sockaddr.addr, sock_len);
1294 res = listen (sfd, 16);
1301 mono_free_address_info (result);
1304 if (agent_config.defer)
1307 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1309 if (agent_config.timeout) {
1314 tv.tv_usec = agent_config.timeout * 1000;
1316 FD_SET (sfd, &readfds);
1318 MONO_PREPARE_BLOCKING;
1319 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1320 MONO_FINISH_BLOCKING;
1323 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1328 conn_fd = socket_transport_accept (sfd);
1332 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1334 /* Connect to the specified address */
1335 /* FIXME: Respect the timeout */
1336 for (rp = result->entries; rp != NULL; rp = rp->next) {
1337 MonoSocketAddress sockaddr;
1340 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1342 sfd = socket (rp->family, rp->socktype,
1347 MONO_PREPARE_BLOCKING;
1348 res = connect (sfd, &sockaddr.addr, sock_len);
1349 MONO_FINISH_BLOCKING;
1352 break; /* Success */
1354 MONO_PREPARE_BLOCKING;
1356 MONO_FINISH_BLOCKING;
1360 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1366 mono_free_address_info (result);
1369 if (!transport_handshake ())
1374 socket_transport_close1 (void)
1376 /* This will interrupt the agent thread */
1377 /* Close the read part only so it can still send back replies */
1378 /* Also shut down the connection listener so that we can exit normally */
1380 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1381 shutdown (conn_fd, SD_BOTH);
1382 shutdown (listen_fd, SD_BOTH);
1383 closesocket (listen_fd);
1385 shutdown (conn_fd, SHUT_RD);
1386 shutdown (listen_fd, SHUT_RDWR);
1387 MONO_PREPARE_BLOCKING;
1389 MONO_FINISH_BLOCKING;
1394 socket_transport_close2 (void)
1397 shutdown (conn_fd, SD_BOTH);
1399 shutdown (conn_fd, SHUT_RDWR);
1404 register_socket_transport (void)
1406 DebuggerTransport trans;
1408 trans.name = "dt_socket";
1409 trans.connect = socket_transport_connect;
1410 trans.close1 = socket_transport_close1;
1411 trans.close2 = socket_transport_close2;
1412 trans.send = socket_transport_send;
1413 trans.recv = socket_transport_recv;
1415 register_transport (&trans);
1419 * socket_fd_transport_connect:
1423 socket_fd_transport_connect (const char *address)
1427 res = sscanf (address, "%d", &conn_fd);
1429 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1433 if (!transport_handshake ())
1438 register_socket_fd_transport (void)
1440 DebuggerTransport trans;
1442 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1443 trans.name = "socket-fd";
1444 trans.connect = socket_fd_transport_connect;
1445 trans.close1 = socket_transport_close1;
1446 trans.close2 = socket_transport_close2;
1447 trans.send = socket_transport_send;
1448 trans.recv = socket_transport_recv;
1450 register_transport (&trans);
1453 #endif /* DISABLE_SOCKET_TRANSPORT */
1459 #define MAX_TRANSPORTS 16
1461 static DebuggerTransport *transport;
1463 static DebuggerTransport transports [MAX_TRANSPORTS];
1464 static int ntransports;
1467 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1470 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1472 register_transport (trans);
1476 register_transport (DebuggerTransport *trans)
1478 g_assert (ntransports < MAX_TRANSPORTS);
1480 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1485 transport_init (void)
1489 #ifndef DISABLE_SOCKET_TRANSPORT
1490 register_socket_transport ();
1491 register_socket_fd_transport ();
1494 for (i = 0; i < ntransports; ++i) {
1495 if (!strcmp (agent_config.transport, transports [i].name))
1498 if (i == ntransports) {
1499 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1500 for (i = 0; i < ntransports; ++i)
1501 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1502 fprintf (stderr, "\n");
1505 transport = &transports [i];
1509 transport_connect (const char *address)
1511 transport->connect (address);
1515 transport_close1 (void)
1517 transport->close1 ();
1521 transport_close2 (void)
1523 transport->close2 ();
1527 transport_send (void *buf, int len)
1529 return transport->send (buf, len);
1533 transport_recv (void *buf, int len)
1535 return transport->recv (buf, len);
1539 mono_debugger_agent_transport_handshake (void)
1541 return transport_handshake ();
1545 transport_handshake (void)
1547 char handshake_msg [128];
1551 disconnected = TRUE;
1553 /* Write handshake message */
1554 sprintf (handshake_msg, "DWP-Handshake");
1557 res = transport_send (handshake_msg, strlen (handshake_msg));
1558 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1560 g_assert (res != -1);
1563 res = transport_recv (buf, strlen (handshake_msg));
1564 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1565 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1570 * To support older clients, the client sends its protocol version after connecting
1571 * using a command. Until that is received, default to our protocol version.
1573 major_version = MAJOR_VERSION;
1574 minor_version = MINOR_VERSION;
1575 protocol_version_set = FALSE;
1577 #ifndef DISABLE_SOCKET_TRANSPORT
1578 // FIXME: Move this somewhere else
1580 * Set TCP_NODELAY on the socket so the client receives events/command
1581 * results immediately.
1585 int result = setsockopt (conn_fd,
1590 g_assert (result >= 0);
1596 disconnected = FALSE;
1601 stop_debugger_thread (void)
1606 transport_close1 ();
1609 * Wait for the thread to exit.
1611 * If we continue with the shutdown without waiting for it, then the client might
1612 * not receive an answer to its last command like a resume.
1614 if (!is_debugger_thread ()) {
1616 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1617 if (!debugger_thread_exited)
1618 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1619 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1620 } while (!debugger_thread_exited);
1623 transport_close2 ();
1627 start_debugger_thread (void)
1629 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1630 g_assert (debugger_thread_handle);
1634 * Functions to decode protocol data
1638 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1641 g_assert (*endbuf <= limit);
1646 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1649 g_assert (*endbuf <= limit);
1651 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1654 static inline gint64
1655 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1657 guint32 high = decode_int (buf, &buf, limit);
1658 guint32 low = decode_int (buf, &buf, limit);
1662 return ((((guint64)high) << 32) | ((guint64)low));
1666 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1668 return decode_int (buf, endbuf, limit);
1672 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1674 int len = decode_int (buf, &buf, limit);
1682 s = (char *)g_malloc (len + 1);
1685 memcpy (s, buf, len);
1694 * Functions to encode protocol data
1698 buffer_init (Buffer *buf, int size)
1700 buf->buf = (guint8 *)g_malloc (size);
1702 buf->end = buf->buf + size;
1706 buffer_len (Buffer *buf)
1708 return buf->p - buf->buf;
1712 buffer_make_room (Buffer *buf, int size)
1714 if (buf->end - buf->p < size) {
1715 int new_size = buf->end - buf->buf + size + 32;
1716 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1717 size = buf->p - buf->buf;
1720 buf->end = buf->buf + new_size;
1725 buffer_add_byte (Buffer *buf, guint8 val)
1727 buffer_make_room (buf, 1);
1733 buffer_add_short (Buffer *buf, guint32 val)
1735 buffer_make_room (buf, 2);
1736 buf->p [0] = (val >> 8) & 0xff;
1737 buf->p [1] = (val >> 0) & 0xff;
1742 buffer_add_int (Buffer *buf, guint32 val)
1744 buffer_make_room (buf, 4);
1745 buf->p [0] = (val >> 24) & 0xff;
1746 buf->p [1] = (val >> 16) & 0xff;
1747 buf->p [2] = (val >> 8) & 0xff;
1748 buf->p [3] = (val >> 0) & 0xff;
1753 buffer_add_long (Buffer *buf, guint64 l)
1755 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1756 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1760 buffer_add_id (Buffer *buf, int id)
1762 buffer_add_int (buf, (guint64)id);
1766 buffer_add_data (Buffer *buf, guint8 *data, int len)
1768 buffer_make_room (buf, len);
1769 memcpy (buf->p, data, len);
1774 buffer_add_string (Buffer *buf, const char *str)
1779 buffer_add_int (buf, 0);
1782 buffer_add_int (buf, len);
1783 buffer_add_data (buf, (guint8*)str, len);
1788 buffer_add_buffer (Buffer *buf, Buffer *data)
1790 buffer_add_data (buf, data->buf, buffer_len (data));
1794 buffer_free (Buffer *buf)
1800 send_packet (int command_set, int command, Buffer *data)
1806 id = InterlockedIncrement (&packet_id);
1808 len = data->p - data->buf + 11;
1809 buffer_init (&buf, len);
1810 buffer_add_int (&buf, len);
1811 buffer_add_int (&buf, id);
1812 buffer_add_byte (&buf, 0); /* flags */
1813 buffer_add_byte (&buf, command_set);
1814 buffer_add_byte (&buf, command);
1815 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1817 res = transport_send (buf.buf, len);
1825 send_reply_packets (int npackets, ReplyPacket *packets)
1832 for (i = 0; i < npackets; ++i)
1833 len += buffer_len (packets [i].data) + 11;
1834 buffer_init (&buf, len);
1835 for (i = 0; i < npackets; ++i) {
1836 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1837 buffer_add_int (&buf, packets [i].id);
1838 buffer_add_byte (&buf, 0x80); /* flags */
1839 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1840 buffer_add_byte (&buf, packets [i].error);
1841 buffer_add_buffer (&buf, packets [i].data);
1844 res = transport_send (buf.buf, len);
1852 send_reply_packet (int id, int error, Buffer *data)
1856 memset (&packet, 0, sizeof (ReplyPacket));
1858 packet.error = error;
1861 return send_reply_packets (1, &packet);
1865 send_buffered_reply_packets (void)
1869 send_reply_packets (nreply_packets, reply_packets);
1870 for (i = 0; i < nreply_packets; ++i)
1871 buffer_free (reply_packets [i].data);
1872 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1877 buffer_reply_packet (int id, int error, Buffer *data)
1881 if (nreply_packets == 128)
1882 send_buffered_reply_packets ();
1884 p = &reply_packets [nreply_packets];
1887 p->data = g_new0 (Buffer, 1);
1888 buffer_init (p->data, buffer_len (data));
1889 buffer_add_buffer (p->data, data);
1898 * Represents an object accessible by the debugger client.
1901 /* Unique id used in the wire protocol to refer to objects */
1904 * A weakref gc handle pointing to the object. The gc handle is used to
1905 * detect if the object was garbage collected.
1910 /* Maps objid -> ObjRef */
1911 /* Protected by the loader lock */
1912 static GHashTable *objrefs;
1913 /* Protected by the loader lock */
1914 static GHashTable *obj_to_objref;
1915 /* Protected by the dbg lock */
1916 static MonoGHashTable *suspended_objs;
1919 free_objref (gpointer value)
1921 ObjRef *o = (ObjRef *)value;
1923 mono_gchandle_free (o->handle);
1931 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1932 obj_to_objref = g_hash_table_new (NULL, NULL);
1933 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1934 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1938 objrefs_cleanup (void)
1940 g_hash_table_destroy (objrefs);
1945 * Return an ObjRef for OBJ.
1948 get_objref (MonoObject *obj)
1951 GSList *reflist = NULL, *l;
1957 if (suspend_count) {
1959 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1962 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1966 mono_loader_lock ();
1968 /* FIXME: The tables can grow indefinitely */
1970 if (mono_gc_is_moving ()) {
1972 * Objects can move, so use a hash table mapping hash codes to lists of
1973 * ObjRef structures.
1975 hash = mono_object_hash (obj);
1977 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1978 for (l = reflist; l; l = l->next) {
1979 ref = (ObjRef *)l->data;
1980 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1981 mono_loader_unlock ();
1986 /* Use a hash table with masked pointers to internalize object references */
1987 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1988 /* ref might refer to a different object with the same addr which was GCd */
1989 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1990 mono_loader_unlock ();
1995 ref = g_new0 (ObjRef, 1);
1996 ref->id = InterlockedIncrement (&objref_id);
1997 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1999 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2001 if (mono_gc_is_moving ()) {
2002 reflist = g_slist_append (reflist, ref);
2003 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2005 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2008 mono_loader_unlock ();
2014 true_pred (gpointer key, gpointer value, gpointer user_data)
2020 clear_suspended_objs (void)
2023 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2028 get_objid (MonoObject *obj)
2030 return get_objref (obj)->id;
2034 * Set OBJ to the object identified by OBJID.
2035 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2039 get_object_allow_null (int objid, MonoObject **obj)
2049 return ERR_INVALID_OBJECT;
2051 mono_loader_lock ();
2053 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2056 *obj = mono_gchandle_get_target (ref->handle);
2057 mono_loader_unlock ();
2059 return ERR_INVALID_OBJECT;
2062 mono_loader_unlock ();
2063 return ERR_INVALID_OBJECT;
2068 get_object (int objid, MonoObject **obj)
2070 ErrorCode err = get_object_allow_null (objid, obj);
2072 if (err != ERR_NONE)
2075 return ERR_INVALID_OBJECT;
2080 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2082 return decode_id (buf, endbuf, limit);
2086 buffer_add_objid (Buffer *buf, MonoObject *o)
2088 buffer_add_id (buf, get_objid (o));
2107 * Represents a runtime structure accessible to the debugger client
2110 /* Unique id used in the wire protocol */
2112 /* Domain of the runtime structure, NULL if the domain was unloaded */
2119 MonoAssembly *assembly;
2120 MonoClassField *field;
2122 MonoProperty *property;
2127 /* Maps runtime structure -> Id */
2128 /* Protected by the dbg lock */
2129 GHashTable *val_to_id [ID_NUM];
2130 /* Classes whose class load event has been sent */
2131 /* Protected by the loader lock */
2132 GHashTable *loaded_classes;
2133 /* Maps MonoClass->GPtrArray of file names */
2134 GHashTable *source_files;
2135 /* Maps source file basename -> GSList of classes */
2136 GHashTable *source_file_to_class;
2137 /* Same with ignore-case */
2138 GHashTable *source_file_to_class_ignorecase;
2142 /* Protected by the dbg lock */
2143 static GPtrArray *ids [ID_NUM];
2150 for (i = 0; i < ID_NUM; ++i)
2151 ids [i] = g_ptr_array_new ();
2159 for (i = 0; i < ID_NUM; ++i) {
2161 for (j = 0; j < ids [i]->len; ++j)
2162 g_free (g_ptr_array_index (ids [i], j));
2163 g_ptr_array_free (ids [i], TRUE);
2170 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2172 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2174 GHashTableIter iter;
2175 GPtrArray *file_names;
2180 for (i = 0; i < ID_NUM; ++i)
2181 if (info->val_to_id [i])
2182 g_hash_table_destroy (info->val_to_id [i]);
2183 g_hash_table_destroy (info->loaded_classes);
2185 g_hash_table_iter_init (&iter, info->source_files);
2186 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2187 for (i = 0; i < file_names->len; ++i)
2188 g_free (g_ptr_array_index (file_names, i));
2189 g_ptr_array_free (file_names, TRUE);
2192 g_hash_table_iter_init (&iter, info->source_file_to_class);
2193 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2198 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2199 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2207 domain_jit_info (domain)->agent_info = NULL;
2209 /* Clear ids referencing structures in the domain */
2211 for (i = 0; i < ID_NUM; ++i) {
2213 for (j = 0; j < ids [i]->len; ++j) {
2214 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2215 if (id->domain == domain)
2222 mono_loader_lock ();
2223 g_hash_table_remove (domains, domain);
2224 mono_loader_unlock ();
2227 static AgentDomainInfo*
2228 get_agent_domain_info (MonoDomain *domain)
2230 AgentDomainInfo *info = NULL;
2232 mono_domain_lock (domain);
2234 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2236 info = g_new0 (AgentDomainInfo, 1);
2237 domain_jit_info (domain)->agent_info = info;
2238 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2239 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2240 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2241 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2244 mono_domain_unlock (domain);
2250 get_id (MonoDomain *domain, IdType type, gpointer val)
2253 AgentDomainInfo *info;
2258 info = get_agent_domain_info (domain);
2262 if (info->val_to_id [type] == NULL)
2263 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2265 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2271 id = g_new0 (Id, 1);
2273 id->id = ids [type]->len + 1;
2274 id->domain = domain;
2277 g_hash_table_insert (info->val_to_id [type], val, id);
2278 g_ptr_array_add (ids [type], id);
2285 static inline gpointer
2286 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2290 int id = decode_id (buf, endbuf, limit);
2299 // FIXME: error handling
2301 g_assert (id > 0 && id <= ids [type]->len);
2303 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2306 if (res->domain == NULL) {
2307 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2308 *err = ERR_UNLOADED;
2313 *domain = res->domain;
2315 return res->data.val;
2319 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2321 int id = get_id (domain, type, val);
2323 buffer_add_id (buf, id);
2327 static inline MonoClass*
2328 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2332 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2333 if (G_UNLIKELY (log_level >= 2) && klass) {
2336 s = mono_type_full_name (&klass->byval_arg);
2337 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2343 static inline MonoAssembly*
2344 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2346 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2349 static inline MonoImage*
2350 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2352 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2355 static inline MonoMethod*
2356 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2360 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2361 if (G_UNLIKELY (log_level >= 2) && m) {
2364 s = mono_method_full_name (m, TRUE);
2365 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2371 static inline MonoClassField*
2372 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2374 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2377 static inline MonoDomain*
2378 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2380 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2383 static inline MonoProperty*
2384 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2386 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2390 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2392 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2393 if (G_UNLIKELY (log_level >= 2) && klass) {
2396 s = mono_type_full_name (&klass->byval_arg);
2397 if (is_debugger_thread ())
2398 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2400 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2406 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2408 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2409 if (G_UNLIKELY (log_level >= 2) && method) {
2412 s = mono_method_full_name (method, 1);
2413 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2419 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2423 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2424 if (G_UNLIKELY (log_level >= 2) && assembly)
2425 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2429 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2431 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2435 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2437 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2441 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2443 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2447 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2449 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2452 static void invoke_method (void);
2459 * save_thread_context:
2461 * Set CTX as the current threads context which is used for computing stack traces.
2462 * This function is signal-safe.
2465 save_thread_context (MonoContext *ctx)
2467 DebuggerTlsData *tls;
2469 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2473 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2475 mono_thread_state_init_from_current (&tls->context);
2478 /* Number of threads suspended */
2480 * If this is equal to the size of thread_to_tls, the runtime is considered
2483 static gint32 threads_suspend_count;
2485 static MonoCoopMutex suspend_mutex;
2487 /* Cond variable used to wait for suspend_count becoming 0 */
2488 static MonoCoopCond suspend_cond;
2490 /* Semaphore used to wait for a thread becoming suspended */
2491 static MonoCoopSem suspend_sem;
2496 mono_coop_mutex_init (&suspend_mutex);
2497 mono_coop_cond_init (&suspend_cond);
2498 mono_coop_sem_init (&suspend_sem, 0);
2503 StackFrameInfo last_frame;
2504 gboolean last_frame_set;
2508 } GetLastFrameUserData;
2511 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2513 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2515 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2518 if (!data->last_frame_set) {
2519 /* Store the last frame */
2520 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2521 data->last_frame_set = TRUE;
2524 /* Store the context/lmf for the frame above the last frame */
2525 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2526 data->lmf = info->lmf;
2527 data->domain = info->domain;
2533 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2535 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2537 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2538 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2539 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2546 * Process interruption of a thread. This should be signal safe.
2548 * This always runs in the debugger thread.
2551 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2554 MonoNativeThreadId tid;
2558 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2559 tid = mono_thread_info_get_tid (info);
2561 // FIXME: Races when the thread leaves managed code before hitting a single step
2564 if (ji && !ji->is_trampoline) {
2565 /* Running managed code, will be suspended by the single step code */
2566 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2569 * Running native code, will be suspended when it returns to/enters
2570 * managed code. Treat it as already suspended.
2571 * This might interrupt the code in process_single_step_inner (), we use the
2572 * tls->suspending flag to avoid races when that happens.
2574 if (!tls->suspended && !tls->suspending) {
2575 GetLastFrameUserData data;
2577 // FIXME: printf is not signal safe, but this is only used during
2578 // debugger debugging
2580 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2581 //save_thread_context (&ctx);
2584 /* Already terminated */
2588 * We are in a difficult position: we want to be able to provide stack
2589 * traces for this thread, but we can't use the current ctx+lmf, since
2590 * the thread is still running, so it might return to managed code,
2591 * making these invalid.
2592 * So we start a stack walk and save the first frame, along with the
2593 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2594 * suspended when it returns to managed code, so the parent's ctx should
2597 data.last_frame_set = FALSE;
2598 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2599 if (data.last_frame_set) {
2600 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2602 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2604 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2605 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2607 tls->async_state.valid = FALSE;
2610 mono_memory_barrier ();
2612 tls->suspended = TRUE;
2613 mono_coop_sem_post (&suspend_sem);
2619 * reset_native_thread_suspend_state:
2621 * Reset the suspended flag and state on native threads
2624 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2626 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2628 if (!tls->really_suspended && tls->suspended) {
2629 tls->suspended = FALSE;
2631 * The thread might still be running if it was executing native code, so the state won't be invalided by
2632 * suspend_current ().
2634 tls->context.valid = FALSE;
2635 tls->async_state.valid = FALSE;
2636 invalidate_frames (tls);
2641 DebuggerTlsData *tls;
2642 gboolean valid_info;
2645 static SuspendThreadResult
2646 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2648 InterruptData *data = (InterruptData *)user_data;
2651 data->valid_info = TRUE;
2652 ji = mono_jit_info_table_find_internal (
2653 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2654 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2658 /* This is signal safe */
2659 thread_interrupt (data->tls, info, ji);
2660 return MonoResumeThread;
2666 * Notify a thread that it needs to suspend.
2669 notify_thread (gpointer key, gpointer value, gpointer user_data)
2671 MonoInternalThread *thread = (MonoInternalThread *)key;
2672 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2673 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2675 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2678 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2680 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2681 InterruptData interrupt_data = { 0 };
2682 interrupt_data.tls = tls;
2684 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2685 if (!interrupt_data.valid_info) {
2686 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2688 * Attached thread which died without detaching.
2690 tls->terminated = TRUE;
2695 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2697 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2701 if (mono_loader_lock_is_owned_by_self ()) {
2703 * Shortcut for the check in suspend_current (). This speeds up processing
2704 * when executing long running code inside the loader lock, i.e. assembly load
2710 if (is_debugger_thread ())
2713 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2714 if (suspend_count - tls->resume_count > 0)
2715 tls->suspending = TRUE;
2717 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2719 if (suspend_count - tls->resume_count == 0) {
2721 * We are executing a single threaded invoke but the single step for
2722 * suspending is still active.
2723 * FIXME: This slows down single threaded invokes.
2725 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2729 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2731 /* Can't suspend in these methods */
2732 method = jinfo_get_method (ji);
2733 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2736 save_thread_context (ctx);
2744 * Increase the suspend count of the VM. While the suspend count is greater
2745 * than 0, runtime threads are suspended at certain points during execution.
2750 mono_loader_lock ();
2752 mono_coop_mutex_lock (&suspend_mutex);
2756 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2758 if (suspend_count == 1) {
2759 // FIXME: Is it safe to call this inside the lock ?
2760 start_single_stepping ();
2761 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2764 mono_coop_mutex_unlock (&suspend_mutex);
2766 if (suspend_count == 1)
2768 * Suspend creation of new threadpool threads, since they cannot run
2770 mono_threadpool_ms_suspend ();
2772 mono_loader_unlock ();
2778 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2786 g_assert (is_debugger_thread ());
2788 mono_loader_lock ();
2790 mono_coop_mutex_lock (&suspend_mutex);
2792 g_assert (suspend_count > 0);
2795 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2797 if (suspend_count == 0) {
2798 // FIXME: Is it safe to call this inside the lock ?
2799 stop_single_stepping ();
2800 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2803 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2804 err = mono_coop_cond_broadcast (&suspend_cond);
2805 g_assert (err == 0);
2807 mono_coop_mutex_unlock (&suspend_mutex);
2808 //g_assert (err == 0);
2810 if (suspend_count == 0)
2811 mono_threadpool_ms_resume ();
2813 mono_loader_unlock ();
2819 * Resume just one thread.
2822 resume_thread (MonoInternalThread *thread)
2825 DebuggerTlsData *tls;
2827 g_assert (is_debugger_thread ());
2829 mono_loader_lock ();
2831 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2834 mono_coop_mutex_lock (&suspend_mutex);
2836 g_assert (suspend_count > 0);
2838 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2840 tls->resume_count += suspend_count;
2843 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2844 * but only the one whose resume_count field is > 0 will be resumed.
2846 err = mono_coop_cond_broadcast (&suspend_cond);
2847 g_assert (err == 0);
2849 mono_coop_mutex_unlock (&suspend_mutex);
2850 //g_assert (err == 0);
2852 mono_loader_unlock ();
2856 free_frames (StackFrame **frames, int nframes)
2860 for (i = 0; i < nframes; ++i) {
2861 if (frames [i]->jit)
2862 mono_debug_free_method_jit_info (frames [i]->jit);
2863 g_free (frames [i]);
2869 invalidate_frames (DebuggerTlsData *tls)
2872 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2875 free_frames (tls->frames, tls->frame_count);
2876 tls->frame_count = 0;
2879 free_frames (tls->restore_frames, tls->restore_frame_count);
2880 tls->restore_frame_count = 0;
2881 tls->restore_frames = NULL;
2887 * Suspend the current thread until the runtime is resumed. If the thread has a
2888 * pending invoke, then the invoke is executed before this function returns.
2891 suspend_current (void)
2893 DebuggerTlsData *tls;
2896 g_assert (!is_debugger_thread ());
2898 if (mono_loader_lock_is_owned_by_self ()) {
2900 * If we own the loader mutex, can't suspend until we release it, since the
2901 * whole runtime can deadlock otherwise.
2906 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2909 mono_coop_mutex_lock (&suspend_mutex);
2911 tls->suspending = FALSE;
2912 tls->really_suspended = TRUE;
2914 if (!tls->suspended) {
2915 tls->suspended = TRUE;
2916 mono_coop_sem_post (&suspend_sem);
2919 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2921 while (suspend_count - tls->resume_count > 0) {
2922 err = mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2923 g_assert (err == 0);
2926 tls->suspended = FALSE;
2927 tls->really_suspended = FALSE;
2929 threads_suspend_count --;
2931 mono_coop_mutex_unlock (&suspend_mutex);
2933 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2935 if (tls->pending_invoke) {
2936 /* Save the original context */
2937 tls->pending_invoke->has_ctx = TRUE;
2938 tls->pending_invoke->ctx = tls->context.ctx;
2943 /* The frame info becomes invalid after a resume */
2944 tls->context.valid = FALSE;
2945 tls->async_state.valid = FALSE;
2946 invalidate_frames (tls);
2950 count_thread (gpointer key, gpointer value, gpointer user_data)
2952 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2954 if (!tls->suspended && !tls->terminated)
2955 *(int*)user_data = *(int*)user_data + 1;
2959 count_threads_to_wait_for (void)
2963 mono_loader_lock ();
2964 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2965 mono_loader_unlock ();
2973 * Wait until the runtime is completely suspended.
2976 wait_for_suspend (void)
2978 int nthreads, nwait, err;
2979 gboolean waited = FALSE;
2981 // FIXME: Threads starting/stopping ?
2982 mono_loader_lock ();
2983 nthreads = mono_g_hash_table_size (thread_to_tls);
2984 mono_loader_unlock ();
2987 nwait = count_threads_to_wait_for ();
2989 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2990 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2991 g_assert (err == 0);
2999 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3005 * Return whenever the runtime is suspended.
3010 return count_threads_to_wait_for () == 0;
3014 no_seq_points_found (MonoMethod *method, int offset)
3017 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3019 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3023 DebuggerTlsData *tls;
3025 } ComputeFramesUserData;
3028 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3030 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3032 MonoMethod *method, *actual_method, *api_method;
3036 if (info->type != FRAME_TYPE_MANAGED) {
3037 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3038 /* Mark the last frame as an invoke frame */
3040 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3046 method = jinfo_get_method (info->ji);
3048 method = info->method;
3049 actual_method = info->actual_method;
3050 api_method = method;
3055 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3058 if (info->il_offset == -1) {
3059 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3060 if (ud->frames == NULL) {
3061 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3062 info->il_offset = sp.il_offset;
3064 if (info->il_offset == -1)
3065 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3068 DEBUG_PRINTF (1, "\tFrame: %s:[il=0x%x, native=0x%x] %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed);
3070 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3071 if (!CHECK_PROTOCOL_VERSION (2, 17))
3072 /* Older clients can't handle this flag */
3074 api_method = mono_marshal_method_from_wrapper (method);
3077 actual_method = api_method;
3078 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3081 frame = g_new0 (StackFrame, 1);
3082 frame->method = method;
3083 frame->actual_method = actual_method;
3084 frame->api_method = api_method;
3085 frame->il_offset = info->il_offset;
3086 frame->native_offset = info->native_offset;
3087 frame->flags = flags;
3088 frame->ji = info->ji;
3089 if (info->reg_locations)
3090 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3093 frame->has_ctx = TRUE;
3095 frame->domain = info->domain;
3097 ud->frames = g_slist_append (ud->frames, frame);
3103 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3105 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3108 * 'tls->filter_ctx' is the location of the throw site.
3110 * mono_walk_stack() will never actually hit the throw site, but unwind
3111 * directly from the filter to the call site; we abort stack unwinding here
3112 * once this happens and resume from the throw site.
3115 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3118 return process_frame (info, ctx, user_data);
3122 * Return a malloc-ed list of StackFrame structures.
3125 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3127 ComputeFramesUserData user_data;
3128 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3133 user_data.tls = tls;
3134 user_data.frames = NULL;
3136 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3138 nframes = g_slist_length (user_data.frames);
3139 res = g_new0 (StackFrame*, nframes);
3140 l = user_data.frames;
3141 for (i = 0; i < nframes; ++i) {
3142 res [i] = (StackFrame *)l->data;
3145 *out_nframes = nframes;
3151 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3153 ComputeFramesUserData user_data;
3155 int i, findex, new_frame_count;
3156 StackFrame **new_frames, *f;
3157 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3159 // FIXME: Locking on tls
3160 if (tls->frames && tls->frames_up_to_date)
3163 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3165 user_data.tls = tls;
3166 user_data.frames = NULL;
3167 if (tls->terminated) {
3168 tls->frame_count = 0;
3170 } if (!tls->really_suspended && tls->async_state.valid) {
3171 /* Have to use the state saved by the signal handler */
3172 process_frame (&tls->async_last_frame, NULL, &user_data);
3173 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3174 } else if (tls->filter_state.valid) {
3176 * We are inside an exception filter.
3178 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3180 if (tls->context.valid)
3181 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3183 * After that, we resume unwinding from the location where the exception has been thrown.
3185 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3186 } else if (tls->context.valid) {
3187 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3190 tls->frame_count = 0;
3194 new_frame_count = g_slist_length (user_data.frames);
3195 new_frames = g_new0 (StackFrame*, new_frame_count);
3197 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3198 f = (StackFrame *)tmp->data;
3201 * Reuse the id for already existing stack frames, so invokes don't invalidate
3202 * the still valid stack frames.
3204 for (i = 0; i < tls->frame_count; ++i) {
3205 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3206 f->id = tls->frames [i]->id;
3211 if (i >= tls->frame_count)
3212 f->id = InterlockedIncrement (&frame_id);
3214 new_frames [findex ++] = f;
3217 g_slist_free (user_data.frames);
3219 invalidate_frames (tls);
3221 tls->frames = new_frames;
3222 tls->frame_count = new_frame_count;
3223 tls->frames_up_to_date = TRUE;
3227 * GHFunc to emit an appdomain creation event
3228 * @param key Don't care
3229 * @param value A loaded appdomain
3230 * @param user_data Don't care
3233 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3235 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3236 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3240 * GHFunc to emit a thread start event
3241 * @param key A thread id
3242 * @param value A thread object
3243 * @param user_data Don't care
3246 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3248 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3249 process_profiler_event (EVENT_KIND_THREAD_START, value);
3253 * GFunc to emit an assembly load event
3254 * @param value A loaded assembly
3255 * @param user_data Don't care
3258 emit_assembly_load (gpointer value, gpointer user_data)
3260 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3264 * GFunc to emit a type load event
3265 * @param value A loaded type
3266 * @param user_data Don't care
3269 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3271 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3275 strdup_tolower (char *s)
3280 for (p = s2; *p; ++p)
3286 * Same as g_path_get_basename () but handles windows paths as well,
3287 * which can occur in .mdb files created by pdb2mdb.
3290 dbg_path_get_basename (const char *filename)
3294 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3295 return g_path_get_basename (filename);
3299 /* No separator -> filename */
3300 r = strrchr (filename, '\\');
3302 return g_strdup (filename);
3304 /* Trailing slash, remove component */
3306 char *copy = g_strdup (filename);
3307 copy [r-filename] = 0;
3308 r = strrchr (copy, '\\');
3312 return g_strdup ("/");
3314 r = g_strdup (&r[1]);
3319 return g_strdup (&r[1]);
3323 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3325 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3327 MonoCustomAttrInfo *ainfo;
3329 if (ji->dbg_attrs_inited)
3333 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3335 if (!step_through_klass)
3336 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3338 if (!non_user_klass)
3339 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3341 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3342 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3344 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3345 ji->dbg_hidden = TRUE;
3346 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3347 ji->dbg_step_through = TRUE;
3348 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3349 ji->dbg_non_user_code = TRUE;
3350 mono_custom_attrs_free (ainfo);
3353 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3354 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3356 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3357 ji->dbg_step_through = TRUE;
3358 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3359 ji->dbg_non_user_code = TRUE;
3360 mono_custom_attrs_free (ainfo);
3363 mono_memory_barrier ();
3364 ji->dbg_attrs_inited = TRUE;
3372 * create_event_list:
3374 * Return a list of event request ids matching EVENT, starting from REQS, which
3375 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3377 * We return request ids, instead of requests, to simplify threading, since
3378 * requests could be deleted anytime when the loader lock is not held.
3379 * LOCKING: Assumes the loader lock is held.
3382 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3385 GSList *events = NULL;
3387 *suspend_policy = SUSPEND_POLICY_NONE;
3390 reqs = event_requests;
3395 for (i = 0; i < reqs->len; ++i) {
3396 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3397 if (req->event_kind == event) {
3398 gboolean filtered = FALSE;
3401 for (j = 0; j < req->nmodifiers; ++j) {
3402 Modifier *mod = &req->modifiers [j];
3404 if (mod->kind == MOD_KIND_COUNT) {
3406 if (mod->data.count > 0) {
3407 if (mod->data.count > 0) {
3409 if (mod->data.count == 0)
3413 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3414 if (mod->data.thread != mono_thread_internal_current ())
3416 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3417 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3419 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3421 if (ei->caught && !mod->caught)
3423 if (!ei->caught && !mod->uncaught)
3425 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3427 gboolean found = FALSE;
3428 MonoAssembly **assemblies = mod->data.assemblies;
3431 for (k = 0; assemblies [k]; ++k)
3432 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3437 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3438 gpointer iter = NULL;
3440 MonoDebugSourceInfo *sinfo;
3441 char *source_file, *s;
3442 gboolean found = FALSE;
3444 GPtrArray *source_file_list;
3446 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3447 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3450 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3451 for (i = 0; i < source_file_list->len; ++i) {
3452 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3454 * Do a case-insesitive match by converting the file name to
3457 s = strdup_tolower (sinfo->source_file);
3458 if (g_hash_table_lookup (mod->data.source_files, s))
3461 char *s2 = dbg_path_get_basename (sinfo->source_file);
3462 char *s3 = strdup_tolower (s2);
3464 if (g_hash_table_lookup (mod->data.source_files, s3))
3471 g_ptr_array_free (source_file_list, TRUE);
3476 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3479 s = mono_type_full_name (&ei->klass->byval_arg);
3480 if (!g_hash_table_lookup (mod->data.type_names, s))
3483 } else if (mod->kind == MOD_KIND_STEP) {
3484 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3485 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3486 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3487 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3489 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3490 init_jit_info_dbg_attrs (ji);
3494 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3495 init_jit_info_dbg_attrs (ji);
3496 if (ji->dbg_step_through)
3499 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3500 init_jit_info_dbg_attrs (ji);
3501 if (ji->dbg_non_user_code)
3508 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3509 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3514 /* Send a VM START/DEATH event by default */
3515 if (event == EVENT_KIND_VM_START)
3516 events = g_slist_append (events, GINT_TO_POINTER (0));
3517 if (event == EVENT_KIND_VM_DEATH)
3518 events = g_slist_append (events, GINT_TO_POINTER (0));
3523 static G_GNUC_UNUSED const char*
3524 event_to_string (EventKind event)
3527 case EVENT_KIND_VM_START: return "VM_START";
3528 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3529 case EVENT_KIND_THREAD_START: return "THREAD_START";
3530 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3531 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3532 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3533 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3534 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3535 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3536 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3537 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3538 case EVENT_KIND_STEP: return "STEP";
3539 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3540 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3541 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3542 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3543 case EVENT_KIND_USER_LOG: return "USER_LOG";
3545 g_assert_not_reached ();
3553 * Send an event to the client, suspending the vm if needed.
3554 * LOCKING: Since this can suspend the calling thread, no locks should be held
3556 * The EVENTS list is freed by this function.
3559 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3563 MonoDomain *domain = mono_domain_get ();
3564 MonoThread *thread = NULL;
3565 MonoObject *keepalive_obj = NULL;
3566 gboolean send_success = FALSE;
3571 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3575 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3576 // FIXME: We miss those events
3577 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3581 if (vm_death_event_sent) {
3582 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3586 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3587 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3592 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3596 if (event == EVENT_KIND_KEEPALIVE)
3597 suspend_policy = SUSPEND_POLICY_NONE;
3602 if (agent_config.defer) {
3603 /* Make sure the thread id is always set when doing deferred debugging */
3604 if (is_debugger_thread ()) {
3605 /* Don't suspend on events from the debugger thread */
3606 suspend_policy = SUSPEND_POLICY_NONE;
3607 thread = mono_thread_get_main ();
3609 else thread = mono_thread_current ();
3611 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3612 // FIXME: Send these with a NULL thread, don't suspend the current thread
3617 nevents = g_slist_length (events);
3618 buffer_init (&buf, 128);
3619 buffer_add_byte (&buf, suspend_policy);
3620 buffer_add_int (&buf, nevents);
3622 for (l = events; l; l = l->next) {
3623 buffer_add_byte (&buf, event); // event kind
3624 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3629 thread = mono_thread_current ();
3631 if (event == EVENT_KIND_VM_START && arg != NULL)
3632 thread = (MonoThread *)arg;
3634 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3637 case EVENT_KIND_THREAD_START:
3638 case EVENT_KIND_THREAD_DEATH:
3640 case EVENT_KIND_APPDOMAIN_CREATE:
3641 case EVENT_KIND_APPDOMAIN_UNLOAD:
3642 buffer_add_domainid (&buf, (MonoDomain *)arg);
3644 case EVENT_KIND_METHOD_ENTRY:
3645 case EVENT_KIND_METHOD_EXIT:
3646 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3648 case EVENT_KIND_ASSEMBLY_LOAD:
3649 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3651 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3652 DebuggerTlsData *tls;
3654 /* The domain the assembly belonged to is not equal to the current domain */
3655 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3657 g_assert (tls->domain_unloading);
3659 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3662 case EVENT_KIND_TYPE_LOAD:
3663 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3665 case EVENT_KIND_BREAKPOINT:
3666 case EVENT_KIND_STEP:
3667 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3668 buffer_add_long (&buf, il_offset);
3670 case EVENT_KIND_VM_START:
3671 buffer_add_domainid (&buf, mono_get_root_domain ());
3673 case EVENT_KIND_VM_DEATH:
3674 if (CHECK_PROTOCOL_VERSION (2, 27))
3675 buffer_add_int (&buf, mono_environment_exitcode_get ());
3677 case EVENT_KIND_EXCEPTION: {
3678 EventInfo *ei = (EventInfo *)arg;
3679 buffer_add_objid (&buf, ei->exc);
3681 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3682 * later after the suspension. (#12494).
3684 keepalive_obj = ei->exc;
3687 case EVENT_KIND_USER_BREAK:
3689 case EVENT_KIND_USER_LOG: {
3690 EventInfo *ei = (EventInfo *)arg;
3691 buffer_add_int (&buf, ei->level);
3692 buffer_add_string (&buf, ei->category ? ei->category : "");
3693 buffer_add_string (&buf, ei->message ? ei->message : "");
3696 case EVENT_KIND_KEEPALIVE:
3697 suspend_policy = SUSPEND_POLICY_NONE;
3700 g_assert_not_reached ();
3704 if (event == EVENT_KIND_VM_START) {
3705 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3706 if (!agent_config.defer)
3707 start_debugger_thread ();
3710 if (event == EVENT_KIND_VM_DEATH) {
3711 vm_death_event_sent = TRUE;
3712 suspend_policy = SUSPEND_POLICY_NONE;
3715 if (mono_runtime_is_shutting_down ())
3716 suspend_policy = SUSPEND_POLICY_NONE;
3718 if (suspend_policy != SUSPEND_POLICY_NONE) {
3720 * Save the thread context and start suspending before sending the packet,
3721 * since we could be receiving the resume request before send_packet ()
3724 save_thread_context (ctx);
3728 /* This will keep this object alive */
3729 get_objref (keepalive_obj);
3732 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3736 g_slist_free (events);
3739 if (!send_success) {
3740 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3744 if (event == EVENT_KIND_VM_START) {
3745 vm_start_event_sent = TRUE;
3748 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer) (gsize) mono_native_thread_id_get (), nevents, event_to_string (event), ecount, suspend_policy);
3750 switch (suspend_policy) {
3751 case SUSPEND_POLICY_NONE:
3753 case SUSPEND_POLICY_ALL:
3756 case SUSPEND_POLICY_EVENT_THREAD:
3760 g_assert_not_reached ();
3765 process_profiler_event (EventKind event, gpointer arg)
3769 EventInfo ei, *ei_arg = NULL;
3771 if (event == EVENT_KIND_TYPE_LOAD) {
3772 ei.klass = (MonoClass *)arg;
3776 mono_loader_lock ();
3777 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3778 mono_loader_unlock ();
3780 process_event (event, arg, 0, NULL, events, suspend_policy);
3784 runtime_initialized (MonoProfiler *prof)
3786 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3787 if (agent_config.defer)
3788 start_debugger_thread ();
3792 runtime_shutdown (MonoProfiler *prof)
3794 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3796 mono_debugger_agent_cleanup ();
3800 thread_startup (MonoProfiler *prof, uintptr_t tid)
3802 MonoInternalThread *thread = mono_thread_internal_current ();
3803 MonoInternalThread *old_thread;
3804 DebuggerTlsData *tls;
3806 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3809 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3811 mono_loader_lock ();
3812 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3813 mono_loader_unlock ();
3815 if (thread == old_thread) {
3817 * For some reason, thread_startup () might be called for the same thread
3818 * multiple times (attach ?).
3820 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3824 * thread_end () might not be called for some threads, and the tid could
3827 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3828 mono_loader_lock ();
3829 mono_g_hash_table_remove (thread_to_tls, old_thread);
3830 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3831 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3832 mono_loader_unlock ();
3836 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3838 // FIXME: Free this somewhere
3839 tls = g_new0 (DebuggerTlsData, 1);
3840 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3841 tls->thread = thread;
3842 mono_native_tls_set_value (debugger_tls_id, tls);
3844 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3846 mono_loader_lock ();
3847 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3848 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3849 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3850 mono_loader_unlock ();
3852 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3855 * suspend_vm () could have missed this thread, so wait for a resume.
3861 thread_end (MonoProfiler *prof, uintptr_t tid)
3863 MonoInternalThread *thread;
3864 DebuggerTlsData *tls = NULL;
3866 mono_loader_lock ();
3867 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3869 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3870 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3872 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3873 tls->terminated = TRUE;
3874 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3875 MONO_GC_UNREGISTER_ROOT (tls->thread);
3879 mono_loader_unlock ();
3881 /* We might be called for threads started before we registered the start callback */
3883 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3885 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3886 && !mono_native_tls_get_value (debugger_tls_id)
3889 * This can happen on darwin since we deregister threads using pthread dtors.
3890 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3895 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3900 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3902 mono_loader_lock ();
3903 g_hash_table_insert (domains, domain, domain);
3904 mono_loader_unlock ();
3906 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3910 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3912 DebuggerTlsData *tls;
3914 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3915 if (is_debugger_thread ())
3919 * Remember the currently unloading appdomain as it is needed to generate
3920 * proper ids for unloading assemblies.
3922 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3924 tls->domain_unloading = domain;
3928 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3930 DebuggerTlsData *tls;
3932 if (is_debugger_thread ())
3935 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3937 tls->domain_unloading = NULL;
3939 clear_breakpoints_for_domain (domain);
3941 mono_loader_lock ();
3942 /* Invalidate each thread's frame stack */
3943 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3944 mono_loader_unlock ();
3946 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3950 * invalidate_each_thread:
3952 * A GHFunc to invalidate frames.
3953 * value must be a DebuggerTlsData*
3956 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3958 invalidate_frames ((DebuggerTlsData *)value);
3962 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3964 /* Sent later in jit_end () */
3966 g_ptr_array_add (pending_assembly_loads, assembly);
3971 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3973 if (is_debugger_thread ())
3976 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3978 clear_event_requests_for_assembly (assembly);
3979 clear_types_for_assembly (assembly);
3983 send_type_load (MonoClass *klass)
3985 gboolean type_load = FALSE;
3986 MonoDomain *domain = mono_domain_get ();
3987 AgentDomainInfo *info = NULL;
3989 info = get_agent_domain_info (domain);
3991 mono_loader_lock ();
3993 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3995 g_hash_table_insert (info->loaded_classes, klass, klass);
3998 mono_loader_unlock ();
4001 emit_type_load (klass, klass, NULL);
4005 * Emit load events for all types currently loaded in the domain.
4006 * Takes the loader and domain locks.
4007 * user_data is unused.
4010 send_types_for_domain (MonoDomain *domain, void *user_data)
4012 AgentDomainInfo *info = NULL;
4014 info = get_agent_domain_info (domain);
4017 mono_loader_lock ();
4018 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4019 mono_loader_unlock ();
4023 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4026 * We emit type load events when the first method of the type is JITted,
4027 * since the class load profiler callbacks might be called with the
4028 * loader lock held. They could also occur in the debugger thread.
4029 * Same for assembly load events.
4032 MonoAssembly *assembly = NULL;
4034 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4036 if (pending_assembly_loads->len > 0) {
4037 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4038 g_ptr_array_remove_index (pending_assembly_loads, 0);
4043 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4049 send_type_load (method->klass);
4052 add_pending_breakpoints (method, jinfo);
4056 * BREAKPOINTS/SINGLE STEPPING
4060 * Contains information about an inserted breakpoint.
4063 long il_offset, native_offset;
4067 } BreakpointInstance;
4070 * Contains generic information about a breakpoint.
4074 * The method where the breakpoint is placed. Can be NULL in which case it
4075 * is inserted into every method. This is used to implement method entry/
4076 * exit events. Can be a generic method definition, in which case the
4077 * breakpoint is inserted into every instance.
4083 * A list of BreakpointInstance structures describing where the breakpoint
4084 * was inserted. There could be more than one because of
4085 * generics/appdomains/method entry/exit.
4087 GPtrArray *children;
4090 /* List of breakpoints */
4091 /* Protected by the loader lock */
4092 static GPtrArray *breakpoints;
4093 /* Maps breakpoint locations to the number of breakpoints at that location */
4094 static GHashTable *bp_locs;
4097 breakpoints_init (void)
4099 breakpoints = g_ptr_array_new ();
4100 bp_locs = g_hash_table_new (NULL, NULL);
4104 * insert_breakpoint:
4106 * Insert the breakpoint described by BP into the method described by
4110 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4113 BreakpointInstance *inst;
4114 SeqPointIterator it;
4115 gboolean it_has_sp = FALSE;
4118 mono_error_init (error);
4120 mono_seq_point_iterator_init (&it, seq_points);
4121 while (mono_seq_point_iterator_next (&it)) {
4122 if (it.seq_point.il_offset == bp->il_offset) {
4130 * The set of IL offsets with seq points doesn't completely match the
4131 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4133 mono_seq_point_iterator_init (&it, seq_points);
4134 while (mono_seq_point_iterator_next (&it)) {
4135 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4136 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4137 it.seq_point.il_offset + 1 == bp->il_offset) {
4145 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4147 mono_seq_point_iterator_init (&it, seq_points);
4148 while (mono_seq_point_iterator_next (&it))
4149 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4152 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4153 g_warning ("%s", s);
4157 g_warning ("%s", s);
4163 inst = g_new0 (BreakpointInstance, 1);
4164 inst->il_offset = it.seq_point.il_offset;
4165 inst->native_offset = it.seq_point.native_offset;
4166 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4168 inst->domain = domain;
4170 mono_loader_lock ();
4172 g_ptr_array_add (bp->children, inst);
4174 mono_loader_unlock ();
4177 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4178 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4181 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4182 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4183 } else if (count == 0) {
4184 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4185 mono_arch_set_breakpoint (ji, inst->ip);
4191 DEBUG_PRINTF (1, "[dbg] Inserted breakpoint at %s:[il=0x%x,native=0x%x] [%p](%d).\n", mono_method_full_name (jinfo_get_method (ji), TRUE), (int)it.seq_point.il_offset, (int)it.seq_point.native_offset, inst->ip, count);
4195 remove_breakpoint (BreakpointInstance *inst)
4197 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4199 MonoJitInfo *ji = inst->ji;
4200 guint8 *ip = inst->ip;
4203 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4204 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4207 g_assert (count > 0);
4209 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4210 mono_arch_clear_breakpoint (ji, ip);
4211 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4219 * This doesn't take any locks.
4221 static inline gboolean
4222 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4228 if (method == bp->method)
4230 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4233 if (bp->method->is_inflated && method->is_inflated) {
4234 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4235 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4237 /* Open generic methods should match closed generic methods of the same class */
4238 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4239 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4240 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4242 /* FIXME: Handle !mvar */
4243 if (t1->type != MONO_TYPE_MVAR)
4254 * add_pending_breakpoints:
4256 * Insert pending breakpoints into the newly JITted method METHOD.
4259 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4262 MonoSeqPointInfo *seq_points;
4264 MonoMethod *jmethod;
4269 domain = mono_domain_get ();
4271 mono_loader_lock ();
4273 for (i = 0; i < breakpoints->len; ++i) {
4274 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4275 gboolean found = FALSE;
4277 if (!bp_matches_method (bp, method))
4280 for (j = 0; j < bp->children->len; ++j) {
4281 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4288 MonoMethod *declaring = NULL;
4290 jmethod = jinfo_get_method (ji);
4291 if (jmethod->is_inflated)
4292 declaring = mono_method_get_declaring_generic_method (jmethod);
4294 mono_domain_lock (domain);
4295 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4296 if (!seq_points && declaring)
4297 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4298 mono_domain_unlock (domain);
4300 /* Could be AOT code */
4302 g_assert (seq_points);
4304 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4308 mono_loader_unlock ();
4312 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4318 mono_error_init (error);
4320 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4322 /* Might be AOTed code */
4323 code = mono_aot_get_method (domain, method);
4325 ji = mono_jit_info_table_find (domain, (char *)code);
4330 insert_breakpoint (seq_points, domain, ji, bp, error);
4334 clear_breakpoint (MonoBreakpoint *bp);
4339 * Set a breakpoint at IL_OFFSET in METHOD.
4340 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4341 * METHOD can also be a generic method definition, in which case a breakpoint
4342 * is placed in all instances of the method.
4343 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4346 static MonoBreakpoint*
4347 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4350 GHashTableIter iter, iter2;
4353 MonoSeqPointInfo *seq_points;
4355 GPtrArray *method_domains;
4356 GPtrArray *method_seq_points;
4360 mono_error_init (error);
4363 // - suspend/resume the vm to prevent code patching problems
4364 // - multiple breakpoints on the same location
4365 // - dynamic methods
4368 bp = g_new0 (MonoBreakpoint, 1);
4369 bp->method = method;
4370 bp->il_offset = il_offset;
4372 bp->children = g_ptr_array_new ();
4374 DEBUG_PRINTF (1, "[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);
4376 methods = g_ptr_array_new ();
4377 method_domains = g_ptr_array_new ();
4378 method_seq_points = g_ptr_array_new ();
4380 mono_loader_lock ();
4381 g_hash_table_iter_init (&iter, domains);
4382 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4383 mono_domain_lock (domain);
4384 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4385 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4386 if (bp_matches_method (bp, m)) {
4387 /* Save the info locally to simplify the code inside the domain lock */
4388 g_ptr_array_add (methods, m);
4389 g_ptr_array_add (method_domains, domain);
4390 g_ptr_array_add (method_seq_points, seq_points);
4393 mono_domain_unlock (domain);
4396 for (i = 0; i < methods->len; ++i) {
4397 m = (MonoMethod *)g_ptr_array_index (methods, i);
4398 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4399 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4400 set_bp_in_method (domain, m, seq_points, bp, error);
4403 g_ptr_array_add (breakpoints, bp);
4404 mono_loader_unlock ();
4406 g_ptr_array_free (methods, TRUE);
4407 g_ptr_array_free (method_domains, TRUE);
4408 g_ptr_array_free (method_seq_points, TRUE);
4410 if (error && !mono_error_ok (error)) {
4411 clear_breakpoint (bp);
4419 clear_breakpoint (MonoBreakpoint *bp)
4423 // FIXME: locking, races
4424 for (i = 0; i < bp->children->len; ++i) {
4425 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4427 remove_breakpoint (inst);
4432 mono_loader_lock ();
4433 g_ptr_array_remove (breakpoints, bp);
4434 mono_loader_unlock ();
4436 g_ptr_array_free (bp->children, TRUE);
4441 breakpoints_cleanup (void)
4445 mono_loader_lock ();
4447 while (i < event_requests->len) {
4448 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4450 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4451 clear_breakpoint ((MonoBreakpoint *)req->info);
4452 g_ptr_array_remove_index_fast (event_requests, i);
4459 for (i = 0; i < breakpoints->len; ++i)
4460 g_free (g_ptr_array_index (breakpoints, i));
4462 g_ptr_array_free (breakpoints, TRUE);
4463 g_hash_table_destroy (bp_locs);
4468 mono_loader_unlock ();
4472 * clear_breakpoints_for_domain:
4474 * Clear breakpoint instances which reference DOMAIN.
4477 clear_breakpoints_for_domain (MonoDomain *domain)
4481 /* This could be called after shutdown */
4485 mono_loader_lock ();
4486 for (i = 0; i < breakpoints->len; ++i) {
4487 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4490 while (j < bp->children->len) {
4491 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4493 if (inst->domain == domain) {
4494 remove_breakpoint (inst);
4498 g_ptr_array_remove_index_fast (bp->children, j);
4504 mono_loader_unlock ();
4510 * Return FALSE if single stepping needs to continue.
4513 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4515 MonoDebugMethodInfo *minfo;
4516 MonoDebugSourceLocation *loc = NULL;
4517 gboolean hit = TRUE;
4520 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4522 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4524 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4528 if (req->depth == STEP_DEPTH_OVER && hit) {
4529 if (!tls->context.valid)
4530 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4531 compute_frame_info (tls->thread, tls);
4532 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4533 /* Hit the breakpoint in a recursive call */
4534 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4539 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4540 method = jinfo_get_method (ji);
4541 if (!tls->context.valid)
4542 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4543 compute_frame_info (tls->thread, tls);
4544 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4545 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4550 if (req->size != STEP_SIZE_LINE)
4553 /* Have to check whenever a different source line was reached */
4554 method = jinfo_get_method (ji);
4555 minfo = mono_debug_lookup_method (method);
4558 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4561 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4562 ss_req->last_method = method;
4564 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4565 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4570 ss_req->last_method = method;
4571 ss_req->last_line = loc->row;
4572 mono_debug_free_source_location (loc);
4579 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4581 return bp->method && bp->method->klass->image->assembly == assembly;
4585 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4589 int i, j, suspend_policy;
4590 guint32 native_offset;
4592 BreakpointInstance *inst;
4593 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4594 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4595 EventKind kind = EVENT_KIND_BREAKPOINT;
4596 MonoContext *ctx = &tls->restore_state.ctx;
4598 MonoSeqPointInfo *info;
4602 // FIXME: Speed this up
4604 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4605 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4606 g_assert (ji && !ji->is_trampoline);
4607 method = jinfo_get_method (ji);
4609 /* Compute the native offset of the breakpoint from the ip */
4610 native_offset = ip - (guint8*)ji->code_start;
4613 * Skip the instruction causing the breakpoint signal.
4616 mono_arch_skip_breakpoint (ctx, ji);
4618 if (method->wrapper_type || tls->disable_breakpoints)
4621 bp_reqs = g_ptr_array_new ();
4622 ss_reqs = g_ptr_array_new ();
4623 ss_reqs_orig = g_ptr_array_new ();
4625 mono_loader_lock ();
4628 * The ip points to the instruction causing the breakpoint event, which is after
4629 * the offset recorded in the seq point map, so find the prev seq point before ip.
4631 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4634 no_seq_points_found (method, native_offset);
4636 g_assert (found_sp);
4638 DEBUG_PRINTF (1, "[%p] Breakpoint hit, method=%s, ip=%p, [il=0x%x,native=0x%x].\n", (gpointer) (gsize) mono_native_thread_id_get (), method->name, ip, sp.il_offset, native_offset);
4641 for (i = 0; i < breakpoints->len; ++i) {
4642 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4647 for (j = 0; j < bp->children->len; ++j) {
4648 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4649 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4650 if (bp->req->event_kind == EVENT_KIND_STEP) {
4651 g_ptr_array_add (ss_reqs_orig, bp->req);
4653 g_ptr_array_add (bp_reqs, bp->req);
4658 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4659 /* Maybe a method entry/exit event */
4660 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4661 kind = EVENT_KIND_METHOD_ENTRY;
4662 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4663 kind = EVENT_KIND_METHOD_EXIT;
4666 /* Process single step requests */
4667 for (i = 0; i < ss_reqs_orig->len; ++i) {
4668 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4669 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4672 if (mono_thread_internal_current () != ss_req->thread)
4675 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4677 g_ptr_array_add (ss_reqs, req);
4679 /* Start single stepping again from the current sequence point */
4680 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4683 if (ss_reqs->len > 0)
4684 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4685 if (bp_reqs->len > 0)
4686 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4687 if (kind != EVENT_KIND_BREAKPOINT)
4688 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4690 mono_loader_unlock ();
4692 g_ptr_array_free (bp_reqs, TRUE);
4693 g_ptr_array_free (ss_reqs, TRUE);
4696 * FIXME: The first event will suspend, so the second will only be sent after the
4700 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4702 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4703 if (enter_leave_events)
4704 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4707 /* Process a breakpoint/single step event after resuming from a signal handler */
4709 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4711 DebuggerTlsData *tls;
4712 MonoThreadUnwindState orig_restore_state;
4715 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4716 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4717 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4718 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4722 /* This is called when resuming from a signal handler, so it shouldn't return */
4723 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4724 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4725 mono_restore_context (&ctx);
4726 g_assert_not_reached ();
4730 process_breakpoint (void)
4732 process_signal_event (process_breakpoint_inner);
4736 resume_from_signal_handler (void *sigctx, void *func)
4738 DebuggerTlsData *tls;
4741 /* Save the original context in TLS */
4742 // FIXME: This might not work on an altstack ?
4743 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4745 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4748 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4749 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4750 // clob:c could be added to op_seq_point.
4752 mono_sigctx_to_monoctx (sigctx, &ctx);
4753 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4754 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4755 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4757 MONO_CONTEXT_SET_IP (&ctx, func);
4759 mono_monoctx_to_sigctx (&ctx, sigctx);
4761 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4762 mono_ppc_set_func_into_sigctx (sigctx, func);
4767 mono_debugger_agent_breakpoint_hit (void *sigctx)
4770 * We are called from a signal handler, and running code there causes all kinds of
4771 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4772 * So set up the signal context to return to the real breakpoint handler function.
4774 resume_from_signal_handler (sigctx, process_breakpoint);
4778 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4780 if (frame->managed) {
4781 *(MonoContext*)data = *ctx;
4790 * Called by System.Diagnostics.Debugger:Break ().
4793 mono_debugger_agent_user_break (void)
4795 if (agent_config.enabled) {
4800 /* Obtain a context */
4801 MONO_CONTEXT_SET_IP (&ctx, NULL);
4802 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
4803 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4805 mono_loader_lock ();
4806 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4807 mono_loader_unlock ();
4809 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4810 } else if (debug_options.native_debugger_break) {
4816 ss_depth_to_string (StepDepth depth)
4819 case STEP_DEPTH_OVER:
4821 case STEP_DEPTH_OUT:
4823 case STEP_DEPTH_INTO:
4826 g_assert_not_reached ();
4832 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4837 int il_offset, suspend_policy;
4840 MonoContext *ctx = &tls->restore_state.ctx;
4843 MonoSeqPointInfo *info;
4845 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4847 /* Skip the instruction causing the single step */
4849 mono_arch_skip_single_step (ctx);
4851 if (suspend_count > 0) {
4852 /* Fastpath during invokes, see in process_suspend () */
4853 if (suspend_count - tls->resume_count == 0)
4855 process_suspend (tls, ctx);
4860 // FIXME: A suspend race
4863 if (mono_thread_internal_current () != ss_req->thread)
4866 if (log_level > 0) {
4867 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4869 DEBUG_PRINTF (1, "[%p] Single step event (depth=%s) at %s (%p)[0x%x], sp %p, last sp %p\n", (gpointer) (gsize) mono_native_thread_id_get (), ss_depth_to_string (ss_req->depth), mono_method_full_name (jinfo_get_method (ji), TRUE), MONO_CONTEXT_GET_IP (ctx), (int)((guint8*)MONO_CONTEXT_GET_IP (ctx) - (guint8*)ji->code_start), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp);
4872 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4873 g_assert (ji && !ji->is_trampoline);
4874 method = jinfo_get_method (ji);
4877 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4882 * Stopping in memset makes half-initialized vtypes visible.
4883 * Stopping in memcpy makes half-copied vtypes visible.
4885 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4889 * The ip points to the instruction causing the single step event, which is before
4890 * the offset recorded in the seq point map, so find the next seq point after ip.
4892 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4895 il_offset = sp.il_offset;
4897 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4900 /* Start single stepping again from the current sequence point */
4901 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4903 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4904 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4905 !strcmp (method->name, ".cctor"))
4908 // FIXME: Has to lock earlier
4910 reqs = g_ptr_array_new ();
4912 mono_loader_lock ();
4914 g_ptr_array_add (reqs, ss_req->req);
4916 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4918 g_ptr_array_free (reqs, TRUE);
4920 mono_loader_unlock ();
4922 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4926 process_single_step (void)
4928 process_signal_event (process_single_step_inner);
4932 * mono_debugger_agent_single_step_event:
4934 * Called from a signal handler to handle a single step event.
4937 mono_debugger_agent_single_step_event (void *sigctx)
4939 /* Resume to process_single_step through the signal context */
4941 // FIXME: Since step out/over is implemented using step in, the step in case should
4942 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4945 if (is_debugger_thread ()) {
4947 * This could happen despite our best effors when the runtime calls
4948 * assembly/type resolve hooks.
4949 * FIXME: Breakpoints too.
4953 mono_sigctx_to_monoctx (sigctx, &ctx);
4954 mono_arch_skip_single_step (&ctx);
4955 mono_monoctx_to_sigctx (&ctx, sigctx);
4959 resume_from_signal_handler (sigctx, process_single_step);
4963 debugger_agent_single_step_from_context (MonoContext *ctx)
4965 DebuggerTlsData *tls;
4966 MonoThreadUnwindState orig_restore_state;
4968 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4969 /* Fastpath during invokes, see in process_suspend () */
4970 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4973 if (is_debugger_thread ())
4978 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4979 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4980 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4981 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4983 process_single_step_inner (tls, FALSE);
4985 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4986 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4990 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4992 DebuggerTlsData *tls;
4993 MonoThreadUnwindState orig_restore_state;
4996 if (is_debugger_thread ())
4999 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5000 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5002 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5004 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5005 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5006 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5008 process_breakpoint_inner (tls, FALSE);
5010 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5011 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5012 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5013 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5017 * start_single_stepping:
5019 * Turn on single stepping. Can be called multiple times, for example,
5020 * by a single step event request + a suspend.
5023 start_single_stepping (void)
5025 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5026 int val = InterlockedIncrement (&ss_count);
5029 mono_arch_start_single_stepping ();
5031 g_assert_not_reached ();
5036 stop_single_stepping (void)
5038 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5039 int val = InterlockedDecrement (&ss_count);
5042 mono_arch_stop_single_stepping ();
5044 g_assert_not_reached ();
5051 * Stop the single stepping operation given by SS_REQ.
5054 ss_stop (SingleStepReq *ss_req)
5059 for (l = ss_req->bps; l; l = l->next) {
5060 clear_breakpoint ((MonoBreakpoint *)l->data);
5062 g_slist_free (ss_req->bps);
5066 if (ss_req->global) {
5067 stop_single_stepping ();
5068 ss_req->global = FALSE;
5075 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5076 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5077 * belong to the same thread as CTX.
5078 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5081 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5082 gboolean step_to_catch, StackFrame **frames, int nframes)
5084 int i, j, frame_index;
5085 SeqPoint *next_sp, *parent_sp = NULL;
5086 SeqPoint local_sp, local_parent_sp;
5089 MonoSeqPointInfo *parent_info;
5090 MonoMethod *parent_sp_method = NULL;
5091 gboolean enable_global = FALSE;
5093 /* Stop the previous operation */
5097 * Implement single stepping using breakpoints if possible.
5099 if (step_to_catch) {
5100 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5101 ss_req->bps = g_slist_append (ss_req->bps, bp);
5105 if (ctx && !frames) {
5106 /* Need parent frames */
5107 if (!tls->context.valid)
5108 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5109 compute_frame_info (tls->thread, tls);
5110 frames = tls->frames;
5111 nframes = tls->frame_count;
5115 * Find the first sequence point in the current or in a previous frame which
5116 * is not the last in its method.
5118 if (ss_req->depth == STEP_DEPTH_OUT) {
5119 /* Ignore seq points in current method */
5120 while (frame_index < nframes) {
5121 StackFrame *frame = frames [frame_index];
5123 method = frame->method;
5124 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5125 sp = (found_sp)? &local_sp : NULL;
5127 if (sp && sp->next_len != 0)
5130 // There could be method calls before the next seq point in the caller when using nested calls
5131 //enable_global = TRUE;
5133 if (sp && sp->next_len == 0) {
5135 while (frame_index < nframes) {
5136 StackFrame *frame = frames [frame_index];
5138 method = frame->method;
5139 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5140 sp = (found_sp)? &local_sp : NULL;
5141 if (sp && sp->next_len != 0)
5147 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5148 while (frame_index < nframes) {
5149 StackFrame *frame = frames [frame_index];
5151 parent_sp_method = frame->method;
5152 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5153 parent_sp = found_sp ? &local_parent_sp : NULL;
5154 if (found_sp && parent_sp->next_len != 0)
5162 if (sp && sp->next_len > 0) {
5163 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5165 mono_seq_point_init_next (info, *sp, next);
5166 for (i = 0; i < sp->next_len; i++) {
5169 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5170 ss_req->bps = g_slist_append (ss_req->bps, bp);
5176 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5178 mono_seq_point_init_next (parent_info, *parent_sp, next);
5179 for (i = 0; i < parent_sp->next_len; i++) {
5182 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5183 ss_req->bps = g_slist_append (ss_req->bps, bp);
5188 if (ss_req->nframes == 0)
5189 ss_req->nframes = nframes;
5191 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5192 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5194 * This is needed since if we leave managed code, and later return to it, step over
5195 * is not going to stop.
5196 * This approach is a bit ugly, since we change the step depth, but it only affects
5197 * clients who reuse the same step request, and only in this special case.
5199 ss_req->depth = STEP_DEPTH_INTO;
5202 if (ss_req->depth == STEP_DEPTH_OVER) {
5203 /* Need to stop in catch clauses as well */
5204 for (i = 0; i < nframes; ++i) {
5205 StackFrame *frame = frames [i];
5208 MonoJitInfo *jinfo = frame->ji;
5209 for (j = 0; j < jinfo->num_clauses; ++j) {
5210 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5212 found_sp = mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp);
5213 sp = (found_sp)? &local_sp : NULL;
5215 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5216 ss_req->bps = g_slist_append (ss_req->bps, bp);
5223 if (ss_req->depth == STEP_DEPTH_INTO) {
5224 /* Enable global stepping so we stop at method entry too */
5225 enable_global = TRUE;
5229 * The ctx/frame info computed above will become invalid when we continue.
5231 tls->context.valid = FALSE;
5232 tls->async_state.valid = FALSE;
5233 invalidate_frames (tls);
5236 if (enable_global) {
5237 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5238 ss_req->global = TRUE;
5239 start_single_stepping ();
5240 } else if (!ss_req->bps) {
5241 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5242 ss_req->global = TRUE;
5243 start_single_stepping ();
5245 ss_req->global = FALSE;
5250 * Start single stepping of thread THREAD
5253 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5255 DebuggerTlsData *tls;
5256 MonoSeqPointInfo *info = NULL;
5257 SeqPoint *sp = NULL;
5260 MonoMethod *method = NULL;
5261 MonoDebugMethodInfo *minfo;
5262 gboolean step_to_catch = FALSE;
5263 gboolean set_ip = FALSE;
5264 StackFrame **frames = NULL;
5267 if (suspend_count == 0)
5268 return ERR_NOT_SUSPENDED;
5270 wait_for_suspend ();
5272 // FIXME: Multiple requests
5274 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5275 return ERR_NOT_IMPLEMENTED;
5278 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5280 ss_req = g_new0 (SingleStepReq, 1);
5282 ss_req->thread = thread;
5283 ss_req->size = size;
5284 ss_req->depth = depth;
5285 ss_req->filter = filter;
5288 mono_loader_lock ();
5289 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5290 mono_loader_unlock ();
5292 g_assert (tls->context.valid);
5294 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5296 * Need to start single stepping from restore_state and not from the current state
5299 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5302 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5304 if (tls->catch_state.valid) {
5306 StackFrameInfo frame;
5307 MonoContext new_ctx;
5308 MonoLMF *lmf = NULL;
5311 * We are stopped at a throw site. Stepping should go to the catch site.
5314 /* Find the the jit info for the catch context */
5315 res = mono_find_jit_info_ext (
5316 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5317 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5318 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5320 g_assert (frame.type == FRAME_TYPE_MANAGED);
5323 * Find the seq point corresponding to the landing site ip, which is the first seq
5326 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5327 sp = (found_sp)? &local_sp : NULL;
5329 no_seq_points_found (frame.method, frame.native_offset);
5332 method = frame.method;
5334 step_to_catch = TRUE;
5335 /* This make sure the seq point is not skipped by process_single_step () */
5336 ss_req->last_sp = NULL;
5339 if (!step_to_catch) {
5340 StackFrame *frame = NULL;
5343 if (frames && nframes)
5346 compute_frame_info (thread, tls);
5348 if (tls->frame_count)
5349 frame = tls->frames [0];
5352 if (ss_req->size == STEP_SIZE_LINE) {
5354 ss_req->last_method = frame->method;
5355 ss_req->last_line = -1;
5357 minfo = mono_debug_lookup_method (frame->method);
5358 if (minfo && frame->il_offset != -1) {
5359 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5362 ss_req->last_line = loc->row;
5370 if (!method && frame->il_offset != -1) {
5371 /* FIXME: Sort the table and use a binary search */
5372 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5373 sp = (found_sp)? &local_sp : NULL;
5375 no_seq_points_found (frame->method, frame->native_offset);
5377 method = frame->method;
5382 ss_req->start_method = method;
5384 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5387 free_frames (frames, nframes);
5393 ss_destroy (SingleStepReq *req)
5396 g_assert (ss_req == req);
5405 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5408 gboolean found = TRUE;
5412 for (l = ss_req->bps; l; l = l->next) {
5413 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5414 clear_breakpoint ((MonoBreakpoint *)l->data);
5415 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5424 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5427 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5433 if (!agent_config.enabled)
5436 mono_loader_lock ();
5437 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5438 mono_loader_unlock ();
5441 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5442 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5444 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5446 g_free (ei.category);
5447 g_free (ei.message);
5451 mono_debugger_agent_debug_log_is_enabled (void)
5453 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5454 return agent_config.enabled;
5457 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5459 mono_debugger_agent_unhandled_exception (MonoException *exc)
5468 memset (&ei, 0, sizeof (EventInfo));
5469 ei.exc = (MonoObject*)exc;
5471 mono_loader_lock ();
5472 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5473 mono_loader_unlock ();
5475 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5480 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5481 MonoContext *catch_ctx)
5483 int i, j, suspend_policy;
5485 MonoJitInfo *ji, *catch_ji;
5487 DebuggerTlsData *tls = NULL;
5489 if (thread_to_tls != NULL) {
5490 MonoInternalThread *thread = mono_thread_internal_current ();
5492 mono_loader_lock ();
5493 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5494 mono_loader_unlock ();
5496 if (tls && tls->abort_requested)
5498 if (tls && tls->disable_breakpoints)
5502 memset (&ei, 0, sizeof (EventInfo));
5504 /* Just-In-Time debugging */
5506 if (agent_config.onuncaught && !inited) {
5507 finish_agent_init (FALSE);
5510 * Send an unsolicited EXCEPTION event with a dummy request id.
5512 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5513 ei.exc = (MonoObject*)exc;
5514 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5517 } else if (agent_config.onthrow && !inited) {
5519 gboolean found = FALSE;
5521 for (l = agent_config.onthrow; l; l = l->next) {
5522 char *ex_type = (char *)l->data;
5523 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5525 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5532 finish_agent_init (FALSE);
5535 * Send an unsolicited EXCEPTION event with a dummy request id.
5537 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5538 ei.exc = (MonoObject*)exc;
5539 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5547 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5549 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5553 ei.exc = (MonoObject*)exc;
5554 ei.caught = catch_ctx != NULL;
5556 mono_loader_lock ();
5558 /* Treat exceptions which are caught in non-user code as unhandled */
5559 for (i = 0; i < event_requests->len; ++i) {
5560 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5561 if (req->event_kind != EVENT_KIND_EXCEPTION)
5564 for (j = 0; j < req->nmodifiers; ++j) {
5565 Modifier *mod = &req->modifiers [j];
5567 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5569 gboolean found = FALSE;
5570 MonoAssembly **assemblies = mod->data.assemblies;
5573 for (k = 0; assemblies [k]; ++k)
5574 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5583 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5584 mono_loader_unlock ();
5586 if (tls && ei.caught && catch_ctx) {
5587 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5588 tls->catch_state.ctx = *catch_ctx;
5589 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5590 tls->catch_state.valid = TRUE;
5593 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5596 tls->catch_state.valid = FALSE;
5600 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5602 DebuggerTlsData *tls;
5607 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5612 * We're about to invoke an exception filter during the first pass of exception handling.
5614 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5615 * 'orig_ctx' is the context where the exception has been thrown.
5618 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5620 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5621 * the call site (line 37) and then continue to Main(), but it would never
5622 * include the throw site (line 32).
5624 * Since exception filters are invoked during the first pass of exception handling,
5625 * the stack frames of the throw site are still intact, so we should include them
5628 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5630 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5631 * but report the location of the 'throw' to the user.
5635 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5639 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5641 DebuggerTlsData *tls;
5646 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5650 tls->filter_state.valid = FALSE;
5654 * buffer_add_value_full:
5656 * Add the encoding of the value at ADDR described by T to the buffer.
5657 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5661 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5662 gboolean as_vtype, GHashTable *parent_vtypes)
5665 gboolean boxed_vtype = FALSE;
5668 if (!(*(void**)addr)) {
5669 /* This can happen with compiler generated locals */
5670 //printf ("%s\n", mono_type_full_name (t));
5671 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5674 g_assert (*(void**)addr);
5675 addr = *(void**)addr;
5680 case MONO_TYPE_BOOLEAN:
5683 case MONO_TYPE_CHAR:
5703 case MONO_TYPE_VOID:
5704 buffer_add_byte (buf, t->type);
5706 case MONO_TYPE_BOOLEAN:
5709 buffer_add_byte (buf, t->type);
5710 buffer_add_int (buf, *(gint8*)addr);
5712 case MONO_TYPE_CHAR:
5715 buffer_add_byte (buf, t->type);
5716 buffer_add_int (buf, *(gint16*)addr);
5721 buffer_add_byte (buf, t->type);
5722 buffer_add_int (buf, *(gint32*)addr);
5727 buffer_add_byte (buf, t->type);
5728 buffer_add_long (buf, *(gint64*)addr);
5732 /* Treat it as a vtype */
5734 case MONO_TYPE_PTR: {
5735 gssize val = *(gssize*)addr;
5737 buffer_add_byte (buf, t->type);
5738 buffer_add_long (buf, val);
5742 case MONO_TYPE_STRING:
5743 case MONO_TYPE_SZARRAY:
5744 case MONO_TYPE_OBJECT:
5745 case MONO_TYPE_CLASS:
5746 case MONO_TYPE_ARRAY:
5747 obj = *(MonoObject**)addr;
5750 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5752 if (obj->vtable->klass->valuetype) {
5753 t = &obj->vtable->klass->byval_arg;
5754 addr = mono_object_unbox (obj);
5757 } else if (obj->vtable->klass->rank) {
5758 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5759 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5760 buffer_add_byte (buf, MONO_TYPE_CLASS);
5762 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5764 buffer_add_objid (buf, obj);
5768 case MONO_TYPE_VALUETYPE:
5769 case MONO_TYPE_TYPEDBYREF: {
5773 MonoClass *klass = mono_class_from_mono_type (t);
5778 * Handle boxed vtypes recursively referencing themselves using fields.
5781 parent_vtypes = g_hash_table_new (NULL, NULL);
5782 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5784 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5785 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5786 buffer_add_int (buf, vtype_index - 1);
5788 /* The client can't handle PARENT_VTYPE */
5789 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5793 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5797 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5798 buffer_add_byte (buf, klass->enumtype);
5799 buffer_add_typeid (buf, domain, klass);
5803 while ((f = mono_class_get_fields (klass, &iter))) {
5804 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5806 if (mono_field_is_deleted (f))
5810 buffer_add_int (buf, nfields);
5813 while ((f = mono_class_get_fields (klass, &iter))) {
5814 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5816 if (mono_field_is_deleted (f))
5818 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5822 g_hash_table_remove (parent_vtypes, addr);
5823 if (g_hash_table_size (parent_vtypes) == 0) {
5824 g_hash_table_destroy (parent_vtypes);
5825 parent_vtypes = NULL;
5830 case MONO_TYPE_GENERICINST:
5831 if (mono_type_generic_inst_is_valuetype (t)) {
5843 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5845 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5849 obj_is_of_type (MonoObject *obj, MonoType *t)
5851 MonoClass *klass = obj->vtable->klass;
5852 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5853 if (mono_class_is_transparent_proxy (klass)) {
5854 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5855 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5865 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5868 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5874 gpointer iter = NULL;
5878 is_enum = decode_byte (buf, &buf, limit);
5879 /* Enums are sent as a normal vtype */
5881 return ERR_NOT_IMPLEMENTED;
5882 klass = decode_typeid (buf, &buf, limit, &d, &err);
5883 if (err != ERR_NONE)
5886 if (t && klass != mono_class_from_mono_type (t)) {
5887 char *name = mono_type_full_name (t);
5888 char *name2 = mono_type_full_name (&klass->byval_arg);
5889 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5892 return ERR_INVALID_ARGUMENT;
5895 nfields = decode_int (buf, &buf, limit);
5896 while ((f = mono_class_get_fields (klass, &iter))) {
5897 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5899 if (mono_field_is_deleted (f))
5901 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5902 if (err != ERR_NONE)
5906 g_assert (nfields == 0);
5914 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5918 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5919 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5920 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5921 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5922 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5923 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5924 char *name = mono_type_full_name (t);
5925 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5927 return ERR_INVALID_ARGUMENT;
5931 case MONO_TYPE_BOOLEAN:
5932 *(guint8*)addr = decode_int (buf, &buf, limit);
5934 case MONO_TYPE_CHAR:
5935 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5938 *(gint8*)addr = decode_int (buf, &buf, limit);
5941 *(guint8*)addr = decode_int (buf, &buf, limit);
5944 *(gint16*)addr = decode_int (buf, &buf, limit);
5947 *(guint16*)addr = decode_int (buf, &buf, limit);
5950 *(gint32*)addr = decode_int (buf, &buf, limit);
5953 *(guint32*)addr = decode_int (buf, &buf, limit);
5956 *(gint64*)addr = decode_long (buf, &buf, limit);
5959 *(guint64*)addr = decode_long (buf, &buf, limit);
5962 *(guint32*)addr = decode_int (buf, &buf, limit);
5965 *(guint64*)addr = decode_long (buf, &buf, limit);
5968 /* We send these as I8, so we get them back as such */
5969 g_assert (type == MONO_TYPE_I8);
5970 *(gssize*)addr = decode_long (buf, &buf, limit);
5972 case MONO_TYPE_GENERICINST:
5973 if (MONO_TYPE_ISSTRUCT (t)) {
5974 /* The client sends these as a valuetype */
5982 /* We send these as vtypes, so we get them back as such */
5983 g_assert (type == MONO_TYPE_VALUETYPE);
5986 case MONO_TYPE_VALUETYPE:
5987 if (type == MONO_TYPE_OBJECT) {
5989 int objid = decode_objid (buf, &buf, limit);
5993 err = get_object (objid, (MonoObject**)&obj);
5994 if (err != ERR_NONE)
5997 return ERR_INVALID_ARGUMENT;
5998 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
5999 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6000 return ERR_INVALID_ARGUMENT;
6002 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6004 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6005 if (err != ERR_NONE)
6011 if (MONO_TYPE_IS_REFERENCE (t)) {
6012 if (type == MONO_TYPE_OBJECT) {
6013 int objid = decode_objid (buf, &buf, limit);
6017 err = get_object (objid, (MonoObject**)&obj);
6018 if (err != ERR_NONE)
6022 if (!obj_is_of_type (obj, t)) {
6023 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6024 return ERR_INVALID_ARGUMENT;
6027 if (obj && obj->vtable->domain != domain)
6028 return ERR_INVALID_ARGUMENT;
6030 mono_gc_wbarrier_generic_store (addr, obj);
6031 } else if (type == VALUE_TYPE_ID_NULL) {
6032 *(MonoObject**)addr = NULL;
6033 } else if (type == MONO_TYPE_VALUETYPE) {
6041 /* This can happen when round-tripping boxed vtypes */
6043 * Obtain vtype class.
6044 * Same as the beginning of the handle_vtype case above.
6047 is_enum = decode_byte (buf, &buf, limit);
6049 return ERR_NOT_IMPLEMENTED;
6050 klass = decode_typeid (buf, &buf, limit, &d, &err);
6051 if (err != ERR_NONE)
6054 /* Decode the vtype into a temporary buffer, then box it. */
6055 vtype_buf_size = mono_class_value_size (klass, NULL);
6056 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6057 g_assert (vtype_buf);
6060 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6061 if (err != ERR_NONE) {
6065 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6068 char *name = mono_type_full_name (t);
6069 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6071 return ERR_INVALID_ARGUMENT;
6085 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6088 int type = decode_byte (buf, &buf, limit);
6090 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6091 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6092 guint8 *nullable_buf;
6095 * First try decoding it as a Nullable`1
6097 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6098 if (err == ERR_NONE)
6102 * Then try decoding as a primitive value or null.
6104 if (targ->type == type) {
6105 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6106 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6107 if (err != ERR_NONE) {
6108 g_free (nullable_buf);
6111 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6112 g_free (nullable_buf);
6115 } else if (type == VALUE_TYPE_ID_NULL) {
6116 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6122 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6126 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6130 guint8 *addr, *gaddr;
6133 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6134 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6137 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6138 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6140 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6142 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6143 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6144 addr += (gint32)var->offset;
6146 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6148 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6150 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6153 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6154 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6155 /* Same as regoffset, but with an indirection */
6156 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6157 addr += (gint32)var->offset;
6159 gaddr = (guint8 *)*(gpointer*)addr;
6161 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6163 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6164 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6165 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6166 MonoGSharedVtMethodRuntimeInfo *info;
6172 g_assert (info_var);
6173 g_assert (locals_var);
6175 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6176 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6177 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6178 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6179 addr += (gint32)info_var->offset;
6180 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6181 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6182 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6184 g_assert_not_reached ();
6188 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6189 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6190 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6191 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6192 addr += (gint32)locals_var->offset;
6193 locals = (guint8 *)*(gpointer*)addr;
6194 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6195 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6197 g_assert_not_reached ();
6201 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6203 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6208 g_assert_not_reached ();
6213 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6217 guint8 *addr, *gaddr;
6219 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6220 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6222 if (MONO_TYPE_IS_REFERENCE (t))
6223 size = sizeof (gpointer);
6225 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6228 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6229 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6231 gboolean is_signed = FALSE;
6234 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6237 // FIXME: Write barriers
6238 mono_gc_memmove_atomic (addr, val, size);
6243 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6248 v = is_signed ? *(gint8*)val : *(guint8*)val;
6251 v = is_signed ? *(gint16*)val : *(guint16*)val;
6254 v = is_signed ? *(gint32*)val : *(guint32*)val;
6257 v = is_signed ? *(gint64*)val : *(guint64*)val;
6260 g_assert_not_reached ();
6263 /* Set value on the stack or in the return ctx */
6264 if (reg_locations [reg]) {
6265 /* Saved on the stack */
6266 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6267 *(reg_locations [reg]) = v;
6270 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6271 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6274 // FIXME: Move these to mono-context.h/c.
6275 mono_arch_context_set_int_reg (ctx, reg, v);
6277 // FIXME: Can't set registers, so we disable linears
6282 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6283 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6284 addr += (gint32)var->offset;
6286 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6289 addr = *(guint8**)addr;
6295 // FIXME: Write barriers
6296 mono_gc_memmove_atomic (addr, val, size);
6298 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6299 /* Same as regoffset, but with an indirection */
6300 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6301 addr += (gint32)var->offset;
6303 gaddr = (guint8 *)*(gpointer*)addr;
6305 // FIXME: Write barriers
6306 mono_gc_memmove_atomic (gaddr, val, size);
6308 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6312 g_assert_not_reached ();
6317 clear_event_request (int req_id, int etype)
6321 mono_loader_lock ();
6322 for (i = 0; i < event_requests->len; ++i) {
6323 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6325 if (req->id == req_id && req->event_kind == etype) {
6326 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6327 clear_breakpoint ((MonoBreakpoint *)req->info);
6328 if (req->event_kind == EVENT_KIND_STEP)
6329 ss_destroy ((SingleStepReq *)req->info);
6330 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6331 clear_breakpoint ((MonoBreakpoint *)req->info);
6332 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6333 clear_breakpoint ((MonoBreakpoint *)req->info);
6334 g_ptr_array_remove_index_fast (event_requests, i);
6339 mono_loader_unlock ();
6343 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6347 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6348 m->kind = MOD_KIND_NONE;
6349 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6350 int count = 0, match_count = 0, pos;
6351 MonoAssembly **newassemblies;
6353 for (i = 0; m->data.assemblies [i]; ++i) {
6355 if (m->data.assemblies [i] == assembly)
6360 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6363 for (i = 0; i < count; ++i)
6364 if (m->data.assemblies [i] != assembly)
6365 newassemblies [pos ++] = m->data.assemblies [i];
6366 g_assert (pos == count - match_count);
6367 g_free (m->data.assemblies);
6368 m->data.assemblies = newassemblies;
6374 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6378 for (i = 0; i < req->nmodifiers; ++i) {
6379 Modifier *m = &req->modifiers [i];
6381 clear_assembly_from_modifier (req, m, assembly);
6386 * clear_event_requests_for_assembly:
6388 * Clear all events requests which reference ASSEMBLY.
6391 clear_event_requests_for_assembly (MonoAssembly *assembly)
6396 mono_loader_lock ();
6400 for (i = 0; i < event_requests->len; ++i) {
6401 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6403 clear_assembly_from_modifiers (req, assembly);
6405 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6406 clear_event_request (req->id, req->event_kind);
6411 if (req->event_kind == EVENT_KIND_STEP)
6412 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6415 mono_loader_unlock ();
6419 * type_comes_from_assembly:
6421 * GHRFunc that returns TRUE if klass comes from assembly
6424 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6426 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6430 * clear_types_for_assembly:
6432 * Clears types from loaded_classes for a given assembly
6435 clear_types_for_assembly (MonoAssembly *assembly)
6437 MonoDomain *domain = mono_domain_get ();
6438 AgentDomainInfo *info = NULL;
6440 if (!domain || !domain_jit_info (domain))
6441 /* Can happen during shutdown */
6444 info = get_agent_domain_info (domain);
6446 mono_loader_lock ();
6447 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6448 mono_loader_unlock ();
6452 add_thread (gpointer key, gpointer value, gpointer user_data)
6454 MonoInternalThread *thread = (MonoInternalThread *)value;
6455 Buffer *buf = (Buffer *)user_data;
6457 buffer_add_objid (buf, (MonoObject*)thread);
6461 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6464 guint8 *end = invoke->endp;
6468 MonoMethodSignature *sig;
6471 MonoObject *this_arg, *res, *exc;
6474 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6477 MonoStopwatch watch;
6479 if (invoke->method) {
6481 * Invoke this method directly, currently only Environment.Exit () is supported.
6484 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (invoke->method, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6486 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6487 mono_error_assert_ok (&error);
6489 g_assert_not_reached ();
6492 m = decode_methodid (p, &p, end, &domain, &err);
6493 if (err != ERR_NONE)
6495 sig = mono_method_signature (m);
6497 if (m->klass->valuetype)
6498 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6500 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6501 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6502 /* Should be null */
6503 int type = decode_byte (p, &p, end);
6504 if (type != VALUE_TYPE_ID_NULL) {
6505 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6506 return ERR_INVALID_ARGUMENT;
6508 memset (this_buf, 0, mono_class_instance_size (m->klass));
6509 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6513 int type = decode_byte (p, &tmp_p, end);
6514 if (type == VALUE_TYPE_ID_NULL) {
6515 memset (this_buf, 0, mono_class_instance_size (m->klass));
6518 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6519 if (err != ERR_NONE)
6523 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6524 if (err != ERR_NONE)
6528 if (!m->klass->valuetype)
6529 this_arg = *(MonoObject**)this_buf;
6533 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6535 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6536 return ERR_INVALID_ARGUMENT;
6538 m = mono_object_get_virtual_method (this_arg, m);
6539 /* Transform this to the format the rest of the code expects it to be */
6540 if (m->klass->valuetype) {
6541 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6542 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6544 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6546 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6547 return ERR_INVALID_ARGUMENT;
6549 m = mono_object_get_virtual_method (this_arg, m);
6550 if (m->klass->valuetype) {
6551 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6552 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6556 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (m, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6558 if (this_arg && this_arg->vtable->domain != domain)
6561 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6562 if (!strcmp (m->name, ".ctor")) {
6563 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6564 return ERR_INVALID_ARGUMENT;
6567 this_arg = mono_object_new_checked (domain, m->klass, &error);
6568 mono_error_assert_ok (&error);
6571 return ERR_INVALID_ARGUMENT;
6575 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6576 return ERR_INVALID_ARGUMENT;
6578 nargs = decode_int (p, &p, end);
6579 if (nargs != sig->param_count)
6580 return ERR_INVALID_ARGUMENT;
6581 /* Use alloca to get gc tracking */
6582 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6583 memset (arg_buf, 0, nargs * sizeof (gpointer));
6584 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6585 for (i = 0; i < nargs; ++i) {
6586 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6587 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6588 if (err != ERR_NONE)
6590 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6593 if (sig->params [i]->byref) {
6594 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6595 *(gpointer*)arg_buf [i] = args [i];
6596 args [i] = arg_buf [i];
6599 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6600 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6601 if (err != ERR_NONE)
6603 args [i] = arg_buf [i];
6610 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6611 tls->disable_breakpoints = TRUE;
6613 tls->disable_breakpoints = FALSE;
6616 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6618 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6619 if (invoke->has_ctx) {
6622 lmf_addr = mono_get_lmf_addr ();
6625 memset (&ext, 0, sizeof (ext));
6626 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6628 ext.debugger_invoke = TRUE;
6629 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6631 mono_set_lmf ((MonoLMF*)&ext);
6635 mono_stopwatch_start (&watch);
6636 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
6637 if (exc == NULL && !mono_error_ok (&error)) {
6638 exc = (MonoObject*) mono_error_convert_to_exception (&error);
6640 mono_error_cleanup (&error); /* FIXME report error */
6642 mono_stopwatch_stop (&watch);
6643 DEBUG_PRINTF (1, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer) (gsize) mono_native_thread_id_get (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch));
6645 buffer_add_byte (buf, 0);
6646 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6648 gboolean out_this = FALSE;
6649 gboolean out_args = FALSE;
6651 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6653 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6655 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6656 if (sig->ret->type == MONO_TYPE_VOID) {
6657 if (!strcmp (m->name, ".ctor")) {
6658 if (!m->klass->valuetype)
6659 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6661 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6663 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6665 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6666 buffer_add_value (buf, sig->ret, &res, domain);
6667 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6668 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6669 MonoClass *k = mono_class_from_mono_type (sig->ret);
6670 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6672 g_assert (nullable_buf);
6673 mono_nullable_init (nullable_buf, res, k);
6674 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6677 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6683 /* Return the new value of the receiver after the call */
6684 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6686 buffer_add_int (buf, nargs);
6687 for (i = 0; i < nargs; ++i) {
6688 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6689 buffer_add_value (buf, sig->params [i], &args [i], domain);
6690 else if (sig->params [i]->byref)
6691 /* add_value () does an indirection */
6692 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6694 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6699 tls->disable_breakpoints = FALSE;
6701 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6702 if (invoke->has_ctx)
6703 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
6707 // FIXME: byref arguments
6715 * Invoke the method given by tls->pending_invoke in the current thread.
6718 invoke_method (void)
6720 DebuggerTlsData *tls;
6726 MonoContext restore_ctx;
6729 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6733 * Store the `InvokeData *' in `tls->invoke' until we're done with
6734 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6737 mono_loader_lock ();
6739 invoke = tls->pending_invoke;
6741 tls->pending_invoke = NULL;
6743 invoke->last_invoke = tls->invoke;
6744 tls->invoke = invoke;
6746 mono_loader_unlock ();
6748 tls->frames_up_to_date = FALSE;
6754 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6755 buffer_init (&buf, 128);
6758 /* Fail the other invokes as well */
6760 err = do_invoke_method (tls, &buf, invoke, p, &p);
6763 if (tls->abort_requested) {
6764 if (CHECK_PROTOCOL_VERSION (2, 42))
6765 err = ERR_INVOKE_ABORTED;
6768 /* Start suspending before sending the reply */
6769 if (mindex == invoke->nmethods - 1) {
6770 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6771 for (i = 0; i < invoke->suspend_count; ++i)
6776 send_reply_packet (id, err, &buf);
6781 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6783 if (invoke->has_ctx)
6784 save_thread_context (&restore_ctx);
6786 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6787 g_assert (tls->resume_count);
6788 tls->resume_count -= invoke->suspend_count;
6791 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6794 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6796 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6797 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6798 * because we reset the abort here.
6801 mono_loader_lock ();
6803 if (tls->abort_requested)
6804 mono_thread_internal_reset_abort (tls->thread);
6806 tls->invoke = tls->invoke->last_invoke;
6807 tls->abort_requested = FALSE;
6809 mono_loader_unlock ();
6818 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6820 MonoThread *thread = (MonoThread *)value;
6821 DebuggerTlsData *tls;
6824 mono_loader_lock ();
6825 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6827 res = tls->really_suspended;
6828 mono_loader_unlock ();
6834 get_source_files_for_type (MonoClass *klass)
6836 gpointer iter = NULL;
6838 MonoDebugSourceInfo *sinfo;
6842 files = g_ptr_array_new ();
6844 while ((method = mono_class_get_methods (klass, &iter))) {
6845 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6846 GPtrArray *source_file_list;
6849 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6850 for (j = 0; j < source_file_list->len; ++j) {
6851 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6852 for (i = 0; i < files->len; ++i)
6853 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6855 if (i == files->len)
6856 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6858 g_ptr_array_free (source_file_list, TRUE);
6866 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6869 case CMD_VM_VERSION: {
6870 char *build_info, *version;
6872 build_info = mono_get_runtime_build_info ();
6873 version = g_strdup_printf ("mono %s", build_info);
6875 buffer_add_string (buf, version); /* vm version */
6876 buffer_add_int (buf, MAJOR_VERSION);
6877 buffer_add_int (buf, MINOR_VERSION);
6878 g_free (build_info);
6882 case CMD_VM_SET_PROTOCOL_VERSION: {
6883 major_version = decode_int (p, &p, end);
6884 minor_version = decode_int (p, &p, end);
6885 protocol_version_set = TRUE;
6886 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6889 case CMD_VM_ALL_THREADS: {
6891 mono_loader_lock ();
6892 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6893 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6894 mono_loader_unlock ();
6897 case CMD_VM_SUSPEND:
6899 wait_for_suspend ();
6902 if (suspend_count == 0)
6903 return ERR_NOT_SUSPENDED;
6905 clear_suspended_objs ();
6907 case CMD_VM_DISPOSE:
6908 /* Clear all event requests */
6909 mono_loader_lock ();
6910 while (event_requests->len > 0) {
6911 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6913 clear_event_request (req->id, req->event_kind);
6915 mono_loader_unlock ();
6917 while (suspend_count > 0)
6919 disconnected = TRUE;
6920 vm_start_event_sent = FALSE;
6923 MonoInternalThread *thread;
6924 DebuggerTlsData *tls;
6925 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6926 MonoClass *env_class;
6928 MonoMethod *exit_method = NULL;
6932 exit_code = decode_int (p, &p, end);
6934 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6936 /* Have to send a reply before exiting */
6937 send_reply_packet (id, 0, buf);
6939 /* Clear all event requests */
6940 mono_loader_lock ();
6941 while (event_requests->len > 0) {
6942 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6944 clear_event_request (req->id, req->event_kind);
6946 mono_loader_unlock ();
6949 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6950 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6951 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6952 * better than doing the shutdown ourselves, since it avoids various races.
6956 wait_for_suspend ();
6958 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6959 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
6961 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6964 mono_loader_lock ();
6965 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6966 mono_loader_unlock ();
6968 if (thread && exit_method) {
6969 mono_loader_lock ();
6970 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6971 mono_loader_unlock ();
6973 args = g_new0 (gpointer, 1);
6974 args [0] = g_malloc (sizeof (int));
6975 *(int*)(args [0]) = exit_code;
6977 tls->pending_invoke = g_new0 (InvokeData, 1);
6978 tls->pending_invoke->method = exit_method;
6979 tls->pending_invoke->args = args;
6980 tls->pending_invoke->nmethods = 1;
6982 while (suspend_count > 0)
6986 * No thread found, do it ourselves.
6987 * FIXME: This can race with normal shutdown etc.
6989 while (suspend_count > 0)
6992 if (!mono_runtime_try_shutdown ())
6995 mono_environment_exitcode_set (exit_code);
6997 /* Suspend all managed threads since the runtime is going away */
6998 DEBUG_PRINTF (1, "Suspending all threads...\n");
6999 mono_thread_suspend_all_other_threads ();
7000 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7001 mono_runtime_quit ();
7002 transport_close2 ();
7003 DEBUG_PRINTF (1, "Exiting...\n");
7009 case CMD_VM_INVOKE_METHOD:
7010 case CMD_VM_INVOKE_METHODS: {
7011 int objid = decode_objid (p, &p, end);
7013 DebuggerTlsData *tls;
7014 int i, count, flags, nmethods;
7017 err = get_object (objid, (MonoObject**)&thread);
7018 if (err != ERR_NONE)
7021 flags = decode_int (p, &p, end);
7023 if (command == CMD_VM_INVOKE_METHODS)
7024 nmethods = decode_int (p, &p, end);
7028 // Wait for suspending if it already started
7030 wait_for_suspend ();
7031 if (!is_suspended ())
7032 return ERR_NOT_SUSPENDED;
7034 mono_loader_lock ();
7035 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7036 mono_loader_unlock ();
7039 if (!tls->really_suspended)
7040 /* The thread is still running native code, can't do invokes */
7041 return ERR_NOT_SUSPENDED;
7044 * Store the invoke data into tls, the thread will execute it after it is
7047 if (tls->pending_invoke)
7048 return ERR_NOT_SUSPENDED;
7049 tls->pending_invoke = g_new0 (InvokeData, 1);
7050 tls->pending_invoke->id = id;
7051 tls->pending_invoke->flags = flags;
7052 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7053 memcpy (tls->pending_invoke->p, p, end - p);
7054 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7055 tls->pending_invoke->suspend_count = suspend_count;
7056 tls->pending_invoke->nmethods = nmethods;
7058 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7059 resume_thread (THREAD_TO_INTERNAL (thread));
7062 count = suspend_count;
7063 for (i = 0; i < count; ++i)
7068 case CMD_VM_ABORT_INVOKE: {
7069 int objid = decode_objid (p, &p, end);
7071 DebuggerTlsData *tls;
7075 err = get_object (objid, (MonoObject**)&thread);
7076 if (err != ERR_NONE)
7079 invoke_id = decode_int (p, &p, end);
7081 mono_loader_lock ();
7082 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7085 if (tls->abort_requested) {
7086 DEBUG_PRINTF (1, "Abort already requested.\n");
7087 mono_loader_unlock ();
7092 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7093 * actually the correct invocation.
7095 * Careful, we do not stop the thread that's doing the invocation, so we can't
7096 * inspect its stack. However, invoke_method() also acquires the loader lock
7097 * when it's done, so we're safe here.
7101 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7102 mono_loader_unlock ();
7103 return ERR_NO_INVOCATION;
7106 tls->abort_requested = TRUE;
7108 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7109 mono_loader_unlock ();
7113 case CMD_VM_SET_KEEPALIVE: {
7114 int timeout = decode_int (p, &p, end);
7115 agent_config.keepalive = timeout;
7117 #ifndef DISABLE_SOCKET_TRANSPORT
7124 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7125 GHashTableIter iter, kiter;
7130 char *fname, *basename;
7131 gboolean ignore_case;
7132 GSList *class_list, *l;
7133 GPtrArray *res_classes, *res_domains;
7135 fname = decode_string (p, &p, end);
7136 ignore_case = decode_byte (p, &p, end);
7138 basename = dbg_path_get_basename (fname);
7140 res_classes = g_ptr_array_new ();
7141 res_domains = g_ptr_array_new ();
7143 mono_loader_lock ();
7144 g_hash_table_iter_init (&iter, domains);
7145 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7146 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7148 /* Update 'source_file_to_class' cache */
7149 g_hash_table_iter_init (&kiter, info->loaded_classes);
7150 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7151 if (!g_hash_table_lookup (info->source_files, klass)) {
7152 files = get_source_files_for_type (klass);
7153 g_hash_table_insert (info->source_files, klass, files);
7155 for (i = 0; i < files->len; ++i) {
7156 char *s = (char *)g_ptr_array_index (files, i);
7157 char *s2 = dbg_path_get_basename (s);
7160 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7162 class_list = g_slist_prepend (class_list, klass);
7163 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7165 class_list = g_slist_prepend (class_list, klass);
7166 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7169 /* The _ignorecase hash contains the lowercase path */
7170 s3 = strdup_tolower (s2);
7171 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7173 class_list = g_slist_prepend (class_list, klass);
7174 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7176 class_list = g_slist_prepend (class_list, klass);
7177 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7189 s = strdup_tolower (basename);
7190 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7193 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7196 for (l = class_list; l; l = l->next) {
7197 klass = (MonoClass *)l->data;
7199 g_ptr_array_add (res_classes, klass);
7200 g_ptr_array_add (res_domains, domain);
7203 mono_loader_unlock ();
7208 buffer_add_int (buf, res_classes->len);
7209 for (i = 0; i < res_classes->len; ++i)
7210 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7211 g_ptr_array_free (res_classes, TRUE);
7212 g_ptr_array_free (res_domains, TRUE);
7215 case CMD_VM_GET_TYPES: {
7216 GHashTableIter iter;
7220 gboolean ignore_case;
7221 GPtrArray *res_classes, *res_domains;
7222 MonoTypeNameParse info;
7224 name = decode_string (p, &p, end);
7225 ignore_case = decode_byte (p, &p, end);
7227 if (!mono_reflection_parse_type (name, &info)) {
7229 mono_reflection_free_type_info (&info);
7230 return ERR_INVALID_ARGUMENT;
7233 res_classes = g_ptr_array_new ();
7234 res_domains = g_ptr_array_new ();
7236 mono_loader_lock ();
7237 g_hash_table_iter_init (&iter, domains);
7238 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7240 gboolean type_resolve;
7244 mono_domain_assemblies_lock (domain);
7245 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7246 ass = (MonoAssembly *)tmp->data;
7250 type_resolve = TRUE;
7251 /* FIXME really okay to call while holding locks? */
7252 t = mono_reflection_get_type_checked (ass->image, &info, ignore_case, &type_resolve, &error);
7253 mono_error_cleanup (&error);
7255 g_ptr_array_add (res_classes, mono_type_get_class (t));
7256 g_ptr_array_add (res_domains, domain);
7260 mono_domain_assemblies_unlock (domain);
7262 mono_loader_unlock ();
7265 mono_reflection_free_type_info (&info);
7267 buffer_add_int (buf, res_classes->len);
7268 for (i = 0; i < res_classes->len; ++i)
7269 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7270 g_ptr_array_free (res_classes, TRUE);
7271 g_ptr_array_free (res_domains, TRUE);
7274 case CMD_VM_START_BUFFERING:
7275 case CMD_VM_STOP_BUFFERING:
7276 /* Handled in the main loop */
7279 return ERR_NOT_IMPLEMENTED;
7286 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7292 case CMD_EVENT_REQUEST_SET: {
7294 int i, event_kind, suspend_policy, nmodifiers;
7298 MonoThread *step_thread;
7299 int step_thread_id = 0;
7300 StepDepth depth = STEP_DEPTH_INTO;
7301 StepSize size = STEP_SIZE_MIN;
7302 StepFilter filter = STEP_FILTER_NONE;
7306 event_kind = decode_byte (p, &p, end);
7307 suspend_policy = decode_byte (p, &p, end);
7308 nmodifiers = decode_byte (p, &p, end);
7310 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7311 req->id = InterlockedIncrement (&event_request_id);
7312 req->event_kind = event_kind;
7313 req->suspend_policy = suspend_policy;
7314 req->nmodifiers = nmodifiers;
7317 for (i = 0; i < nmodifiers; ++i) {
7318 mod = (ModifierKind)decode_byte (p, &p, end);
7320 req->modifiers [i].kind = mod;
7321 if (mod == MOD_KIND_COUNT) {
7322 req->modifiers [i].data.count = decode_int (p, &p, end);
7323 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7324 method = decode_methodid (p, &p, end, &domain, &err);
7325 if (err != ERR_NONE)
7327 location = decode_long (p, &p, end);
7328 } else if (mod == MOD_KIND_STEP) {
7329 step_thread_id = decode_id (p, &p, end);
7330 size = (StepSize)decode_int (p, &p, end);
7331 depth = (StepDepth)decode_int (p, &p, end);
7332 if (CHECK_PROTOCOL_VERSION (2, 16))
7333 filter = (StepFilter)decode_int (p, &p, end);
7334 req->modifiers [i].data.filter = filter;
7335 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7336 /* Treat STEP_THOUGH the same as HIDDEN */
7337 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7338 } else if (mod == MOD_KIND_THREAD_ONLY) {
7339 int id = decode_id (p, &p, end);
7341 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7342 if (err != ERR_NONE) {
7346 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7347 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7349 if (err != ERR_NONE)
7351 req->modifiers [i].caught = decode_byte (p, &p, end);
7352 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7353 if (CHECK_PROTOCOL_VERSION (2, 25))
7354 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7356 req->modifiers [i].subclasses = TRUE;
7357 DEBUG_PRINTF (1, "[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" : "");
7359 req->modifiers [i].data.exc_class = exc_class;
7361 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7363 return ERR_INVALID_ARGUMENT;
7366 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7367 int n = decode_int (p, &p, end);
7370 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7371 for (j = 0; j < n; ++j) {
7372 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7373 if (err != ERR_NONE) {
7374 g_free (req->modifiers [i].data.assemblies);
7378 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7379 int n = decode_int (p, &p, end);
7382 modifier = &req->modifiers [i];
7383 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7384 for (j = 0; j < n; ++j) {
7385 char *s = decode_string (p, &p, end);
7389 s2 = strdup_tolower (s);
7390 g_hash_table_insert (modifier->data.source_files, s2, s2);
7394 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7395 int n = decode_int (p, &p, end);
7398 modifier = &req->modifiers [i];
7399 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7400 for (j = 0; j < n; ++j) {
7401 char *s = decode_string (p, &p, end);
7404 g_hash_table_insert (modifier->data.type_names, s, s);
7408 return ERR_NOT_IMPLEMENTED;
7412 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7415 req->info = set_breakpoint (method, location, req, &error);
7416 if (!mono_error_ok (&error)) {
7418 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7419 mono_error_cleanup (&error);
7420 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7422 } else if (req->event_kind == EVENT_KIND_STEP) {
7423 g_assert (step_thread_id);
7425 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7426 if (err != ERR_NONE) {
7431 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7432 if (err != ERR_NONE) {
7436 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7437 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7438 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7439 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7440 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7441 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7443 if (req->nmodifiers) {
7445 return ERR_NOT_IMPLEMENTED;
7449 mono_loader_lock ();
7450 g_ptr_array_add (event_requests, req);
7452 if (agent_config.defer) {
7453 /* Transmit cached data to the client on receipt of the event request */
7454 switch (req->event_kind) {
7455 case EVENT_KIND_APPDOMAIN_CREATE:
7456 /* Emit load events for currently loaded domains */
7457 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7459 case EVENT_KIND_ASSEMBLY_LOAD:
7460 /* Emit load events for currently loaded assemblies */
7461 mono_assembly_foreach (emit_assembly_load, NULL);
7463 case EVENT_KIND_THREAD_START:
7464 /* Emit start events for currently started threads */
7465 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7467 case EVENT_KIND_TYPE_LOAD:
7468 /* Emit type load events for currently loaded types */
7469 mono_domain_foreach (send_types_for_domain, NULL);
7475 mono_loader_unlock ();
7477 buffer_add_int (buf, req->id);
7480 case CMD_EVENT_REQUEST_CLEAR: {
7481 int etype = decode_byte (p, &p, end);
7482 int req_id = decode_int (p, &p, end);
7484 // FIXME: Make a faster mapping from req_id to request
7485 mono_loader_lock ();
7486 clear_event_request (req_id, etype);
7487 mono_loader_unlock ();
7490 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7493 mono_loader_lock ();
7495 while (i < event_requests->len) {
7496 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7498 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7499 clear_breakpoint ((MonoBreakpoint *)req->info);
7501 g_ptr_array_remove_index_fast (event_requests, i);
7507 mono_loader_unlock ();
7511 return ERR_NOT_IMPLEMENTED;
7518 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7524 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7525 buffer_add_domainid (buf, mono_get_root_domain ());
7528 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7529 domain = decode_domainid (p, &p, end, NULL, &err);
7530 if (err != ERR_NONE)
7532 buffer_add_string (buf, domain->friendly_name);
7535 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7540 domain = decode_domainid (p, &p, end, NULL, &err);
7541 if (err != ERR_NONE)
7543 mono_loader_lock ();
7545 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7548 buffer_add_int (buf, count);
7549 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7550 ass = (MonoAssembly *)tmp->data;
7551 buffer_add_assemblyid (buf, domain, ass);
7553 mono_loader_unlock ();
7556 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7557 domain = decode_domainid (p, &p, end, NULL, &err);
7558 if (err != ERR_NONE)
7561 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7564 case CMD_APPDOMAIN_GET_CORLIB: {
7565 domain = decode_domainid (p, &p, end, NULL, &err);
7566 if (err != ERR_NONE)
7569 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7572 case CMD_APPDOMAIN_CREATE_STRING: {
7576 domain = decode_domainid (p, &p, end, NULL, &err);
7577 if (err != ERR_NONE)
7579 s = decode_string (p, &p, end);
7581 o = mono_string_new (domain, s);
7582 buffer_add_objid (buf, (MonoObject*)o);
7585 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7588 MonoDomain *domain2;
7591 domain = decode_domainid (p, &p, end, NULL, &err);
7592 if (err != ERR_NONE)
7594 klass = decode_typeid (p, &p, end, &domain2, &err);
7595 if (err != ERR_NONE)
7599 g_assert (domain == domain2);
7601 o = mono_object_new_checked (domain, klass, &error);
7602 mono_error_assert_ok (&error);
7604 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7605 if (err != ERR_NONE)
7608 buffer_add_objid (buf, o);
7612 return ERR_NOT_IMPLEMENTED;
7619 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7625 ass = decode_assemblyid (p, &p, end, &domain, &err);
7626 if (err != ERR_NONE)
7630 case CMD_ASSEMBLY_GET_LOCATION: {
7631 buffer_add_string (buf, mono_image_get_filename (ass->image));
7634 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7638 if (ass->image->dynamic) {
7639 buffer_add_id (buf, 0);
7641 token = mono_image_get_entry_point (ass->image);
7643 buffer_add_id (buf, 0);
7646 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
7648 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7649 buffer_add_methodid (buf, domain, m);
7654 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7655 buffer_add_moduleid (buf, domain, ass->image);
7658 case CMD_ASSEMBLY_GET_OBJECT: {
7660 MonoObject *o = (MonoObject*)mono_assembly_get_object_checked (domain, ass, &error);
7662 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7663 return ERR_INVALID_OBJECT;
7665 buffer_add_objid (buf, o);
7668 case CMD_ASSEMBLY_GET_TYPE: {
7670 char *s = decode_string (p, &p, end);
7671 gboolean ignorecase = decode_byte (p, &p, end);
7672 MonoTypeNameParse info;
7674 gboolean type_resolve, res;
7675 MonoDomain *d = mono_domain_get ();
7677 /* This is needed to be able to find referenced assemblies */
7678 res = mono_domain_set (domain, FALSE);
7681 if (!mono_reflection_parse_type (s, &info)) {
7684 if (info.assembly.name)
7686 t = mono_reflection_get_type_checked (ass->image, &info, ignorecase, &type_resolve, &error);
7687 if (!is_ok (&error)) {
7688 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7689 mono_reflection_free_type_info (&info);
7691 return ERR_INVALID_ARGUMENT;
7694 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7695 mono_reflection_free_type_info (&info);
7698 mono_domain_set (d, TRUE);
7702 case CMD_ASSEMBLY_GET_NAME: {
7704 MonoAssembly *mass = ass;
7706 name = g_strdup_printf (
7707 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7709 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7710 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7711 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7712 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7714 buffer_add_string (buf, name);
7719 return ERR_NOT_IMPLEMENTED;
7726 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7732 case CMD_MODULE_GET_INFO: {
7733 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7736 basename = g_path_get_basename (image->name);
7737 buffer_add_string (buf, basename); // name
7738 buffer_add_string (buf, image->module_name); // scopename
7739 buffer_add_string (buf, image->name); // fqname
7740 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7741 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7746 return ERR_NOT_IMPLEMENTED;
7753 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7759 case CMD_FIELD_GET_INFO: {
7760 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7762 buffer_add_string (buf, f->name);
7763 buffer_add_typeid (buf, domain, f->parent);
7764 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7765 buffer_add_int (buf, f->type->attrs);
7769 return ERR_NOT_IMPLEMENTED;
7776 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7778 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7779 /* Special case these so the client doesn't have to handle Type objects */
7781 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7782 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7783 } else if (MONO_TYPE_IS_REFERENCE (t))
7784 buffer_add_value (buf, t, &val, domain);
7786 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7790 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7796 buffer_add_int (buf, 0);
7800 for (i = 0; i < cinfo->num_attrs; ++i) {
7801 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7804 buffer_add_int (buf, nattrs);
7806 for (i = 0; i < cinfo->num_attrs; ++i) {
7807 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7808 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7809 MonoArray *typed_args, *named_args;
7811 CattrNamedArg *arginfo = NULL;
7814 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7815 if (!mono_error_ok (&error)) {
7816 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7817 mono_error_cleanup (&error);
7818 return ERR_LOADER_ERROR;
7821 buffer_add_methodid (buf, domain, attr->ctor);
7825 buffer_add_int (buf, mono_array_length (typed_args));
7826 for (j = 0; j < mono_array_length (typed_args); ++j) {
7827 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7829 t = mono_method_signature (attr->ctor)->params [j];
7831 buffer_add_cattr_arg (buf, t, domain, val);
7834 buffer_add_int (buf, 0);
7839 buffer_add_int (buf, mono_array_length (named_args));
7841 for (j = 0; j < mono_array_length (named_args); ++j) {
7842 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7844 if (arginfo [j].prop) {
7845 buffer_add_byte (buf, 0x54);
7846 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7847 } else if (arginfo [j].field) {
7848 buffer_add_byte (buf, 0x53);
7849 buffer_add_fieldid (buf, domain, arginfo [j].field);
7851 g_assert_not_reached ();
7854 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7857 buffer_add_int (buf, 0);
7866 /* FIXME: Code duplication with icall.c */
7868 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7873 mono_class_setup_interfaces (klass, error);
7874 if (!mono_error_ok (error))
7877 for (i = 0; i < klass->interface_count; i++) {
7878 ic = klass->interfaces [i];
7879 g_hash_table_insert (ifaces, ic, ic);
7881 collect_interfaces (ic, ifaces, error);
7882 if (!mono_error_ok (error))
7888 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7900 case CMD_TYPE_GET_INFO: {
7901 buffer_add_string (buf, klass->name_space);
7902 buffer_add_string (buf, klass->name);
7904 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7905 buffer_add_string (buf, name);
7907 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7908 buffer_add_moduleid (buf, domain, klass->image);
7909 buffer_add_typeid (buf, domain, klass->parent);
7910 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7911 buffer_add_typeid (buf, domain, klass->element_class);
7913 buffer_add_id (buf, 0);
7914 buffer_add_int (buf, klass->type_token);
7915 buffer_add_byte (buf, klass->rank);
7916 buffer_add_int (buf, klass->flags);
7918 type = &klass->byval_arg;
7919 // FIXME: Can't decide whenever a class represents a byref type
7922 if (type->type == MONO_TYPE_PTR)
7924 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7926 if (type->type == MONO_TYPE_VALUETYPE)
7928 if (klass->enumtype)
7930 if (klass->generic_container)
7932 if (klass->generic_container || klass->generic_class)
7934 buffer_add_byte (buf, b);
7937 while ((nested = mono_class_get_nested_types (klass, &iter)))
7939 buffer_add_int (buf, nnested);
7941 while ((nested = mono_class_get_nested_types (klass, &iter)))
7942 buffer_add_typeid (buf, domain, nested);
7943 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7944 if (klass->generic_container)
7945 buffer_add_typeid (buf, domain, klass);
7946 else if (klass->generic_class)
7947 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7949 buffer_add_id (buf, 0);
7951 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7954 if (klass->generic_class) {
7955 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7957 count = inst->type_argc;
7958 buffer_add_int (buf, count);
7959 for (i = 0; i < count; i++)
7960 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7961 } else if (klass->generic_container) {
7962 MonoGenericContainer *container = klass->generic_container;
7965 count = container->type_argc;
7966 buffer_add_int (buf, count);
7967 for (i = 0; i < count; i++) {
7968 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
7969 buffer_add_typeid (buf, domain, pklass);
7972 buffer_add_int (buf, 0);
7977 case CMD_TYPE_GET_METHODS: {
7980 gpointer iter = NULL;
7983 mono_class_setup_methods (klass);
7985 nmethods = mono_class_num_methods (klass);
7987 buffer_add_int (buf, nmethods);
7989 while ((m = mono_class_get_methods (klass, &iter))) {
7990 buffer_add_methodid (buf, domain, m);
7993 g_assert (i == nmethods);
7996 case CMD_TYPE_GET_FIELDS: {
7999 gpointer iter = NULL;
8002 nfields = mono_class_num_fields (klass);
8004 buffer_add_int (buf, nfields);
8006 while ((f = mono_class_get_fields (klass, &iter))) {
8007 buffer_add_fieldid (buf, domain, f);
8008 buffer_add_string (buf, f->name);
8009 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8010 buffer_add_int (buf, f->type->attrs);
8013 g_assert (i == nfields);
8016 case CMD_TYPE_GET_PROPERTIES: {
8019 gpointer iter = NULL;
8022 nprops = mono_class_num_properties (klass);
8024 buffer_add_int (buf, nprops);
8026 while ((p = mono_class_get_properties (klass, &iter))) {
8027 buffer_add_propertyid (buf, domain, p);
8028 buffer_add_string (buf, p->name);
8029 buffer_add_methodid (buf, domain, p->get);
8030 buffer_add_methodid (buf, domain, p->set);
8031 buffer_add_int (buf, p->attrs);
8034 g_assert (i == nprops);
8037 case CMD_TYPE_GET_CATTRS: {
8038 MonoClass *attr_klass;
8039 MonoCustomAttrInfo *cinfo;
8041 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8042 /* attr_klass can be NULL */
8043 if (err != ERR_NONE)
8046 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8047 if (!is_ok (&error)) {
8048 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8049 return ERR_LOADER_ERROR;
8052 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8053 if (err != ERR_NONE)
8057 case CMD_TYPE_GET_FIELD_CATTRS: {
8058 MonoClass *attr_klass;
8059 MonoCustomAttrInfo *cinfo;
8060 MonoClassField *field;
8062 field = decode_fieldid (p, &p, end, NULL, &err);
8063 if (err != ERR_NONE)
8065 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8066 if (err != ERR_NONE)
8069 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8070 if (!is_ok (&error)) {
8071 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8072 return ERR_LOADER_ERROR;
8075 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8076 if (err != ERR_NONE)
8080 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8081 MonoClass *attr_klass;
8082 MonoCustomAttrInfo *cinfo;
8085 prop = decode_propertyid (p, &p, end, NULL, &err);
8086 if (err != ERR_NONE)
8088 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8089 if (err != ERR_NONE)
8092 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8093 if (!is_ok (&error)) {
8094 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8095 return ERR_LOADER_ERROR;
8098 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8099 if (err != ERR_NONE)
8103 case CMD_TYPE_GET_VALUES:
8104 case CMD_TYPE_GET_VALUES_2: {
8111 MonoThread *thread_obj;
8112 MonoInternalThread *thread = NULL;
8113 guint32 special_static_type;
8115 if (command == CMD_TYPE_GET_VALUES_2) {
8116 int objid = decode_objid (p, &p, end);
8119 err = get_object (objid, (MonoObject**)&thread_obj);
8120 if (err != ERR_NONE)
8123 thread = THREAD_TO_INTERNAL (thread_obj);
8126 len = decode_int (p, &p, end);
8127 for (i = 0; i < len; ++i) {
8128 f = decode_fieldid (p, &p, end, NULL, &err);
8129 if (err != ERR_NONE)
8132 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8133 return ERR_INVALID_FIELDID;
8134 special_static_type = mono_class_field_get_special_static_type (f);
8135 if (special_static_type != SPECIAL_STATIC_NONE) {
8136 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8137 return ERR_INVALID_FIELDID;
8140 /* Check that the field belongs to the object */
8142 for (k = klass; k; k = k->parent) {
8143 if (k == f->parent) {
8149 return ERR_INVALID_FIELDID;
8151 vtable = mono_class_vtable (domain, f->parent);
8152 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8153 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8154 buffer_add_value (buf, f->type, val, domain);
8159 case CMD_TYPE_SET_VALUES: {
8167 len = decode_int (p, &p, end);
8168 for (i = 0; i < len; ++i) {
8169 f = decode_fieldid (p, &p, end, NULL, &err);
8170 if (err != ERR_NONE)
8173 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8174 return ERR_INVALID_FIELDID;
8175 if (mono_class_field_is_special_static (f))
8176 return ERR_INVALID_FIELDID;
8178 /* Check that the field belongs to the object */
8180 for (k = klass; k; k = k->parent) {
8181 if (k == f->parent) {
8187 return ERR_INVALID_FIELDID;
8189 // FIXME: Check for literal/const
8191 vtable = mono_class_vtable (domain, f->parent);
8192 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8193 err = decode_value (f->type, domain, val, p, &p, end);
8194 if (err != ERR_NONE) {
8198 if (MONO_TYPE_IS_REFERENCE (f->type))
8199 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8201 mono_field_static_set_value (vtable, f, val);
8206 case CMD_TYPE_GET_OBJECT: {
8207 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8208 if (!mono_error_ok (&error)) {
8209 mono_error_cleanup (&error);
8210 return ERR_INVALID_OBJECT;
8212 buffer_add_objid (buf, o);
8215 case CMD_TYPE_GET_SOURCE_FILES:
8216 case CMD_TYPE_GET_SOURCE_FILES_2: {
8217 char *source_file, *base;
8221 files = get_source_files_for_type (klass);
8223 buffer_add_int (buf, files->len);
8224 for (i = 0; i < files->len; ++i) {
8225 source_file = (char *)g_ptr_array_index (files, i);
8226 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8227 buffer_add_string (buf, source_file);
8229 base = dbg_path_get_basename (source_file);
8230 buffer_add_string (buf, base);
8233 g_free (source_file);
8235 g_ptr_array_free (files, TRUE);
8238 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8239 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8241 if (err != ERR_NONE)
8243 if (mono_class_is_assignable_from (klass, oklass))
8244 buffer_add_byte (buf, 1);
8246 buffer_add_byte (buf, 0);
8249 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8250 char *name = decode_string (p, &p, end);
8251 int i, flags = decode_int (p, &p, end);
8252 MonoException *ex = NULL;
8253 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8256 return ERR_LOADER_ERROR;
8257 buffer_add_int (buf, array->len);
8258 for (i = 0; i < array->len; ++i) {
8259 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8260 buffer_add_methodid (buf, domain, method);
8263 g_ptr_array_free (array, TRUE);
8267 case CMD_TYPE_GET_INTERFACES: {
8269 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8270 MonoClass *tclass, *iface;
8271 GHashTableIter iter;
8275 for (parent = tclass; parent; parent = parent->parent) {
8276 mono_class_setup_interfaces (parent, &error);
8277 if (!mono_error_ok (&error))
8278 return ERR_LOADER_ERROR;
8279 collect_interfaces (parent, iface_hash, &error);
8280 if (!mono_error_ok (&error))
8281 return ERR_LOADER_ERROR;
8284 buffer_add_int (buf, g_hash_table_size (iface_hash));
8286 g_hash_table_iter_init (&iter, iface_hash);
8287 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8288 buffer_add_typeid (buf, domain, iface);
8289 g_hash_table_destroy (iface_hash);
8292 case CMD_TYPE_GET_INTERFACE_MAP: {
8293 int tindex, ioffset;
8294 gboolean variance_used;
8296 int len, nmethods, i;
8300 len = decode_int (p, &p, end);
8301 mono_class_setup_vtable (klass);
8303 for (tindex = 0; tindex < len; ++tindex) {
8304 iclass = decode_typeid (p, &p, end, NULL, &err);
8305 if (err != ERR_NONE)
8308 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8310 return ERR_INVALID_ARGUMENT;
8312 nmethods = mono_class_num_methods (iclass);
8313 buffer_add_int (buf, nmethods);
8316 while ((method = mono_class_get_methods (iclass, &iter))) {
8317 buffer_add_methodid (buf, domain, method);
8319 for (i = 0; i < nmethods; ++i)
8320 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8324 case CMD_TYPE_IS_INITIALIZED: {
8325 MonoVTable *vtable = mono_class_vtable (domain, klass);
8328 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8330 buffer_add_int (buf, 0);
8333 case CMD_TYPE_CREATE_INSTANCE: {
8337 obj = mono_object_new_checked (domain, klass, &error);
8338 mono_error_assert_ok (&error);
8339 buffer_add_objid (buf, obj);
8343 return ERR_NOT_IMPLEMENTED;
8350 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8353 MonoDomain *old_domain;
8357 klass = decode_typeid (p, &p, end, &domain, &err);
8358 if (err != ERR_NONE)
8361 old_domain = mono_domain_get ();
8363 mono_domain_set (domain, TRUE);
8365 err = type_commands_internal (command, klass, domain, p, end, buf);
8367 mono_domain_set (old_domain, TRUE);
8373 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8375 MonoMethodHeader *header;
8379 case CMD_METHOD_GET_NAME: {
8380 buffer_add_string (buf, method->name);
8383 case CMD_METHOD_GET_DECLARING_TYPE: {
8384 buffer_add_typeid (buf, domain, method->klass);
8387 case CMD_METHOD_GET_DEBUG_INFO: {
8389 MonoDebugMethodInfo *minfo;
8391 int i, j, n_il_offsets;
8393 GPtrArray *source_file_list;
8394 MonoSymSeqPoint *sym_seq_points;
8396 header = mono_method_get_header_checked (method, &error);
8398 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8399 buffer_add_int (buf, 0);
8400 buffer_add_string (buf, "");
8401 buffer_add_int (buf, 0);
8405 minfo = mono_debug_lookup_method (method);
8407 buffer_add_int (buf, header->code_size);
8408 buffer_add_string (buf, "");
8409 buffer_add_int (buf, 0);
8410 mono_metadata_free_mh (header);
8414 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8415 buffer_add_int (buf, header->code_size);
8416 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8417 buffer_add_int (buf, source_file_list->len);
8418 for (i = 0; i < source_file_list->len; ++i) {
8419 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8420 buffer_add_string (buf, sinfo->source_file);
8421 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8422 for (j = 0; j < 16; ++j)
8423 buffer_add_byte (buf, sinfo->hash [j]);
8427 buffer_add_string (buf, source_file);
8429 buffer_add_int (buf, n_il_offsets);
8430 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8431 for (i = 0; i < n_il_offsets; ++i) {
8432 MonoSymSeqPoint *sp = &sym_seq_points [i];
8433 const char *srcfile = "";
8435 if (source_files [i] != -1) {
8436 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8437 srcfile = sinfo->source_file;
8439 DEBUG_PRINTF (10, "IL%x -> %s:%d %d %d %d\n", sp->il_offset, srcfile, sp->line, sp->column, sp->end_line, sp->end_column);
8440 buffer_add_int (buf, sp->il_offset);
8441 buffer_add_int (buf, sp->line);
8442 if (CHECK_PROTOCOL_VERSION (2, 13))
8443 buffer_add_int (buf, source_files [i]);
8444 if (CHECK_PROTOCOL_VERSION (2, 19))
8445 buffer_add_int (buf, sp->column);
8446 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8447 buffer_add_int (buf, sp->end_line);
8448 buffer_add_int (buf, sp->end_column);
8451 g_free (source_file);
8452 g_free (source_files);
8453 g_free (sym_seq_points);
8454 g_ptr_array_free (source_file_list, TRUE);
8455 mono_metadata_free_mh (header);
8458 case CMD_METHOD_GET_PARAM_INFO: {
8459 MonoMethodSignature *sig = mono_method_signature (method);
8463 /* FIXME: mono_class_from_mono_type () and byrefs */
8465 /* FIXME: Use a smaller encoding */
8466 buffer_add_int (buf, sig->call_convention);
8467 buffer_add_int (buf, sig->param_count);
8468 buffer_add_int (buf, sig->generic_param_count);
8469 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8470 for (i = 0; i < sig->param_count; ++i) {
8472 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8475 /* Emit parameter names */
8476 names = g_new (char *, sig->param_count);
8477 mono_method_get_param_names (method, (const char **) names);
8478 for (i = 0; i < sig->param_count; ++i)
8479 buffer_add_string (buf, names [i]);
8484 case CMD_METHOD_GET_LOCALS_INFO: {
8487 MonoDebugLocalsInfo *locals;
8488 int *locals_map = NULL;
8490 header = mono_method_get_header_checked (method, &error);
8492 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8493 return ERR_INVALID_ARGUMENT;
8496 locals = mono_debug_lookup_locals (method);
8498 buffer_add_int (buf, header->num_locals);
8500 for (i = 0; i < header->num_locals; ++i) {
8501 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8504 for (i = 0; i < header->num_locals; ++i) {
8506 sprintf (lname, "V_%d", i);
8507 buffer_add_string (buf, lname);
8510 for (i = 0; i < header->num_locals; ++i) {
8511 buffer_add_int (buf, 0);
8512 buffer_add_int (buf, header->code_size);
8515 num_locals = locals->num_locals;
8516 buffer_add_int (buf, num_locals);
8519 for (i = 0; i < num_locals; ++i) {
8520 g_assert (locals->locals [i].index < header->num_locals);
8521 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8524 for (i = 0; i < num_locals; ++i)
8525 buffer_add_string (buf, locals->locals [i].name);
8527 for (i = 0; i < num_locals; ++i) {
8528 if (locals->locals [i].block) {
8529 buffer_add_int (buf, locals->locals [i].block->start_offset);
8530 buffer_add_int (buf, locals->locals [i].block->end_offset);
8532 buffer_add_int (buf, 0);
8533 buffer_add_int (buf, header->code_size);
8537 mono_metadata_free_mh (header);
8540 mono_debug_free_locals (locals);
8541 g_free (locals_map);
8545 case CMD_METHOD_GET_INFO:
8546 buffer_add_int (buf, method->flags);
8547 buffer_add_int (buf, method->iflags);
8548 buffer_add_int (buf, method->token);
8549 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8551 if (method->is_generic)
8553 if (mono_method_signature (method)->generic_param_count)
8555 buffer_add_byte (buf, attrs);
8556 if (method->is_generic || method->is_inflated) {
8559 if (method->is_generic) {
8562 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8564 result = imethod->declaring;
8565 if (imethod->context.class_inst) {
8566 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8567 /*Generic methods gets the context of the GTD.*/
8568 if (mono_class_get_context (klass)) {
8570 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8571 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8576 buffer_add_methodid (buf, domain, result);
8578 buffer_add_id (buf, 0);
8580 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8581 if (mono_method_signature (method)->generic_param_count) {
8584 if (method->is_inflated) {
8585 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8587 count = inst->type_argc;
8588 buffer_add_int (buf, count);
8590 for (i = 0; i < count; i++)
8591 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8593 buffer_add_int (buf, 0);
8595 } else if (method->is_generic) {
8596 MonoGenericContainer *container = mono_method_get_generic_container (method);
8598 count = mono_method_signature (method)->generic_param_count;
8599 buffer_add_int (buf, count);
8600 for (i = 0; i < count; i++) {
8601 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8602 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
8603 buffer_add_typeid (buf, domain, pklass);
8606 buffer_add_int (buf, 0);
8609 buffer_add_int (buf, 0);
8614 case CMD_METHOD_GET_BODY: {
8618 header = mono_method_get_header_checked (method, &error);
8620 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8621 buffer_add_int (buf, 0);
8623 if (CHECK_PROTOCOL_VERSION (2, 18))
8624 buffer_add_int (buf, 0);
8626 buffer_add_int (buf, header->code_size);
8627 for (i = 0; i < header->code_size; ++i)
8628 buffer_add_byte (buf, header->code [i]);
8630 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8631 buffer_add_int (buf, header->num_clauses);
8632 for (i = 0; i < header->num_clauses; ++i) {
8633 MonoExceptionClause *clause = &header->clauses [i];
8635 buffer_add_int (buf, clause->flags);
8636 buffer_add_int (buf, clause->try_offset);
8637 buffer_add_int (buf, clause->try_len);
8638 buffer_add_int (buf, clause->handler_offset);
8639 buffer_add_int (buf, clause->handler_len);
8640 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8641 buffer_add_typeid (buf, domain, clause->data.catch_class);
8642 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8643 buffer_add_int (buf, clause->data.filter_offset);
8647 mono_metadata_free_mh (header);
8652 case CMD_METHOD_RESOLVE_TOKEN: {
8653 guint32 token = decode_int (p, &p, end);
8656 switch (mono_metadata_token_code (token)) {
8657 case MONO_TOKEN_STRING: {
8661 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8664 s2 = mono_string_to_utf8 (s);
8666 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8667 buffer_add_string (buf, s2);
8673 MonoClass *handle_class;
8675 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8676 val = mono_method_get_wrapper_data (method, token);
8677 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8679 if (handle_class == NULL) {
8680 // Can't figure out the token type
8681 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8686 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8688 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8691 if (handle_class == mono_defaults.typehandle_class) {
8692 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8693 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8694 buffer_add_typeid (buf, domain, (MonoClass *) val);
8696 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8697 } else if (handle_class == mono_defaults.fieldhandle_class) {
8698 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8699 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8700 } else if (handle_class == mono_defaults.methodhandle_class) {
8701 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8702 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8703 } else if (handle_class == mono_defaults.string_class) {
8706 s = mono_string_to_utf8 ((MonoString *)val);
8707 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8708 buffer_add_string (buf, s);
8711 g_assert_not_reached ();
8718 case CMD_METHOD_GET_CATTRS: {
8720 MonoClass *attr_klass;
8721 MonoCustomAttrInfo *cinfo;
8723 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8724 /* attr_klass can be NULL */
8725 if (err != ERR_NONE)
8728 cinfo = mono_custom_attrs_from_method_checked (method, &error);
8729 if (!is_ok (&error)) {
8730 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8731 return ERR_LOADER_ERROR;
8734 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8735 if (err != ERR_NONE)
8739 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8741 MonoType **type_argv;
8745 MonoGenericInst *ginst;
8746 MonoGenericContext tmp_context;
8747 MonoMethod *inflated;
8749 type_argc = decode_int (p, &p, end);
8750 type_argv = g_new0 (MonoType*, type_argc);
8751 for (i = 0; i < type_argc; ++i) {
8752 klass = decode_typeid (p, &p, end, &d, &err);
8753 if (err != ERR_NONE) {
8759 return ERR_INVALID_ARGUMENT;
8761 type_argv [i] = &klass->byval_arg;
8763 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8765 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8766 tmp_context.method_inst = ginst;
8768 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8769 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8770 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8771 return ERR_INVALID_ARGUMENT;
8772 buffer_add_methodid (buf, domain, inflated);
8776 return ERR_NOT_IMPLEMENTED;
8783 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8786 MonoDomain *old_domain;
8790 method = decode_methodid (p, &p, end, &domain, &err);
8791 if (err != ERR_NONE)
8794 old_domain = mono_domain_get ();
8796 mono_domain_set (domain, TRUE);
8798 err = method_commands_internal (command, method, domain, p, end, buf);
8800 mono_domain_set (old_domain, TRUE);
8806 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8808 int objid = decode_objid (p, &p, end);
8810 MonoThread *thread_obj;
8811 MonoInternalThread *thread;
8813 err = get_object (objid, (MonoObject**)&thread_obj);
8814 if (err != ERR_NONE)
8817 thread = THREAD_TO_INTERNAL (thread_obj);
8820 case CMD_THREAD_GET_NAME: {
8822 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8825 buffer_add_int (buf, 0);
8830 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8832 buffer_add_int (buf, len);
8833 buffer_add_data (buf, (guint8*)name, len);
8838 case CMD_THREAD_GET_FRAME_INFO: {
8839 DebuggerTlsData *tls;
8840 int i, start_frame, length;
8842 // Wait for suspending if it already started
8843 // FIXME: Races with suspend_count
8844 while (!is_suspended ()) {
8846 wait_for_suspend ();
8850 wait_for_suspend ();
8851 if (!is_suspended ())
8852 return ERR_NOT_SUSPENDED;
8855 start_frame = decode_int (p, &p, end);
8856 length = decode_int (p, &p, end);
8858 if (start_frame != 0 || length != -1)
8859 return ERR_NOT_IMPLEMENTED;
8861 mono_loader_lock ();
8862 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8863 mono_loader_unlock ();
8866 compute_frame_info (thread, tls);
8868 buffer_add_int (buf, tls->frame_count);
8869 for (i = 0; i < tls->frame_count; ++i) {
8870 buffer_add_int (buf, tls->frames [i]->id);
8871 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8872 buffer_add_int (buf, tls->frames [i]->il_offset);
8874 * Instead of passing the frame type directly to the client, we associate
8875 * it with the previous frame using a set of flags. This avoids lots of
8876 * conditional code in the client, since a frame whose type isn't
8877 * FRAME_TYPE_MANAGED has no method, location, etc.
8879 buffer_add_byte (buf, tls->frames [i]->flags);
8884 case CMD_THREAD_GET_STATE:
8885 buffer_add_int (buf, thread->state);
8887 case CMD_THREAD_GET_INFO:
8888 buffer_add_byte (buf, thread->threadpool_thread);
8890 case CMD_THREAD_GET_ID:
8891 buffer_add_long (buf, (guint64)(gsize)thread);
8893 case CMD_THREAD_GET_TID:
8894 buffer_add_long (buf, (guint64)thread->tid);
8896 case CMD_THREAD_SET_IP: {
8897 DebuggerTlsData *tls;
8900 MonoSeqPointInfo *seq_points;
8905 method = decode_methodid (p, &p, end, &domain, &err);
8906 if (err != ERR_NONE)
8908 il_offset = decode_long (p, &p, end);
8910 while (!is_suspended ()) {
8912 wait_for_suspend ();
8915 mono_loader_lock ();
8916 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8917 mono_loader_unlock ();
8920 compute_frame_info (thread, tls);
8921 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8922 return ERR_INVALID_ARGUMENT;
8924 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
8926 g_assert (seq_points);
8929 return ERR_INVALID_ARGUMENT;
8931 // FIXME: Check that the ip change is safe
8933 DEBUG_PRINTF (1, "[dbg] Setting IP to %s:0x%0x(0x%0x)\n", tls->frames [0]->actual_method->name, (int)sp.il_offset, (int)sp.native_offset);
8934 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8938 return ERR_NOT_IMPLEMENTED;
8945 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8949 MonoThread *thread_obj;
8950 MonoInternalThread *thread;
8951 int pos, i, len, frame_idx;
8952 DebuggerTlsData *tls;
8954 MonoDebugMethodJitInfo *jit;
8955 MonoMethodSignature *sig;
8957 MonoMethodHeader *header;
8959 objid = decode_objid (p, &p, end);
8960 err = get_object (objid, (MonoObject**)&thread_obj);
8961 if (err != ERR_NONE)
8964 thread = THREAD_TO_INTERNAL (thread_obj);
8966 id = decode_id (p, &p, end);
8968 mono_loader_lock ();
8969 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8970 mono_loader_unlock ();
8973 for (i = 0; i < tls->frame_count; ++i) {
8974 if (tls->frames [i]->id == id)
8977 if (i == tls->frame_count)
8978 return ERR_INVALID_FRAMEID;
8981 frame = tls->frames [frame_idx];
8983 /* This is supported for frames without has_ctx etc. set */
8984 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
8985 if (CHECK_PROTOCOL_VERSION (2, 38))
8986 buffer_add_domainid (buf, frame->domain);
8990 if (!frame->has_ctx)
8991 return ERR_ABSENT_INFORMATION;
8994 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8995 if (!frame->jit && frame->api_method->is_inflated)
8996 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
9000 /* This could happen for aot images with no jit debug info */
9001 s = mono_method_full_name (frame->api_method, TRUE);
9002 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
9004 return ERR_ABSENT_INFORMATION;
9009 sig = mono_method_signature (frame->actual_method);
9011 if (!mono_get_seq_points (frame->domain, frame->actual_method))
9013 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9015 return ERR_ABSENT_INFORMATION;
9018 case CMD_STACK_FRAME_GET_VALUES: {
9020 len = decode_int (p, &p, end);
9021 header = mono_method_get_header_checked (frame->actual_method, &error);
9022 mono_error_assert_ok (&error); /* FIXME report error */
9024 for (i = 0; i < len; ++i) {
9025 pos = decode_int (p, &p, end);
9030 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9032 g_assert (pos >= 0 && pos < jit->num_params);
9034 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9036 MonoDebugLocalsInfo *locals;
9038 locals = mono_debug_lookup_locals (frame->method);
9040 g_assert (pos < locals->num_locals);
9041 pos = locals->locals [pos].index;
9042 mono_debug_free_locals (locals);
9044 g_assert (pos >= 0 && pos < jit->num_locals);
9046 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9048 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9051 mono_metadata_free_mh (header);
9054 case CMD_STACK_FRAME_GET_THIS: {
9055 if (frame->api_method->klass->valuetype) {
9056 if (!sig->hasthis) {
9057 MonoObject *p = NULL;
9058 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9060 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9063 if (!sig->hasthis) {
9064 MonoObject *p = NULL;
9065 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9067 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9072 case CMD_STACK_FRAME_SET_VALUES: {
9076 MonoDebugVarInfo *var;
9078 len = decode_int (p, &p, end);
9079 header = mono_method_get_header_checked (frame->actual_method, &error);
9080 mono_error_assert_ok (&error); /* FIXME report error */
9082 for (i = 0; i < len; ++i) {
9083 pos = decode_int (p, &p, end);
9088 g_assert (pos >= 0 && pos < jit->num_params);
9090 t = sig->params [pos];
9091 var = &jit->params [pos];
9093 MonoDebugLocalsInfo *locals;
9095 locals = mono_debug_lookup_locals (frame->method);
9097 g_assert (pos < locals->num_locals);
9098 pos = locals->locals [pos].index;
9099 mono_debug_free_locals (locals);
9101 g_assert (pos >= 0 && pos < jit->num_locals);
9103 t = header->locals [pos];
9104 var = &jit->locals [pos];
9107 if (MONO_TYPE_IS_REFERENCE (t))
9108 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9110 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9111 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9112 if (err != ERR_NONE)
9115 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9117 mono_metadata_free_mh (header);
9120 case CMD_STACK_FRAME_GET_DOMAIN: {
9121 if (CHECK_PROTOCOL_VERSION (2, 38))
9122 buffer_add_domainid (buf, frame->domain);
9126 return ERR_NOT_IMPLEMENTED;
9133 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9136 int objid, index, len, i, esize;
9140 objid = decode_objid (p, &p, end);
9141 err = get_object (objid, (MonoObject**)&arr);
9142 if (err != ERR_NONE)
9146 case CMD_ARRAY_REF_GET_LENGTH:
9147 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9149 buffer_add_int (buf, arr->max_length);
9150 buffer_add_int (buf, 0);
9152 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9153 buffer_add_int (buf, arr->bounds [i].length);
9154 buffer_add_int (buf, arr->bounds [i].lower_bound);
9158 case CMD_ARRAY_REF_GET_VALUES:
9159 index = decode_int (p, &p, end);
9160 len = decode_int (p, &p, end);
9162 g_assert (index >= 0 && len >= 0);
9163 // Reordered to avoid integer overflow
9164 g_assert (!(index > arr->max_length - len));
9166 esize = mono_array_element_size (arr->obj.vtable->klass);
9167 for (i = index; i < index + len; ++i) {
9168 elem = (gpointer*)((char*)arr->vector + (i * esize));
9169 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9172 case CMD_ARRAY_REF_SET_VALUES:
9173 index = decode_int (p, &p, end);
9174 len = decode_int (p, &p, end);
9176 g_assert (index >= 0 && len >= 0);
9177 // Reordered to avoid integer overflow
9178 g_assert (!(index > arr->max_length - len));
9180 esize = mono_array_element_size (arr->obj.vtable->klass);
9181 for (i = index; i < index + len; ++i) {
9182 elem = (gpointer*)((char*)arr->vector + (i * esize));
9184 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9188 return ERR_NOT_IMPLEMENTED;
9195 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9201 int i, index, length;
9203 gboolean use_utf16 = FALSE;
9205 objid = decode_objid (p, &p, end);
9206 err = get_object (objid, (MonoObject**)&str);
9207 if (err != ERR_NONE)
9211 case CMD_STRING_REF_GET_VALUE:
9212 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9213 for (i = 0; i < mono_string_length (str); ++i)
9214 if (mono_string_chars (str)[i] == 0)
9216 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9219 buffer_add_int (buf, mono_string_length (str) * 2);
9220 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9222 s = mono_string_to_utf8 (str);
9223 buffer_add_string (buf, s);
9227 case CMD_STRING_REF_GET_LENGTH:
9228 buffer_add_long (buf, mono_string_length (str));
9230 case CMD_STRING_REF_GET_CHARS:
9231 index = decode_long (p, &p, end);
9232 length = decode_long (p, &p, end);
9233 if (index > mono_string_length (str) - length)
9234 return ERR_INVALID_ARGUMENT;
9235 c = mono_string_chars (str) + index;
9236 for (i = 0; i < length; ++i)
9237 buffer_add_short (buf, c [i]);
9240 return ERR_NOT_IMPLEMENTED;
9247 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9257 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9258 objid = decode_objid (p, &p, end);
9259 err = get_object (objid, &obj);
9260 if (err != ERR_NONE)
9261 buffer_add_int (buf, 1);
9263 buffer_add_int (buf, 0);
9267 objid = decode_objid (p, &p, end);
9268 err = get_object (objid, &obj);
9269 if (err != ERR_NONE)
9272 MonoClass *obj_type;
9273 gboolean remote_obj = FALSE;
9275 obj_type = obj->vtable->klass;
9276 if (mono_class_is_transparent_proxy (obj_type)) {
9277 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9281 g_assert (obj_type);
9284 case CMD_OBJECT_REF_GET_TYPE:
9285 /* This handles transparent proxies too */
9286 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9288 case CMD_OBJECT_REF_GET_VALUES:
9289 len = decode_int (p, &p, end);
9291 for (i = 0; i < len; ++i) {
9292 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9293 if (err != ERR_NONE)
9296 /* Check that the field belongs to the object */
9298 for (k = obj_type; k; k = k->parent) {
9299 if (k == f->parent) {
9305 return ERR_INVALID_FIELDID;
9307 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9311 if (mono_class_field_is_special_static (f))
9312 return ERR_INVALID_FIELDID;
9314 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9315 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9316 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9317 mono_field_static_get_value (vtable, f, val);
9318 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9321 guint8 *field_value = NULL;
9322 void *field_storage = NULL;
9325 #ifndef DISABLE_REMOTING
9326 field_value = mono_load_remote_field(obj, obj_type, f, &field_storage);
9328 g_assert_not_reached ();
9331 field_value = (guint8*)obj + f->offset;
9333 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9337 case CMD_OBJECT_REF_SET_VALUES:
9338 len = decode_int (p, &p, end);
9340 for (i = 0; i < len; ++i) {
9341 f = decode_fieldid (p, &p, end, NULL, &err);
9342 if (err != ERR_NONE)
9345 /* Check that the field belongs to the object */
9347 for (k = obj_type; k; k = k->parent) {
9348 if (k == f->parent) {
9354 return ERR_INVALID_FIELDID;
9356 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9360 if (mono_class_field_is_special_static (f))
9361 return ERR_INVALID_FIELDID;
9363 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9364 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9366 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9367 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9368 if (err != ERR_NONE) {
9372 mono_field_static_set_value (vtable, f, val);
9375 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9376 if (err != ERR_NONE)
9381 case CMD_OBJECT_REF_GET_ADDRESS:
9382 buffer_add_long (buf, (gssize)obj);
9384 case CMD_OBJECT_REF_GET_DOMAIN:
9385 buffer_add_domainid (buf, obj->vtable->domain);
9387 case CMD_OBJECT_REF_GET_INFO:
9388 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9389 buffer_add_domainid (buf, obj->vtable->domain);
9392 return ERR_NOT_IMPLEMENTED;
9399 command_set_to_string (CommandSet command_set)
9401 switch (command_set) {
9404 case CMD_SET_OBJECT_REF:
9405 return "OBJECT_REF";
9406 case CMD_SET_STRING_REF:
9407 return "STRING_REF";
9408 case CMD_SET_THREAD:
9410 case CMD_SET_ARRAY_REF:
9412 case CMD_SET_EVENT_REQUEST:
9413 return "EVENT_REQUEST";
9414 case CMD_SET_STACK_FRAME:
9415 return "STACK_FRAME";
9416 case CMD_SET_APPDOMAIN:
9418 case CMD_SET_ASSEMBLY:
9420 case CMD_SET_METHOD:
9424 case CMD_SET_MODULE:
9435 static const char* vm_cmds_str [] = {
9443 "SET_PROTOCOL_VERSION",
9446 "GET_TYPES_FOR_SOURCE_FILE",
9451 static const char* thread_cmds_str[] = {
9461 static const char* event_cmds_str[] = {
9464 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9467 static const char* appdomain_cmds_str[] = {
9469 "GET_FRIENDLY_NAME",
9471 "GET_ENTRY_ASSEMBLY",
9474 "CREATE_BOXED_VALUE"
9477 static const char* assembly_cmds_str[] = {
9480 "GET_MANIFEST_MODULE",
9486 static const char* module_cmds_str[] = {
9490 static const char* field_cmds_str[] = {
9494 static const char* method_cmds_str[] = {
9496 "GET_DECLARING_TYPE",
9504 "MAKE_GENERIC_METHOD"
9507 static const char* type_cmds_str[] = {
9515 "IS_ASSIGNABLE_FROM",
9519 "GET_PROPERTY_CATTRS",
9520 "GET_SOURCE_FILES_2",
9522 "GET_METHODS_BY_NAME_FLAGS",
9524 "GET_INTERFACE_MAP",
9528 static const char* stack_frame_cmds_str[] = {
9535 static const char* array_cmds_str[] = {
9541 static const char* string_cmds_str[] = {
9547 static const char* object_cmds_str[] = {
9558 cmd_to_string (CommandSet set, int command)
9566 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9568 case CMD_SET_OBJECT_REF:
9569 cmds = object_cmds_str;
9570 cmds_len = G_N_ELEMENTS (object_cmds_str);
9572 case CMD_SET_STRING_REF:
9573 cmds = string_cmds_str;
9574 cmds_len = G_N_ELEMENTS (string_cmds_str);
9576 case CMD_SET_THREAD:
9577 cmds = thread_cmds_str;
9578 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9580 case CMD_SET_ARRAY_REF:
9581 cmds = array_cmds_str;
9582 cmds_len = G_N_ELEMENTS (array_cmds_str);
9584 case CMD_SET_EVENT_REQUEST:
9585 cmds = event_cmds_str;
9586 cmds_len = G_N_ELEMENTS (event_cmds_str);
9588 case CMD_SET_STACK_FRAME:
9589 cmds = stack_frame_cmds_str;
9590 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9592 case CMD_SET_APPDOMAIN:
9593 cmds = appdomain_cmds_str;
9594 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9596 case CMD_SET_ASSEMBLY:
9597 cmds = assembly_cmds_str;
9598 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9600 case CMD_SET_METHOD:
9601 cmds = method_cmds_str;
9602 cmds_len = G_N_ELEMENTS (method_cmds_str);
9605 cmds = type_cmds_str;
9606 cmds_len = G_N_ELEMENTS (type_cmds_str);
9608 case CMD_SET_MODULE:
9609 cmds = module_cmds_str;
9610 cmds_len = G_N_ELEMENTS (module_cmds_str);
9613 cmds = field_cmds_str;
9614 cmds_len = G_N_ELEMENTS (field_cmds_str);
9617 cmds = event_cmds_str;
9618 cmds_len = G_N_ELEMENTS (event_cmds_str);
9623 if (command > 0 && command <= cmds_len)
9624 return cmds [command - 1];
9630 wait_for_attach (void)
9632 #ifndef DISABLE_SOCKET_TRANSPORT
9633 if (listen_fd == -1) {
9634 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9638 /* Block and wait for client connection */
9639 conn_fd = socket_transport_accept (listen_fd);
9641 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9642 if (conn_fd == -1) {
9643 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9647 g_assert_not_reached ();
9651 disconnected = !transport_handshake ();
9653 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9663 * This thread handles communication with the debugger client using a JDWP
9666 static guint32 WINAPI
9667 debugger_thread (void *arg)
9669 int res, len, id, flags, command = 0;
9670 CommandSet command_set = (CommandSet)0;
9671 guint8 header [HEADER_LENGTH];
9672 guint8 *data, *p, *end;
9676 gboolean attach_failed = FALSE;
9677 gpointer attach_cookie, attach_dummy;
9679 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9681 debugger_thread_id = mono_native_thread_id_get ();
9683 attach_cookie = mono_jit_thread_attach (mono_get_root_domain (), &attach_dummy);
9685 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9687 mono_set_is_debugger_attached (TRUE);
9689 if (agent_config.defer) {
9690 if (!wait_for_attach ()) {
9691 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9692 attach_failed = TRUE; // Don't abort process when we can't listen
9694 /* Send start event to client */
9695 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9699 while (!attach_failed) {
9700 res = transport_recv (header, HEADER_LENGTH);
9702 /* This will break if the socket is closed during shutdown too */
9703 if (res != HEADER_LENGTH) {
9704 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9709 end = header + HEADER_LENGTH;
9711 len = decode_int (p, &p, end);
9712 id = decode_int (p, &p, end);
9713 flags = decode_byte (p, &p, end);
9714 command_set = (CommandSet)decode_byte (p, &p, end);
9715 command = decode_byte (p, &p, end);
9717 g_assert (flags == 0);
9720 const char *cmd_str;
9723 cmd_str = cmd_to_string (command_set, command);
9725 sprintf (cmd_num, "%d", command);
9729 DEBUG_PRINTF (1, "[dbg] Command %s(%s) [%d][at=%lx].\n", command_set_to_string (command_set), cmd_str, id, (long)mono_100ns_ticks () / 10000);
9732 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
9733 if (len - HEADER_LENGTH > 0)
9735 res = transport_recv (data, len - HEADER_LENGTH);
9736 if (res != len - HEADER_LENGTH) {
9737 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9743 end = data + (len - HEADER_LENGTH);
9745 buffer_init (&buf, 128);
9750 /* Process the request */
9751 switch (command_set) {
9753 err = vm_commands (command, id, p, end, &buf);
9754 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
9755 /* Sent after the invoke is complete */
9758 case CMD_SET_EVENT_REQUEST:
9759 err = event_commands (command, p, end, &buf);
9761 case CMD_SET_APPDOMAIN:
9762 err = domain_commands (command, p, end, &buf);
9764 case CMD_SET_ASSEMBLY:
9765 err = assembly_commands (command, p, end, &buf);
9767 case CMD_SET_MODULE:
9768 err = module_commands (command, p, end, &buf);
9771 err = field_commands (command, p, end, &buf);
9774 err = type_commands (command, p, end, &buf);
9776 case CMD_SET_METHOD:
9777 err = method_commands (command, p, end, &buf);
9779 case CMD_SET_THREAD:
9780 err = thread_commands (command, p, end, &buf);
9782 case CMD_SET_STACK_FRAME:
9783 err = frame_commands (command, p, end, &buf);
9785 case CMD_SET_ARRAY_REF:
9786 err = array_commands (command, p, end, &buf);
9788 case CMD_SET_STRING_REF:
9789 err = string_commands (command, p, end, &buf);
9791 case CMD_SET_OBJECT_REF:
9792 err = object_commands (command, p, end, &buf);
9795 err = ERR_NOT_IMPLEMENTED;
9798 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9799 buffer_replies = TRUE;
9803 if (buffer_replies) {
9804 buffer_reply_packet (id, err, &buf);
9806 send_reply_packet (id, err, &buf);
9807 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9811 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9812 send_buffered_reply_packets ();
9813 buffer_replies = FALSE;
9819 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9823 mono_set_is_debugger_attached (FALSE);
9825 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
9826 debugger_thread_exited = TRUE;
9827 mono_coop_cond_signal (&debugger_thread_exited_cond);
9828 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
9830 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9832 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9833 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9834 start_debugger_thread ();
9837 mono_jit_thread_detach (attach_cookie, &attach_dummy);
9842 #else /* DISABLE_DEBUGGER_AGENT */
9845 mono_debugger_agent_parse_options (char *options)
9847 g_error ("This runtime is configured with the debugger agent disabled.");
9851 mono_debugger_agent_init (void)
9856 mono_debugger_agent_breakpoint_hit (void *sigctx)
9861 mono_debugger_agent_single_step_event (void *sigctx)
9866 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9871 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9872 MonoContext *catch_ctx)
9877 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9882 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9887 mono_debugger_agent_user_break (void)
9893 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9898 mono_debugger_agent_debug_log_is_enabled (void)
9904 mono_debugger_agent_unhandled_exception (MonoException *exc)
9906 g_assert_not_reached ();
9910 debugger_agent_single_step_from_context (MonoContext *ctx)
9912 g_assert_not_reached ();
9916 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9918 g_assert_not_reached ();