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.
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #ifdef HAVE_SYS_TYPES_H
17 #include <sys/types.h>
19 #ifdef HAVE_SYS_SELECT_H
20 #include <sys/select.h>
22 #ifdef HAVE_SYS_SOCKET_H
23 #include <sys/socket.h>
25 #ifdef HAVE_NETINET_TCP_H
26 #include <netinet/tcp.h>
28 #ifdef HAVE_NETINET_IN_H
29 #include <netinet/in.h>
49 #ifdef PLATFORM_ANDROID
51 #include <linux/tcp.h>
52 #include <sys/endian.h>
55 #include <mono/metadata/mono-debug.h>
56 #include <mono/metadata/mono-debug-debugger.h>
57 #include <mono/metadata/debug-mono-symfile.h>
58 #include <mono/metadata/gc-internals.h>
59 #include <mono/metadata/environment.h>
60 #include <mono/metadata/threads-types.h>
61 #include <mono/metadata/threadpool.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/metadata/w32socket.h>
67 #include <mono/utils/mono-coop-mutex.h>
68 #include <mono/utils/mono-coop-semaphore.h>
69 #include <mono/utils/mono-error-internals.h>
70 #include <mono/utils/mono-stack-unwinding.h>
71 #include <mono/utils/mono-time.h>
72 #include <mono/utils/mono-threads.h>
73 #include <mono/utils/networking.h>
74 #include <mono/utils/mono-proclib.h>
75 #include "debugger-agent.h"
77 #include "seq-points.h"
78 #include <mono/utils/w32api.h>
81 * On iOS we can't use System.Environment.Exit () as it will do the wrong
84 #if !defined (TARGET_IOS)
85 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
89 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
90 #define DISABLE_DEBUGGER_AGENT 1
93 #ifdef DISABLE_SOFT_DEBUG
94 #define DISABLE_DEBUGGER_AGENT 1
97 #ifndef DISABLE_DEBUGGER_AGENT
99 #include <mono/utils/mono-os-mutex.h>
101 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
124 guint32 il_offset, native_offset;
128 * If method is gshared, this is the actual instance, otherwise this is equal to
131 MonoMethod *actual_method;
133 * This is the method which is visible to debugger clients. Same as method,
134 * except for native-to-managed wrappers.
136 MonoMethod *api_method;
138 MonoDebugMethodJitInfo *jit;
141 mgreg_t *reg_locations [MONO_MAX_IREGS];
143 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
144 * the frame can become invalid.
149 typedef struct _InvokeData InvokeData;
157 /* This is the context which needs to be restored after the invoke */
161 * If this is set, invoke this method with the arguments given by ARGS.
165 guint32 suspend_count;
168 InvokeData *last_invoke;
172 MonoThreadUnwindState context;
174 /* This is computed on demand when it is requested using the wire protocol */
175 /* It is freed up when the thread is resumed */
179 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
182 gboolean frames_up_to_date;
184 * Points to data about a pending invoke which needs to be executed after the thread
187 InvokeData *pending_invoke;
189 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
194 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
195 * within a finite amount of time.
199 * Set to TRUE if this thread is suspended in suspend_current ().
201 gboolean really_suspended;
202 /* Used to pass the context to the breakpoint/single step handler */
203 MonoContext handler_ctx;
204 /* Whenever thread_stop () was called for this thread */
207 /* Whenever to disable breakpoints (used during invokes) */
208 gboolean disable_breakpoints;
211 * Number of times this thread has been resumed using resume_thread ().
213 guint32 resume_count;
215 MonoInternalThread *thread;
218 * Information about the frame which transitioned to native code for running
221 StackFrameInfo async_last_frame;
224 * The context where the stack walk can be started for running threads.
226 MonoThreadUnwindState async_state;
229 * The context used for filter clauses
231 MonoThreadUnwindState filter_state;
233 gboolean abort_requested;
236 * The current mono_runtime_invoke_checked invocation.
241 * The context where single stepping should resume while the thread is suspended because
242 * of an EXCEPTION event.
244 MonoThreadUnwindState catch_state;
247 * The context which needs to be restored after handling a single step/breakpoint
248 * event. This is the same as the ctx at step/breakpoint site, but includes changes
249 * to caller saved registers done by set_var ().
251 MonoThreadUnwindState restore_state;
252 /* Frames computed from restore_state */
253 int restore_frame_count;
254 StackFrame **restore_frames;
256 /* The currently unloading appdomain */
257 MonoDomain *domain_unloading;
262 void (*connect) (const char *address);
263 void (*close1) (void);
264 void (*close2) (void);
265 gboolean (*send) (void *buf, int len);
266 int (*recv) (void *buf, int len);
270 * Wire Protocol definitions
273 #define HEADER_LENGTH 11
275 #define MAJOR_VERSION 2
276 #define MINOR_VERSION 45
280 CMD_SET_OBJECT_REF = 9,
281 CMD_SET_STRING_REF = 10,
283 CMD_SET_ARRAY_REF = 13,
284 CMD_SET_EVENT_REQUEST = 15,
285 CMD_SET_STACK_FRAME = 16,
286 CMD_SET_APPDOMAIN = 20,
287 CMD_SET_ASSEMBLY = 21,
296 EVENT_KIND_VM_START = 0,
297 EVENT_KIND_VM_DEATH = 1,
298 EVENT_KIND_THREAD_START = 2,
299 EVENT_KIND_THREAD_DEATH = 3,
300 EVENT_KIND_APPDOMAIN_CREATE = 4,
301 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
302 EVENT_KIND_METHOD_ENTRY = 6,
303 EVENT_KIND_METHOD_EXIT = 7,
304 EVENT_KIND_ASSEMBLY_LOAD = 8,
305 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
306 EVENT_KIND_BREAKPOINT = 10,
307 EVENT_KIND_STEP = 11,
308 EVENT_KIND_TYPE_LOAD = 12,
309 EVENT_KIND_EXCEPTION = 13,
310 EVENT_KIND_KEEPALIVE = 14,
311 EVENT_KIND_USER_BREAK = 15,
312 EVENT_KIND_USER_LOG = 16
316 SUSPEND_POLICY_NONE = 0,
317 SUSPEND_POLICY_EVENT_THREAD = 1,
318 SUSPEND_POLICY_ALL = 2
323 ERR_INVALID_OBJECT = 20,
324 ERR_INVALID_FIELDID = 25,
325 ERR_INVALID_FRAMEID = 30,
326 ERR_NOT_IMPLEMENTED = 100,
327 ERR_NOT_SUSPENDED = 101,
328 ERR_INVALID_ARGUMENT = 102,
330 ERR_NO_INVOCATION = 104,
331 ERR_ABSENT_INFORMATION = 105,
332 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
333 ERR_INVOKE_ABORTED = 107,
334 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
339 MOD_KIND_THREAD_ONLY = 3,
340 MOD_KIND_LOCATION_ONLY = 7,
341 MOD_KIND_EXCEPTION_ONLY = 8,
343 MOD_KIND_ASSEMBLY_ONLY = 11,
344 MOD_KIND_SOURCE_FILE_ONLY = 12,
345 MOD_KIND_TYPE_NAME_ONLY = 13,
361 STEP_FILTER_NONE = 0,
362 STEP_FILTER_STATIC_CTOR = 1,
363 STEP_FILTER_DEBUGGER_HIDDEN = 2,
364 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
365 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
369 TOKEN_TYPE_STRING = 0,
371 TOKEN_TYPE_FIELD = 2,
372 TOKEN_TYPE_METHOD = 3,
373 TOKEN_TYPE_UNKNOWN = 4
377 VALUE_TYPE_ID_NULL = 0xf0,
378 VALUE_TYPE_ID_TYPE = 0xf1,
379 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
383 FRAME_FLAG_DEBUGGER_INVOKE = 1,
384 FRAME_FLAG_NATIVE_TRANSITION = 2
388 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
389 INVOKE_FLAG_SINGLE_THREADED = 2,
390 INVOKE_FLAG_RETURN_OUT_THIS = 4,
391 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
392 INVOKE_FLAG_VIRTUAL = 16
396 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
397 } BindingFlagsExtensions;
401 CMD_VM_ALL_THREADS = 2,
406 CMD_VM_INVOKE_METHOD = 7,
407 CMD_VM_SET_PROTOCOL_VERSION = 8,
408 CMD_VM_ABORT_INVOKE = 9,
409 CMD_VM_SET_KEEPALIVE = 10,
410 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
411 CMD_VM_GET_TYPES = 12,
412 CMD_VM_INVOKE_METHODS = 13,
413 CMD_VM_START_BUFFERING = 14,
414 CMD_VM_STOP_BUFFERING = 15
418 CMD_THREAD_GET_FRAME_INFO = 1,
419 CMD_THREAD_GET_NAME = 2,
420 CMD_THREAD_GET_STATE = 3,
421 CMD_THREAD_GET_INFO = 4,
422 CMD_THREAD_GET_ID = 5,
423 CMD_THREAD_GET_TID = 6,
424 CMD_THREAD_SET_IP = 7
428 CMD_EVENT_REQUEST_SET = 1,
429 CMD_EVENT_REQUEST_CLEAR = 2,
430 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
438 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
439 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
440 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
441 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
442 CMD_APPDOMAIN_CREATE_STRING = 5,
443 CMD_APPDOMAIN_GET_CORLIB = 6,
444 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
448 CMD_ASSEMBLY_GET_LOCATION = 1,
449 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
450 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
451 CMD_ASSEMBLY_GET_OBJECT = 4,
452 CMD_ASSEMBLY_GET_TYPE = 5,
453 CMD_ASSEMBLY_GET_NAME = 6,
454 CMD_ASSEMBLY_GET_DOMAIN = 7
458 CMD_MODULE_GET_INFO = 1,
462 CMD_FIELD_GET_INFO = 1,
466 CMD_METHOD_GET_NAME = 1,
467 CMD_METHOD_GET_DECLARING_TYPE = 2,
468 CMD_METHOD_GET_DEBUG_INFO = 3,
469 CMD_METHOD_GET_PARAM_INFO = 4,
470 CMD_METHOD_GET_LOCALS_INFO = 5,
471 CMD_METHOD_GET_INFO = 6,
472 CMD_METHOD_GET_BODY = 7,
473 CMD_METHOD_RESOLVE_TOKEN = 8,
474 CMD_METHOD_GET_CATTRS = 9,
475 CMD_METHOD_MAKE_GENERIC_METHOD = 10
479 CMD_TYPE_GET_INFO = 1,
480 CMD_TYPE_GET_METHODS = 2,
481 CMD_TYPE_GET_FIELDS = 3,
482 CMD_TYPE_GET_VALUES = 4,
483 CMD_TYPE_GET_OBJECT = 5,
484 CMD_TYPE_GET_SOURCE_FILES = 6,
485 CMD_TYPE_SET_VALUES = 7,
486 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
487 CMD_TYPE_GET_PROPERTIES = 9,
488 CMD_TYPE_GET_CATTRS = 10,
489 CMD_TYPE_GET_FIELD_CATTRS = 11,
490 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
491 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
492 CMD_TYPE_GET_VALUES_2 = 14,
493 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
494 CMD_TYPE_GET_INTERFACES = 16,
495 CMD_TYPE_GET_INTERFACE_MAP = 17,
496 CMD_TYPE_IS_INITIALIZED = 18,
497 CMD_TYPE_CREATE_INSTANCE = 19
501 CMD_STACK_FRAME_GET_VALUES = 1,
502 CMD_STACK_FRAME_GET_THIS = 2,
503 CMD_STACK_FRAME_SET_VALUES = 3,
504 CMD_STACK_FRAME_GET_DOMAIN = 4,
505 CMD_STACK_FRAME_SET_THIS = 5,
509 CMD_ARRAY_REF_GET_LENGTH = 1,
510 CMD_ARRAY_REF_GET_VALUES = 2,
511 CMD_ARRAY_REF_SET_VALUES = 3,
515 CMD_STRING_REF_GET_VALUE = 1,
516 CMD_STRING_REF_GET_LENGTH = 2,
517 CMD_STRING_REF_GET_CHARS = 3
521 CMD_OBJECT_REF_GET_TYPE = 1,
522 CMD_OBJECT_REF_GET_VALUES = 2,
523 CMD_OBJECT_REF_IS_COLLECTED = 3,
524 CMD_OBJECT_REF_GET_ADDRESS = 4,
525 CMD_OBJECT_REF_GET_DOMAIN = 5,
526 CMD_OBJECT_REF_SET_VALUES = 6,
527 CMD_OBJECT_REF_GET_INFO = 7,
533 int count; /* For kind == MOD_KIND_COUNT */
534 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
535 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
536 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
537 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
538 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
539 StepFilter filter; /* For kind == MOD_KIND_STEP */
541 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
550 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
554 * Describes a single step request.
558 MonoInternalThread *thread;
564 MonoMethod *start_method;
565 MonoMethod *last_method;
567 /* Whenever single stepping is performed using start/stop_single_stepping () */
569 /* The list of breakpoints used to implement step-over */
571 /* The number of frames at the start of a step-over */
573 /* If set, don't stop in methods that are not part of user assemblies */
574 MonoAssembly** user_assemblies;
575 /* Used to distinguish stepping breakpoint hits in parallel tasks executions */
577 /* Used to know if we are in process of async step-out and distishing from exception breakpoints */
578 MonoMethod* async_stepout_method;
582 * Contains additional information for an event
585 /* For EVENT_KIND_EXCEPTION */
587 MonoContext catch_ctx;
589 /* For EVENT_KIND_USER_LOG */
591 char *category, *message;
592 /* For EVENT_KIND_TYPE_LOAD */
596 /* Dummy structure used for the profiler callbacks */
602 guint8 *buf, *p, *end;
605 typedef struct ReplyPacket {
611 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
613 #ifdef PLATFORM_ANDROID
614 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
616 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
620 #define get_last_sock_error() WSAGetLastError()
621 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
622 #define MONO_EINTR WSAEINTR
624 #define get_last_sock_error() errno
625 #define MONO_EWOULDBLOCK EWOULDBLOCK
626 #define MONO_EINTR EINTR
629 #define CHECK_PROTOCOL_VERSION(major,minor) \
630 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
636 static AgentConfig agent_config;
639 * Whenever the agent is fully initialized.
640 * When using the onuncaught or onthrow options, only some parts of the agent are
641 * initialized on startup, and the full initialization which includes connection
642 * establishment and the startup of the agent thread is only done in response to
645 static gint32 inited;
647 #ifndef DISABLE_SOCKET_TRANSPORT
649 static int listen_fd;
652 static int packet_id = 0;
654 static int objref_id = 0;
656 static int event_request_id = 0;
658 static int frame_id = 0;
660 static GPtrArray *event_requests;
662 static MonoNativeTlsKey debugger_tls_id;
664 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
666 /* Maps MonoInternalThread -> DebuggerTlsData */
667 /* Protected by the loader lock */
668 static MonoGHashTable *thread_to_tls;
670 /* Maps tid -> MonoInternalThread */
671 /* Protected by the loader lock */
672 static MonoGHashTable *tid_to_thread;
674 /* Maps tid -> MonoThread (not MonoInternalThread) */
675 /* Protected by the loader lock */
676 static MonoGHashTable *tid_to_thread_obj;
678 static MonoNativeThreadId debugger_thread_id;
680 static MonoThreadHandle *debugger_thread_handle;
682 static int log_level;
684 static gboolean embedding;
686 static FILE *log_file;
688 /* Assemblies whose assembly load event has no been sent yet */
689 /* Protected by the dbg lock */
690 static GPtrArray *pending_assembly_loads;
692 /* Whenever the debugger thread has exited */
693 static gboolean debugger_thread_exited;
695 /* Cond variable used to wait for debugger_thread_exited becoming true */
696 static MonoCoopCond debugger_thread_exited_cond;
698 /* Mutex for the cond var above */
699 static MonoCoopMutex debugger_thread_exited_mutex;
701 static DebuggerProfiler debugger_profiler;
703 /* The single step request instance */
704 static SingleStepReq *ss_req;
706 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
707 /* Number of single stepping operations in progress */
711 /* The protocol version of the client */
712 static int major_version, minor_version;
714 /* Whenever the variables above are set by the client */
715 static gboolean protocol_version_set;
717 /* A hash table containing all active domains */
718 /* Protected by the loader lock */
719 static GHashTable *domains;
721 /* The number of times the runtime is suspended */
722 static gint32 suspend_count;
724 /* Whenever to buffer reply messages and send them together */
725 static gboolean buffer_replies;
727 /* Buffered reply packets */
728 static ReplyPacket reply_packets [128];
731 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
732 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
733 static MonoCoopMutex debug_mutex;
735 static void transport_init (void);
736 static void transport_connect (const char *address);
737 static gboolean transport_handshake (void);
738 static void register_transport (DebuggerTransport *trans);
740 static gsize WINAPI debugger_thread (void *arg);
742 static void runtime_initialized (MonoProfiler *prof);
744 static void runtime_shutdown (MonoProfiler *prof);
746 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
748 static void thread_end (MonoProfiler *prof, uintptr_t tid);
750 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
752 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
754 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
756 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
758 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
760 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
762 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
764 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
766 static void emit_assembly_load (gpointer assembly, gpointer user_data);
768 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
770 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
772 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
774 static void start_single_stepping (void);
776 static void stop_single_stepping (void);
778 static void suspend_current (void);
780 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
782 static void clear_types_for_assembly (MonoAssembly *assembly);
784 static void clear_breakpoints_for_domain (MonoDomain *domain);
786 static void process_profiler_event (EventKind event, gpointer arg);
788 /* Submodule init/cleanup */
789 static void breakpoints_init (void);
790 static void breakpoints_cleanup (void);
792 static void objrefs_init (void);
793 static void objrefs_cleanup (void);
795 static void ids_init (void);
796 static void ids_cleanup (void);
798 static void suspend_init (void);
800 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
801 StackFrame **frames, int nframes);
802 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
803 static void ss_destroy (SingleStepReq *req);
805 static void start_debugger_thread (void);
806 static void stop_debugger_thread (void);
808 static void finish_agent_init (gboolean on_startup);
810 static void process_profiler_event (EventKind event, gpointer arg);
812 static void invalidate_frames (DebuggerTlsData *tls);
814 #ifndef DISABLE_SOCKET_TRANSPORT
816 register_socket_transport (void);
819 static inline gboolean
820 is_debugger_thread (void)
822 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
826 parse_address (char *address, char **host, int *port)
828 char *pos = strchr (address, ':');
830 if (pos == NULL || pos == address)
833 size_t len = pos - address;
834 *host = (char *)g_malloc (len + 1);
835 memcpy (*host, address, len);
836 (*host) [len] = '\0';
838 *port = atoi (pos + 1);
846 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
847 fprintf (stderr, "Available options:\n");
848 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
849 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
850 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
851 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
852 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
853 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
854 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
855 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
856 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
857 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
861 parse_flag (const char *option, char *flag)
863 if (!strcmp (flag, "y"))
865 else if (!strcmp (flag, "n"))
868 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
875 mono_debugger_agent_parse_options (char *options)
882 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
883 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
887 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
889 options = g_strdup_printf ("%s,%s", options, extra);
891 agent_config.enabled = TRUE;
892 agent_config.suspend = TRUE;
893 agent_config.server = FALSE;
894 agent_config.defer = FALSE;
895 agent_config.address = NULL;
897 //agent_config.log_level = 10;
899 args = g_strsplit (options, ",", -1);
900 for (ptr = args; ptr && *ptr; ptr ++) {
903 if (strncmp (arg, "transport=", 10) == 0) {
904 agent_config.transport = g_strdup (arg + 10);
905 } else if (strncmp (arg, "address=", 8) == 0) {
906 agent_config.address = g_strdup (arg + 8);
907 } else if (strncmp (arg, "loglevel=", 9) == 0) {
908 agent_config.log_level = atoi (arg + 9);
909 } else if (strncmp (arg, "logfile=", 8) == 0) {
910 agent_config.log_file = g_strdup (arg + 8);
911 } else if (strncmp (arg, "suspend=", 8) == 0) {
912 agent_config.suspend = parse_flag ("suspend", arg + 8);
913 } else if (strncmp (arg, "server=", 7) == 0) {
914 agent_config.server = parse_flag ("server", arg + 7);
915 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
916 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
917 } else if (strncmp (arg, "onthrow=", 8) == 0) {
918 /* We support multiple onthrow= options */
919 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
920 } else if (strncmp (arg, "onthrow", 7) == 0) {
921 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
922 } else if (strncmp (arg, "help", 4) == 0) {
925 } else if (strncmp (arg, "timeout=", 8) == 0) {
926 agent_config.timeout = atoi (arg + 8);
927 } else if (strncmp (arg, "launch=", 7) == 0) {
928 agent_config.launch = g_strdup (arg + 7);
929 } else if (strncmp (arg, "embedding=", 10) == 0) {
930 agent_config.embedding = atoi (arg + 10) == 1;
931 } else if (strncmp (arg, "keepalive=", 10) == 0) {
932 agent_config.keepalive = atoi (arg + 10);
933 } else if (strncmp (arg, "setpgid=", 8) == 0) {
934 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
941 if (agent_config.server && !agent_config.suspend) {
942 /* Waiting for deferred attachment */
943 agent_config.defer = TRUE;
944 if (agent_config.address == NULL) {
945 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
949 //agent_config.log_level = 0;
951 if (agent_config.transport == NULL) {
952 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
956 if (agent_config.address == NULL && !agent_config.server) {
957 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
962 if (!strcmp (agent_config.transport, "dt_socket")) {
963 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
964 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
971 mono_debugger_agent_init (void)
973 mono_coop_mutex_init_recursive (&debug_mutex);
975 if (!agent_config.enabled)
980 /* Need to know whenever a thread has acquired the loader mutex */
981 mono_loader_lock_track_ownership (TRUE);
983 event_requests = g_ptr_array_new ();
985 mono_coop_mutex_init (&debugger_thread_exited_mutex);
986 mono_coop_cond_init (&debugger_thread_exited_cond);
988 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
989 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
990 mono_profiler_install_runtime_initialized (runtime_initialized);
991 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
992 mono_profiler_install_thread (thread_startup, thread_end);
993 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
994 mono_profiler_install_jit_end (jit_end);
996 mono_native_tls_alloc (&debugger_tls_id, NULL);
998 /* Needed by the hash_table_new_type () call below */
999 mono_gc_base_init ();
1001 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
1002 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
1004 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1005 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1007 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");
1008 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
1010 pending_assembly_loads = g_ptr_array_new ();
1011 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1013 log_level = agent_config.log_level;
1015 embedding = agent_config.embedding;
1016 disconnected = TRUE;
1018 if (agent_config.log_file) {
1019 log_file = fopen (agent_config.log_file, "w+");
1021 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1030 breakpoints_init ();
1033 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1035 * This is needed because currently we don't handle liveness info.
1037 mini_get_debug_options ()->mdb_optimizations = TRUE;
1039 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1040 /* This is needed because we can't set local variables in registers yet */
1041 mono_disable_optimizations (MONO_OPT_LINEARS);
1045 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1046 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1047 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1050 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1053 if (agent_config.setpgid)
1057 if (!agent_config.onuncaught && !agent_config.onthrow)
1058 finish_agent_init (TRUE);
1062 * finish_agent_init:
1064 * Finish the initialization of the agent. This involves connecting the transport
1065 * and starting the agent thread. This is either done at startup, or
1066 * in response to some event like an unhandled exception.
1069 finish_agent_init (gboolean on_startup)
1073 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1076 if (agent_config.launch) {
1079 // FIXME: Generated address
1080 // FIXME: Races with transport_connect ()
1082 argv [0] = agent_config.launch;
1083 argv [1] = agent_config.transport;
1084 argv [2] = agent_config.address;
1087 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1089 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1094 transport_connect (agent_config.address);
1097 /* Do some which is usually done after sending the VMStart () event */
1098 vm_start_event_sent = TRUE;
1099 start_debugger_thread ();
1104 mono_debugger_agent_cleanup (void)
1109 stop_debugger_thread ();
1111 breakpoints_cleanup ();
1120 #ifndef DISABLE_SOCKET_TRANSPORT
1125 * recv() + handle incomplete reads and EINTR
1128 socket_transport_recv (void *buf, int len)
1134 static gint64 last_keepalive;
1141 res = recv (fd, (char *) buf + total, len - total, flags);
1144 if (agent_config.keepalive) {
1145 gboolean need_keepalive = FALSE;
1146 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1147 need_keepalive = TRUE;
1148 } else if (res == -1) {
1149 /* This could happen if recv () is interrupted repeatedly */
1150 msecs = mono_msec_ticks ();
1151 if (msecs - last_keepalive >= agent_config.keepalive) {
1152 need_keepalive = TRUE;
1153 last_keepalive = msecs;
1156 if (need_keepalive) {
1157 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1161 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1169 set_keepalive (void)
1174 if (!agent_config.keepalive || !conn_fd)
1177 tv.tv_sec = agent_config.keepalive / 1000;
1178 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1180 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1181 g_assert (result >= 0);
1185 socket_transport_accept (int socket_fd)
1188 conn_fd = accept (socket_fd, NULL, NULL);
1191 if (conn_fd == -1) {
1192 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1194 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1201 socket_transport_send (void *data, int len)
1208 res = send (conn_fd, data, len, 0);
1209 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1220 * socket_transport_connect:
1222 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1225 socket_transport_connect (const char *address)
1227 MonoAddressInfo *result;
1228 MonoAddressEntry *rp;
1229 int sfd = -1, s, res;
1233 if (agent_config.address) {
1234 res = parse_address (agent_config.address, &host, &port);
1235 g_assert (res == 0);
1246 mono_network_init ();
1248 /* Obtain address(es) matching host/port */
1249 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1251 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1256 if (agent_config.server) {
1257 /* Wait for a connection */
1259 struct sockaddr_in addr;
1262 /* No address, generate one */
1263 sfd = socket (AF_INET, SOCK_STREAM, 0);
1266 /* This will bind the socket to a random port */
1267 res = listen (sfd, 16);
1269 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1274 addrlen = sizeof (addr);
1275 memset (&addr, 0, sizeof (addr));
1276 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1277 g_assert (res == 0);
1279 host = (char*)"127.0.0.1";
1280 port = ntohs (addr.sin_port);
1282 /* Emit the address to stdout */
1283 /* FIXME: Should print another interface, not localhost */
1284 printf ("%s:%d\n", host, port);
1286 /* Listen on the provided address */
1287 for (rp = result->entries; rp != NULL; rp = rp->next) {
1288 MonoSocketAddress sockaddr;
1292 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1294 sfd = socket (rp->family, rp->socktype,
1299 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1302 res = bind (sfd, &sockaddr.addr, sock_len);
1306 res = listen (sfd, 16);
1313 mono_free_address_info (result);
1316 if (agent_config.defer)
1319 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1321 if (agent_config.timeout) {
1326 tv.tv_usec = agent_config.timeout * 1000;
1328 FD_SET (sfd, &readfds);
1331 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1335 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1340 conn_fd = socket_transport_accept (sfd);
1344 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1346 /* Connect to the specified address */
1347 /* FIXME: Respect the timeout */
1348 for (rp = result->entries; rp != NULL; rp = rp->next) {
1349 MonoSocketAddress sockaddr;
1352 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1354 sfd = socket (rp->family, rp->socktype,
1360 res = connect (sfd, &sockaddr.addr, sock_len);
1364 break; /* Success */
1372 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1378 mono_free_address_info (result);
1381 if (!transport_handshake ())
1386 socket_transport_close1 (void)
1388 /* This will interrupt the agent thread */
1389 /* Close the read part only so it can still send back replies */
1390 /* Also shut down the connection listener so that we can exit normally */
1392 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1393 shutdown (conn_fd, SD_BOTH);
1394 shutdown (listen_fd, SD_BOTH);
1395 closesocket (listen_fd);
1397 shutdown (conn_fd, SHUT_RD);
1398 shutdown (listen_fd, SHUT_RDWR);
1406 socket_transport_close2 (void)
1409 shutdown (conn_fd, SD_BOTH);
1411 shutdown (conn_fd, SHUT_RDWR);
1416 register_socket_transport (void)
1418 DebuggerTransport trans;
1420 trans.name = "dt_socket";
1421 trans.connect = socket_transport_connect;
1422 trans.close1 = socket_transport_close1;
1423 trans.close2 = socket_transport_close2;
1424 trans.send = socket_transport_send;
1425 trans.recv = socket_transport_recv;
1427 register_transport (&trans);
1431 * socket_fd_transport_connect:
1435 socket_fd_transport_connect (const char *address)
1439 res = sscanf (address, "%d", &conn_fd);
1441 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1445 if (!transport_handshake ())
1450 register_socket_fd_transport (void)
1452 DebuggerTransport trans;
1454 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1455 trans.name = "socket-fd";
1456 trans.connect = socket_fd_transport_connect;
1457 trans.close1 = socket_transport_close1;
1458 trans.close2 = socket_transport_close2;
1459 trans.send = socket_transport_send;
1460 trans.recv = socket_transport_recv;
1462 register_transport (&trans);
1465 #endif /* DISABLE_SOCKET_TRANSPORT */
1471 #define MAX_TRANSPORTS 16
1473 static DebuggerTransport *transport;
1475 static DebuggerTransport transports [MAX_TRANSPORTS];
1476 static int ntransports;
1479 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1482 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1484 register_transport (trans);
1488 register_transport (DebuggerTransport *trans)
1490 g_assert (ntransports < MAX_TRANSPORTS);
1492 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1497 transport_init (void)
1501 #ifndef DISABLE_SOCKET_TRANSPORT
1502 register_socket_transport ();
1503 register_socket_fd_transport ();
1506 for (i = 0; i < ntransports; ++i) {
1507 if (!strcmp (agent_config.transport, transports [i].name))
1510 if (i == ntransports) {
1511 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1512 for (i = 0; i < ntransports; ++i)
1513 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1514 fprintf (stderr, "\n");
1517 transport = &transports [i];
1521 transport_connect (const char *address)
1523 transport->connect (address);
1527 transport_close1 (void)
1529 transport->close1 ();
1533 transport_close2 (void)
1535 transport->close2 ();
1539 transport_send (void *buf, int len)
1541 return transport->send (buf, len);
1545 transport_recv (void *buf, int len)
1547 return transport->recv (buf, len);
1551 mono_debugger_agent_transport_handshake (void)
1553 return transport_handshake ();
1557 transport_handshake (void)
1559 char handshake_msg [128];
1563 disconnected = TRUE;
1565 /* Write handshake message */
1566 sprintf (handshake_msg, "DWP-Handshake");
1569 res = transport_send (handshake_msg, strlen (handshake_msg));
1570 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1572 g_assert (res != -1);
1575 res = transport_recv (buf, strlen (handshake_msg));
1576 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1577 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1582 * To support older clients, the client sends its protocol version after connecting
1583 * using a command. Until that is received, default to our protocol version.
1585 major_version = MAJOR_VERSION;
1586 minor_version = MINOR_VERSION;
1587 protocol_version_set = FALSE;
1589 #ifndef DISABLE_SOCKET_TRANSPORT
1590 // FIXME: Move this somewhere else
1592 * Set TCP_NODELAY on the socket so the client receives events/command
1593 * results immediately.
1597 int result = setsockopt (conn_fd,
1602 g_assert (result >= 0);
1608 disconnected = FALSE;
1613 stop_debugger_thread (void)
1618 transport_close1 ();
1621 * Wait for the thread to exit.
1623 * If we continue with the shutdown without waiting for it, then the client might
1624 * not receive an answer to its last command like a resume.
1626 if (!is_debugger_thread ()) {
1628 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1629 if (!debugger_thread_exited)
1630 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1631 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1632 } while (!debugger_thread_exited);
1635 transport_close2 ();
1639 start_debugger_thread (void)
1641 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, NULL, NULL);
1642 g_assert (debugger_thread_handle);
1646 * Functions to decode protocol data
1650 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1653 g_assert (*endbuf <= limit);
1658 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1661 g_assert (*endbuf <= limit);
1663 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1666 static inline gint64
1667 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1669 guint32 high = decode_int (buf, &buf, limit);
1670 guint32 low = decode_int (buf, &buf, limit);
1674 return ((((guint64)high) << 32) | ((guint64)low));
1678 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1680 return decode_int (buf, endbuf, limit);
1684 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1686 int len = decode_int (buf, &buf, limit);
1694 s = (char *)g_malloc (len + 1);
1697 memcpy (s, buf, len);
1706 * Functions to encode protocol data
1710 buffer_init (Buffer *buf, int size)
1712 buf->buf = (guint8 *)g_malloc (size);
1714 buf->end = buf->buf + size;
1718 buffer_len (Buffer *buf)
1720 return buf->p - buf->buf;
1724 buffer_make_room (Buffer *buf, int size)
1726 if (buf->end - buf->p < size) {
1727 int new_size = buf->end - buf->buf + size + 32;
1728 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1729 size = buf->p - buf->buf;
1732 buf->end = buf->buf + new_size;
1737 buffer_add_byte (Buffer *buf, guint8 val)
1739 buffer_make_room (buf, 1);
1745 buffer_add_short (Buffer *buf, guint32 val)
1747 buffer_make_room (buf, 2);
1748 buf->p [0] = (val >> 8) & 0xff;
1749 buf->p [1] = (val >> 0) & 0xff;
1754 buffer_add_int (Buffer *buf, guint32 val)
1756 buffer_make_room (buf, 4);
1757 buf->p [0] = (val >> 24) & 0xff;
1758 buf->p [1] = (val >> 16) & 0xff;
1759 buf->p [2] = (val >> 8) & 0xff;
1760 buf->p [3] = (val >> 0) & 0xff;
1765 buffer_add_long (Buffer *buf, guint64 l)
1767 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1768 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1772 buffer_add_id (Buffer *buf, int id)
1774 buffer_add_int (buf, (guint64)id);
1778 buffer_add_data (Buffer *buf, guint8 *data, int len)
1780 buffer_make_room (buf, len);
1781 memcpy (buf->p, data, len);
1786 buffer_add_string (Buffer *buf, const char *str)
1791 buffer_add_int (buf, 0);
1794 buffer_add_int (buf, len);
1795 buffer_add_data (buf, (guint8*)str, len);
1800 buffer_add_buffer (Buffer *buf, Buffer *data)
1802 buffer_add_data (buf, data->buf, buffer_len (data));
1806 buffer_free (Buffer *buf)
1812 send_packet (int command_set, int command, Buffer *data)
1818 id = InterlockedIncrement (&packet_id);
1820 len = data->p - data->buf + 11;
1821 buffer_init (&buf, len);
1822 buffer_add_int (&buf, len);
1823 buffer_add_int (&buf, id);
1824 buffer_add_byte (&buf, 0); /* flags */
1825 buffer_add_byte (&buf, command_set);
1826 buffer_add_byte (&buf, command);
1827 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1829 res = transport_send (buf.buf, len);
1837 send_reply_packets (int npackets, ReplyPacket *packets)
1844 for (i = 0; i < npackets; ++i)
1845 len += buffer_len (packets [i].data) + 11;
1846 buffer_init (&buf, len);
1847 for (i = 0; i < npackets; ++i) {
1848 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1849 buffer_add_int (&buf, packets [i].id);
1850 buffer_add_byte (&buf, 0x80); /* flags */
1851 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1852 buffer_add_byte (&buf, packets [i].error);
1853 buffer_add_buffer (&buf, packets [i].data);
1856 res = transport_send (buf.buf, len);
1864 send_reply_packet (int id, int error, Buffer *data)
1868 memset (&packet, 0, sizeof (ReplyPacket));
1870 packet.error = error;
1873 return send_reply_packets (1, &packet);
1877 send_buffered_reply_packets (void)
1881 send_reply_packets (nreply_packets, reply_packets);
1882 for (i = 0; i < nreply_packets; ++i)
1883 buffer_free (reply_packets [i].data);
1884 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1889 buffer_reply_packet (int id, int error, Buffer *data)
1893 if (nreply_packets == 128)
1894 send_buffered_reply_packets ();
1896 p = &reply_packets [nreply_packets];
1899 p->data = g_new0 (Buffer, 1);
1900 buffer_init (p->data, buffer_len (data));
1901 buffer_add_buffer (p->data, data);
1910 * Represents an object accessible by the debugger client.
1913 /* Unique id used in the wire protocol to refer to objects */
1916 * A weakref gc handle pointing to the object. The gc handle is used to
1917 * detect if the object was garbage collected.
1922 /* Maps objid -> ObjRef */
1923 /* Protected by the loader lock */
1924 static GHashTable *objrefs;
1925 /* Protected by the loader lock */
1926 static GHashTable *obj_to_objref;
1927 /* Protected by the dbg lock */
1928 static MonoGHashTable *suspended_objs;
1931 free_objref (gpointer value)
1933 ObjRef *o = (ObjRef *)value;
1935 mono_gchandle_free (o->handle);
1943 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1944 obj_to_objref = g_hash_table_new (NULL, NULL);
1945 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1946 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1950 objrefs_cleanup (void)
1952 g_hash_table_destroy (objrefs);
1957 * Return an ObjRef for OBJ.
1960 get_objref (MonoObject *obj)
1963 GSList *reflist = NULL, *l;
1969 if (suspend_count) {
1971 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1974 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1978 mono_loader_lock ();
1980 /* FIXME: The tables can grow indefinitely */
1982 if (mono_gc_is_moving ()) {
1984 * Objects can move, so use a hash table mapping hash codes to lists of
1985 * ObjRef structures.
1987 hash = mono_object_hash (obj);
1989 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1990 for (l = reflist; l; l = l->next) {
1991 ref = (ObjRef *)l->data;
1992 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1993 mono_loader_unlock ();
1998 /* Use a hash table with masked pointers to internalize object references */
1999 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2000 /* ref might refer to a different object with the same addr which was GCd */
2001 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2002 mono_loader_unlock ();
2007 ref = g_new0 (ObjRef, 1);
2008 ref->id = InterlockedIncrement (&objref_id);
2009 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2011 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2013 if (mono_gc_is_moving ()) {
2014 reflist = g_slist_append (reflist, ref);
2015 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2017 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2020 mono_loader_unlock ();
2026 true_pred (gpointer key, gpointer value, gpointer user_data)
2032 clear_suspended_objs (void)
2035 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2040 get_objid (MonoObject *obj)
2045 return get_objref (obj)->id;
2049 * Set OBJ to the object identified by OBJID.
2050 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2054 get_object_allow_null (int objid, MonoObject **obj)
2064 return ERR_INVALID_OBJECT;
2066 mono_loader_lock ();
2068 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2071 *obj = mono_gchandle_get_target (ref->handle);
2072 mono_loader_unlock ();
2074 return ERR_INVALID_OBJECT;
2077 mono_loader_unlock ();
2078 return ERR_INVALID_OBJECT;
2083 get_object (int objid, MonoObject **obj)
2085 ErrorCode err = get_object_allow_null (objid, obj);
2087 if (err != ERR_NONE)
2090 return ERR_INVALID_OBJECT;
2095 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2097 return decode_id (buf, endbuf, limit);
2101 buffer_add_objid (Buffer *buf, MonoObject *o)
2103 buffer_add_id (buf, get_objid (o));
2122 * Represents a runtime structure accessible to the debugger client
2125 /* Unique id used in the wire protocol */
2127 /* Domain of the runtime structure, NULL if the domain was unloaded */
2134 MonoAssembly *assembly;
2135 MonoClassField *field;
2137 MonoProperty *property;
2142 /* Maps runtime structure -> Id */
2143 /* Protected by the dbg lock */
2144 GHashTable *val_to_id [ID_NUM];
2145 /* Classes whose class load event has been sent */
2146 /* Protected by the loader lock */
2147 GHashTable *loaded_classes;
2148 /* Maps MonoClass->GPtrArray of file names */
2149 GHashTable *source_files;
2150 /* Maps source file basename -> GSList of classes */
2151 GHashTable *source_file_to_class;
2152 /* Same with ignore-case */
2153 GHashTable *source_file_to_class_ignorecase;
2157 /* Protected by the dbg lock */
2158 static GPtrArray *ids [ID_NUM];
2165 for (i = 0; i < ID_NUM; ++i)
2166 ids [i] = g_ptr_array_new ();
2174 for (i = 0; i < ID_NUM; ++i) {
2176 for (j = 0; j < ids [i]->len; ++j)
2177 g_free (g_ptr_array_index (ids [i], j));
2178 g_ptr_array_free (ids [i], TRUE);
2185 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2187 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2189 GHashTableIter iter;
2190 GPtrArray *file_names;
2195 for (i = 0; i < ID_NUM; ++i)
2196 if (info->val_to_id [i])
2197 g_hash_table_destroy (info->val_to_id [i]);
2198 g_hash_table_destroy (info->loaded_classes);
2200 g_hash_table_iter_init (&iter, info->source_files);
2201 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2202 for (i = 0; i < file_names->len; ++i)
2203 g_free (g_ptr_array_index (file_names, i));
2204 g_ptr_array_free (file_names, TRUE);
2207 g_hash_table_iter_init (&iter, info->source_file_to_class);
2208 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2213 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2214 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2222 domain_jit_info (domain)->agent_info = NULL;
2224 /* Clear ids referencing structures in the domain */
2226 for (i = 0; i < ID_NUM; ++i) {
2228 for (j = 0; j < ids [i]->len; ++j) {
2229 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2230 if (id->domain == domain)
2237 mono_loader_lock ();
2238 g_hash_table_remove (domains, domain);
2239 mono_loader_unlock ();
2242 static AgentDomainInfo*
2243 get_agent_domain_info (MonoDomain *domain)
2245 AgentDomainInfo *info = NULL;
2247 mono_domain_lock (domain);
2249 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2251 info = g_new0 (AgentDomainInfo, 1);
2252 domain_jit_info (domain)->agent_info = info;
2253 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2254 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2255 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2256 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2259 mono_domain_unlock (domain);
2265 get_id (MonoDomain *domain, IdType type, gpointer val)
2268 AgentDomainInfo *info;
2273 info = get_agent_domain_info (domain);
2277 if (info->val_to_id [type] == NULL)
2278 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2280 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2286 id = g_new0 (Id, 1);
2288 id->id = ids [type]->len + 1;
2289 id->domain = domain;
2292 g_hash_table_insert (info->val_to_id [type], val, id);
2293 g_ptr_array_add (ids [type], id);
2300 static inline gpointer
2301 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2305 int id = decode_id (buf, endbuf, limit);
2314 // FIXME: error handling
2316 g_assert (id > 0 && id <= ids [type]->len);
2318 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2321 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2322 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2323 *err = ERR_UNLOADED;
2328 *domain = res->domain;
2330 return res->data.val;
2334 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2336 int id = get_id (domain, type, val);
2338 buffer_add_id (buf, id);
2342 static inline MonoClass*
2343 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2347 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2348 if (G_UNLIKELY (log_level >= 2) && klass) {
2351 s = mono_type_full_name (&klass->byval_arg);
2352 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2358 static inline MonoAssembly*
2359 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2361 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2364 static inline MonoImage*
2365 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2367 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2370 static inline MonoMethod*
2371 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2375 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2376 if (G_UNLIKELY (log_level >= 2) && m) {
2379 s = mono_method_full_name (m, TRUE);
2380 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2386 static inline MonoClassField*
2387 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2389 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2392 static inline MonoDomain*
2393 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2395 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2398 static inline MonoProperty*
2399 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2401 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2405 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2407 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2408 if (G_UNLIKELY (log_level >= 2) && klass) {
2411 s = mono_type_full_name (&klass->byval_arg);
2412 if (is_debugger_thread ())
2413 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2415 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2421 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2423 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2424 if (G_UNLIKELY (log_level >= 2) && method) {
2427 s = mono_method_full_name (method, 1);
2428 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2434 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2438 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2439 if (G_UNLIKELY (log_level >= 2) && assembly)
2440 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2444 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2446 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2450 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2452 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2456 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2458 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2462 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2464 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2467 static void invoke_method (void);
2474 * save_thread_context:
2476 * Set CTX as the current threads context which is used for computing stack traces.
2477 * This function is signal-safe.
2480 save_thread_context (MonoContext *ctx)
2482 DebuggerTlsData *tls;
2484 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2488 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2490 mono_thread_state_init_from_current (&tls->context);
2493 /* Number of threads suspended */
2495 * If this is equal to the size of thread_to_tls, the runtime is considered
2498 static gint32 threads_suspend_count;
2500 static MonoCoopMutex suspend_mutex;
2502 /* Cond variable used to wait for suspend_count becoming 0 */
2503 static MonoCoopCond suspend_cond;
2505 /* Semaphore used to wait for a thread becoming suspended */
2506 static MonoCoopSem suspend_sem;
2511 mono_coop_mutex_init (&suspend_mutex);
2512 mono_coop_cond_init (&suspend_cond);
2513 mono_coop_sem_init (&suspend_sem, 0);
2518 StackFrameInfo last_frame;
2519 gboolean last_frame_set;
2523 } GetLastFrameUserData;
2526 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2528 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2530 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2533 if (!data->last_frame_set) {
2534 /* Store the last frame */
2535 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2536 data->last_frame_set = TRUE;
2539 /* Store the context/lmf for the frame above the last frame */
2540 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2541 data->lmf = info->lmf;
2542 data->domain = info->domain;
2548 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2550 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2552 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2553 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2554 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2561 * Process interruption of a thread. This should be signal safe.
2563 * This always runs in the debugger thread.
2566 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2569 MonoNativeThreadId tid;
2573 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2574 tid = mono_thread_info_get_tid (info);
2576 // FIXME: Races when the thread leaves managed code before hitting a single step
2579 if (ji && !ji->is_trampoline) {
2580 /* Running managed code, will be suspended by the single step code */
2581 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2584 * Running native code, will be suspended when it returns to/enters
2585 * managed code. Treat it as already suspended.
2586 * This might interrupt the code in process_single_step_inner (), we use the
2587 * tls->suspending flag to avoid races when that happens.
2589 if (!tls->suspended && !tls->suspending) {
2590 GetLastFrameUserData data;
2592 // FIXME: printf is not signal safe, but this is only used during
2593 // debugger debugging
2595 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2596 //save_thread_context (&ctx);
2599 /* Already terminated */
2603 * We are in a difficult position: we want to be able to provide stack
2604 * traces for this thread, but we can't use the current ctx+lmf, since
2605 * the thread is still running, so it might return to managed code,
2606 * making these invalid.
2607 * So we start a stack walk and save the first frame, along with the
2608 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2609 * suspended when it returns to managed code, so the parent's ctx should
2612 data.last_frame_set = FALSE;
2613 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2614 if (data.last_frame_set) {
2615 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2617 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2619 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2620 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2622 tls->async_state.valid = FALSE;
2625 mono_memory_barrier ();
2627 tls->suspended = TRUE;
2628 mono_coop_sem_post (&suspend_sem);
2634 * reset_native_thread_suspend_state:
2636 * Reset the suspended flag and state on native threads
2639 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2641 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2643 if (!tls->really_suspended && tls->suspended) {
2644 tls->suspended = FALSE;
2646 * The thread might still be running if it was executing native code, so the state won't be invalided by
2647 * suspend_current ().
2649 tls->context.valid = FALSE;
2650 tls->async_state.valid = FALSE;
2651 invalidate_frames (tls);
2656 DebuggerTlsData *tls;
2657 gboolean valid_info;
2660 static SuspendThreadResult
2661 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2663 InterruptData *data = (InterruptData *)user_data;
2666 data->valid_info = TRUE;
2667 ji = mono_jit_info_table_find_internal (
2668 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2669 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2673 /* This is signal safe */
2674 thread_interrupt (data->tls, info, ji);
2675 return MonoResumeThread;
2681 * Notify a thread that it needs to suspend.
2684 notify_thread (gpointer key, gpointer value, gpointer user_data)
2686 MonoInternalThread *thread = (MonoInternalThread *)key;
2687 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2688 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2690 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2693 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2695 /* This is _not_ equivalent to mono_thread_internal_abort () */
2696 InterruptData interrupt_data = { 0 };
2697 interrupt_data.tls = tls;
2699 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2700 if (!interrupt_data.valid_info) {
2701 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2703 * Attached thread which died without detaching.
2705 tls->terminated = TRUE;
2710 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2712 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2716 if (mono_loader_lock_is_owned_by_self ()) {
2718 * Shortcut for the check in suspend_current (). This speeds up processing
2719 * when executing long running code inside the loader lock, i.e. assembly load
2725 if (is_debugger_thread ())
2728 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2729 if (suspend_count - tls->resume_count > 0)
2730 tls->suspending = TRUE;
2732 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2734 if (suspend_count - tls->resume_count == 0) {
2736 * We are executing a single threaded invoke but the single step for
2737 * suspending is still active.
2738 * FIXME: This slows down single threaded invokes.
2740 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2744 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2746 /* Can't suspend in these methods */
2747 method = jinfo_get_method (ji);
2748 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2751 save_thread_context (ctx);
2759 * Increase the suspend count of the VM. While the suspend count is greater
2760 * than 0, runtime threads are suspended at certain points during execution.
2765 mono_loader_lock ();
2767 mono_coop_mutex_lock (&suspend_mutex);
2771 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2773 if (suspend_count == 1) {
2774 // FIXME: Is it safe to call this inside the lock ?
2775 start_single_stepping ();
2776 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2779 mono_coop_mutex_unlock (&suspend_mutex);
2781 if (suspend_count == 1)
2783 * Suspend creation of new threadpool threads, since they cannot run
2785 mono_threadpool_suspend ();
2787 mono_loader_unlock ();
2793 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2799 g_assert (is_debugger_thread ());
2801 mono_loader_lock ();
2803 mono_coop_mutex_lock (&suspend_mutex);
2805 g_assert (suspend_count > 0);
2808 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2810 if (suspend_count == 0) {
2811 // FIXME: Is it safe to call this inside the lock ?
2812 stop_single_stepping ();
2813 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2816 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2817 mono_coop_cond_broadcast (&suspend_cond);
2819 mono_coop_mutex_unlock (&suspend_mutex);
2820 //g_assert (err == 0);
2822 if (suspend_count == 0)
2823 mono_threadpool_resume ();
2825 mono_loader_unlock ();
2831 * Resume just one thread.
2834 resume_thread (MonoInternalThread *thread)
2836 DebuggerTlsData *tls;
2838 g_assert (is_debugger_thread ());
2840 mono_loader_lock ();
2842 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2845 mono_coop_mutex_lock (&suspend_mutex);
2847 g_assert (suspend_count > 0);
2849 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2851 tls->resume_count += suspend_count;
2854 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2855 * but only the one whose resume_count field is > 0 will be resumed.
2857 mono_coop_cond_broadcast (&suspend_cond);
2859 mono_coop_mutex_unlock (&suspend_mutex);
2860 //g_assert (err == 0);
2862 mono_loader_unlock ();
2866 free_frames (StackFrame **frames, int nframes)
2870 for (i = 0; i < nframes; ++i) {
2871 if (frames [i]->jit)
2872 mono_debug_free_method_jit_info (frames [i]->jit);
2873 g_free (frames [i]);
2879 invalidate_frames (DebuggerTlsData *tls)
2882 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2885 free_frames (tls->frames, tls->frame_count);
2886 tls->frame_count = 0;
2889 free_frames (tls->restore_frames, tls->restore_frame_count);
2890 tls->restore_frame_count = 0;
2891 tls->restore_frames = NULL;
2897 * Suspend the current thread until the runtime is resumed. If the thread has a
2898 * pending invoke, then the invoke is executed before this function returns.
2901 suspend_current (void)
2903 DebuggerTlsData *tls;
2905 g_assert (!is_debugger_thread ());
2907 if (mono_loader_lock_is_owned_by_self ()) {
2909 * If we own the loader mutex, can't suspend until we release it, since the
2910 * whole runtime can deadlock otherwise.
2915 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2918 mono_coop_mutex_lock (&suspend_mutex);
2920 tls->suspending = FALSE;
2921 tls->really_suspended = TRUE;
2923 if (!tls->suspended) {
2924 tls->suspended = TRUE;
2925 mono_coop_sem_post (&suspend_sem);
2928 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2930 while (suspend_count - tls->resume_count > 0) {
2931 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2934 tls->suspended = FALSE;
2935 tls->really_suspended = FALSE;
2937 threads_suspend_count --;
2939 mono_coop_mutex_unlock (&suspend_mutex);
2941 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2943 if (tls->pending_invoke) {
2944 /* Save the original context */
2945 tls->pending_invoke->has_ctx = TRUE;
2946 tls->pending_invoke->ctx = tls->context.ctx;
2951 /* The frame info becomes invalid after a resume */
2952 tls->context.valid = FALSE;
2953 tls->async_state.valid = FALSE;
2954 invalidate_frames (tls);
2958 count_thread (gpointer key, gpointer value, gpointer user_data)
2960 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2962 if (!tls->suspended && !tls->terminated)
2963 *(int*)user_data = *(int*)user_data + 1;
2967 count_threads_to_wait_for (void)
2971 mono_loader_lock ();
2972 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2973 mono_loader_unlock ();
2981 * Wait until the runtime is completely suspended.
2984 wait_for_suspend (void)
2986 int nthreads, nwait, err;
2987 gboolean waited = FALSE;
2989 // FIXME: Threads starting/stopping ?
2990 mono_loader_lock ();
2991 nthreads = mono_g_hash_table_size (thread_to_tls);
2992 mono_loader_unlock ();
2995 nwait = count_threads_to_wait_for ();
2997 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2998 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2999 g_assert (err == 0);
3007 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3013 * Return whenever the runtime is suspended.
3018 return count_threads_to_wait_for () == 0;
3022 no_seq_points_found (MonoMethod *method, int offset)
3025 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3027 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3031 DebuggerTlsData *tls;
3033 } ComputeFramesUserData;
3036 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3038 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3040 MonoMethod *method, *actual_method, *api_method;
3044 if (info->type != FRAME_TYPE_MANAGED) {
3045 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3046 /* Mark the last frame as an invoke frame */
3048 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3054 method = jinfo_get_method (info->ji);
3056 method = info->method;
3057 actual_method = info->actual_method;
3058 api_method = method;
3063 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3066 if (info->il_offset == -1) {
3067 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3068 if (ud->frames == NULL) {
3069 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3070 info->il_offset = sp.il_offset;
3072 if (info->il_offset == -1)
3073 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3076 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);
3078 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3079 if (!CHECK_PROTOCOL_VERSION (2, 17))
3080 /* Older clients can't handle this flag */
3082 api_method = mono_marshal_method_from_wrapper (method);
3085 actual_method = api_method;
3086 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3089 frame = g_new0 (StackFrame, 1);
3090 frame->method = method;
3091 frame->actual_method = actual_method;
3092 frame->api_method = api_method;
3093 frame->il_offset = info->il_offset;
3094 frame->native_offset = info->native_offset;
3095 frame->flags = flags;
3096 frame->ji = info->ji;
3097 if (info->reg_locations)
3098 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3101 frame->has_ctx = TRUE;
3103 frame->domain = info->domain;
3105 ud->frames = g_slist_append (ud->frames, frame);
3111 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3113 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3116 * 'tls->filter_ctx' is the location of the throw site.
3118 * mono_walk_stack() will never actually hit the throw site, but unwind
3119 * directly from the filter to the call site; we abort stack unwinding here
3120 * once this happens and resume from the throw site.
3123 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3126 return process_frame (info, ctx, user_data);
3130 * Return a malloc-ed list of StackFrame structures.
3133 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3135 ComputeFramesUserData user_data;
3136 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3141 user_data.tls = tls;
3142 user_data.frames = NULL;
3144 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3146 nframes = g_slist_length (user_data.frames);
3147 res = g_new0 (StackFrame*, nframes);
3148 l = user_data.frames;
3149 for (i = 0; i < nframes; ++i) {
3150 res [i] = (StackFrame *)l->data;
3153 *out_nframes = nframes;
3159 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3161 ComputeFramesUserData user_data;
3163 int i, findex, new_frame_count;
3164 StackFrame **new_frames, *f;
3165 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3167 // FIXME: Locking on tls
3168 if (tls->frames && tls->frames_up_to_date)
3171 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3173 user_data.tls = tls;
3174 user_data.frames = NULL;
3175 if (tls->terminated) {
3176 tls->frame_count = 0;
3178 } if (!tls->really_suspended && tls->async_state.valid) {
3179 /* Have to use the state saved by the signal handler */
3180 process_frame (&tls->async_last_frame, NULL, &user_data);
3181 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3182 } else if (tls->filter_state.valid) {
3184 * We are inside an exception filter.
3186 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3188 if (tls->context.valid)
3189 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3191 * After that, we resume unwinding from the location where the exception has been thrown.
3193 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3194 } else if (tls->context.valid) {
3195 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3198 tls->frame_count = 0;
3202 new_frame_count = g_slist_length (user_data.frames);
3203 new_frames = g_new0 (StackFrame*, new_frame_count);
3205 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3206 f = (StackFrame *)tmp->data;
3209 * Reuse the id for already existing stack frames, so invokes don't invalidate
3210 * the still valid stack frames.
3212 for (i = 0; i < tls->frame_count; ++i) {
3213 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3214 f->id = tls->frames [i]->id;
3219 if (i >= tls->frame_count)
3220 f->id = InterlockedIncrement (&frame_id);
3222 new_frames [findex ++] = f;
3225 g_slist_free (user_data.frames);
3227 invalidate_frames (tls);
3229 tls->frames = new_frames;
3230 tls->frame_count = new_frame_count;
3231 tls->frames_up_to_date = TRUE;
3235 * GHFunc to emit an appdomain creation event
3236 * @param key Don't care
3237 * @param value A loaded appdomain
3238 * @param user_data Don't care
3241 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3243 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3244 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3248 * GHFunc to emit a thread start event
3249 * @param key A thread id
3250 * @param value A thread object
3251 * @param user_data Don't care
3254 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3256 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3257 process_profiler_event (EVENT_KIND_THREAD_START, value);
3261 * GFunc to emit an assembly load event
3262 * @param value A loaded assembly
3263 * @param user_data Don't care
3266 emit_assembly_load (gpointer value, gpointer user_data)
3268 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3272 * GFunc to emit a type load event
3273 * @param value A loaded type
3274 * @param user_data Don't care
3277 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3279 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3283 strdup_tolower (char *s)
3288 for (p = s2; *p; ++p)
3294 * Same as g_path_get_basename () but handles windows paths as well,
3295 * which can occur in .mdb files created by pdb2mdb.
3298 dbg_path_get_basename (const char *filename)
3302 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3303 return g_path_get_basename (filename);
3307 /* No separator -> filename */
3308 r = strrchr (filename, '\\');
3310 return g_strdup (filename);
3312 /* Trailing slash, remove component */
3314 char *copy = g_strdup (filename);
3315 copy [r-filename] = 0;
3316 r = strrchr (copy, '\\');
3320 return g_strdup ("/");
3322 r = g_strdup (&r[1]);
3327 return g_strdup (&r[1]);
3331 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3333 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3335 MonoCustomAttrInfo *ainfo;
3337 if (ji->dbg_attrs_inited)
3341 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3343 if (!step_through_klass)
3344 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3346 if (!non_user_klass)
3347 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3349 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3350 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3352 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3353 ji->dbg_hidden = TRUE;
3354 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3355 ji->dbg_step_through = TRUE;
3356 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3357 ji->dbg_non_user_code = TRUE;
3358 mono_custom_attrs_free (ainfo);
3361 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3362 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3364 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3365 ji->dbg_step_through = TRUE;
3366 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3367 ji->dbg_non_user_code = TRUE;
3368 mono_custom_attrs_free (ainfo);
3371 mono_memory_barrier ();
3372 ji->dbg_attrs_inited = TRUE;
3380 * create_event_list:
3382 * Return a list of event request ids matching EVENT, starting from REQS, which
3383 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3385 * We return request ids, instead of requests, to simplify threading, since
3386 * requests could be deleted anytime when the loader lock is not held.
3387 * LOCKING: Assumes the loader lock is held.
3390 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3393 GSList *events = NULL;
3395 *suspend_policy = SUSPEND_POLICY_NONE;
3398 reqs = event_requests;
3403 for (i = 0; i < reqs->len; ++i) {
3404 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3405 if (req->event_kind == event) {
3406 gboolean filtered = FALSE;
3409 for (j = 0; j < req->nmodifiers; ++j) {
3410 Modifier *mod = &req->modifiers [j];
3412 if (mod->kind == MOD_KIND_COUNT) {
3414 if (mod->data.count > 0) {
3415 if (mod->data.count > 0) {
3417 if (mod->data.count == 0)
3421 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3422 if (mod->data.thread != mono_thread_internal_current ())
3424 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3425 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3427 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3429 if (ei->caught && !mod->caught)
3431 if (!ei->caught && !mod->uncaught)
3433 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3435 gboolean found = FALSE;
3436 MonoAssembly **assemblies = mod->data.assemblies;
3439 for (k = 0; assemblies [k]; ++k)
3440 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3445 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3446 gpointer iter = NULL;
3448 MonoDebugSourceInfo *sinfo;
3449 char *source_file, *s;
3450 gboolean found = FALSE;
3452 GPtrArray *source_file_list;
3454 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3455 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3458 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3459 for (i = 0; i < source_file_list->len; ++i) {
3460 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3462 * Do a case-insesitive match by converting the file name to
3465 s = strdup_tolower (sinfo->source_file);
3466 if (g_hash_table_lookup (mod->data.source_files, s))
3469 char *s2 = dbg_path_get_basename (sinfo->source_file);
3470 char *s3 = strdup_tolower (s2);
3472 if (g_hash_table_lookup (mod->data.source_files, s3))
3479 g_ptr_array_free (source_file_list, TRUE);
3484 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3487 s = mono_type_full_name (&ei->klass->byval_arg);
3488 if (!g_hash_table_lookup (mod->data.type_names, s))
3491 } else if (mod->kind == MOD_KIND_STEP) {
3492 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3493 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3494 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3495 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3497 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3498 init_jit_info_dbg_attrs (ji);
3502 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3503 init_jit_info_dbg_attrs (ji);
3504 if (ji->dbg_step_through)
3507 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3508 init_jit_info_dbg_attrs (ji);
3509 if (ji->dbg_non_user_code)
3516 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3517 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3522 /* Send a VM START/DEATH event by default */
3523 if (event == EVENT_KIND_VM_START)
3524 events = g_slist_append (events, GINT_TO_POINTER (0));
3525 if (event == EVENT_KIND_VM_DEATH)
3526 events = g_slist_append (events, GINT_TO_POINTER (0));
3531 static G_GNUC_UNUSED const char*
3532 event_to_string (EventKind event)
3535 case EVENT_KIND_VM_START: return "VM_START";
3536 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3537 case EVENT_KIND_THREAD_START: return "THREAD_START";
3538 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3539 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3540 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3541 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3542 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3543 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3544 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3545 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3546 case EVENT_KIND_STEP: return "STEP";
3547 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3548 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3549 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3550 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3551 case EVENT_KIND_USER_LOG: return "USER_LOG";
3553 g_assert_not_reached ();
3561 * Send an event to the client, suspending the vm if needed.
3562 * LOCKING: Since this can suspend the calling thread, no locks should be held
3564 * The EVENTS list is freed by this function.
3567 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3571 MonoDomain *domain = mono_domain_get ();
3572 MonoThread *thread = NULL;
3573 MonoObject *keepalive_obj = NULL;
3574 gboolean send_success = FALSE;
3579 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3583 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3584 // FIXME: We miss those events
3585 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3589 if (vm_death_event_sent) {
3590 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3594 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3595 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3600 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3604 if (event == EVENT_KIND_KEEPALIVE)
3605 suspend_policy = SUSPEND_POLICY_NONE;
3610 if (agent_config.defer) {
3611 /* Make sure the thread id is always set when doing deferred debugging */
3612 if (is_debugger_thread ()) {
3613 /* Don't suspend on events from the debugger thread */
3614 suspend_policy = SUSPEND_POLICY_NONE;
3615 thread = mono_thread_get_main ();
3617 else thread = mono_thread_current ();
3619 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3620 // FIXME: Send these with a NULL thread, don't suspend the current thread
3625 nevents = g_slist_length (events);
3626 buffer_init (&buf, 128);
3627 buffer_add_byte (&buf, suspend_policy);
3628 buffer_add_int (&buf, nevents);
3630 for (l = events; l; l = l->next) {
3631 buffer_add_byte (&buf, event); // event kind
3632 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3636 if (event == EVENT_KIND_VM_DEATH) {
3640 thread = mono_thread_current ();
3642 if (event == EVENT_KIND_VM_START && arg != NULL)
3643 thread = (MonoThread *)arg;
3646 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3649 case EVENT_KIND_THREAD_START:
3650 case EVENT_KIND_THREAD_DEATH:
3652 case EVENT_KIND_APPDOMAIN_CREATE:
3653 case EVENT_KIND_APPDOMAIN_UNLOAD:
3654 buffer_add_domainid (&buf, (MonoDomain *)arg);
3656 case EVENT_KIND_METHOD_ENTRY:
3657 case EVENT_KIND_METHOD_EXIT:
3658 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3660 case EVENT_KIND_ASSEMBLY_LOAD:
3661 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3663 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3664 DebuggerTlsData *tls;
3666 /* The domain the assembly belonged to is not equal to the current domain */
3667 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3669 g_assert (tls->domain_unloading);
3671 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3674 case EVENT_KIND_TYPE_LOAD:
3675 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3677 case EVENT_KIND_BREAKPOINT:
3678 case EVENT_KIND_STEP:
3679 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3680 buffer_add_long (&buf, il_offset);
3682 case EVENT_KIND_VM_START:
3683 buffer_add_domainid (&buf, mono_get_root_domain ());
3685 case EVENT_KIND_VM_DEATH:
3686 if (CHECK_PROTOCOL_VERSION (2, 27))
3687 buffer_add_int (&buf, mono_environment_exitcode_get ());
3689 case EVENT_KIND_EXCEPTION: {
3690 EventInfo *ei = (EventInfo *)arg;
3691 buffer_add_objid (&buf, ei->exc);
3693 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3694 * later after the suspension. (#12494).
3696 keepalive_obj = ei->exc;
3699 case EVENT_KIND_USER_BREAK:
3701 case EVENT_KIND_USER_LOG: {
3702 EventInfo *ei = (EventInfo *)arg;
3703 buffer_add_int (&buf, ei->level);
3704 buffer_add_string (&buf, ei->category ? ei->category : "");
3705 buffer_add_string (&buf, ei->message ? ei->message : "");
3708 case EVENT_KIND_KEEPALIVE:
3709 suspend_policy = SUSPEND_POLICY_NONE;
3712 g_assert_not_reached ();
3716 if (event == EVENT_KIND_VM_START) {
3717 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3718 if (!agent_config.defer)
3719 start_debugger_thread ();
3722 if (event == EVENT_KIND_VM_DEATH) {
3723 vm_death_event_sent = TRUE;
3724 suspend_policy = SUSPEND_POLICY_NONE;
3727 if (mono_runtime_is_shutting_down ())
3728 suspend_policy = SUSPEND_POLICY_NONE;
3730 if (suspend_policy != SUSPEND_POLICY_NONE) {
3732 * Save the thread context and start suspending before sending the packet,
3733 * since we could be receiving the resume request before send_packet ()
3736 save_thread_context (ctx);
3740 /* This will keep this object alive */
3741 get_objref (keepalive_obj);
3744 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3748 g_slist_free (events);
3751 if (!send_success) {
3752 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3756 if (event == EVENT_KIND_VM_START) {
3757 vm_start_event_sent = TRUE;
3760 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);
3762 switch (suspend_policy) {
3763 case SUSPEND_POLICY_NONE:
3765 case SUSPEND_POLICY_ALL:
3768 case SUSPEND_POLICY_EVENT_THREAD:
3772 g_assert_not_reached ();
3777 process_profiler_event (EventKind event, gpointer arg)
3781 EventInfo ei, *ei_arg = NULL;
3783 if (event == EVENT_KIND_TYPE_LOAD) {
3784 ei.klass = (MonoClass *)arg;
3788 mono_loader_lock ();
3789 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3790 mono_loader_unlock ();
3792 process_event (event, arg, 0, NULL, events, suspend_policy);
3796 runtime_initialized (MonoProfiler *prof)
3798 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3799 if (agent_config.defer)
3800 start_debugger_thread ();
3804 runtime_shutdown (MonoProfiler *prof)
3806 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3808 mono_debugger_agent_cleanup ();
3812 thread_startup (MonoProfiler *prof, uintptr_t tid)
3814 MonoInternalThread *thread = mono_thread_internal_current ();
3815 MonoInternalThread *old_thread;
3816 DebuggerTlsData *tls;
3818 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3821 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3823 mono_loader_lock ();
3824 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3825 mono_loader_unlock ();
3827 if (thread == old_thread) {
3829 * For some reason, thread_startup () might be called for the same thread
3830 * multiple times (attach ?).
3832 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3836 * thread_end () might not be called for some threads, and the tid could
3839 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3840 mono_loader_lock ();
3841 mono_g_hash_table_remove (thread_to_tls, old_thread);
3842 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3843 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3844 mono_loader_unlock ();
3848 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3850 // FIXME: Free this somewhere
3851 tls = g_new0 (DebuggerTlsData, 1);
3852 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3853 tls->thread = thread;
3854 mono_native_tls_set_value (debugger_tls_id, tls);
3856 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3858 mono_loader_lock ();
3859 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3860 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3861 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3862 mono_loader_unlock ();
3864 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3867 * suspend_vm () could have missed this thread, so wait for a resume.
3873 thread_end (MonoProfiler *prof, uintptr_t tid)
3875 MonoInternalThread *thread;
3876 DebuggerTlsData *tls = NULL;
3878 mono_loader_lock ();
3879 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3881 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3882 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3884 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3885 tls->terminated = TRUE;
3886 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3887 MONO_GC_UNREGISTER_ROOT (tls->thread);
3891 mono_loader_unlock ();
3893 /* We might be called for threads started before we registered the start callback */
3895 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3897 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3898 && !mono_native_tls_get_value (debugger_tls_id)
3901 * This can happen on darwin since we deregister threads using pthread dtors.
3902 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3907 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3912 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3914 mono_loader_lock ();
3915 g_hash_table_insert (domains, domain, domain);
3916 mono_loader_unlock ();
3918 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3922 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3924 DebuggerTlsData *tls;
3926 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3927 if (is_debugger_thread ())
3931 * Remember the currently unloading appdomain as it is needed to generate
3932 * proper ids for unloading assemblies.
3934 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3936 tls->domain_unloading = domain;
3940 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3942 DebuggerTlsData *tls;
3944 if (is_debugger_thread ())
3947 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3949 tls->domain_unloading = NULL;
3951 clear_breakpoints_for_domain (domain);
3953 mono_loader_lock ();
3954 /* Invalidate each thread's frame stack */
3955 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3956 mono_loader_unlock ();
3958 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3962 * invalidate_each_thread:
3964 * A GHFunc to invalidate frames.
3965 * value must be a DebuggerTlsData*
3968 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3970 invalidate_frames ((DebuggerTlsData *)value);
3974 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3976 /* Sent later in jit_end () */
3978 g_ptr_array_add (pending_assembly_loads, assembly);
3983 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3985 if (is_debugger_thread ())
3988 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3990 clear_event_requests_for_assembly (assembly);
3991 clear_types_for_assembly (assembly);
3995 send_type_load (MonoClass *klass)
3997 gboolean type_load = FALSE;
3998 MonoDomain *domain = mono_domain_get ();
3999 AgentDomainInfo *info = NULL;
4001 info = get_agent_domain_info (domain);
4003 mono_loader_lock ();
4005 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4007 g_hash_table_insert (info->loaded_classes, klass, klass);
4010 mono_loader_unlock ();
4013 emit_type_load (klass, klass, NULL);
4017 * Emit load events for all types currently loaded in the domain.
4018 * Takes the loader and domain locks.
4019 * user_data is unused.
4022 send_types_for_domain (MonoDomain *domain, void *user_data)
4024 MonoDomain* old_domain;
4025 AgentDomainInfo *info = NULL;
4027 info = get_agent_domain_info (domain);
4030 old_domain = mono_domain_get ();
4032 mono_domain_set (domain, TRUE);
4034 mono_loader_lock ();
4035 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4036 mono_loader_unlock ();
4038 mono_domain_set (old_domain, TRUE);
4042 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4045 MonoDomain* old_domain;
4047 old_domain = mono_domain_get ();
4049 mono_domain_set (domain, TRUE);
4051 mono_domain_assemblies_lock (domain);
4052 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4053 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4054 emit_assembly_load (ass, NULL);
4056 mono_domain_assemblies_unlock (domain);
4058 mono_domain_set (old_domain, TRUE);
4062 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4065 * We emit type load events when the first method of the type is JITted,
4066 * since the class load profiler callbacks might be called with the
4067 * loader lock held. They could also occur in the debugger thread.
4068 * Same for assembly load events.
4071 MonoAssembly *assembly = NULL;
4073 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4075 if (pending_assembly_loads->len > 0) {
4076 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4077 g_ptr_array_remove_index (pending_assembly_loads, 0);
4082 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4088 send_type_load (method->klass);
4091 add_pending_breakpoints (method, jinfo);
4095 * BREAKPOINTS/SINGLE STEPPING
4099 * Contains information about an inserted breakpoint.
4102 long il_offset, native_offset;
4106 } BreakpointInstance;
4109 * Contains generic information about a breakpoint.
4113 * The method where the breakpoint is placed. Can be NULL in which case it
4114 * is inserted into every method. This is used to implement method entry/
4115 * exit events. Can be a generic method definition, in which case the
4116 * breakpoint is inserted into every instance.
4122 * A list of BreakpointInstance structures describing where the breakpoint
4123 * was inserted. There could be more than one because of
4124 * generics/appdomains/method entry/exit.
4126 GPtrArray *children;
4129 /* List of breakpoints */
4130 /* Protected by the loader lock */
4131 static GPtrArray *breakpoints;
4132 /* Maps breakpoint locations to the number of breakpoints at that location */
4133 static GHashTable *bp_locs;
4136 breakpoints_init (void)
4138 breakpoints = g_ptr_array_new ();
4139 bp_locs = g_hash_table_new (NULL, NULL);
4143 * insert_breakpoint:
4145 * Insert the breakpoint described by BP into the method described by
4149 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4152 BreakpointInstance *inst;
4153 SeqPointIterator it;
4154 gboolean it_has_sp = FALSE;
4157 mono_error_init (error);
4159 mono_seq_point_iterator_init (&it, seq_points);
4160 while (mono_seq_point_iterator_next (&it)) {
4161 if (it.seq_point.il_offset == bp->il_offset) {
4169 * The set of IL offsets with seq points doesn't completely match the
4170 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4172 mono_seq_point_iterator_init (&it, seq_points);
4173 while (mono_seq_point_iterator_next (&it)) {
4174 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4175 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4176 it.seq_point.il_offset + 1 == bp->il_offset) {
4184 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4186 mono_seq_point_iterator_init (&it, seq_points);
4187 while (mono_seq_point_iterator_next (&it))
4188 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4191 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4192 g_warning ("%s", s);
4196 g_warning ("%s", s);
4202 inst = g_new0 (BreakpointInstance, 1);
4203 inst->il_offset = it.seq_point.il_offset;
4204 inst->native_offset = it.seq_point.native_offset;
4205 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4207 inst->domain = domain;
4209 mono_loader_lock ();
4211 g_ptr_array_add (bp->children, inst);
4213 mono_loader_unlock ();
4216 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4217 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4220 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4221 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4222 } else if (count == 0) {
4223 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4224 mono_arch_set_breakpoint (ji, inst->ip);
4230 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);
4234 remove_breakpoint (BreakpointInstance *inst)
4236 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4238 MonoJitInfo *ji = inst->ji;
4239 guint8 *ip = inst->ip;
4242 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4243 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4246 g_assert (count > 0);
4248 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4249 mono_arch_clear_breakpoint (ji, ip);
4250 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4258 * This doesn't take any locks.
4260 static inline gboolean
4261 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4267 if (method == bp->method)
4269 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4272 if (bp->method->is_inflated && method->is_inflated) {
4273 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4274 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4276 /* Open generic methods should match closed generic methods of the same class */
4277 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4278 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4279 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4281 /* FIXME: Handle !mvar */
4282 if (t1->type != MONO_TYPE_MVAR)
4293 * add_pending_breakpoints:
4295 * Insert pending breakpoints into the newly JITted method METHOD.
4298 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4301 MonoSeqPointInfo *seq_points;
4303 MonoMethod *jmethod;
4308 domain = mono_domain_get ();
4310 mono_loader_lock ();
4312 for (i = 0; i < breakpoints->len; ++i) {
4313 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4314 gboolean found = FALSE;
4316 if (!bp_matches_method (bp, method))
4319 for (j = 0; j < bp->children->len; ++j) {
4320 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4327 MonoMethod *declaring = NULL;
4329 jmethod = jinfo_get_method (ji);
4330 if (jmethod->is_inflated)
4331 declaring = mono_method_get_declaring_generic_method (jmethod);
4333 mono_domain_lock (domain);
4334 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4335 if (!seq_points && declaring)
4336 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4337 mono_domain_unlock (domain);
4339 /* Could be AOT code */
4341 g_assert (seq_points);
4343 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4347 mono_loader_unlock ();
4351 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4357 mono_error_init (error);
4359 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4363 /* Might be AOTed code */
4364 mono_class_init (method->klass);
4365 code = mono_aot_get_method_checked (domain, method, &oerror);
4367 mono_error_assert_ok (&oerror);
4368 ji = mono_jit_info_table_find (domain, (char *)code);
4373 insert_breakpoint (seq_points, domain, ji, bp, error);
4377 clear_breakpoint (MonoBreakpoint *bp);
4382 * Set a breakpoint at IL_OFFSET in METHOD.
4383 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4384 * METHOD can also be a generic method definition, in which case a breakpoint
4385 * is placed in all instances of the method.
4386 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4389 static MonoBreakpoint*
4390 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4393 GHashTableIter iter, iter2;
4396 MonoSeqPointInfo *seq_points;
4398 GPtrArray *method_domains;
4399 GPtrArray *method_seq_points;
4403 mono_error_init (error);
4406 // - suspend/resume the vm to prevent code patching problems
4407 // - multiple breakpoints on the same location
4408 // - dynamic methods
4411 bp = g_new0 (MonoBreakpoint, 1);
4412 bp->method = method;
4413 bp->il_offset = il_offset;
4415 bp->children = g_ptr_array_new ();
4417 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);
4419 methods = g_ptr_array_new ();
4420 method_domains = g_ptr_array_new ();
4421 method_seq_points = g_ptr_array_new ();
4423 mono_loader_lock ();
4424 g_hash_table_iter_init (&iter, domains);
4425 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4426 mono_domain_lock (domain);
4427 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4428 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4429 if (bp_matches_method (bp, m)) {
4430 /* Save the info locally to simplify the code inside the domain lock */
4431 g_ptr_array_add (methods, m);
4432 g_ptr_array_add (method_domains, domain);
4433 g_ptr_array_add (method_seq_points, seq_points);
4436 mono_domain_unlock (domain);
4439 for (i = 0; i < methods->len; ++i) {
4440 m = (MonoMethod *)g_ptr_array_index (methods, i);
4441 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4442 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4443 set_bp_in_method (domain, m, seq_points, bp, error);
4446 g_ptr_array_add (breakpoints, bp);
4447 mono_loader_unlock ();
4449 g_ptr_array_free (methods, TRUE);
4450 g_ptr_array_free (method_domains, TRUE);
4451 g_ptr_array_free (method_seq_points, TRUE);
4453 if (error && !mono_error_ok (error)) {
4454 clear_breakpoint (bp);
4462 clear_breakpoint (MonoBreakpoint *bp)
4466 // FIXME: locking, races
4467 for (i = 0; i < bp->children->len; ++i) {
4468 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4470 remove_breakpoint (inst);
4475 mono_loader_lock ();
4476 g_ptr_array_remove (breakpoints, bp);
4477 mono_loader_unlock ();
4479 g_ptr_array_free (bp->children, TRUE);
4484 breakpoints_cleanup (void)
4488 mono_loader_lock ();
4490 while (i < event_requests->len) {
4491 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4493 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4494 clear_breakpoint ((MonoBreakpoint *)req->info);
4495 g_ptr_array_remove_index_fast (event_requests, i);
4502 for (i = 0; i < breakpoints->len; ++i)
4503 g_free (g_ptr_array_index (breakpoints, i));
4505 g_ptr_array_free (breakpoints, TRUE);
4506 g_hash_table_destroy (bp_locs);
4511 mono_loader_unlock ();
4515 * clear_breakpoints_for_domain:
4517 * Clear breakpoint instances which reference DOMAIN.
4520 clear_breakpoints_for_domain (MonoDomain *domain)
4524 /* This could be called after shutdown */
4528 mono_loader_lock ();
4529 for (i = 0; i < breakpoints->len; ++i) {
4530 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4533 while (j < bp->children->len) {
4534 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4536 if (inst->domain == domain) {
4537 remove_breakpoint (inst);
4541 g_ptr_array_remove_index_fast (bp->children, j);
4547 mono_loader_unlock ();
4551 * ss_calculate_framecount:
4553 * Ensure DebuggerTlsData fields are filled out.
4555 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4557 if (!tls->context.valid)
4558 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4559 compute_frame_info (tls->thread, tls);
4563 ensure_jit (StackFrame* frame)
4566 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4567 if (!frame->jit && frame->api_method->is_inflated)
4568 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4572 /* This could happen for aot images with no jit debug info */
4573 s = mono_method_full_name (frame->api_method, TRUE);
4574 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4585 * Return FALSE if single stepping needs to continue.
4588 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4590 MonoDebugMethodInfo *minfo;
4591 MonoDebugSourceLocation *loc = NULL;
4592 gboolean hit = TRUE;
4594 if (req->async_stepout_method == method) {
4595 DEBUG_PRINTF (1, "[%p] Breakpoint hit during async step-out at %s hit, continuing stepping out.\n", (gpointer)(gsize)mono_native_thread_id_get (), method->name);
4599 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4601 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4603 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);
4607 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4608 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4610 ss_calculate_framecount (tls, ctx);
4612 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4613 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4614 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4615 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4616 /* Hit the breakpoint in a recursive call, don't halt */
4617 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping %s, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), is_step_out ? "out" : "over");
4622 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4623 ss_calculate_framecount (tls, ctx);
4624 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4625 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);
4630 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4632 for (int i = 0; i < asyncMethod->num_awaits; i++)
4634 if (asyncMethod->yield_offsets[i] == sp->il_offset || asyncMethod->resume_offsets[i] == sp->il_offset) {
4635 mono_debug_free_method_async_debug_info (asyncMethod);
4639 mono_debug_free_method_async_debug_info (asyncMethod);
4642 if (req->size != STEP_SIZE_LINE)
4645 /* Have to check whenever a different source line was reached */
4646 minfo = mono_debug_lookup_method (method);
4649 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4652 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);
4653 ss_req->last_method = method;
4655 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4656 ss_calculate_framecount (tls, ctx);
4657 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4658 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4664 ss_req->last_method = method;
4665 ss_req->last_line = loc->row;
4666 mono_debug_free_source_location (loc);
4673 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4675 return bp->method && bp->method->klass->image->assembly == assembly;
4679 get_this (StackFrame *frame)
4681 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4682 MonoDebugVarInfo *var = frame->jit->this_var;
4683 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4686 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4687 addr += (gint32)var->offset;
4688 return *(MonoObject**)addr;
4691 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4692 //since thread probably changed...
4694 get_this_async_id (StackFrame *frame)
4696 return get_objid (get_this (frame));
4699 static MonoMethod* set_notification_method_cache = NULL;
4702 get_set_notification_method ()
4704 if(set_notification_method_cache != NULL)
4705 return set_notification_method_cache;
4707 MonoClass* async_builder_class = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder");
4708 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4709 mono_error_assert_ok (&error);
4710 g_assert (array->len == 1);
4711 set_notification_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4712 g_ptr_array_free (array, TRUE);
4713 return set_notification_method_cache;
4717 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4719 MonoObject* obj = get_this (frame);
4721 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4722 g_assert (builder_field);
4723 MonoObject* builder;
4725 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4726 mono_error_assert_ok (&error);
4730 gboolean arg = TRUE;
4732 mono_runtime_invoke_checked (get_set_notification_method(), mono_object_unbox (builder), args, &error);
4733 mono_error_assert_ok (&error);
4734 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4737 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4740 get_notify_debugger_of_wait_completion_method ()
4742 if (notify_debugger_of_wait_completion_method_cache != NULL)
4743 return notify_debugger_of_wait_completion_method_cache;
4745 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4746 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4747 mono_error_assert_ok (&error);
4748 g_assert (array->len == 1);
4749 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4750 g_ptr_array_free (array, TRUE);
4751 return notify_debugger_of_wait_completion_method_cache;
4755 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4759 int i, j, suspend_policy;
4760 guint32 native_offset;
4762 BreakpointInstance *inst;
4763 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4764 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4765 EventKind kind = EVENT_KIND_BREAKPOINT;
4766 MonoContext *ctx = &tls->restore_state.ctx;
4768 MonoSeqPointInfo *info;
4772 // FIXME: Speed this up
4774 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4775 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4776 g_assert (ji && !ji->is_trampoline);
4777 method = jinfo_get_method (ji);
4779 /* Compute the native offset of the breakpoint from the ip */
4780 native_offset = ip - (guint8*)ji->code_start;
4783 * Skip the instruction causing the breakpoint signal.
4786 mono_arch_skip_breakpoint (ctx, ji);
4788 if (method->wrapper_type || tls->disable_breakpoints)
4791 bp_reqs = g_ptr_array_new ();
4792 ss_reqs = g_ptr_array_new ();
4793 ss_reqs_orig = g_ptr_array_new ();
4795 mono_loader_lock ();
4798 * The ip points to the instruction causing the breakpoint event, which is after
4799 * the offset recorded in the seq point map, so find the prev seq point before ip.
4801 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4804 no_seq_points_found (method, native_offset);
4806 g_assert (found_sp);
4808 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);
4811 for (i = 0; i < breakpoints->len; ++i) {
4812 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4817 for (j = 0; j < bp->children->len; ++j) {
4818 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4819 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4820 if (bp->req->event_kind == EVENT_KIND_STEP) {
4821 g_ptr_array_add (ss_reqs_orig, bp->req);
4823 g_ptr_array_add (bp_reqs, bp->req);
4828 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4829 /* Maybe a method entry/exit event */
4830 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4831 kind = EVENT_KIND_METHOD_ENTRY;
4832 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4833 kind = EVENT_KIND_METHOD_EXIT;
4836 /* Process single step requests */
4837 for (i = 0; i < ss_reqs_orig->len; ++i) {
4838 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4839 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4842 //if we hit async_stepout_method, it's our no matter which thread
4843 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4844 //We have different thread and we don't have async stepping in progress
4845 //it's breakpoint in parallel thread, ignore it
4846 if (ss_req->async_id == 0)
4849 tls->context.valid = FALSE;
4850 tls->async_state.valid = FALSE;
4851 invalidate_frames (tls);
4852 ss_calculate_framecount(tls, ctx);
4853 //make sure we have enough data to get current async method instance id
4854 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4857 //Check method is async before calling get_this_async_id
4858 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4862 mono_debug_free_method_async_debug_info (asyncMethod);
4864 //breakpoint was hit in parallelly executing async method, ignore it
4865 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4869 //Update stepping request to new thread/frame_count that we are continuing on
4870 //so continuing with normal stepping works as expected
4871 if (ss_req->async_stepout_method || ss_req->async_id) {
4872 tls->context.valid = FALSE;
4873 tls->async_state.valid = FALSE;
4874 invalidate_frames (tls);
4875 ss_calculate_framecount (tls, ctx);
4876 ss_req->thread = mono_thread_internal_current ();
4877 ss_req->nframes = tls->frame_count;
4880 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4882 g_ptr_array_add (ss_reqs, req);
4884 /* Start single stepping again from the current sequence point */
4885 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4888 if (ss_reqs->len > 0)
4889 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4890 if (bp_reqs->len > 0)
4891 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4892 if (kind != EVENT_KIND_BREAKPOINT)
4893 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4895 mono_loader_unlock ();
4897 g_ptr_array_free (bp_reqs, TRUE);
4898 g_ptr_array_free (ss_reqs, TRUE);
4901 * FIXME: The first event will suspend, so the second will only be sent after the
4905 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4907 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4908 if (enter_leave_events)
4909 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4912 /* Process a breakpoint/single step event after resuming from a signal handler */
4914 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4916 DebuggerTlsData *tls;
4917 MonoThreadUnwindState orig_restore_state;
4920 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4921 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4922 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4923 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4927 /* This is called when resuming from a signal handler, so it shouldn't return */
4928 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4929 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4930 mono_restore_context (&ctx);
4931 g_assert_not_reached ();
4935 process_breakpoint (void)
4937 process_signal_event (process_breakpoint_inner);
4941 resume_from_signal_handler (void *sigctx, void *func)
4943 DebuggerTlsData *tls;
4946 /* Save the original context in TLS */
4947 // FIXME: This might not work on an altstack ?
4948 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4950 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4953 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4954 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4955 // clob:c could be added to op_seq_point.
4957 mono_sigctx_to_monoctx (sigctx, &ctx);
4958 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4959 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4960 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4962 MONO_CONTEXT_SET_IP (&ctx, func);
4964 mono_monoctx_to_sigctx (&ctx, sigctx);
4966 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4967 mono_ppc_set_func_into_sigctx (sigctx, func);
4972 mono_debugger_agent_breakpoint_hit (void *sigctx)
4975 * We are called from a signal handler, and running code there causes all kinds of
4976 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4977 * So set up the signal context to return to the real breakpoint handler function.
4979 resume_from_signal_handler (sigctx, process_breakpoint);
4983 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4985 if (frame->managed) {
4986 *(MonoContext*)data = *ctx;
4995 * Called by System.Diagnostics.Debugger:Break ().
4998 mono_debugger_agent_user_break (void)
5000 if (agent_config.enabled) {
5005 /* Obtain a context */
5006 MONO_CONTEXT_SET_IP (&ctx, NULL);
5007 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
5008 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
5010 mono_loader_lock ();
5011 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5012 mono_loader_unlock ();
5014 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5015 } else if (debug_options.native_debugger_break) {
5021 ss_depth_to_string (StepDepth depth)
5024 case STEP_DEPTH_OVER:
5026 case STEP_DEPTH_OUT:
5028 case STEP_DEPTH_INTO:
5031 g_assert_not_reached ();
5037 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5042 int il_offset, suspend_policy;
5045 MonoContext *ctx = &tls->restore_state.ctx;
5048 MonoSeqPointInfo *info;
5050 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5052 /* Skip the instruction causing the single step */
5054 mono_arch_skip_single_step (ctx);
5056 if (suspend_count > 0) {
5057 /* Fastpath during invokes, see in process_suspend () */
5058 if (suspend_count - tls->resume_count == 0)
5060 process_suspend (tls, ctx);
5065 // FIXME: A suspend race
5068 if (mono_thread_internal_current () != ss_req->thread)
5071 if (log_level > 0) {
5072 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5074 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);
5077 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5078 g_assert (ji && !ji->is_trampoline);
5079 method = jinfo_get_method (ji);
5082 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5087 * Stopping in memset makes half-initialized vtypes visible.
5088 * Stopping in memcpy makes half-copied vtypes visible.
5090 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5094 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5095 * hence we prefer this check here.
5097 if (ss_req->user_assemblies) {
5098 gboolean found = FALSE;
5099 for (int k = 0; ss_req->user_assemblies[k]; k++)
5100 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5110 * The ip points to the instruction causing the single step event, which is before
5111 * the offset recorded in the seq point map, so find the next seq point after ip.
5113 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
5116 il_offset = sp.il_offset;
5118 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5121 /* Start single stepping again from the current sequence point */
5122 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5124 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5125 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5126 !strcmp (method->name, ".cctor"))
5129 // FIXME: Has to lock earlier
5131 reqs = g_ptr_array_new ();
5133 mono_loader_lock ();
5135 g_ptr_array_add (reqs, ss_req->req);
5137 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5139 g_ptr_array_free (reqs, TRUE);
5141 mono_loader_unlock ();
5143 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5147 process_single_step (void)
5149 process_signal_event (process_single_step_inner);
5153 * mono_debugger_agent_single_step_event:
5155 * Called from a signal handler to handle a single step event.
5158 mono_debugger_agent_single_step_event (void *sigctx)
5160 /* Resume to process_single_step through the signal context */
5162 // FIXME: Since step out/over is implemented using step in, the step in case should
5163 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5166 if (is_debugger_thread ()) {
5168 * This could happen despite our best effors when the runtime calls
5169 * assembly/type resolve hooks.
5170 * FIXME: Breakpoints too.
5174 mono_sigctx_to_monoctx (sigctx, &ctx);
5175 mono_arch_skip_single_step (&ctx);
5176 mono_monoctx_to_sigctx (&ctx, sigctx);
5180 resume_from_signal_handler (sigctx, process_single_step);
5184 debugger_agent_single_step_from_context (MonoContext *ctx)
5186 DebuggerTlsData *tls;
5187 MonoThreadUnwindState orig_restore_state;
5189 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5190 /* Fastpath during invokes, see in process_suspend () */
5191 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5194 if (is_debugger_thread ())
5199 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5200 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5201 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5202 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5204 process_single_step_inner (tls, FALSE);
5206 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5207 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5211 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5213 DebuggerTlsData *tls;
5214 MonoThreadUnwindState orig_restore_state;
5217 if (is_debugger_thread ())
5220 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5221 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5223 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5225 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5226 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5227 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5229 process_breakpoint_inner (tls, FALSE);
5231 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5232 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5233 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5234 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5238 * start_single_stepping:
5240 * Turn on single stepping. Can be called multiple times, for example,
5241 * by a single step event request + a suspend.
5244 start_single_stepping (void)
5246 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5247 int val = InterlockedIncrement (&ss_count);
5250 mono_arch_start_single_stepping ();
5252 g_assert_not_reached ();
5257 stop_single_stepping (void)
5259 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5260 int val = InterlockedDecrement (&ss_count);
5263 mono_arch_stop_single_stepping ();
5265 g_assert_not_reached ();
5272 * Stop the single stepping operation given by SS_REQ.
5275 ss_stop (SingleStepReq *ss_req)
5280 for (l = ss_req->bps; l; l = l->next) {
5281 clear_breakpoint ((MonoBreakpoint *)l->data);
5283 g_slist_free (ss_req->bps);
5287 ss_req->async_id = 0;
5288 ss_req->async_stepout_method = NULL;
5289 if (ss_req->global) {
5290 stop_single_stepping ();
5291 ss_req->global = FALSE;
5298 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5301 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5303 if (ss_req_bp_cache) {
5304 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5305 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5307 for (GSList *l = bps; l; l = l->next) {
5308 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5309 if (bp->method == method && bp->il_offset == il_offset)
5318 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5321 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5323 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5324 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5325 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5331 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5334 ss_bp_hash (gconstpointer data)
5336 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5337 guint hash = (guint) (uintptr_t) s->method;
5338 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5339 hash ^= ((guint)s->il_offset) >> 16;
5343 #define MAX_LINEAR_SCAN_BPS 7
5348 * Create a new breakpoint and add it to a step request.
5349 * Will adjust the bp count and cache used by ss_start.
5352 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5353 MonoMethod *method, guint32 il_offset)
5355 // This list is getting too long, switch to using the hash table
5356 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5357 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5358 for (GSList *l = ss_req->bps; l; l = l->next)
5359 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5362 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5363 // Create and add breakpoint
5364 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5365 ss_req->bps = g_slist_append (ss_req->bps, bp);
5366 if (*ss_req_bp_cache)
5367 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5368 (*ss_req_bp_count)++;
5370 DEBUG_PRINTF (1, "[dbg] Candidate breakpoint at %s:[il=0x%x] is a duplicate for this step request, will not add.\n", mono_method_full_name (method, TRUE), (int)il_offset);
5375 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5379 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5380 mono_seq_point_init_next (info, *sp, next);
5381 for (int i = 0; i < sp->next_len; i++) {
5382 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5383 if (!is_last_non_empty (&next [i], info)) {
5399 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5400 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5401 * belong to the same thread as CTX.
5402 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5405 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5406 gboolean step_to_catch, StackFrame **frames, int nframes)
5408 int i, j, frame_index;
5409 SeqPoint *next_sp, *parent_sp = NULL;
5410 SeqPoint local_sp, local_parent_sp;
5412 MonoSeqPointInfo *parent_info;
5413 MonoMethod *parent_sp_method = NULL;
5414 gboolean enable_global = FALSE;
5416 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5417 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5418 int ss_req_bp_count = g_slist_length (ss_req->bps);
5419 GHashTable *ss_req_bp_cache = NULL;
5421 /* Stop the previous operation */
5425 * Implement single stepping using breakpoints if possible.
5427 if (step_to_catch) {
5428 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5432 if (ctx && !frames) {
5433 /* Need parent frames */
5434 if (!tls->context.valid)
5435 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5436 compute_frame_info (tls->thread, tls);
5437 frames = tls->frames;
5438 nframes = tls->frame_count;
5441 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5443 /* Need to stop in catch clauses as well */
5444 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5445 StackFrame *frame = frames [i];
5448 MonoJitInfo *jinfo = frame->ji;
5449 for (j = 0; j < jinfo->num_clauses; ++j) {
5450 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5451 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5453 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5455 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5456 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5461 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5462 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5464 // Check if we hit yield_offset during normal stepping, because if we did...
5465 // Go into special async stepping mode which places breakpoint on resumeOffset
5466 // of this await call and sets async_id so we can distinguish it from parallel executions
5467 for (i = 0; i < asyncMethod->num_awaits; i++) {
5468 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5469 ss_req->async_id = get_this_async_id (frames [0]);
5470 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5471 if (ss_req_bp_cache)
5472 g_hash_table_destroy (ss_req_bp_cache);
5473 mono_debug_free_method_async_debug_info (asyncMethod);
5477 //If we are at end of async method and doing step-in or step-over...
5478 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5479 if (is_last_non_empty (sp, info)) {
5480 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5482 if (ss_req->depth == STEP_DEPTH_OUT) {
5483 set_set_notification_for_wait_completion_flag (frames [0]);
5484 ss_req->async_id = get_this_async_id (frames [0]);
5485 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5486 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5487 if (ss_req_bp_cache)
5488 g_hash_table_destroy (ss_req_bp_cache);
5489 mono_debug_free_method_async_debug_info (asyncMethod);
5495 mono_debug_free_method_async_debug_info (asyncMethod);
5498 * Find the first sequence point in the current or in a previous frame which
5499 * is not the last in its method.
5501 if (ss_req->depth == STEP_DEPTH_OUT) {
5502 /* Ignore seq points in current method */
5503 while (frame_index < nframes) {
5504 StackFrame *frame = frames [frame_index];
5506 method = frame->method;
5507 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5508 sp = (found_sp)? &local_sp : NULL;
5510 if (sp && sp->next_len != 0)
5513 // There could be method calls before the next seq point in the caller when using nested calls
5514 //enable_global = TRUE;
5516 if (sp && sp->next_len == 0) {
5518 while (frame_index < nframes) {
5519 StackFrame *frame = frames [frame_index];
5521 method = frame->method;
5522 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5523 sp = (found_sp)? &local_sp : NULL;
5524 if (sp && sp->next_len != 0)
5530 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5531 while (frame_index < nframes) {
5532 StackFrame *frame = frames [frame_index];
5534 parent_sp_method = frame->method;
5535 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5536 parent_sp = found_sp ? &local_parent_sp : NULL;
5537 if (found_sp && parent_sp->next_len != 0)
5545 if (sp && sp->next_len > 0) {
5546 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5548 mono_seq_point_init_next (info, *sp, next);
5549 for (i = 0; i < sp->next_len; i++) {
5552 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5558 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5560 mono_seq_point_init_next (parent_info, *parent_sp, next);
5561 for (i = 0; i < parent_sp->next_len; i++) {
5564 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5569 if (ss_req->nframes == 0)
5570 ss_req->nframes = nframes;
5572 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5573 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5575 * This is needed since if we leave managed code, and later return to it, step over
5576 * is not going to stop.
5577 * This approach is a bit ugly, since we change the step depth, but it only affects
5578 * clients who reuse the same step request, and only in this special case.
5580 ss_req->depth = STEP_DEPTH_INTO;
5583 if (ss_req->depth == STEP_DEPTH_INTO) {
5584 /* Enable global stepping so we stop at method entry too */
5585 enable_global = TRUE;
5589 * The ctx/frame info computed above will become invalid when we continue.
5591 tls->context.valid = FALSE;
5592 tls->async_state.valid = FALSE;
5593 invalidate_frames (tls);
5596 if (enable_global) {
5597 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5598 ss_req->global = TRUE;
5599 start_single_stepping ();
5600 } else if (!ss_req->bps) {
5601 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5602 ss_req->global = TRUE;
5603 start_single_stepping ();
5605 ss_req->global = FALSE;
5608 if (ss_req_bp_cache)
5609 g_hash_table_destroy (ss_req_bp_cache);
5613 * Start single stepping of thread THREAD
5616 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5618 DebuggerTlsData *tls;
5619 MonoSeqPointInfo *info = NULL;
5620 SeqPoint *sp = NULL;
5623 MonoMethod *method = NULL;
5624 MonoDebugMethodInfo *minfo;
5625 gboolean step_to_catch = FALSE;
5626 gboolean set_ip = FALSE;
5627 StackFrame **frames = NULL;
5630 if (suspend_count == 0)
5631 return ERR_NOT_SUSPENDED;
5633 wait_for_suspend ();
5635 // FIXME: Multiple requests
5637 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5638 return ERR_NOT_IMPLEMENTED;
5641 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5643 ss_req = g_new0 (SingleStepReq, 1);
5645 ss_req->thread = thread;
5646 ss_req->size = size;
5647 ss_req->depth = depth;
5648 ss_req->filter = filter;
5651 for (int i = 0; i < req->nmodifiers; i++) {
5652 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5653 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5658 mono_loader_lock ();
5659 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5660 mono_loader_unlock ();
5662 if (!tls->context.valid) {
5663 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5664 return ERR_INVALID_ARGUMENT;
5667 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5669 * Need to start single stepping from restore_state and not from the current state
5672 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5675 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5677 if (tls->catch_state.valid) {
5679 StackFrameInfo frame;
5680 MonoContext new_ctx;
5681 MonoLMF *lmf = NULL;
5684 * We are stopped at a throw site. Stepping should go to the catch site.
5687 /* Find the the jit info for the catch context */
5688 res = mono_find_jit_info_ext (
5689 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5690 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5691 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5693 g_assert (frame.type == FRAME_TYPE_MANAGED);
5696 * Find the seq point corresponding to the landing site ip, which is the first seq
5699 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5700 sp = (found_sp)? &local_sp : NULL;
5702 no_seq_points_found (frame.method, frame.native_offset);
5705 method = frame.method;
5707 step_to_catch = TRUE;
5708 /* This make sure the seq point is not skipped by process_single_step () */
5709 ss_req->last_sp = NULL;
5712 if (!step_to_catch) {
5713 StackFrame *frame = NULL;
5716 if (frames && nframes)
5719 compute_frame_info (thread, tls);
5721 if (tls->frame_count)
5722 frame = tls->frames [0];
5725 if (ss_req->size == STEP_SIZE_LINE) {
5727 ss_req->last_method = frame->method;
5728 ss_req->last_line = -1;
5730 minfo = mono_debug_lookup_method (frame->method);
5731 if (minfo && frame->il_offset != -1) {
5732 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5735 ss_req->last_line = loc->row;
5743 if (!method && frame->il_offset != -1) {
5744 /* FIXME: Sort the table and use a binary search */
5745 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5746 sp = (found_sp)? &local_sp : NULL;
5748 no_seq_points_found (frame->method, frame->native_offset);
5750 method = frame->method;
5755 ss_req->start_method = method;
5757 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5760 free_frames (frames, nframes);
5766 ss_destroy (SingleStepReq *req)
5769 g_assert (ss_req == req);
5778 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5781 gboolean found = TRUE;
5785 for (l = ss_req->bps; l; l = l->next) {
5786 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5787 clear_breakpoint ((MonoBreakpoint *)l->data);
5788 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5797 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5800 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5807 if (!agent_config.enabled)
5810 mono_loader_lock ();
5811 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5812 mono_loader_unlock ();
5817 ei.category = mono_string_to_utf8_checked (category, &error);
5818 mono_error_cleanup (&error);
5822 ei.message = mono_string_to_utf8_checked (message, &error);
5823 mono_error_cleanup (&error);
5826 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5828 g_free (ei.category);
5829 g_free (ei.message);
5833 mono_debugger_agent_debug_log_is_enabled (void)
5835 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5836 return agent_config.enabled;
5839 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5841 mono_debugger_agent_unhandled_exception (MonoException *exc)
5850 memset (&ei, 0, sizeof (EventInfo));
5851 ei.exc = (MonoObject*)exc;
5853 mono_loader_lock ();
5854 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5855 mono_loader_unlock ();
5857 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5862 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5863 MonoContext *catch_ctx)
5865 int i, j, suspend_policy;
5867 MonoJitInfo *ji, *catch_ji;
5869 DebuggerTlsData *tls = NULL;
5871 if (thread_to_tls != NULL) {
5872 MonoInternalThread *thread = mono_thread_internal_current ();
5874 mono_loader_lock ();
5875 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5876 mono_loader_unlock ();
5878 if (tls && tls->abort_requested)
5880 if (tls && tls->disable_breakpoints)
5884 memset (&ei, 0, sizeof (EventInfo));
5886 /* Just-In-Time debugging */
5888 if (agent_config.onuncaught && !inited) {
5889 finish_agent_init (FALSE);
5892 * Send an unsolicited EXCEPTION event with a dummy request id.
5894 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5895 ei.exc = (MonoObject*)exc;
5896 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5899 } else if (agent_config.onthrow && !inited) {
5901 gboolean found = FALSE;
5903 for (l = agent_config.onthrow; l; l = l->next) {
5904 char *ex_type = (char *)l->data;
5905 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5907 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5914 finish_agent_init (FALSE);
5917 * Send an unsolicited EXCEPTION event with a dummy request id.
5919 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5920 ei.exc = (MonoObject*)exc;
5921 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5929 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5931 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5935 ei.exc = (MonoObject*)exc;
5936 ei.caught = catch_ctx != NULL;
5938 mono_loader_lock ();
5940 /* Treat exceptions which are caught in non-user code as unhandled */
5941 for (i = 0; i < event_requests->len; ++i) {
5942 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5943 if (req->event_kind != EVENT_KIND_EXCEPTION)
5946 for (j = 0; j < req->nmodifiers; ++j) {
5947 Modifier *mod = &req->modifiers [j];
5949 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5951 gboolean found = FALSE;
5952 MonoAssembly **assemblies = mod->data.assemblies;
5955 for (k = 0; assemblies [k]; ++k)
5956 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5965 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5966 mono_loader_unlock ();
5968 if (tls && ei.caught && catch_ctx) {
5969 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5970 tls->catch_state.ctx = *catch_ctx;
5971 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5972 tls->catch_state.valid = TRUE;
5975 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5978 tls->catch_state.valid = FALSE;
5982 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5984 DebuggerTlsData *tls;
5989 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5994 * We're about to invoke an exception filter during the first pass of exception handling.
5996 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5997 * 'orig_ctx' is the context where the exception has been thrown.
6000 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6002 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6003 * the call site (line 37) and then continue to Main(), but it would never
6004 * include the throw site (line 32).
6006 * Since exception filters are invoked during the first pass of exception handling,
6007 * the stack frames of the throw site are still intact, so we should include them
6010 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6012 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6013 * but report the location of the 'throw' to the user.
6017 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6021 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6023 DebuggerTlsData *tls;
6028 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6032 tls->filter_state.valid = FALSE;
6036 * buffer_add_value_full:
6038 * Add the encoding of the value at ADDR described by T to the buffer.
6039 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6043 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6044 gboolean as_vtype, GHashTable *parent_vtypes)
6047 gboolean boxed_vtype = FALSE;
6050 if (!(*(void**)addr)) {
6051 /* This can happen with compiler generated locals */
6052 //printf ("%s\n", mono_type_full_name (t));
6053 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6056 g_assert (*(void**)addr);
6057 addr = *(void**)addr;
6062 case MONO_TYPE_BOOLEAN:
6065 case MONO_TYPE_CHAR:
6085 case MONO_TYPE_VOID:
6086 buffer_add_byte (buf, t->type);
6088 case MONO_TYPE_BOOLEAN:
6091 buffer_add_byte (buf, t->type);
6092 buffer_add_int (buf, *(gint8*)addr);
6094 case MONO_TYPE_CHAR:
6097 buffer_add_byte (buf, t->type);
6098 buffer_add_int (buf, *(gint16*)addr);
6103 buffer_add_byte (buf, t->type);
6104 buffer_add_int (buf, *(gint32*)addr);
6109 buffer_add_byte (buf, t->type);
6110 buffer_add_long (buf, *(gint64*)addr);
6114 /* Treat it as a vtype */
6116 case MONO_TYPE_PTR: {
6117 gssize val = *(gssize*)addr;
6119 buffer_add_byte (buf, t->type);
6120 buffer_add_long (buf, val);
6124 case MONO_TYPE_STRING:
6125 case MONO_TYPE_SZARRAY:
6126 case MONO_TYPE_OBJECT:
6127 case MONO_TYPE_CLASS:
6128 case MONO_TYPE_ARRAY:
6129 obj = *(MonoObject**)addr;
6132 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6134 if (obj->vtable->klass->valuetype) {
6135 t = &obj->vtable->klass->byval_arg;
6136 addr = mono_object_unbox (obj);
6139 } else if (obj->vtable->klass->rank) {
6140 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6141 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6142 buffer_add_byte (buf, MONO_TYPE_CLASS);
6144 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6146 buffer_add_objid (buf, obj);
6150 case MONO_TYPE_VALUETYPE:
6151 case MONO_TYPE_TYPEDBYREF: {
6155 MonoClass *klass = mono_class_from_mono_type (t);
6160 * Handle boxed vtypes recursively referencing themselves using fields.
6163 parent_vtypes = g_hash_table_new (NULL, NULL);
6164 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6166 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6167 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6168 buffer_add_int (buf, vtype_index - 1);
6170 /* The client can't handle PARENT_VTYPE */
6171 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6175 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6179 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6180 buffer_add_byte (buf, klass->enumtype);
6181 buffer_add_typeid (buf, domain, klass);
6185 while ((f = mono_class_get_fields (klass, &iter))) {
6186 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6188 if (mono_field_is_deleted (f))
6192 buffer_add_int (buf, nfields);
6195 while ((f = mono_class_get_fields (klass, &iter))) {
6196 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6198 if (mono_field_is_deleted (f))
6200 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6204 g_hash_table_remove (parent_vtypes, addr);
6205 if (g_hash_table_size (parent_vtypes) == 0) {
6206 g_hash_table_destroy (parent_vtypes);
6207 parent_vtypes = NULL;
6212 case MONO_TYPE_GENERICINST:
6213 if (mono_type_generic_inst_is_valuetype (t)) {
6225 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6227 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6231 obj_is_of_type (MonoObject *obj, MonoType *t)
6233 MonoClass *klass = obj->vtable->klass;
6234 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6235 if (mono_class_is_transparent_proxy (klass)) {
6236 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6237 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6247 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6250 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6256 gpointer iter = NULL;
6260 is_enum = decode_byte (buf, &buf, limit);
6261 /* Enums are sent as a normal vtype */
6263 return ERR_NOT_IMPLEMENTED;
6264 klass = decode_typeid (buf, &buf, limit, &d, &err);
6265 if (err != ERR_NONE)
6268 if (t && klass != mono_class_from_mono_type (t)) {
6269 char *name = mono_type_full_name (t);
6270 char *name2 = mono_type_full_name (&klass->byval_arg);
6271 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6274 return ERR_INVALID_ARGUMENT;
6277 nfields = decode_int (buf, &buf, limit);
6278 while ((f = mono_class_get_fields (klass, &iter))) {
6279 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6281 if (mono_field_is_deleted (f))
6283 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6284 if (err != ERR_NONE)
6288 g_assert (nfields == 0);
6296 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6300 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6301 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6302 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6303 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6304 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6305 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6306 char *name = mono_type_full_name (t);
6307 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6309 return ERR_INVALID_ARGUMENT;
6313 case MONO_TYPE_BOOLEAN:
6314 *(guint8*)addr = decode_int (buf, &buf, limit);
6316 case MONO_TYPE_CHAR:
6317 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6320 *(gint8*)addr = decode_int (buf, &buf, limit);
6323 *(guint8*)addr = decode_int (buf, &buf, limit);
6326 *(gint16*)addr = decode_int (buf, &buf, limit);
6329 *(guint16*)addr = decode_int (buf, &buf, limit);
6332 *(gint32*)addr = decode_int (buf, &buf, limit);
6335 *(guint32*)addr = decode_int (buf, &buf, limit);
6338 *(gint64*)addr = decode_long (buf, &buf, limit);
6341 *(guint64*)addr = decode_long (buf, &buf, limit);
6344 *(guint32*)addr = decode_int (buf, &buf, limit);
6347 *(guint64*)addr = decode_long (buf, &buf, limit);
6350 /* We send these as I8, so we get them back as such */
6351 g_assert (type == MONO_TYPE_I8);
6352 *(gssize*)addr = decode_long (buf, &buf, limit);
6354 case MONO_TYPE_GENERICINST:
6355 if (MONO_TYPE_ISSTRUCT (t)) {
6356 /* The client sends these as a valuetype */
6364 /* We send these as vtypes, so we get them back as such */
6365 g_assert (type == MONO_TYPE_VALUETYPE);
6368 case MONO_TYPE_VALUETYPE:
6369 if (type == MONO_TYPE_OBJECT) {
6371 int objid = decode_objid (buf, &buf, limit);
6375 err = get_object (objid, (MonoObject**)&obj);
6376 if (err != ERR_NONE)
6379 return ERR_INVALID_ARGUMENT;
6380 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6381 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6382 return ERR_INVALID_ARGUMENT;
6384 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6386 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6387 if (err != ERR_NONE)
6393 if (MONO_TYPE_IS_REFERENCE (t)) {
6394 if (type == MONO_TYPE_OBJECT) {
6395 int objid = decode_objid (buf, &buf, limit);
6399 err = get_object (objid, (MonoObject**)&obj);
6400 if (err != ERR_NONE)
6404 if (!obj_is_of_type (obj, t)) {
6405 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6406 return ERR_INVALID_ARGUMENT;
6409 if (obj && obj->vtable->domain != domain)
6410 return ERR_INVALID_ARGUMENT;
6412 mono_gc_wbarrier_generic_store (addr, obj);
6413 } else if (type == VALUE_TYPE_ID_NULL) {
6414 *(MonoObject**)addr = NULL;
6415 } else if (type == MONO_TYPE_VALUETYPE) {
6424 /* This can happen when round-tripping boxed vtypes */
6426 * Obtain vtype class.
6427 * Same as the beginning of the handle_vtype case above.
6430 is_enum = decode_byte (buf, &buf, limit);
6432 return ERR_NOT_IMPLEMENTED;
6433 klass = decode_typeid (buf, &buf, limit, &d, &err);
6434 if (err != ERR_NONE)
6437 /* Decode the vtype into a temporary buffer, then box it. */
6438 vtype_buf_size = mono_class_value_size (klass, NULL);
6439 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6440 g_assert (vtype_buf);
6443 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6444 if (err != ERR_NONE) {
6448 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6449 mono_error_cleanup (&error);
6452 char *name = mono_type_full_name (t);
6453 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6455 return ERR_INVALID_ARGUMENT;
6469 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6473 int type = decode_byte (buf, &buf, limit);
6475 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6476 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6477 guint8 *nullable_buf;
6480 * First try decoding it as a Nullable`1
6482 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6483 if (err == ERR_NONE)
6487 * Then try decoding as a primitive value or null.
6489 if (targ->type == type) {
6490 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6491 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6492 if (err != ERR_NONE) {
6493 g_free (nullable_buf);
6496 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6497 if (!is_ok (&error)) {
6498 mono_error_cleanup (&error);
6499 return ERR_INVALID_OBJECT;
6501 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6502 g_free (nullable_buf);
6505 } else if (type == VALUE_TYPE_ID_NULL) {
6506 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6512 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6516 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6520 guint8 *addr, *gaddr;
6523 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6524 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6527 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6528 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6530 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6532 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6533 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6534 addr += (gint32)var->offset;
6536 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6538 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6540 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6543 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6544 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6545 /* Same as regoffset, but with an indirection */
6546 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6547 addr += (gint32)var->offset;
6549 gaddr = (guint8 *)*(gpointer*)addr;
6551 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6553 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6554 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6555 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6556 MonoGSharedVtMethodRuntimeInfo *info;
6562 g_assert (info_var);
6563 g_assert (locals_var);
6565 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6566 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6567 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6568 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6569 addr += (gint32)info_var->offset;
6570 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6571 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6572 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6574 g_assert_not_reached ();
6578 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6579 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6580 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6581 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6582 addr += (gint32)locals_var->offset;
6583 locals = (guint8 *)*(gpointer*)addr;
6584 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6585 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6587 g_assert_not_reached ();
6591 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6593 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6598 g_assert_not_reached ();
6603 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6607 guint8 *addr, *gaddr;
6609 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6610 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6612 if (MONO_TYPE_IS_REFERENCE (t))
6613 size = sizeof (gpointer);
6615 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6618 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6619 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6621 gboolean is_signed = FALSE;
6624 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6627 // FIXME: Write barriers
6628 mono_gc_memmove_atomic (addr, val, size);
6633 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6638 v = is_signed ? *(gint8*)val : *(guint8*)val;
6641 v = is_signed ? *(gint16*)val : *(guint16*)val;
6644 v = is_signed ? *(gint32*)val : *(guint32*)val;
6647 v = is_signed ? *(gint64*)val : *(guint64*)val;
6650 g_assert_not_reached ();
6653 /* Set value on the stack or in the return ctx */
6654 if (reg_locations [reg]) {
6655 /* Saved on the stack */
6656 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6657 *(reg_locations [reg]) = v;
6660 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6661 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6664 // FIXME: Move these to mono-context.h/c.
6665 mono_arch_context_set_int_reg (ctx, reg, v);
6667 // FIXME: Can't set registers, so we disable linears
6672 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6673 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6674 addr += (gint32)var->offset;
6676 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6679 addr = *(guint8**)addr;
6685 // FIXME: Write barriers
6686 mono_gc_memmove_atomic (addr, val, size);
6688 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6689 /* Same as regoffset, but with an indirection */
6690 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6691 addr += (gint32)var->offset;
6693 gaddr = (guint8 *)*(gpointer*)addr;
6695 // FIXME: Write barriers
6696 mono_gc_memmove_atomic (gaddr, val, size);
6698 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6702 g_assert_not_reached ();
6707 clear_event_request (int req_id, int etype)
6711 mono_loader_lock ();
6712 for (i = 0; i < event_requests->len; ++i) {
6713 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6715 if (req->id == req_id && req->event_kind == etype) {
6716 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6717 clear_breakpoint ((MonoBreakpoint *)req->info);
6718 if (req->event_kind == EVENT_KIND_STEP)
6719 ss_destroy ((SingleStepReq *)req->info);
6720 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6721 clear_breakpoint ((MonoBreakpoint *)req->info);
6722 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6723 clear_breakpoint ((MonoBreakpoint *)req->info);
6724 g_ptr_array_remove_index_fast (event_requests, i);
6729 mono_loader_unlock ();
6733 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6737 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6738 m->kind = MOD_KIND_NONE;
6739 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6740 int count = 0, match_count = 0, pos;
6741 MonoAssembly **newassemblies;
6743 for (i = 0; m->data.assemblies [i]; ++i) {
6745 if (m->data.assemblies [i] == assembly)
6750 // +1 because we don't know length and we use last element to check for end
6751 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6754 for (i = 0; i < count; ++i)
6755 if (m->data.assemblies [i] != assembly)
6756 newassemblies [pos ++] = m->data.assemblies [i];
6757 g_assert (pos == count - match_count);
6758 g_free (m->data.assemblies);
6759 m->data.assemblies = newassemblies;
6765 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6769 for (i = 0; i < req->nmodifiers; ++i) {
6770 Modifier *m = &req->modifiers [i];
6772 clear_assembly_from_modifier (req, m, assembly);
6777 * clear_event_requests_for_assembly:
6779 * Clear all events requests which reference ASSEMBLY.
6782 clear_event_requests_for_assembly (MonoAssembly *assembly)
6787 mono_loader_lock ();
6791 for (i = 0; i < event_requests->len; ++i) {
6792 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6794 clear_assembly_from_modifiers (req, assembly);
6796 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6797 clear_event_request (req->id, req->event_kind);
6802 if (req->event_kind == EVENT_KIND_STEP)
6803 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6806 mono_loader_unlock ();
6810 * type_comes_from_assembly:
6812 * GHRFunc that returns TRUE if klass comes from assembly
6815 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6817 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6821 * clear_types_for_assembly:
6823 * Clears types from loaded_classes for a given assembly
6826 clear_types_for_assembly (MonoAssembly *assembly)
6828 MonoDomain *domain = mono_domain_get ();
6829 AgentDomainInfo *info = NULL;
6831 if (!domain || !domain_jit_info (domain))
6832 /* Can happen during shutdown */
6835 info = get_agent_domain_info (domain);
6837 mono_loader_lock ();
6838 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6839 mono_loader_unlock ();
6843 add_thread (gpointer key, gpointer value, gpointer user_data)
6845 MonoInternalThread *thread = (MonoInternalThread *)value;
6846 Buffer *buf = (Buffer *)user_data;
6848 buffer_add_objid (buf, (MonoObject*)thread);
6852 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6855 guint8 *end = invoke->endp;
6859 MonoMethodSignature *sig;
6862 MonoObject *this_arg, *res, *exc;
6865 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6868 MonoStopwatch watch;
6870 if (invoke->method) {
6872 * Invoke this method directly, currently only Environment.Exit () is supported.
6875 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>");
6877 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6878 mono_error_assert_ok (&error);
6880 g_assert_not_reached ();
6883 m = decode_methodid (p, &p, end, &domain, &err);
6884 if (err != ERR_NONE)
6886 sig = mono_method_signature (m);
6888 if (m->klass->valuetype)
6889 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6891 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6892 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6893 /* Should be null */
6894 int type = decode_byte (p, &p, end);
6895 if (type != VALUE_TYPE_ID_NULL) {
6896 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6897 return ERR_INVALID_ARGUMENT;
6899 memset (this_buf, 0, mono_class_instance_size (m->klass));
6900 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6904 int type = decode_byte (p, &tmp_p, end);
6905 if (type == VALUE_TYPE_ID_NULL) {
6906 memset (this_buf, 0, mono_class_instance_size (m->klass));
6909 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6910 if (err != ERR_NONE)
6914 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6915 if (err != ERR_NONE)
6919 if (!m->klass->valuetype)
6920 this_arg = *(MonoObject**)this_buf;
6924 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6926 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6927 return ERR_INVALID_ARGUMENT;
6929 m = mono_object_get_virtual_method (this_arg, m);
6930 /* Transform this to the format the rest of the code expects it to be */
6931 if (m->klass->valuetype) {
6932 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6933 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6935 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6937 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6938 return ERR_INVALID_ARGUMENT;
6940 m = mono_object_get_virtual_method (this_arg, m);
6941 if (m->klass->valuetype) {
6942 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6943 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6947 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>");
6949 if (this_arg && this_arg->vtable->domain != domain)
6952 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6953 if (!strcmp (m->name, ".ctor")) {
6954 if (mono_class_is_abstract (m->klass))
6955 return ERR_INVALID_ARGUMENT;
6958 this_arg = mono_object_new_checked (domain, m->klass, &error);
6959 mono_error_assert_ok (&error);
6962 return ERR_INVALID_ARGUMENT;
6966 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6967 return ERR_INVALID_ARGUMENT;
6969 nargs = decode_int (p, &p, end);
6970 if (nargs != sig->param_count)
6971 return ERR_INVALID_ARGUMENT;
6972 /* Use alloca to get gc tracking */
6973 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6974 memset (arg_buf, 0, nargs * sizeof (gpointer));
6975 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6976 for (i = 0; i < nargs; ++i) {
6977 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6978 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6979 if (err != ERR_NONE)
6981 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6984 if (sig->params [i]->byref) {
6985 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6986 *(gpointer*)arg_buf [i] = args [i];
6987 args [i] = arg_buf [i];
6990 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6991 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6992 if (err != ERR_NONE)
6994 args [i] = arg_buf [i];
7001 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7002 tls->disable_breakpoints = TRUE;
7004 tls->disable_breakpoints = FALSE;
7007 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7009 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7010 if (invoke->has_ctx) {
7013 lmf_addr = mono_get_lmf_addr ();
7016 memset (&ext, 0, sizeof (ext));
7017 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7019 ext.debugger_invoke = TRUE;
7020 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7022 mono_set_lmf ((MonoLMF*)&ext);
7026 mono_stopwatch_start (&watch);
7027 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7028 if (exc == NULL && !mono_error_ok (&error)) {
7029 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7031 mono_error_cleanup (&error); /* FIXME report error */
7033 mono_stopwatch_stop (&watch);
7034 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));
7036 buffer_add_byte (buf, 0);
7037 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7039 gboolean out_this = FALSE;
7040 gboolean out_args = FALSE;
7042 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7044 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7046 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7047 if (sig->ret->type == MONO_TYPE_VOID) {
7048 if (!strcmp (m->name, ".ctor")) {
7049 if (!m->klass->valuetype)
7050 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7052 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7054 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7056 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7057 buffer_add_value (buf, sig->ret, &res, domain);
7058 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7059 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7060 MonoClass *k = mono_class_from_mono_type (sig->ret);
7061 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7063 g_assert (nullable_buf);
7064 mono_nullable_init (nullable_buf, res, k);
7065 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7068 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7074 /* Return the new value of the receiver after the call */
7075 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7077 buffer_add_int (buf, nargs);
7078 for (i = 0; i < nargs; ++i) {
7079 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7080 buffer_add_value (buf, sig->params [i], &args [i], domain);
7081 else if (sig->params [i]->byref)
7082 /* add_value () does an indirection */
7083 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7085 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7090 tls->disable_breakpoints = FALSE;
7092 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7093 if (invoke->has_ctx)
7094 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7098 // FIXME: byref arguments
7106 * Invoke the method given by tls->pending_invoke in the current thread.
7109 invoke_method (void)
7111 DebuggerTlsData *tls;
7117 MonoContext restore_ctx;
7120 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7124 * Store the `InvokeData *' in `tls->invoke' until we're done with
7125 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7128 mono_loader_lock ();
7130 invoke = tls->pending_invoke;
7132 tls->pending_invoke = NULL;
7134 invoke->last_invoke = tls->invoke;
7135 tls->invoke = invoke;
7137 mono_loader_unlock ();
7139 tls->frames_up_to_date = FALSE;
7145 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7146 buffer_init (&buf, 128);
7149 /* Fail the other invokes as well */
7151 err = do_invoke_method (tls, &buf, invoke, p, &p);
7154 if (tls->abort_requested) {
7155 if (CHECK_PROTOCOL_VERSION (2, 42))
7156 err = ERR_INVOKE_ABORTED;
7159 /* Start suspending before sending the reply */
7160 if (mindex == invoke->nmethods - 1) {
7161 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7162 for (i = 0; i < invoke->suspend_count; ++i)
7167 send_reply_packet (id, err, &buf);
7172 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7174 if (invoke->has_ctx)
7175 save_thread_context (&restore_ctx);
7177 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7178 g_assert (tls->resume_count);
7179 tls->resume_count -= invoke->suspend_count;
7182 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7185 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7187 * It is possible that mono_thread_internal_abort () was called
7188 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7189 * because we reset the abort here.
7192 mono_loader_lock ();
7194 if (tls->abort_requested)
7195 mono_thread_internal_reset_abort (tls->thread);
7197 tls->invoke = tls->invoke->last_invoke;
7198 tls->abort_requested = FALSE;
7200 mono_loader_unlock ();
7209 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7211 MonoThread *thread = (MonoThread *)value;
7212 DebuggerTlsData *tls;
7215 mono_loader_lock ();
7216 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7218 res = tls->really_suspended;
7219 mono_loader_unlock ();
7225 get_source_files_for_type (MonoClass *klass)
7227 gpointer iter = NULL;
7229 MonoDebugSourceInfo *sinfo;
7233 files = g_ptr_array_new ();
7235 while ((method = mono_class_get_methods (klass, &iter))) {
7236 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7237 GPtrArray *source_file_list;
7240 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7241 for (j = 0; j < source_file_list->len; ++j) {
7242 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7243 for (i = 0; i < files->len; ++i)
7244 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7246 if (i == files->len)
7247 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7249 g_ptr_array_free (source_file_list, TRUE);
7257 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7260 case CMD_VM_VERSION: {
7261 char *build_info, *version;
7263 build_info = mono_get_runtime_build_info ();
7264 version = g_strdup_printf ("mono %s", build_info);
7266 buffer_add_string (buf, version); /* vm version */
7267 buffer_add_int (buf, MAJOR_VERSION);
7268 buffer_add_int (buf, MINOR_VERSION);
7269 g_free (build_info);
7273 case CMD_VM_SET_PROTOCOL_VERSION: {
7274 major_version = decode_int (p, &p, end);
7275 minor_version = decode_int (p, &p, end);
7276 protocol_version_set = TRUE;
7277 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7280 case CMD_VM_ALL_THREADS: {
7282 mono_loader_lock ();
7283 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7284 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7285 mono_loader_unlock ();
7288 case CMD_VM_SUSPEND:
7290 wait_for_suspend ();
7293 if (suspend_count == 0)
7294 return ERR_NOT_SUSPENDED;
7296 clear_suspended_objs ();
7298 case CMD_VM_DISPOSE:
7299 /* Clear all event requests */
7300 mono_loader_lock ();
7301 while (event_requests->len > 0) {
7302 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7304 clear_event_request (req->id, req->event_kind);
7306 mono_loader_unlock ();
7308 while (suspend_count > 0)
7310 disconnected = TRUE;
7311 vm_start_event_sent = FALSE;
7314 MonoInternalThread *thread;
7315 DebuggerTlsData *tls;
7316 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7317 MonoClass *env_class;
7319 MonoMethod *exit_method = NULL;
7323 exit_code = decode_int (p, &p, end);
7325 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7327 /* Have to send a reply before exiting */
7328 send_reply_packet (id, 0, buf);
7330 /* Clear all event requests */
7331 mono_loader_lock ();
7332 while (event_requests->len > 0) {
7333 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7335 clear_event_request (req->id, req->event_kind);
7337 mono_loader_unlock ();
7340 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7341 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7342 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7343 * better than doing the shutdown ourselves, since it avoids various races.
7347 wait_for_suspend ();
7349 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7350 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7352 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7355 mono_loader_lock ();
7356 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7357 mono_loader_unlock ();
7359 if (thread && exit_method) {
7360 mono_loader_lock ();
7361 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7362 mono_loader_unlock ();
7364 args = g_new0 (gpointer, 1);
7365 args [0] = g_malloc (sizeof (int));
7366 *(int*)(args [0]) = exit_code;
7368 tls->pending_invoke = g_new0 (InvokeData, 1);
7369 tls->pending_invoke->method = exit_method;
7370 tls->pending_invoke->args = args;
7371 tls->pending_invoke->nmethods = 1;
7373 while (suspend_count > 0)
7377 * No thread found, do it ourselves.
7378 * FIXME: This can race with normal shutdown etc.
7380 while (suspend_count > 0)
7383 if (!mono_runtime_try_shutdown ())
7386 mono_environment_exitcode_set (exit_code);
7388 /* Suspend all managed threads since the runtime is going away */
7389 DEBUG_PRINTF (1, "Suspending all threads...\n");
7390 mono_thread_suspend_all_other_threads ();
7391 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7392 mono_runtime_quit ();
7393 transport_close2 ();
7394 DEBUG_PRINTF (1, "Exiting...\n");
7400 case CMD_VM_INVOKE_METHOD:
7401 case CMD_VM_INVOKE_METHODS: {
7402 int objid = decode_objid (p, &p, end);
7404 DebuggerTlsData *tls;
7405 int i, count, flags, nmethods;
7408 err = get_object (objid, (MonoObject**)&thread);
7409 if (err != ERR_NONE)
7412 flags = decode_int (p, &p, end);
7414 if (command == CMD_VM_INVOKE_METHODS)
7415 nmethods = decode_int (p, &p, end);
7419 // Wait for suspending if it already started
7421 wait_for_suspend ();
7422 if (!is_suspended ())
7423 return ERR_NOT_SUSPENDED;
7425 mono_loader_lock ();
7426 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7427 mono_loader_unlock ();
7430 if (!tls->really_suspended)
7431 /* The thread is still running native code, can't do invokes */
7432 return ERR_NOT_SUSPENDED;
7435 * Store the invoke data into tls, the thread will execute it after it is
7438 if (tls->pending_invoke)
7439 return ERR_NOT_SUSPENDED;
7440 tls->pending_invoke = g_new0 (InvokeData, 1);
7441 tls->pending_invoke->id = id;
7442 tls->pending_invoke->flags = flags;
7443 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7444 memcpy (tls->pending_invoke->p, p, end - p);
7445 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7446 tls->pending_invoke->suspend_count = suspend_count;
7447 tls->pending_invoke->nmethods = nmethods;
7449 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7450 resume_thread (THREAD_TO_INTERNAL (thread));
7453 count = suspend_count;
7454 for (i = 0; i < count; ++i)
7459 case CMD_VM_ABORT_INVOKE: {
7460 int objid = decode_objid (p, &p, end);
7462 DebuggerTlsData *tls;
7466 err = get_object (objid, (MonoObject**)&thread);
7467 if (err != ERR_NONE)
7470 invoke_id = decode_int (p, &p, end);
7472 mono_loader_lock ();
7473 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7476 if (tls->abort_requested) {
7477 DEBUG_PRINTF (1, "Abort already requested.\n");
7478 mono_loader_unlock ();
7483 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7484 * actually the correct invocation.
7486 * Careful, we do not stop the thread that's doing the invocation, so we can't
7487 * inspect its stack. However, invoke_method() also acquires the loader lock
7488 * when it's done, so we're safe here.
7492 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7493 mono_loader_unlock ();
7494 return ERR_NO_INVOCATION;
7497 tls->abort_requested = TRUE;
7499 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7500 mono_loader_unlock ();
7504 case CMD_VM_SET_KEEPALIVE: {
7505 int timeout = decode_int (p, &p, end);
7506 agent_config.keepalive = timeout;
7508 #ifndef DISABLE_SOCKET_TRANSPORT
7515 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7516 GHashTableIter iter, kiter;
7521 char *fname, *basename;
7522 gboolean ignore_case;
7523 GSList *class_list, *l;
7524 GPtrArray *res_classes, *res_domains;
7526 fname = decode_string (p, &p, end);
7527 ignore_case = decode_byte (p, &p, end);
7529 basename = dbg_path_get_basename (fname);
7531 res_classes = g_ptr_array_new ();
7532 res_domains = g_ptr_array_new ();
7534 mono_loader_lock ();
7535 g_hash_table_iter_init (&iter, domains);
7536 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7537 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7539 /* Update 'source_file_to_class' cache */
7540 g_hash_table_iter_init (&kiter, info->loaded_classes);
7541 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7542 if (!g_hash_table_lookup (info->source_files, klass)) {
7543 files = get_source_files_for_type (klass);
7544 g_hash_table_insert (info->source_files, klass, files);
7546 for (i = 0; i < files->len; ++i) {
7547 char *s = (char *)g_ptr_array_index (files, i);
7548 char *s2 = dbg_path_get_basename (s);
7551 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7553 class_list = g_slist_prepend (class_list, klass);
7554 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7556 class_list = g_slist_prepend (class_list, klass);
7557 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7560 /* The _ignorecase hash contains the lowercase path */
7561 s3 = strdup_tolower (s2);
7562 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7564 class_list = g_slist_prepend (class_list, klass);
7565 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7567 class_list = g_slist_prepend (class_list, klass);
7568 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7580 s = strdup_tolower (basename);
7581 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7584 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7587 for (l = class_list; l; l = l->next) {
7588 klass = (MonoClass *)l->data;
7590 g_ptr_array_add (res_classes, klass);
7591 g_ptr_array_add (res_domains, domain);
7594 mono_loader_unlock ();
7599 buffer_add_int (buf, res_classes->len);
7600 for (i = 0; i < res_classes->len; ++i)
7601 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7602 g_ptr_array_free (res_classes, TRUE);
7603 g_ptr_array_free (res_domains, TRUE);
7606 case CMD_VM_GET_TYPES: {
7607 GHashTableIter iter;
7611 gboolean ignore_case;
7612 GPtrArray *res_classes, *res_domains;
7613 MonoTypeNameParse info;
7615 name = decode_string (p, &p, end);
7616 ignore_case = decode_byte (p, &p, end);
7618 if (!mono_reflection_parse_type (name, &info)) {
7620 mono_reflection_free_type_info (&info);
7621 return ERR_INVALID_ARGUMENT;
7624 res_classes = g_ptr_array_new ();
7625 res_domains = g_ptr_array_new ();
7627 mono_loader_lock ();
7628 g_hash_table_iter_init (&iter, domains);
7629 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7631 gboolean type_resolve;
7635 mono_domain_assemblies_lock (domain);
7636 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7637 ass = (MonoAssembly *)tmp->data;
7641 type_resolve = TRUE;
7642 /* FIXME really okay to call while holding locks? */
7643 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7644 mono_error_cleanup (&error);
7646 g_ptr_array_add (res_classes, mono_type_get_class (t));
7647 g_ptr_array_add (res_domains, domain);
7651 mono_domain_assemblies_unlock (domain);
7653 mono_loader_unlock ();
7656 mono_reflection_free_type_info (&info);
7658 buffer_add_int (buf, res_classes->len);
7659 for (i = 0; i < res_classes->len; ++i)
7660 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7661 g_ptr_array_free (res_classes, TRUE);
7662 g_ptr_array_free (res_domains, TRUE);
7665 case CMD_VM_START_BUFFERING:
7666 case CMD_VM_STOP_BUFFERING:
7667 /* Handled in the main loop */
7670 return ERR_NOT_IMPLEMENTED;
7677 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7683 case CMD_EVENT_REQUEST_SET: {
7685 int i, event_kind, suspend_policy, nmodifiers;
7689 MonoThread *step_thread;
7690 int step_thread_id = 0;
7691 StepDepth depth = STEP_DEPTH_INTO;
7692 StepSize size = STEP_SIZE_MIN;
7693 StepFilter filter = STEP_FILTER_NONE;
7697 event_kind = decode_byte (p, &p, end);
7698 suspend_policy = decode_byte (p, &p, end);
7699 nmodifiers = decode_byte (p, &p, end);
7701 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7702 req->id = InterlockedIncrement (&event_request_id);
7703 req->event_kind = event_kind;
7704 req->suspend_policy = suspend_policy;
7705 req->nmodifiers = nmodifiers;
7708 for (i = 0; i < nmodifiers; ++i) {
7709 mod = (ModifierKind)decode_byte (p, &p, end);
7711 req->modifiers [i].kind = mod;
7712 if (mod == MOD_KIND_COUNT) {
7713 req->modifiers [i].data.count = decode_int (p, &p, end);
7714 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7715 method = decode_methodid (p, &p, end, &domain, &err);
7716 if (err != ERR_NONE)
7718 location = decode_long (p, &p, end);
7719 } else if (mod == MOD_KIND_STEP) {
7720 step_thread_id = decode_id (p, &p, end);
7721 size = (StepSize)decode_int (p, &p, end);
7722 depth = (StepDepth)decode_int (p, &p, end);
7723 if (CHECK_PROTOCOL_VERSION (2, 16))
7724 filter = (StepFilter)decode_int (p, &p, end);
7725 req->modifiers [i].data.filter = filter;
7726 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7727 /* Treat STEP_THOUGH the same as HIDDEN */
7728 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7729 } else if (mod == MOD_KIND_THREAD_ONLY) {
7730 int id = decode_id (p, &p, end);
7732 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7733 if (err != ERR_NONE) {
7737 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7738 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7740 if (err != ERR_NONE)
7742 req->modifiers [i].caught = decode_byte (p, &p, end);
7743 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7744 if (CHECK_PROTOCOL_VERSION (2, 25))
7745 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7747 req->modifiers [i].subclasses = TRUE;
7748 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" : "");
7750 req->modifiers [i].data.exc_class = exc_class;
7752 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7754 return ERR_INVALID_ARGUMENT;
7757 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7758 int n = decode_int (p, &p, end);
7761 // +1 because we don't know length and we use last element to check for end
7762 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7763 for (j = 0; j < n; ++j) {
7764 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7765 if (err != ERR_NONE) {
7766 g_free (req->modifiers [i].data.assemblies);
7770 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7771 int n = decode_int (p, &p, end);
7774 modifier = &req->modifiers [i];
7775 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7776 for (j = 0; j < n; ++j) {
7777 char *s = decode_string (p, &p, end);
7781 s2 = strdup_tolower (s);
7782 g_hash_table_insert (modifier->data.source_files, s2, s2);
7786 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7787 int n = decode_int (p, &p, end);
7790 modifier = &req->modifiers [i];
7791 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7792 for (j = 0; j < n; ++j) {
7793 char *s = decode_string (p, &p, end);
7796 g_hash_table_insert (modifier->data.type_names, s, s);
7800 return ERR_NOT_IMPLEMENTED;
7804 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7807 req->info = set_breakpoint (method, location, req, &error);
7808 if (!mono_error_ok (&error)) {
7810 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7811 mono_error_cleanup (&error);
7812 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7814 } else if (req->event_kind == EVENT_KIND_STEP) {
7815 g_assert (step_thread_id);
7817 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7818 if (err != ERR_NONE) {
7823 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7824 if (err != ERR_NONE) {
7828 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7829 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7830 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7831 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7832 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7833 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7835 if (req->nmodifiers) {
7837 return ERR_NOT_IMPLEMENTED;
7841 mono_loader_lock ();
7842 g_ptr_array_add (event_requests, req);
7844 if (agent_config.defer) {
7845 /* Transmit cached data to the client on receipt of the event request */
7846 switch (req->event_kind) {
7847 case EVENT_KIND_APPDOMAIN_CREATE:
7848 /* Emit load events for currently loaded domains */
7849 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7851 case EVENT_KIND_ASSEMBLY_LOAD:
7852 /* Emit load events for currently loaded assemblies */
7853 mono_domain_foreach (send_assemblies_for_domain, NULL);
7855 case EVENT_KIND_THREAD_START:
7856 /* Emit start events for currently started threads */
7857 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7859 case EVENT_KIND_TYPE_LOAD:
7860 /* Emit type load events for currently loaded types */
7861 mono_domain_foreach (send_types_for_domain, NULL);
7867 mono_loader_unlock ();
7869 buffer_add_int (buf, req->id);
7872 case CMD_EVENT_REQUEST_CLEAR: {
7873 int etype = decode_byte (p, &p, end);
7874 int req_id = decode_int (p, &p, end);
7876 // FIXME: Make a faster mapping from req_id to request
7877 mono_loader_lock ();
7878 clear_event_request (req_id, etype);
7879 mono_loader_unlock ();
7882 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7885 mono_loader_lock ();
7887 while (i < event_requests->len) {
7888 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7890 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7891 clear_breakpoint ((MonoBreakpoint *)req->info);
7893 g_ptr_array_remove_index_fast (event_requests, i);
7899 mono_loader_unlock ();
7903 return ERR_NOT_IMPLEMENTED;
7910 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7916 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7917 buffer_add_domainid (buf, mono_get_root_domain ());
7920 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7921 domain = decode_domainid (p, &p, end, NULL, &err);
7922 if (err != ERR_NONE)
7924 buffer_add_string (buf, domain->friendly_name);
7927 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7932 domain = decode_domainid (p, &p, end, NULL, &err);
7933 if (err != ERR_NONE)
7935 mono_loader_lock ();
7937 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7940 buffer_add_int (buf, count);
7941 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7942 ass = (MonoAssembly *)tmp->data;
7943 buffer_add_assemblyid (buf, domain, ass);
7945 mono_loader_unlock ();
7948 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7949 domain = decode_domainid (p, &p, end, NULL, &err);
7950 if (err != ERR_NONE)
7953 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7956 case CMD_APPDOMAIN_GET_CORLIB: {
7957 domain = decode_domainid (p, &p, end, NULL, &err);
7958 if (err != ERR_NONE)
7961 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7964 case CMD_APPDOMAIN_CREATE_STRING: {
7968 domain = decode_domainid (p, &p, end, NULL, &err);
7969 if (err != ERR_NONE)
7971 s = decode_string (p, &p, end);
7973 o = mono_string_new (domain, s);
7974 buffer_add_objid (buf, (MonoObject*)o);
7977 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7980 MonoDomain *domain2;
7983 domain = decode_domainid (p, &p, end, NULL, &err);
7984 if (err != ERR_NONE)
7986 klass = decode_typeid (p, &p, end, &domain2, &err);
7987 if (err != ERR_NONE)
7991 g_assert (domain == domain2);
7993 o = mono_object_new_checked (domain, klass, &error);
7994 mono_error_assert_ok (&error);
7996 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7997 if (err != ERR_NONE)
8000 buffer_add_objid (buf, o);
8004 return ERR_NOT_IMPLEMENTED;
8011 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8013 HANDLE_FUNCTION_ENTER();
8014 ErrorCode err = ERR_NONE;
8015 mono_error_init (error);
8016 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8017 if (MONO_HANDLE_IS_NULL (o)) {
8018 err = ERR_INVALID_OBJECT;
8021 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8023 HANDLE_FUNCTION_RETURN_VAL (err);
8028 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8034 ass = decode_assemblyid (p, &p, end, &domain, &err);
8035 if (err != ERR_NONE)
8039 case CMD_ASSEMBLY_GET_LOCATION: {
8040 buffer_add_string (buf, mono_image_get_filename (ass->image));
8043 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8047 if (ass->image->dynamic) {
8048 buffer_add_id (buf, 0);
8050 token = mono_image_get_entry_point (ass->image);
8052 buffer_add_id (buf, 0);
8055 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8057 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8058 buffer_add_methodid (buf, domain, m);
8063 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8064 buffer_add_moduleid (buf, domain, ass->image);
8067 case CMD_ASSEMBLY_GET_OBJECT: {
8069 err = get_assembly_object_command (domain, ass, buf, &error);
8070 mono_error_cleanup (&error);
8073 case CMD_ASSEMBLY_GET_DOMAIN: {
8074 buffer_add_domainid (buf, domain);
8077 case CMD_ASSEMBLY_GET_TYPE: {
8079 char *s = decode_string (p, &p, end);
8080 gboolean ignorecase = decode_byte (p, &p, end);
8081 MonoTypeNameParse info;
8083 gboolean type_resolve, res;
8084 MonoDomain *d = mono_domain_get ();
8086 /* This is needed to be able to find referenced assemblies */
8087 res = mono_domain_set (domain, FALSE);
8090 if (!mono_reflection_parse_type (s, &info)) {
8093 if (info.assembly.name)
8095 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8096 if (!is_ok (&error)) {
8097 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8098 mono_reflection_free_type_info (&info);
8100 return ERR_INVALID_ARGUMENT;
8103 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8104 mono_reflection_free_type_info (&info);
8107 mono_domain_set (d, TRUE);
8111 case CMD_ASSEMBLY_GET_NAME: {
8113 MonoAssembly *mass = ass;
8115 name = g_strdup_printf (
8116 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8118 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8119 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8120 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8121 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8123 buffer_add_string (buf, name);
8128 return ERR_NOT_IMPLEMENTED;
8135 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8141 case CMD_MODULE_GET_INFO: {
8142 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8145 basename = g_path_get_basename (image->name);
8146 buffer_add_string (buf, basename); // name
8147 buffer_add_string (buf, image->module_name); // scopename
8148 buffer_add_string (buf, image->name); // fqname
8149 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8150 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8155 return ERR_NOT_IMPLEMENTED;
8162 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8168 case CMD_FIELD_GET_INFO: {
8169 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8171 buffer_add_string (buf, f->name);
8172 buffer_add_typeid (buf, domain, f->parent);
8173 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8174 buffer_add_int (buf, f->type->attrs);
8178 return ERR_NOT_IMPLEMENTED;
8185 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8187 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8188 /* Special case these so the client doesn't have to handle Type objects */
8190 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8191 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8192 } else if (MONO_TYPE_IS_REFERENCE (t))
8193 buffer_add_value (buf, t, &val, domain);
8195 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8199 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8205 buffer_add_int (buf, 0);
8209 for (i = 0; i < cinfo->num_attrs; ++i) {
8210 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8213 buffer_add_int (buf, nattrs);
8215 for (i = 0; i < cinfo->num_attrs; ++i) {
8216 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8217 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8218 MonoArray *typed_args, *named_args;
8220 CattrNamedArg *arginfo = NULL;
8223 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8224 if (!mono_error_ok (&error)) {
8225 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8226 mono_error_cleanup (&error);
8227 return ERR_LOADER_ERROR;
8230 buffer_add_methodid (buf, domain, attr->ctor);
8234 buffer_add_int (buf, mono_array_length (typed_args));
8235 for (j = 0; j < mono_array_length (typed_args); ++j) {
8236 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8238 t = mono_method_signature (attr->ctor)->params [j];
8240 buffer_add_cattr_arg (buf, t, domain, val);
8243 buffer_add_int (buf, 0);
8248 buffer_add_int (buf, mono_array_length (named_args));
8250 for (j = 0; j < mono_array_length (named_args); ++j) {
8251 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8253 if (arginfo [j].prop) {
8254 buffer_add_byte (buf, 0x54);
8255 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8256 } else if (arginfo [j].field) {
8257 buffer_add_byte (buf, 0x53);
8258 buffer_add_fieldid (buf, domain, arginfo [j].field);
8260 g_assert_not_reached ();
8263 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8266 buffer_add_int (buf, 0);
8275 /* FIXME: Code duplication with icall.c */
8277 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8282 mono_class_setup_interfaces (klass, error);
8283 if (!mono_error_ok (error))
8286 for (i = 0; i < klass->interface_count; i++) {
8287 ic = klass->interfaces [i];
8288 g_hash_table_insert (ifaces, ic, ic);
8290 collect_interfaces (ic, ifaces, error);
8291 if (!mono_error_ok (error))
8297 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8309 case CMD_TYPE_GET_INFO: {
8310 buffer_add_string (buf, klass->name_space);
8311 buffer_add_string (buf, klass->name);
8313 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8314 buffer_add_string (buf, name);
8316 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8317 buffer_add_moduleid (buf, domain, klass->image);
8318 buffer_add_typeid (buf, domain, klass->parent);
8319 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8320 buffer_add_typeid (buf, domain, klass->element_class);
8322 buffer_add_id (buf, 0);
8323 buffer_add_int (buf, klass->type_token);
8324 buffer_add_byte (buf, klass->rank);
8325 buffer_add_int (buf, mono_class_get_flags (klass));
8327 type = &klass->byval_arg;
8328 // FIXME: Can't decide whenever a class represents a byref type
8331 if (type->type == MONO_TYPE_PTR)
8333 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8335 if (type->type == MONO_TYPE_VALUETYPE)
8337 if (klass->enumtype)
8339 if (mono_class_is_gtd (klass))
8341 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8343 buffer_add_byte (buf, b);
8346 while ((nested = mono_class_get_nested_types (klass, &iter)))
8348 buffer_add_int (buf, nnested);
8350 while ((nested = mono_class_get_nested_types (klass, &iter)))
8351 buffer_add_typeid (buf, domain, nested);
8352 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8353 if (mono_class_is_gtd (klass))
8354 buffer_add_typeid (buf, domain, klass);
8355 else if (mono_class_is_ginst (klass))
8356 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8358 buffer_add_id (buf, 0);
8360 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8363 if (mono_class_is_ginst (klass)) {
8364 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8366 count = inst->type_argc;
8367 buffer_add_int (buf, count);
8368 for (i = 0; i < count; i++)
8369 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8370 } else if (mono_class_is_gtd (klass)) {
8371 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8374 count = container->type_argc;
8375 buffer_add_int (buf, count);
8376 for (i = 0; i < count; i++) {
8377 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8378 buffer_add_typeid (buf, domain, pklass);
8381 buffer_add_int (buf, 0);
8386 case CMD_TYPE_GET_METHODS: {
8389 gpointer iter = NULL;
8392 mono_class_setup_methods (klass);
8394 nmethods = mono_class_num_methods (klass);
8396 buffer_add_int (buf, nmethods);
8398 while ((m = mono_class_get_methods (klass, &iter))) {
8399 buffer_add_methodid (buf, domain, m);
8402 g_assert (i == nmethods);
8405 case CMD_TYPE_GET_FIELDS: {
8408 gpointer iter = NULL;
8411 nfields = mono_class_num_fields (klass);
8413 buffer_add_int (buf, nfields);
8415 while ((f = mono_class_get_fields (klass, &iter))) {
8416 buffer_add_fieldid (buf, domain, f);
8417 buffer_add_string (buf, f->name);
8418 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8419 buffer_add_int (buf, f->type->attrs);
8422 g_assert (i == nfields);
8425 case CMD_TYPE_GET_PROPERTIES: {
8428 gpointer iter = NULL;
8431 nprops = mono_class_num_properties (klass);
8433 buffer_add_int (buf, nprops);
8435 while ((p = mono_class_get_properties (klass, &iter))) {
8436 buffer_add_propertyid (buf, domain, p);
8437 buffer_add_string (buf, p->name);
8438 buffer_add_methodid (buf, domain, p->get);
8439 buffer_add_methodid (buf, domain, p->set);
8440 buffer_add_int (buf, p->attrs);
8443 g_assert (i == nprops);
8446 case CMD_TYPE_GET_CATTRS: {
8447 MonoClass *attr_klass;
8448 MonoCustomAttrInfo *cinfo;
8450 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8451 /* attr_klass can be NULL */
8452 if (err != ERR_NONE)
8455 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8456 if (!is_ok (&error)) {
8457 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8458 return ERR_LOADER_ERROR;
8461 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8462 if (err != ERR_NONE)
8466 case CMD_TYPE_GET_FIELD_CATTRS: {
8467 MonoClass *attr_klass;
8468 MonoCustomAttrInfo *cinfo;
8469 MonoClassField *field;
8471 field = decode_fieldid (p, &p, end, NULL, &err);
8472 if (err != ERR_NONE)
8474 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8475 if (err != ERR_NONE)
8478 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8479 if (!is_ok (&error)) {
8480 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8481 return ERR_LOADER_ERROR;
8484 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8485 if (err != ERR_NONE)
8489 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8490 MonoClass *attr_klass;
8491 MonoCustomAttrInfo *cinfo;
8494 prop = decode_propertyid (p, &p, end, NULL, &err);
8495 if (err != ERR_NONE)
8497 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8498 if (err != ERR_NONE)
8501 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8502 if (!is_ok (&error)) {
8503 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8504 return ERR_LOADER_ERROR;
8507 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8508 if (err != ERR_NONE)
8512 case CMD_TYPE_GET_VALUES:
8513 case CMD_TYPE_GET_VALUES_2: {
8520 MonoThread *thread_obj;
8521 MonoInternalThread *thread = NULL;
8522 guint32 special_static_type;
8524 if (command == CMD_TYPE_GET_VALUES_2) {
8525 int objid = decode_objid (p, &p, end);
8528 err = get_object (objid, (MonoObject**)&thread_obj);
8529 if (err != ERR_NONE)
8532 thread = THREAD_TO_INTERNAL (thread_obj);
8535 len = decode_int (p, &p, end);
8536 for (i = 0; i < len; ++i) {
8537 f = decode_fieldid (p, &p, end, NULL, &err);
8538 if (err != ERR_NONE)
8541 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8542 return ERR_INVALID_FIELDID;
8543 special_static_type = mono_class_field_get_special_static_type (f);
8544 if (special_static_type != SPECIAL_STATIC_NONE) {
8545 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8546 return ERR_INVALID_FIELDID;
8549 /* Check that the field belongs to the object */
8551 for (k = klass; k; k = k->parent) {
8552 if (k == f->parent) {
8558 return ERR_INVALID_FIELDID;
8560 vtable = mono_class_vtable (domain, f->parent);
8561 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8562 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8563 if (!is_ok (&error))
8564 return ERR_INVALID_FIELDID;
8565 buffer_add_value (buf, f->type, val, domain);
8570 case CMD_TYPE_SET_VALUES: {
8578 len = decode_int (p, &p, end);
8579 for (i = 0; i < len; ++i) {
8580 f = decode_fieldid (p, &p, end, NULL, &err);
8581 if (err != ERR_NONE)
8584 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8585 return ERR_INVALID_FIELDID;
8586 if (mono_class_field_is_special_static (f))
8587 return ERR_INVALID_FIELDID;
8589 /* Check that the field belongs to the object */
8591 for (k = klass; k; k = k->parent) {
8592 if (k == f->parent) {
8598 return ERR_INVALID_FIELDID;
8600 // FIXME: Check for literal/const
8602 vtable = mono_class_vtable (domain, f->parent);
8603 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8604 err = decode_value (f->type, domain, val, p, &p, end);
8605 if (err != ERR_NONE) {
8609 if (MONO_TYPE_IS_REFERENCE (f->type))
8610 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8612 mono_field_static_set_value (vtable, f, val);
8617 case CMD_TYPE_GET_OBJECT: {
8618 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8619 if (!mono_error_ok (&error)) {
8620 mono_error_cleanup (&error);
8621 return ERR_INVALID_OBJECT;
8623 buffer_add_objid (buf, o);
8626 case CMD_TYPE_GET_SOURCE_FILES:
8627 case CMD_TYPE_GET_SOURCE_FILES_2: {
8628 char *source_file, *base;
8632 files = get_source_files_for_type (klass);
8634 buffer_add_int (buf, files->len);
8635 for (i = 0; i < files->len; ++i) {
8636 source_file = (char *)g_ptr_array_index (files, i);
8637 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8638 buffer_add_string (buf, source_file);
8640 base = dbg_path_get_basename (source_file);
8641 buffer_add_string (buf, base);
8644 g_free (source_file);
8646 g_ptr_array_free (files, TRUE);
8649 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8650 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8652 if (err != ERR_NONE)
8654 if (mono_class_is_assignable_from (klass, oklass))
8655 buffer_add_byte (buf, 1);
8657 buffer_add_byte (buf, 0);
8660 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8661 char *name = decode_string (p, &p, end);
8662 int i, flags = decode_int (p, &p, end);
8666 mono_error_init (&error);
8667 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8668 if (!is_ok (&error)) {
8669 mono_error_cleanup (&error);
8670 return ERR_LOADER_ERROR;
8672 buffer_add_int (buf, array->len);
8673 for (i = 0; i < array->len; ++i) {
8674 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8675 buffer_add_methodid (buf, domain, method);
8678 g_ptr_array_free (array, TRUE);
8682 case CMD_TYPE_GET_INTERFACES: {
8684 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8685 MonoClass *tclass, *iface;
8686 GHashTableIter iter;
8690 for (parent = tclass; parent; parent = parent->parent) {
8691 mono_class_setup_interfaces (parent, &error);
8692 if (!mono_error_ok (&error))
8693 return ERR_LOADER_ERROR;
8694 collect_interfaces (parent, iface_hash, &error);
8695 if (!mono_error_ok (&error))
8696 return ERR_LOADER_ERROR;
8699 buffer_add_int (buf, g_hash_table_size (iface_hash));
8701 g_hash_table_iter_init (&iter, iface_hash);
8702 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8703 buffer_add_typeid (buf, domain, iface);
8704 g_hash_table_destroy (iface_hash);
8707 case CMD_TYPE_GET_INTERFACE_MAP: {
8708 int tindex, ioffset;
8709 gboolean variance_used;
8711 int len, nmethods, i;
8715 len = decode_int (p, &p, end);
8716 mono_class_setup_vtable (klass);
8718 for (tindex = 0; tindex < len; ++tindex) {
8719 iclass = decode_typeid (p, &p, end, NULL, &err);
8720 if (err != ERR_NONE)
8723 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8725 return ERR_INVALID_ARGUMENT;
8727 nmethods = mono_class_num_methods (iclass);
8728 buffer_add_int (buf, nmethods);
8731 while ((method = mono_class_get_methods (iclass, &iter))) {
8732 buffer_add_methodid (buf, domain, method);
8734 for (i = 0; i < nmethods; ++i)
8735 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8739 case CMD_TYPE_IS_INITIALIZED: {
8740 MonoVTable *vtable = mono_class_vtable (domain, klass);
8743 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8745 buffer_add_int (buf, 0);
8748 case CMD_TYPE_CREATE_INSTANCE: {
8752 obj = mono_object_new_checked (domain, klass, &error);
8753 mono_error_assert_ok (&error);
8754 buffer_add_objid (buf, obj);
8758 return ERR_NOT_IMPLEMENTED;
8765 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8768 MonoDomain *old_domain;
8772 klass = decode_typeid (p, &p, end, &domain, &err);
8773 if (err != ERR_NONE)
8776 old_domain = mono_domain_get ();
8778 mono_domain_set (domain, TRUE);
8780 err = type_commands_internal (command, klass, domain, p, end, buf);
8782 mono_domain_set (old_domain, TRUE);
8788 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8790 MonoMethodHeader *header;
8794 case CMD_METHOD_GET_NAME: {
8795 buffer_add_string (buf, method->name);
8798 case CMD_METHOD_GET_DECLARING_TYPE: {
8799 buffer_add_typeid (buf, domain, method->klass);
8802 case CMD_METHOD_GET_DEBUG_INFO: {
8804 MonoDebugMethodInfo *minfo;
8806 int i, j, n_il_offsets;
8808 GPtrArray *source_file_list;
8809 MonoSymSeqPoint *sym_seq_points;
8811 header = mono_method_get_header_checked (method, &error);
8813 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8814 buffer_add_int (buf, 0);
8815 buffer_add_string (buf, "");
8816 buffer_add_int (buf, 0);
8820 minfo = mono_debug_lookup_method (method);
8822 buffer_add_int (buf, header->code_size);
8823 buffer_add_string (buf, "");
8824 buffer_add_int (buf, 0);
8825 mono_metadata_free_mh (header);
8829 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8830 buffer_add_int (buf, header->code_size);
8831 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8832 buffer_add_int (buf, source_file_list->len);
8833 for (i = 0; i < source_file_list->len; ++i) {
8834 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8835 buffer_add_string (buf, sinfo->source_file);
8836 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8837 for (j = 0; j < 16; ++j)
8838 buffer_add_byte (buf, sinfo->hash [j]);
8842 buffer_add_string (buf, source_file);
8844 buffer_add_int (buf, n_il_offsets);
8845 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8846 for (i = 0; i < n_il_offsets; ++i) {
8847 MonoSymSeqPoint *sp = &sym_seq_points [i];
8848 const char *srcfile = "";
8850 if (source_files [i] != -1) {
8851 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8852 srcfile = sinfo->source_file;
8854 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);
8855 buffer_add_int (buf, sp->il_offset);
8856 buffer_add_int (buf, sp->line);
8857 if (CHECK_PROTOCOL_VERSION (2, 13))
8858 buffer_add_int (buf, source_files [i]);
8859 if (CHECK_PROTOCOL_VERSION (2, 19))
8860 buffer_add_int (buf, sp->column);
8861 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8862 buffer_add_int (buf, sp->end_line);
8863 buffer_add_int (buf, sp->end_column);
8866 g_free (source_file);
8867 g_free (source_files);
8868 g_free (sym_seq_points);
8869 g_ptr_array_free (source_file_list, TRUE);
8870 mono_metadata_free_mh (header);
8873 case CMD_METHOD_GET_PARAM_INFO: {
8874 MonoMethodSignature *sig = mono_method_signature (method);
8878 /* FIXME: mono_class_from_mono_type () and byrefs */
8880 /* FIXME: Use a smaller encoding */
8881 buffer_add_int (buf, sig->call_convention);
8882 buffer_add_int (buf, sig->param_count);
8883 buffer_add_int (buf, sig->generic_param_count);
8884 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8885 for (i = 0; i < sig->param_count; ++i) {
8887 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8890 /* Emit parameter names */
8891 names = g_new (char *, sig->param_count);
8892 mono_method_get_param_names (method, (const char **) names);
8893 for (i = 0; i < sig->param_count; ++i)
8894 buffer_add_string (buf, names [i]);
8899 case CMD_METHOD_GET_LOCALS_INFO: {
8902 MonoDebugLocalsInfo *locals;
8903 int *locals_map = NULL;
8905 header = mono_method_get_header_checked (method, &error);
8907 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8908 return ERR_INVALID_ARGUMENT;
8911 locals = mono_debug_lookup_locals (method);
8913 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8915 buffer_add_int (buf, 1);
8916 buffer_add_int (buf, 0);
8917 buffer_add_int (buf, header->code_size);
8919 buffer_add_int (buf, header->num_locals);
8921 for (i = 0; i < header->num_locals; ++i) {
8922 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8925 for (i = 0; i < header->num_locals; ++i) {
8927 sprintf (lname, "V_%d", i);
8928 buffer_add_string (buf, lname);
8931 for (i = 0; i < header->num_locals; ++i) {
8932 buffer_add_int (buf, 0);
8933 buffer_add_int (buf, header->code_size);
8936 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8938 buffer_add_int (buf, locals->num_blocks);
8940 for (i = 0; i < locals->num_blocks; ++i) {
8941 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8942 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8943 last_start = locals->code_blocks [i].start_offset;
8947 num_locals = locals->num_locals;
8948 buffer_add_int (buf, num_locals);
8951 for (i = 0; i < num_locals; ++i) {
8952 g_assert (locals->locals [i].index < header->num_locals);
8953 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8956 for (i = 0; i < num_locals; ++i)
8957 buffer_add_string (buf, locals->locals [i].name);
8959 for (i = 0; i < num_locals; ++i) {
8960 if (locals->locals [i].block) {
8961 buffer_add_int (buf, locals->locals [i].block->start_offset);
8962 buffer_add_int (buf, locals->locals [i].block->end_offset);
8964 buffer_add_int (buf, 0);
8965 buffer_add_int (buf, header->code_size);
8969 mono_metadata_free_mh (header);
8972 mono_debug_free_locals (locals);
8973 g_free (locals_map);
8977 case CMD_METHOD_GET_INFO:
8978 buffer_add_int (buf, method->flags);
8979 buffer_add_int (buf, method->iflags);
8980 buffer_add_int (buf, method->token);
8981 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8983 if (method->is_generic)
8985 if (mono_method_signature (method)->generic_param_count)
8987 buffer_add_byte (buf, attrs);
8988 if (method->is_generic || method->is_inflated) {
8991 if (method->is_generic) {
8994 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8996 result = imethod->declaring;
8997 if (imethod->context.class_inst) {
8998 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8999 /*Generic methods gets the context of the GTD.*/
9000 if (mono_class_get_context (klass)) {
9002 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
9003 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9008 buffer_add_methodid (buf, domain, result);
9010 buffer_add_id (buf, 0);
9012 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9013 if (mono_method_signature (method)->generic_param_count) {
9016 if (method->is_inflated) {
9017 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9019 count = inst->type_argc;
9020 buffer_add_int (buf, count);
9022 for (i = 0; i < count; i++)
9023 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9025 buffer_add_int (buf, 0);
9027 } else if (method->is_generic) {
9028 MonoGenericContainer *container = mono_method_get_generic_container (method);
9030 count = mono_method_signature (method)->generic_param_count;
9031 buffer_add_int (buf, count);
9032 for (i = 0; i < count; i++) {
9033 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9034 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9035 buffer_add_typeid (buf, domain, pklass);
9038 buffer_add_int (buf, 0);
9041 buffer_add_int (buf, 0);
9046 case CMD_METHOD_GET_BODY: {
9050 header = mono_method_get_header_checked (method, &error);
9052 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9053 buffer_add_int (buf, 0);
9055 if (CHECK_PROTOCOL_VERSION (2, 18))
9056 buffer_add_int (buf, 0);
9058 buffer_add_int (buf, header->code_size);
9059 for (i = 0; i < header->code_size; ++i)
9060 buffer_add_byte (buf, header->code [i]);
9062 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9063 buffer_add_int (buf, header->num_clauses);
9064 for (i = 0; i < header->num_clauses; ++i) {
9065 MonoExceptionClause *clause = &header->clauses [i];
9067 buffer_add_int (buf, clause->flags);
9068 buffer_add_int (buf, clause->try_offset);
9069 buffer_add_int (buf, clause->try_len);
9070 buffer_add_int (buf, clause->handler_offset);
9071 buffer_add_int (buf, clause->handler_len);
9072 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9073 buffer_add_typeid (buf, domain, clause->data.catch_class);
9074 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9075 buffer_add_int (buf, clause->data.filter_offset);
9079 mono_metadata_free_mh (header);
9084 case CMD_METHOD_RESOLVE_TOKEN: {
9085 guint32 token = decode_int (p, &p, end);
9088 switch (mono_metadata_token_code (token)) {
9089 case MONO_TOKEN_STRING: {
9094 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9095 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9097 s2 = mono_string_to_utf8_checked (s, &error);
9098 mono_error_assert_ok (&error);
9100 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9101 buffer_add_string (buf, s2);
9108 MonoClass *handle_class;
9110 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9111 val = mono_method_get_wrapper_data (method, token);
9112 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9114 if (handle_class == NULL) {
9115 // Can't figure out the token type
9116 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9120 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9122 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9125 if (handle_class == mono_defaults.typehandle_class) {
9126 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9127 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9128 buffer_add_typeid (buf, domain, (MonoClass *) val);
9130 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9131 } else if (handle_class == mono_defaults.fieldhandle_class) {
9132 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9133 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9134 } else if (handle_class == mono_defaults.methodhandle_class) {
9135 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9136 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9137 } else if (handle_class == mono_defaults.string_class) {
9140 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9141 mono_error_assert_ok (&error);
9142 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9143 buffer_add_string (buf, s);
9146 g_assert_not_reached ();
9153 case CMD_METHOD_GET_CATTRS: {
9155 MonoClass *attr_klass;
9156 MonoCustomAttrInfo *cinfo;
9158 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9159 /* attr_klass can be NULL */
9160 if (err != ERR_NONE)
9163 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9164 if (!is_ok (&error)) {
9165 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9166 return ERR_LOADER_ERROR;
9169 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9170 if (err != ERR_NONE)
9174 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9176 MonoType **type_argv;
9180 MonoGenericInst *ginst;
9181 MonoGenericContext tmp_context;
9182 MonoMethod *inflated;
9184 type_argc = decode_int (p, &p, end);
9185 type_argv = g_new0 (MonoType*, type_argc);
9186 for (i = 0; i < type_argc; ++i) {
9187 klass = decode_typeid (p, &p, end, &d, &err);
9188 if (err != ERR_NONE) {
9194 return ERR_INVALID_ARGUMENT;
9196 type_argv [i] = &klass->byval_arg;
9198 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9200 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9201 tmp_context.method_inst = ginst;
9203 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9204 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9205 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9206 return ERR_INVALID_ARGUMENT;
9207 buffer_add_methodid (buf, domain, inflated);
9211 return ERR_NOT_IMPLEMENTED;
9218 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9221 MonoDomain *old_domain;
9225 method = decode_methodid (p, &p, end, &domain, &err);
9226 if (err != ERR_NONE)
9229 old_domain = mono_domain_get ();
9231 mono_domain_set (domain, TRUE);
9233 err = method_commands_internal (command, method, domain, p, end, buf);
9235 mono_domain_set (old_domain, TRUE);
9241 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9243 int objid = decode_objid (p, &p, end);
9245 MonoThread *thread_obj;
9246 MonoInternalThread *thread;
9248 err = get_object (objid, (MonoObject**)&thread_obj);
9249 if (err != ERR_NONE)
9252 thread = THREAD_TO_INTERNAL (thread_obj);
9255 case CMD_THREAD_GET_NAME: {
9257 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9260 buffer_add_int (buf, 0);
9265 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9267 buffer_add_int (buf, len);
9268 buffer_add_data (buf, (guint8*)name, len);
9273 case CMD_THREAD_GET_FRAME_INFO: {
9274 DebuggerTlsData *tls;
9275 int i, start_frame, length;
9277 // Wait for suspending if it already started
9278 // FIXME: Races with suspend_count
9279 while (!is_suspended ()) {
9281 wait_for_suspend ();
9285 wait_for_suspend ();
9286 if (!is_suspended ())
9287 return ERR_NOT_SUSPENDED;
9290 start_frame = decode_int (p, &p, end);
9291 length = decode_int (p, &p, end);
9293 if (start_frame != 0 || length != -1)
9294 return ERR_NOT_IMPLEMENTED;
9296 mono_loader_lock ();
9297 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9298 mono_loader_unlock ();
9301 compute_frame_info (thread, tls);
9303 buffer_add_int (buf, tls->frame_count);
9304 for (i = 0; i < tls->frame_count; ++i) {
9305 buffer_add_int (buf, tls->frames [i]->id);
9306 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9307 buffer_add_int (buf, tls->frames [i]->il_offset);
9309 * Instead of passing the frame type directly to the client, we associate
9310 * it with the previous frame using a set of flags. This avoids lots of
9311 * conditional code in the client, since a frame whose type isn't
9312 * FRAME_TYPE_MANAGED has no method, location, etc.
9314 buffer_add_byte (buf, tls->frames [i]->flags);
9319 case CMD_THREAD_GET_STATE:
9320 buffer_add_int (buf, thread->state);
9322 case CMD_THREAD_GET_INFO:
9323 buffer_add_byte (buf, thread->threadpool_thread);
9325 case CMD_THREAD_GET_ID:
9326 buffer_add_long (buf, (guint64)(gsize)thread);
9328 case CMD_THREAD_GET_TID:
9329 buffer_add_long (buf, (guint64)thread->tid);
9331 case CMD_THREAD_SET_IP: {
9332 DebuggerTlsData *tls;
9335 MonoSeqPointInfo *seq_points;
9340 method = decode_methodid (p, &p, end, &domain, &err);
9341 if (err != ERR_NONE)
9343 il_offset = decode_long (p, &p, end);
9345 while (!is_suspended ()) {
9347 wait_for_suspend ();
9350 mono_loader_lock ();
9351 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9352 mono_loader_unlock ();
9355 compute_frame_info (thread, tls);
9356 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9357 return ERR_INVALID_ARGUMENT;
9359 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9361 g_assert (seq_points);
9364 return ERR_INVALID_ARGUMENT;
9366 // FIXME: Check that the ip change is safe
9368 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);
9369 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9373 return ERR_NOT_IMPLEMENTED;
9380 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9384 MonoThread *thread_obj;
9385 MonoInternalThread *thread;
9386 int pos, i, len, frame_idx;
9387 DebuggerTlsData *tls;
9389 MonoDebugMethodJitInfo *jit;
9390 MonoMethodSignature *sig;
9392 MonoMethodHeader *header;
9394 objid = decode_objid (p, &p, end);
9395 err = get_object (objid, (MonoObject**)&thread_obj);
9396 if (err != ERR_NONE)
9399 thread = THREAD_TO_INTERNAL (thread_obj);
9401 id = decode_id (p, &p, end);
9403 mono_loader_lock ();
9404 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9405 mono_loader_unlock ();
9408 for (i = 0; i < tls->frame_count; ++i) {
9409 if (tls->frames [i]->id == id)
9412 if (i == tls->frame_count)
9413 return ERR_INVALID_FRAMEID;
9416 frame = tls->frames [frame_idx];
9418 /* This is supported for frames without has_ctx etc. set */
9419 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9420 if (CHECK_PROTOCOL_VERSION (2, 38))
9421 buffer_add_domainid (buf, frame->domain);
9425 if (!frame->has_ctx)
9426 return ERR_ABSENT_INFORMATION;
9428 if (!ensure_jit (frame))
9429 return ERR_ABSENT_INFORMATION;
9433 sig = mono_method_signature (frame->actual_method);
9435 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9437 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9439 return ERR_ABSENT_INFORMATION;
9442 case CMD_STACK_FRAME_GET_VALUES: {
9444 len = decode_int (p, &p, end);
9445 header = mono_method_get_header_checked (frame->actual_method, &error);
9446 mono_error_assert_ok (&error); /* FIXME report error */
9448 for (i = 0; i < len; ++i) {
9449 pos = decode_int (p, &p, end);
9454 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9456 g_assert (pos >= 0 && pos < jit->num_params);
9458 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9460 MonoDebugLocalsInfo *locals;
9462 locals = mono_debug_lookup_locals (frame->method);
9464 g_assert (pos < locals->num_locals);
9465 pos = locals->locals [pos].index;
9466 mono_debug_free_locals (locals);
9468 g_assert (pos >= 0 && pos < jit->num_locals);
9470 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9472 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9475 mono_metadata_free_mh (header);
9478 case CMD_STACK_FRAME_GET_THIS: {
9479 if (frame->api_method->klass->valuetype) {
9480 if (!sig->hasthis) {
9481 MonoObject *p = NULL;
9482 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9484 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9487 if (!sig->hasthis) {
9488 MonoObject *p = NULL;
9489 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9491 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9496 case CMD_STACK_FRAME_SET_VALUES: {
9500 MonoDebugVarInfo *var;
9502 len = decode_int (p, &p, end);
9503 header = mono_method_get_header_checked (frame->actual_method, &error);
9504 mono_error_assert_ok (&error); /* FIXME report error */
9506 for (i = 0; i < len; ++i) {
9507 pos = decode_int (p, &p, end);
9512 g_assert (pos >= 0 && pos < jit->num_params);
9514 t = sig->params [pos];
9515 var = &jit->params [pos];
9517 MonoDebugLocalsInfo *locals;
9519 locals = mono_debug_lookup_locals (frame->method);
9521 g_assert (pos < locals->num_locals);
9522 pos = locals->locals [pos].index;
9523 mono_debug_free_locals (locals);
9525 g_assert (pos >= 0 && pos < jit->num_locals);
9527 t = header->locals [pos];
9528 var = &jit->locals [pos];
9531 if (MONO_TYPE_IS_REFERENCE (t))
9532 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9534 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9535 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9536 if (err != ERR_NONE)
9539 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9541 mono_metadata_free_mh (header);
9544 case CMD_STACK_FRAME_GET_DOMAIN: {
9545 if (CHECK_PROTOCOL_VERSION (2, 38))
9546 buffer_add_domainid (buf, frame->domain);
9549 case CMD_STACK_FRAME_SET_THIS: {
9552 MonoDebugVarInfo *var;
9554 t = &frame->actual_method->klass->byval_arg;
9555 /* Checked by the sender */
9556 g_assert (MONO_TYPE_ISSTRUCT (t));
9557 var = jit->this_var;
9560 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9561 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9562 if (err != ERR_NONE)
9565 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9569 return ERR_NOT_IMPLEMENTED;
9576 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9579 int objid, index, len, i, esize;
9583 objid = decode_objid (p, &p, end);
9584 err = get_object (objid, (MonoObject**)&arr);
9585 if (err != ERR_NONE)
9589 case CMD_ARRAY_REF_GET_LENGTH:
9590 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9592 buffer_add_int (buf, arr->max_length);
9593 buffer_add_int (buf, 0);
9595 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9596 buffer_add_int (buf, arr->bounds [i].length);
9597 buffer_add_int (buf, arr->bounds [i].lower_bound);
9601 case CMD_ARRAY_REF_GET_VALUES:
9602 index = decode_int (p, &p, end);
9603 len = decode_int (p, &p, end);
9605 g_assert (index >= 0 && len >= 0);
9606 // Reordered to avoid integer overflow
9607 g_assert (!(index > arr->max_length - len));
9609 esize = mono_array_element_size (arr->obj.vtable->klass);
9610 for (i = index; i < index + len; ++i) {
9611 elem = (gpointer*)((char*)arr->vector + (i * esize));
9612 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9615 case CMD_ARRAY_REF_SET_VALUES:
9616 index = decode_int (p, &p, end);
9617 len = decode_int (p, &p, end);
9619 g_assert (index >= 0 && len >= 0);
9620 // Reordered to avoid integer overflow
9621 g_assert (!(index > arr->max_length - len));
9623 esize = mono_array_element_size (arr->obj.vtable->klass);
9624 for (i = index; i < index + len; ++i) {
9625 elem = (gpointer*)((char*)arr->vector + (i * esize));
9627 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9631 return ERR_NOT_IMPLEMENTED;
9638 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9644 int i, index, length;
9646 gboolean use_utf16 = FALSE;
9648 objid = decode_objid (p, &p, end);
9649 err = get_object (objid, (MonoObject**)&str);
9650 if (err != ERR_NONE)
9654 case CMD_STRING_REF_GET_VALUE:
9655 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9656 for (i = 0; i < mono_string_length (str); ++i)
9657 if (mono_string_chars (str)[i] == 0)
9659 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9662 buffer_add_int (buf, mono_string_length (str) * 2);
9663 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9666 s = mono_string_to_utf8_checked (str, &error);
9667 mono_error_assert_ok (&error);
9668 buffer_add_string (buf, s);
9672 case CMD_STRING_REF_GET_LENGTH:
9673 buffer_add_long (buf, mono_string_length (str));
9675 case CMD_STRING_REF_GET_CHARS:
9676 index = decode_long (p, &p, end);
9677 length = decode_long (p, &p, end);
9678 if (index > mono_string_length (str) - length)
9679 return ERR_INVALID_ARGUMENT;
9680 c = mono_string_chars (str) + index;
9681 for (i = 0; i < length; ++i)
9682 buffer_add_short (buf, c [i]);
9685 return ERR_NOT_IMPLEMENTED;
9692 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9703 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9704 objid = decode_objid (p, &p, end);
9705 err = get_object (objid, &obj);
9706 if (err != ERR_NONE)
9707 buffer_add_int (buf, 1);
9709 buffer_add_int (buf, 0);
9713 objid = decode_objid (p, &p, end);
9714 err = get_object (objid, &obj);
9715 if (err != ERR_NONE)
9718 MonoClass *obj_type;
9719 gboolean remote_obj = FALSE;
9721 obj_type = obj->vtable->klass;
9722 if (mono_class_is_transparent_proxy (obj_type)) {
9723 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9727 g_assert (obj_type);
9730 case CMD_OBJECT_REF_GET_TYPE:
9731 /* This handles transparent proxies too */
9732 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9734 case CMD_OBJECT_REF_GET_VALUES:
9735 len = decode_int (p, &p, end);
9737 for (i = 0; i < len; ++i) {
9738 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9739 if (err != ERR_NONE)
9742 /* Check that the field belongs to the object */
9744 for (k = obj_type; k; k = k->parent) {
9745 if (k == f->parent) {
9751 return ERR_INVALID_FIELDID;
9753 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9757 if (mono_class_field_is_special_static (f))
9758 return ERR_INVALID_FIELDID;
9760 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9761 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9762 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9763 mono_field_static_get_value_checked (vtable, f, val, &error);
9764 if (!is_ok (&error)) {
9765 mono_error_cleanup (&error); /* FIXME report the error */
9766 return ERR_INVALID_OBJECT;
9768 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9771 guint8 *field_value = NULL;
9774 #ifndef DISABLE_REMOTING
9775 void *field_storage = NULL;
9776 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9777 if (!is_ok (&error)) {
9778 mono_error_cleanup (&error); /* FIXME report the error */
9779 return ERR_INVALID_OBJECT;
9782 g_assert_not_reached ();
9785 field_value = (guint8*)obj + f->offset;
9787 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9791 case CMD_OBJECT_REF_SET_VALUES:
9792 len = decode_int (p, &p, end);
9794 for (i = 0; i < len; ++i) {
9795 f = decode_fieldid (p, &p, end, NULL, &err);
9796 if (err != ERR_NONE)
9799 /* Check that the field belongs to the object */
9801 for (k = obj_type; k; k = k->parent) {
9802 if (k == f->parent) {
9808 return ERR_INVALID_FIELDID;
9810 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9814 if (mono_class_field_is_special_static (f))
9815 return ERR_INVALID_FIELDID;
9817 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9818 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9820 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9821 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9822 if (err != ERR_NONE) {
9826 mono_field_static_set_value (vtable, f, val);
9829 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9830 if (err != ERR_NONE)
9835 case CMD_OBJECT_REF_GET_ADDRESS:
9836 buffer_add_long (buf, (gssize)obj);
9838 case CMD_OBJECT_REF_GET_DOMAIN:
9839 buffer_add_domainid (buf, obj->vtable->domain);
9841 case CMD_OBJECT_REF_GET_INFO:
9842 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9843 buffer_add_domainid (buf, obj->vtable->domain);
9846 return ERR_NOT_IMPLEMENTED;
9853 command_set_to_string (CommandSet command_set)
9855 switch (command_set) {
9858 case CMD_SET_OBJECT_REF:
9859 return "OBJECT_REF";
9860 case CMD_SET_STRING_REF:
9861 return "STRING_REF";
9862 case CMD_SET_THREAD:
9864 case CMD_SET_ARRAY_REF:
9866 case CMD_SET_EVENT_REQUEST:
9867 return "EVENT_REQUEST";
9868 case CMD_SET_STACK_FRAME:
9869 return "STACK_FRAME";
9870 case CMD_SET_APPDOMAIN:
9872 case CMD_SET_ASSEMBLY:
9874 case CMD_SET_METHOD:
9878 case CMD_SET_MODULE:
9889 static const char* vm_cmds_str [] = {
9897 "SET_PROTOCOL_VERSION",
9900 "GET_TYPES_FOR_SOURCE_FILE",
9905 static const char* thread_cmds_str[] = {
9915 static const char* event_cmds_str[] = {
9918 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9921 static const char* appdomain_cmds_str[] = {
9923 "GET_FRIENDLY_NAME",
9925 "GET_ENTRY_ASSEMBLY",
9928 "CREATE_BOXED_VALUE"
9931 static const char* assembly_cmds_str[] = {
9934 "GET_MANIFEST_MODULE",
9941 static const char* module_cmds_str[] = {
9945 static const char* field_cmds_str[] = {
9949 static const char* method_cmds_str[] = {
9951 "GET_DECLARING_TYPE",
9959 "MAKE_GENERIC_METHOD"
9962 static const char* type_cmds_str[] = {
9970 "IS_ASSIGNABLE_FROM",
9974 "GET_PROPERTY_CATTRS",
9975 "GET_SOURCE_FILES_2",
9977 "GET_METHODS_BY_NAME_FLAGS",
9979 "GET_INTERFACE_MAP",
9983 static const char* stack_frame_cmds_str[] = {
9991 static const char* array_cmds_str[] = {
9997 static const char* string_cmds_str[] = {
10003 static const char* object_cmds_str[] = {
10014 cmd_to_string (CommandSet set, int command)
10021 cmds = vm_cmds_str;
10022 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10024 case CMD_SET_OBJECT_REF:
10025 cmds = object_cmds_str;
10026 cmds_len = G_N_ELEMENTS (object_cmds_str);
10028 case CMD_SET_STRING_REF:
10029 cmds = string_cmds_str;
10030 cmds_len = G_N_ELEMENTS (string_cmds_str);
10032 case CMD_SET_THREAD:
10033 cmds = thread_cmds_str;
10034 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10036 case CMD_SET_ARRAY_REF:
10037 cmds = array_cmds_str;
10038 cmds_len = G_N_ELEMENTS (array_cmds_str);
10040 case CMD_SET_EVENT_REQUEST:
10041 cmds = event_cmds_str;
10042 cmds_len = G_N_ELEMENTS (event_cmds_str);
10044 case CMD_SET_STACK_FRAME:
10045 cmds = stack_frame_cmds_str;
10046 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10048 case CMD_SET_APPDOMAIN:
10049 cmds = appdomain_cmds_str;
10050 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10052 case CMD_SET_ASSEMBLY:
10053 cmds = assembly_cmds_str;
10054 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10056 case CMD_SET_METHOD:
10057 cmds = method_cmds_str;
10058 cmds_len = G_N_ELEMENTS (method_cmds_str);
10061 cmds = type_cmds_str;
10062 cmds_len = G_N_ELEMENTS (type_cmds_str);
10064 case CMD_SET_MODULE:
10065 cmds = module_cmds_str;
10066 cmds_len = G_N_ELEMENTS (module_cmds_str);
10068 case CMD_SET_FIELD:
10069 cmds = field_cmds_str;
10070 cmds_len = G_N_ELEMENTS (field_cmds_str);
10072 case CMD_SET_EVENT:
10073 cmds = event_cmds_str;
10074 cmds_len = G_N_ELEMENTS (event_cmds_str);
10079 if (command > 0 && command <= cmds_len)
10080 return cmds [command - 1];
10086 wait_for_attach (void)
10088 #ifndef DISABLE_SOCKET_TRANSPORT
10089 if (listen_fd == -1) {
10090 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10094 /* Block and wait for client connection */
10095 conn_fd = socket_transport_accept (listen_fd);
10097 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10098 if (conn_fd == -1) {
10099 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10103 g_assert_not_reached ();
10107 disconnected = !transport_handshake ();
10108 if (disconnected) {
10109 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10119 * This thread handles communication with the debugger client using a JDWP
10122 static gsize WINAPI
10123 debugger_thread (void *arg)
10126 int res, len, id, flags, command = 0;
10127 CommandSet command_set = (CommandSet)0;
10128 guint8 header [HEADER_LENGTH];
10129 guint8 *data, *p, *end;
10133 gboolean attach_failed = FALSE;
10135 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10137 debugger_thread_id = mono_native_thread_id_get ();
10139 MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
10140 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, FALSE, &error);
10141 mono_error_assert_ok (&error);
10143 thread->internal_thread->state |= ThreadState_Background;
10144 thread->internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10146 if (agent_config.defer) {
10147 if (!wait_for_attach ()) {
10148 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10149 attach_failed = TRUE; // Don't abort process when we can't listen
10151 mono_set_is_debugger_attached (TRUE);
10152 /* Send start event to client */
10153 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10156 mono_set_is_debugger_attached (TRUE);
10159 while (!attach_failed) {
10160 res = transport_recv (header, HEADER_LENGTH);
10162 /* This will break if the socket is closed during shutdown too */
10163 if (res != HEADER_LENGTH) {
10164 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10169 end = header + HEADER_LENGTH;
10171 len = decode_int (p, &p, end);
10172 id = decode_int (p, &p, end);
10173 flags = decode_byte (p, &p, end);
10174 command_set = (CommandSet)decode_byte (p, &p, end);
10175 command = decode_byte (p, &p, end);
10177 g_assert (flags == 0);
10180 const char *cmd_str;
10181 char cmd_num [256];
10183 cmd_str = cmd_to_string (command_set, command);
10185 sprintf (cmd_num, "%d", command);
10189 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);
10192 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10193 if (len - HEADER_LENGTH > 0)
10195 res = transport_recv (data, len - HEADER_LENGTH);
10196 if (res != len - HEADER_LENGTH) {
10197 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10203 end = data + (len - HEADER_LENGTH);
10205 buffer_init (&buf, 128);
10210 /* Process the request */
10211 switch (command_set) {
10213 err = vm_commands (command, id, p, end, &buf);
10214 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10215 /* Sent after the invoke is complete */
10218 case CMD_SET_EVENT_REQUEST:
10219 err = event_commands (command, p, end, &buf);
10221 case CMD_SET_APPDOMAIN:
10222 err = domain_commands (command, p, end, &buf);
10224 case CMD_SET_ASSEMBLY:
10225 err = assembly_commands (command, p, end, &buf);
10227 case CMD_SET_MODULE:
10228 err = module_commands (command, p, end, &buf);
10230 case CMD_SET_FIELD:
10231 err = field_commands (command, p, end, &buf);
10234 err = type_commands (command, p, end, &buf);
10236 case CMD_SET_METHOD:
10237 err = method_commands (command, p, end, &buf);
10239 case CMD_SET_THREAD:
10240 err = thread_commands (command, p, end, &buf);
10242 case CMD_SET_STACK_FRAME:
10243 err = frame_commands (command, p, end, &buf);
10245 case CMD_SET_ARRAY_REF:
10246 err = array_commands (command, p, end, &buf);
10248 case CMD_SET_STRING_REF:
10249 err = string_commands (command, p, end, &buf);
10251 case CMD_SET_OBJECT_REF:
10252 err = object_commands (command, p, end, &buf);
10255 err = ERR_NOT_IMPLEMENTED;
10258 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10259 buffer_replies = TRUE;
10263 if (buffer_replies) {
10264 buffer_reply_packet (id, err, &buf);
10266 send_reply_packet (id, err, &buf);
10267 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10271 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10272 send_buffered_reply_packets ();
10273 buffer_replies = FALSE;
10277 buffer_free (&buf);
10279 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10283 mono_set_is_debugger_attached (FALSE);
10285 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10286 debugger_thread_exited = TRUE;
10287 mono_coop_cond_signal (&debugger_thread_exited_cond);
10288 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10290 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10292 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10293 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10294 start_debugger_thread ();
10300 #else /* DISABLE_DEBUGGER_AGENT */
10303 mono_debugger_agent_parse_options (char *options)
10305 g_error ("This runtime is configured with the debugger agent disabled.");
10309 mono_debugger_agent_init (void)
10314 mono_debugger_agent_breakpoint_hit (void *sigctx)
10319 mono_debugger_agent_single_step_event (void *sigctx)
10324 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10329 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10330 MonoContext *catch_ctx)
10335 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10340 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10345 mono_debugger_agent_user_break (void)
10351 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10356 mono_debugger_agent_debug_log_is_enabled (void)
10362 mono_debugger_agent_unhandled_exception (MonoException *exc)
10364 g_assert_not_reached ();
10368 debugger_agent_single_step_from_context (MonoContext *ctx)
10370 g_assert_not_reached ();
10374 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10376 g_assert_not_reached ();