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 *host = (char *)g_malloc (pos - address + 1);
834 strncpy (*host, address, pos - address);
835 (*host) [pos - address] = '\0';
837 *port = atoi (pos + 1);
845 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
846 fprintf (stderr, "Available options:\n");
847 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
848 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
849 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
850 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
851 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
852 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
853 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
854 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
855 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
856 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
860 parse_flag (const char *option, char *flag)
862 if (!strcmp (flag, "y"))
864 else if (!strcmp (flag, "n"))
867 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
874 mono_debugger_agent_parse_options (char *options)
881 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
882 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
886 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
888 options = g_strdup_printf ("%s,%s", options, extra);
890 agent_config.enabled = TRUE;
891 agent_config.suspend = TRUE;
892 agent_config.server = FALSE;
893 agent_config.defer = FALSE;
894 agent_config.address = NULL;
896 //agent_config.log_level = 10;
898 args = g_strsplit (options, ",", -1);
899 for (ptr = args; ptr && *ptr; ptr ++) {
902 if (strncmp (arg, "transport=", 10) == 0) {
903 agent_config.transport = g_strdup (arg + 10);
904 } else if (strncmp (arg, "address=", 8) == 0) {
905 agent_config.address = g_strdup (arg + 8);
906 } else if (strncmp (arg, "loglevel=", 9) == 0) {
907 agent_config.log_level = atoi (arg + 9);
908 } else if (strncmp (arg, "logfile=", 8) == 0) {
909 agent_config.log_file = g_strdup (arg + 8);
910 } else if (strncmp (arg, "suspend=", 8) == 0) {
911 agent_config.suspend = parse_flag ("suspend", arg + 8);
912 } else if (strncmp (arg, "server=", 7) == 0) {
913 agent_config.server = parse_flag ("server", arg + 7);
914 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
915 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
916 } else if (strncmp (arg, "onthrow=", 8) == 0) {
917 /* We support multiple onthrow= options */
918 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
919 } else if (strncmp (arg, "onthrow", 7) == 0) {
920 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
921 } else if (strncmp (arg, "help", 4) == 0) {
924 } else if (strncmp (arg, "timeout=", 8) == 0) {
925 agent_config.timeout = atoi (arg + 8);
926 } else if (strncmp (arg, "launch=", 7) == 0) {
927 agent_config.launch = g_strdup (arg + 7);
928 } else if (strncmp (arg, "embedding=", 10) == 0) {
929 agent_config.embedding = atoi (arg + 10) == 1;
930 } else if (strncmp (arg, "keepalive=", 10) == 0) {
931 agent_config.keepalive = atoi (arg + 10);
932 } else if (strncmp (arg, "setpgid=", 8) == 0) {
933 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
940 if (agent_config.server && !agent_config.suspend) {
941 /* Waiting for deferred attachment */
942 agent_config.defer = TRUE;
943 if (agent_config.address == NULL) {
944 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
948 //agent_config.log_level = 0;
950 if (agent_config.transport == NULL) {
951 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
955 if (agent_config.address == NULL && !agent_config.server) {
956 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
961 if (!strcmp (agent_config.transport, "dt_socket")) {
962 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
963 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
970 mono_debugger_agent_init (void)
972 mono_coop_mutex_init_recursive (&debug_mutex);
974 if (!agent_config.enabled)
979 /* Need to know whenever a thread has acquired the loader mutex */
980 mono_loader_lock_track_ownership (TRUE);
982 event_requests = g_ptr_array_new ();
984 mono_coop_mutex_init (&debugger_thread_exited_mutex);
985 mono_coop_cond_init (&debugger_thread_exited_cond);
987 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
988 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
989 mono_profiler_install_runtime_initialized (runtime_initialized);
990 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
991 mono_profiler_install_thread (thread_startup, thread_end);
992 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
993 mono_profiler_install_jit_end (jit_end);
995 mono_native_tls_alloc (&debugger_tls_id, NULL);
997 /* Needed by the hash_table_new_type () call below */
998 mono_gc_base_init ();
1000 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
1001 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
1003 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1004 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1006 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");
1007 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
1009 pending_assembly_loads = g_ptr_array_new ();
1010 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1012 log_level = agent_config.log_level;
1014 embedding = agent_config.embedding;
1015 disconnected = TRUE;
1017 if (agent_config.log_file) {
1018 log_file = fopen (agent_config.log_file, "w+");
1020 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1029 breakpoints_init ();
1032 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1034 * This is needed because currently we don't handle liveness info.
1036 mini_get_debug_options ()->mdb_optimizations = TRUE;
1038 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1039 /* This is needed because we can't set local variables in registers yet */
1040 mono_disable_optimizations (MONO_OPT_LINEARS);
1044 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1045 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1046 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1049 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1052 if (agent_config.setpgid)
1056 if (!agent_config.onuncaught && !agent_config.onthrow)
1057 finish_agent_init (TRUE);
1061 * finish_agent_init:
1063 * Finish the initialization of the agent. This involves connecting the transport
1064 * and starting the agent thread. This is either done at startup, or
1065 * in response to some event like an unhandled exception.
1068 finish_agent_init (gboolean on_startup)
1072 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1075 if (agent_config.launch) {
1078 // FIXME: Generated address
1079 // FIXME: Races with transport_connect ()
1081 argv [0] = agent_config.launch;
1082 argv [1] = agent_config.transport;
1083 argv [2] = agent_config.address;
1086 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1088 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1093 transport_connect (agent_config.address);
1096 /* Do some which is usually done after sending the VMStart () event */
1097 vm_start_event_sent = TRUE;
1098 start_debugger_thread ();
1103 mono_debugger_agent_cleanup (void)
1108 stop_debugger_thread ();
1110 breakpoints_cleanup ();
1119 #ifndef DISABLE_SOCKET_TRANSPORT
1124 * recv() + handle incomplete reads and EINTR
1127 socket_transport_recv (void *buf, int len)
1133 static gint64 last_keepalive;
1140 res = recv (fd, (char *) buf + total, len - total, flags);
1143 if (agent_config.keepalive) {
1144 gboolean need_keepalive = FALSE;
1145 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1146 need_keepalive = TRUE;
1147 } else if (res == -1) {
1148 /* This could happen if recv () is interrupted repeatedly */
1149 msecs = mono_msec_ticks ();
1150 if (msecs - last_keepalive >= agent_config.keepalive) {
1151 need_keepalive = TRUE;
1152 last_keepalive = msecs;
1155 if (need_keepalive) {
1156 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1160 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1168 set_keepalive (void)
1173 if (!agent_config.keepalive || !conn_fd)
1176 tv.tv_sec = agent_config.keepalive / 1000;
1177 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1179 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1180 g_assert (result >= 0);
1184 socket_transport_accept (int socket_fd)
1187 conn_fd = accept (socket_fd, NULL, NULL);
1190 if (conn_fd == -1) {
1191 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1193 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1200 socket_transport_send (void *data, int len)
1207 res = send (conn_fd, data, len, 0);
1208 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1219 * socket_transport_connect:
1221 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1224 socket_transport_connect (const char *address)
1226 MonoAddressInfo *result;
1227 MonoAddressEntry *rp;
1228 int sfd = -1, s, res;
1232 if (agent_config.address) {
1233 res = parse_address (agent_config.address, &host, &port);
1234 g_assert (res == 0);
1245 mono_network_init ();
1247 /* Obtain address(es) matching host/port */
1248 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1250 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1255 if (agent_config.server) {
1256 /* Wait for a connection */
1258 struct sockaddr_in addr;
1261 /* No address, generate one */
1262 sfd = socket (AF_INET, SOCK_STREAM, 0);
1265 /* This will bind the socket to a random port */
1266 res = listen (sfd, 16);
1268 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1273 addrlen = sizeof (addr);
1274 memset (&addr, 0, sizeof (addr));
1275 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1276 g_assert (res == 0);
1278 host = (char*)"127.0.0.1";
1279 port = ntohs (addr.sin_port);
1281 /* Emit the address to stdout */
1282 /* FIXME: Should print another interface, not localhost */
1283 printf ("%s:%d\n", host, port);
1285 /* Listen on the provided address */
1286 for (rp = result->entries; rp != NULL; rp = rp->next) {
1287 MonoSocketAddress sockaddr;
1291 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1293 sfd = socket (rp->family, rp->socktype,
1298 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1301 res = bind (sfd, &sockaddr.addr, sock_len);
1305 res = listen (sfd, 16);
1312 mono_free_address_info (result);
1315 if (agent_config.defer)
1318 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1320 if (agent_config.timeout) {
1325 tv.tv_usec = agent_config.timeout * 1000;
1327 FD_SET (sfd, &readfds);
1330 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1334 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1339 conn_fd = socket_transport_accept (sfd);
1343 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1345 /* Connect to the specified address */
1346 /* FIXME: Respect the timeout */
1347 for (rp = result->entries; rp != NULL; rp = rp->next) {
1348 MonoSocketAddress sockaddr;
1351 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1353 sfd = socket (rp->family, rp->socktype,
1359 res = connect (sfd, &sockaddr.addr, sock_len);
1363 break; /* Success */
1371 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1377 mono_free_address_info (result);
1380 if (!transport_handshake ())
1385 socket_transport_close1 (void)
1387 /* This will interrupt the agent thread */
1388 /* Close the read part only so it can still send back replies */
1389 /* Also shut down the connection listener so that we can exit normally */
1391 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1392 shutdown (conn_fd, SD_BOTH);
1393 shutdown (listen_fd, SD_BOTH);
1394 closesocket (listen_fd);
1396 shutdown (conn_fd, SHUT_RD);
1397 shutdown (listen_fd, SHUT_RDWR);
1405 socket_transport_close2 (void)
1408 shutdown (conn_fd, SD_BOTH);
1410 shutdown (conn_fd, SHUT_RDWR);
1415 register_socket_transport (void)
1417 DebuggerTransport trans;
1419 trans.name = "dt_socket";
1420 trans.connect = socket_transport_connect;
1421 trans.close1 = socket_transport_close1;
1422 trans.close2 = socket_transport_close2;
1423 trans.send = socket_transport_send;
1424 trans.recv = socket_transport_recv;
1426 register_transport (&trans);
1430 * socket_fd_transport_connect:
1434 socket_fd_transport_connect (const char *address)
1438 res = sscanf (address, "%d", &conn_fd);
1440 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1444 if (!transport_handshake ())
1449 register_socket_fd_transport (void)
1451 DebuggerTransport trans;
1453 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1454 trans.name = "socket-fd";
1455 trans.connect = socket_fd_transport_connect;
1456 trans.close1 = socket_transport_close1;
1457 trans.close2 = socket_transport_close2;
1458 trans.send = socket_transport_send;
1459 trans.recv = socket_transport_recv;
1461 register_transport (&trans);
1464 #endif /* DISABLE_SOCKET_TRANSPORT */
1470 #define MAX_TRANSPORTS 16
1472 static DebuggerTransport *transport;
1474 static DebuggerTransport transports [MAX_TRANSPORTS];
1475 static int ntransports;
1478 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1481 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1483 register_transport (trans);
1487 register_transport (DebuggerTransport *trans)
1489 g_assert (ntransports < MAX_TRANSPORTS);
1491 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1496 transport_init (void)
1500 #ifndef DISABLE_SOCKET_TRANSPORT
1501 register_socket_transport ();
1502 register_socket_fd_transport ();
1505 for (i = 0; i < ntransports; ++i) {
1506 if (!strcmp (agent_config.transport, transports [i].name))
1509 if (i == ntransports) {
1510 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1511 for (i = 0; i < ntransports; ++i)
1512 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1513 fprintf (stderr, "\n");
1516 transport = &transports [i];
1520 transport_connect (const char *address)
1522 transport->connect (address);
1526 transport_close1 (void)
1528 transport->close1 ();
1532 transport_close2 (void)
1534 transport->close2 ();
1538 transport_send (void *buf, int len)
1540 return transport->send (buf, len);
1544 transport_recv (void *buf, int len)
1546 return transport->recv (buf, len);
1550 mono_debugger_agent_transport_handshake (void)
1552 return transport_handshake ();
1556 transport_handshake (void)
1558 char handshake_msg [128];
1562 disconnected = TRUE;
1564 /* Write handshake message */
1565 sprintf (handshake_msg, "DWP-Handshake");
1568 res = transport_send (handshake_msg, strlen (handshake_msg));
1569 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1571 g_assert (res != -1);
1574 res = transport_recv (buf, strlen (handshake_msg));
1575 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1576 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1581 * To support older clients, the client sends its protocol version after connecting
1582 * using a command. Until that is received, default to our protocol version.
1584 major_version = MAJOR_VERSION;
1585 minor_version = MINOR_VERSION;
1586 protocol_version_set = FALSE;
1588 #ifndef DISABLE_SOCKET_TRANSPORT
1589 // FIXME: Move this somewhere else
1591 * Set TCP_NODELAY on the socket so the client receives events/command
1592 * results immediately.
1596 int result = setsockopt (conn_fd,
1601 g_assert (result >= 0);
1607 disconnected = FALSE;
1612 stop_debugger_thread (void)
1617 transport_close1 ();
1620 * Wait for the thread to exit.
1622 * If we continue with the shutdown without waiting for it, then the client might
1623 * not receive an answer to its last command like a resume.
1625 if (!is_debugger_thread ()) {
1627 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1628 if (!debugger_thread_exited)
1629 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1630 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1631 } while (!debugger_thread_exited);
1634 transport_close2 ();
1638 start_debugger_thread (void)
1640 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, NULL, NULL);
1641 g_assert (debugger_thread_handle);
1645 * Functions to decode protocol data
1649 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1652 g_assert (*endbuf <= limit);
1657 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1660 g_assert (*endbuf <= limit);
1662 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1665 static inline gint64
1666 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1668 guint32 high = decode_int (buf, &buf, limit);
1669 guint32 low = decode_int (buf, &buf, limit);
1673 return ((((guint64)high) << 32) | ((guint64)low));
1677 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1679 return decode_int (buf, endbuf, limit);
1683 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1685 int len = decode_int (buf, &buf, limit);
1693 s = (char *)g_malloc (len + 1);
1696 memcpy (s, buf, len);
1705 * Functions to encode protocol data
1709 buffer_init (Buffer *buf, int size)
1711 buf->buf = (guint8 *)g_malloc (size);
1713 buf->end = buf->buf + size;
1717 buffer_len (Buffer *buf)
1719 return buf->p - buf->buf;
1723 buffer_make_room (Buffer *buf, int size)
1725 if (buf->end - buf->p < size) {
1726 int new_size = buf->end - buf->buf + size + 32;
1727 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1728 size = buf->p - buf->buf;
1731 buf->end = buf->buf + new_size;
1736 buffer_add_byte (Buffer *buf, guint8 val)
1738 buffer_make_room (buf, 1);
1744 buffer_add_short (Buffer *buf, guint32 val)
1746 buffer_make_room (buf, 2);
1747 buf->p [0] = (val >> 8) & 0xff;
1748 buf->p [1] = (val >> 0) & 0xff;
1753 buffer_add_int (Buffer *buf, guint32 val)
1755 buffer_make_room (buf, 4);
1756 buf->p [0] = (val >> 24) & 0xff;
1757 buf->p [1] = (val >> 16) & 0xff;
1758 buf->p [2] = (val >> 8) & 0xff;
1759 buf->p [3] = (val >> 0) & 0xff;
1764 buffer_add_long (Buffer *buf, guint64 l)
1766 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1767 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1771 buffer_add_id (Buffer *buf, int id)
1773 buffer_add_int (buf, (guint64)id);
1777 buffer_add_data (Buffer *buf, guint8 *data, int len)
1779 buffer_make_room (buf, len);
1780 memcpy (buf->p, data, len);
1785 buffer_add_string (Buffer *buf, const char *str)
1790 buffer_add_int (buf, 0);
1793 buffer_add_int (buf, len);
1794 buffer_add_data (buf, (guint8*)str, len);
1799 buffer_add_buffer (Buffer *buf, Buffer *data)
1801 buffer_add_data (buf, data->buf, buffer_len (data));
1805 buffer_free (Buffer *buf)
1811 send_packet (int command_set, int command, Buffer *data)
1817 id = InterlockedIncrement (&packet_id);
1819 len = data->p - data->buf + 11;
1820 buffer_init (&buf, len);
1821 buffer_add_int (&buf, len);
1822 buffer_add_int (&buf, id);
1823 buffer_add_byte (&buf, 0); /* flags */
1824 buffer_add_byte (&buf, command_set);
1825 buffer_add_byte (&buf, command);
1826 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1828 res = transport_send (buf.buf, len);
1836 send_reply_packets (int npackets, ReplyPacket *packets)
1843 for (i = 0; i < npackets; ++i)
1844 len += buffer_len (packets [i].data) + 11;
1845 buffer_init (&buf, len);
1846 for (i = 0; i < npackets; ++i) {
1847 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1848 buffer_add_int (&buf, packets [i].id);
1849 buffer_add_byte (&buf, 0x80); /* flags */
1850 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1851 buffer_add_byte (&buf, packets [i].error);
1852 buffer_add_buffer (&buf, packets [i].data);
1855 res = transport_send (buf.buf, len);
1863 send_reply_packet (int id, int error, Buffer *data)
1867 memset (&packet, 0, sizeof (ReplyPacket));
1869 packet.error = error;
1872 return send_reply_packets (1, &packet);
1876 send_buffered_reply_packets (void)
1880 send_reply_packets (nreply_packets, reply_packets);
1881 for (i = 0; i < nreply_packets; ++i)
1882 buffer_free (reply_packets [i].data);
1883 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1888 buffer_reply_packet (int id, int error, Buffer *data)
1892 if (nreply_packets == 128)
1893 send_buffered_reply_packets ();
1895 p = &reply_packets [nreply_packets];
1898 p->data = g_new0 (Buffer, 1);
1899 buffer_init (p->data, buffer_len (data));
1900 buffer_add_buffer (p->data, data);
1909 * Represents an object accessible by the debugger client.
1912 /* Unique id used in the wire protocol to refer to objects */
1915 * A weakref gc handle pointing to the object. The gc handle is used to
1916 * detect if the object was garbage collected.
1921 /* Maps objid -> ObjRef */
1922 /* Protected by the loader lock */
1923 static GHashTable *objrefs;
1924 /* Protected by the loader lock */
1925 static GHashTable *obj_to_objref;
1926 /* Protected by the dbg lock */
1927 static MonoGHashTable *suspended_objs;
1930 free_objref (gpointer value)
1932 ObjRef *o = (ObjRef *)value;
1934 mono_gchandle_free (o->handle);
1942 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1943 obj_to_objref = g_hash_table_new (NULL, NULL);
1944 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1945 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1949 objrefs_cleanup (void)
1951 g_hash_table_destroy (objrefs);
1956 * Return an ObjRef for OBJ.
1959 get_objref (MonoObject *obj)
1962 GSList *reflist = NULL, *l;
1968 if (suspend_count) {
1970 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1973 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1977 mono_loader_lock ();
1979 /* FIXME: The tables can grow indefinitely */
1981 if (mono_gc_is_moving ()) {
1983 * Objects can move, so use a hash table mapping hash codes to lists of
1984 * ObjRef structures.
1986 hash = mono_object_hash (obj);
1988 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1989 for (l = reflist; l; l = l->next) {
1990 ref = (ObjRef *)l->data;
1991 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1992 mono_loader_unlock ();
1997 /* Use a hash table with masked pointers to internalize object references */
1998 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1999 /* ref might refer to a different object with the same addr which was GCd */
2000 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2001 mono_loader_unlock ();
2006 ref = g_new0 (ObjRef, 1);
2007 ref->id = InterlockedIncrement (&objref_id);
2008 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2010 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2012 if (mono_gc_is_moving ()) {
2013 reflist = g_slist_append (reflist, ref);
2014 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2016 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2019 mono_loader_unlock ();
2025 true_pred (gpointer key, gpointer value, gpointer user_data)
2031 clear_suspended_objs (void)
2034 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2039 get_objid (MonoObject *obj)
2044 return get_objref (obj)->id;
2048 * Set OBJ to the object identified by OBJID.
2049 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2053 get_object_allow_null (int objid, MonoObject **obj)
2063 return ERR_INVALID_OBJECT;
2065 mono_loader_lock ();
2067 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2070 *obj = mono_gchandle_get_target (ref->handle);
2071 mono_loader_unlock ();
2073 return ERR_INVALID_OBJECT;
2076 mono_loader_unlock ();
2077 return ERR_INVALID_OBJECT;
2082 get_object (int objid, MonoObject **obj)
2084 ErrorCode err = get_object_allow_null (objid, obj);
2086 if (err != ERR_NONE)
2089 return ERR_INVALID_OBJECT;
2094 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2096 return decode_id (buf, endbuf, limit);
2100 buffer_add_objid (Buffer *buf, MonoObject *o)
2102 buffer_add_id (buf, get_objid (o));
2121 * Represents a runtime structure accessible to the debugger client
2124 /* Unique id used in the wire protocol */
2126 /* Domain of the runtime structure, NULL if the domain was unloaded */
2133 MonoAssembly *assembly;
2134 MonoClassField *field;
2136 MonoProperty *property;
2141 /* Maps runtime structure -> Id */
2142 /* Protected by the dbg lock */
2143 GHashTable *val_to_id [ID_NUM];
2144 /* Classes whose class load event has been sent */
2145 /* Protected by the loader lock */
2146 GHashTable *loaded_classes;
2147 /* Maps MonoClass->GPtrArray of file names */
2148 GHashTable *source_files;
2149 /* Maps source file basename -> GSList of classes */
2150 GHashTable *source_file_to_class;
2151 /* Same with ignore-case */
2152 GHashTable *source_file_to_class_ignorecase;
2156 /* Protected by the dbg lock */
2157 static GPtrArray *ids [ID_NUM];
2164 for (i = 0; i < ID_NUM; ++i)
2165 ids [i] = g_ptr_array_new ();
2173 for (i = 0; i < ID_NUM; ++i) {
2175 for (j = 0; j < ids [i]->len; ++j)
2176 g_free (g_ptr_array_index (ids [i], j));
2177 g_ptr_array_free (ids [i], TRUE);
2184 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2186 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2188 GHashTableIter iter;
2189 GPtrArray *file_names;
2194 for (i = 0; i < ID_NUM; ++i)
2195 if (info->val_to_id [i])
2196 g_hash_table_destroy (info->val_to_id [i]);
2197 g_hash_table_destroy (info->loaded_classes);
2199 g_hash_table_iter_init (&iter, info->source_files);
2200 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2201 for (i = 0; i < file_names->len; ++i)
2202 g_free (g_ptr_array_index (file_names, i));
2203 g_ptr_array_free (file_names, TRUE);
2206 g_hash_table_iter_init (&iter, info->source_file_to_class);
2207 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2212 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2213 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2221 domain_jit_info (domain)->agent_info = NULL;
2223 /* Clear ids referencing structures in the domain */
2225 for (i = 0; i < ID_NUM; ++i) {
2227 for (j = 0; j < ids [i]->len; ++j) {
2228 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2229 if (id->domain == domain)
2236 mono_loader_lock ();
2237 g_hash_table_remove (domains, domain);
2238 mono_loader_unlock ();
2241 static AgentDomainInfo*
2242 get_agent_domain_info (MonoDomain *domain)
2244 AgentDomainInfo *info = NULL;
2246 mono_domain_lock (domain);
2248 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2250 info = g_new0 (AgentDomainInfo, 1);
2251 domain_jit_info (domain)->agent_info = info;
2252 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2253 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2254 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2255 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2258 mono_domain_unlock (domain);
2264 get_id (MonoDomain *domain, IdType type, gpointer val)
2267 AgentDomainInfo *info;
2272 info = get_agent_domain_info (domain);
2276 if (info->val_to_id [type] == NULL)
2277 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2279 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2285 id = g_new0 (Id, 1);
2287 id->id = ids [type]->len + 1;
2288 id->domain = domain;
2291 g_hash_table_insert (info->val_to_id [type], val, id);
2292 g_ptr_array_add (ids [type], id);
2299 static inline gpointer
2300 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2304 int id = decode_id (buf, endbuf, limit);
2313 // FIXME: error handling
2315 g_assert (id > 0 && id <= ids [type]->len);
2317 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2320 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2321 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2322 *err = ERR_UNLOADED;
2327 *domain = res->domain;
2329 return res->data.val;
2333 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2335 int id = get_id (domain, type, val);
2337 buffer_add_id (buf, id);
2341 static inline MonoClass*
2342 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2346 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2347 if (G_UNLIKELY (log_level >= 2) && klass) {
2350 s = mono_type_full_name (&klass->byval_arg);
2351 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2357 static inline MonoAssembly*
2358 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2360 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2363 static inline MonoImage*
2364 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2366 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2369 static inline MonoMethod*
2370 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2374 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2375 if (G_UNLIKELY (log_level >= 2) && m) {
2378 s = mono_method_full_name (m, TRUE);
2379 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2385 static inline MonoClassField*
2386 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2388 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2391 static inline MonoDomain*
2392 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2394 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2397 static inline MonoProperty*
2398 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2400 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2404 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2406 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2407 if (G_UNLIKELY (log_level >= 2) && klass) {
2410 s = mono_type_full_name (&klass->byval_arg);
2411 if (is_debugger_thread ())
2412 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2414 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2420 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2422 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2423 if (G_UNLIKELY (log_level >= 2) && method) {
2426 s = mono_method_full_name (method, 1);
2427 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2433 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2437 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2438 if (G_UNLIKELY (log_level >= 2) && assembly)
2439 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2443 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2445 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2449 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2451 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2455 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2457 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2461 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2463 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2466 static void invoke_method (void);
2473 * save_thread_context:
2475 * Set CTX as the current threads context which is used for computing stack traces.
2476 * This function is signal-safe.
2479 save_thread_context (MonoContext *ctx)
2481 DebuggerTlsData *tls;
2483 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2487 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2489 mono_thread_state_init_from_current (&tls->context);
2492 /* Number of threads suspended */
2494 * If this is equal to the size of thread_to_tls, the runtime is considered
2497 static gint32 threads_suspend_count;
2499 static MonoCoopMutex suspend_mutex;
2501 /* Cond variable used to wait for suspend_count becoming 0 */
2502 static MonoCoopCond suspend_cond;
2504 /* Semaphore used to wait for a thread becoming suspended */
2505 static MonoCoopSem suspend_sem;
2510 mono_coop_mutex_init (&suspend_mutex);
2511 mono_coop_cond_init (&suspend_cond);
2512 mono_coop_sem_init (&suspend_sem, 0);
2517 StackFrameInfo last_frame;
2518 gboolean last_frame_set;
2522 } GetLastFrameUserData;
2525 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2527 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2529 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2532 if (!data->last_frame_set) {
2533 /* Store the last frame */
2534 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2535 data->last_frame_set = TRUE;
2538 /* Store the context/lmf for the frame above the last frame */
2539 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2540 data->lmf = info->lmf;
2541 data->domain = info->domain;
2547 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2549 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2551 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2552 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2553 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2560 * Process interruption of a thread. This should be signal safe.
2562 * This always runs in the debugger thread.
2565 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2568 MonoNativeThreadId tid;
2572 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2573 tid = mono_thread_info_get_tid (info);
2575 // FIXME: Races when the thread leaves managed code before hitting a single step
2578 if (ji && !ji->is_trampoline) {
2579 /* Running managed code, will be suspended by the single step code */
2580 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2583 * Running native code, will be suspended when it returns to/enters
2584 * managed code. Treat it as already suspended.
2585 * This might interrupt the code in process_single_step_inner (), we use the
2586 * tls->suspending flag to avoid races when that happens.
2588 if (!tls->suspended && !tls->suspending) {
2589 GetLastFrameUserData data;
2591 // FIXME: printf is not signal safe, but this is only used during
2592 // debugger debugging
2594 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2595 //save_thread_context (&ctx);
2598 /* Already terminated */
2602 * We are in a difficult position: we want to be able to provide stack
2603 * traces for this thread, but we can't use the current ctx+lmf, since
2604 * the thread is still running, so it might return to managed code,
2605 * making these invalid.
2606 * So we start a stack walk and save the first frame, along with the
2607 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2608 * suspended when it returns to managed code, so the parent's ctx should
2611 data.last_frame_set = FALSE;
2612 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2613 if (data.last_frame_set) {
2614 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2616 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2618 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2619 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2621 tls->async_state.valid = FALSE;
2624 mono_memory_barrier ();
2626 tls->suspended = TRUE;
2627 mono_coop_sem_post (&suspend_sem);
2633 * reset_native_thread_suspend_state:
2635 * Reset the suspended flag and state on native threads
2638 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2640 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2642 if (!tls->really_suspended && tls->suspended) {
2643 tls->suspended = FALSE;
2645 * The thread might still be running if it was executing native code, so the state won't be invalided by
2646 * suspend_current ().
2648 tls->context.valid = FALSE;
2649 tls->async_state.valid = FALSE;
2650 invalidate_frames (tls);
2655 DebuggerTlsData *tls;
2656 gboolean valid_info;
2659 static SuspendThreadResult
2660 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2662 InterruptData *data = (InterruptData *)user_data;
2665 data->valid_info = TRUE;
2666 ji = mono_jit_info_table_find_internal (
2667 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2668 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2672 /* This is signal safe */
2673 thread_interrupt (data->tls, info, ji);
2674 return MonoResumeThread;
2680 * Notify a thread that it needs to suspend.
2683 notify_thread (gpointer key, gpointer value, gpointer user_data)
2685 MonoInternalThread *thread = (MonoInternalThread *)key;
2686 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2687 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2689 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2692 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2694 /* This is _not_ equivalent to mono_thread_internal_abort () */
2695 InterruptData interrupt_data = { 0 };
2696 interrupt_data.tls = tls;
2698 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2699 if (!interrupt_data.valid_info) {
2700 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2702 * Attached thread which died without detaching.
2704 tls->terminated = TRUE;
2709 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2711 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2715 if (mono_loader_lock_is_owned_by_self ()) {
2717 * Shortcut for the check in suspend_current (). This speeds up processing
2718 * when executing long running code inside the loader lock, i.e. assembly load
2724 if (is_debugger_thread ())
2727 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2728 if (suspend_count - tls->resume_count > 0)
2729 tls->suspending = TRUE;
2731 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2733 if (suspend_count - tls->resume_count == 0) {
2735 * We are executing a single threaded invoke but the single step for
2736 * suspending is still active.
2737 * FIXME: This slows down single threaded invokes.
2739 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2743 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2745 /* Can't suspend in these methods */
2746 method = jinfo_get_method (ji);
2747 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2750 save_thread_context (ctx);
2758 * Increase the suspend count of the VM. While the suspend count is greater
2759 * than 0, runtime threads are suspended at certain points during execution.
2764 mono_loader_lock ();
2766 mono_coop_mutex_lock (&suspend_mutex);
2770 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2772 if (suspend_count == 1) {
2773 // FIXME: Is it safe to call this inside the lock ?
2774 start_single_stepping ();
2775 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2778 mono_coop_mutex_unlock (&suspend_mutex);
2780 if (suspend_count == 1)
2782 * Suspend creation of new threadpool threads, since they cannot run
2784 mono_threadpool_suspend ();
2786 mono_loader_unlock ();
2792 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2798 g_assert (is_debugger_thread ());
2800 mono_loader_lock ();
2802 mono_coop_mutex_lock (&suspend_mutex);
2804 g_assert (suspend_count > 0);
2807 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2809 if (suspend_count == 0) {
2810 // FIXME: Is it safe to call this inside the lock ?
2811 stop_single_stepping ();
2812 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2815 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2816 mono_coop_cond_broadcast (&suspend_cond);
2818 mono_coop_mutex_unlock (&suspend_mutex);
2819 //g_assert (err == 0);
2821 if (suspend_count == 0)
2822 mono_threadpool_resume ();
2824 mono_loader_unlock ();
2830 * Resume just one thread.
2833 resume_thread (MonoInternalThread *thread)
2835 DebuggerTlsData *tls;
2837 g_assert (is_debugger_thread ());
2839 mono_loader_lock ();
2841 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2844 mono_coop_mutex_lock (&suspend_mutex);
2846 g_assert (suspend_count > 0);
2848 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2850 tls->resume_count += suspend_count;
2853 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2854 * but only the one whose resume_count field is > 0 will be resumed.
2856 mono_coop_cond_broadcast (&suspend_cond);
2858 mono_coop_mutex_unlock (&suspend_mutex);
2859 //g_assert (err == 0);
2861 mono_loader_unlock ();
2865 free_frames (StackFrame **frames, int nframes)
2869 for (i = 0; i < nframes; ++i) {
2870 if (frames [i]->jit)
2871 mono_debug_free_method_jit_info (frames [i]->jit);
2872 g_free (frames [i]);
2878 invalidate_frames (DebuggerTlsData *tls)
2881 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2884 free_frames (tls->frames, tls->frame_count);
2885 tls->frame_count = 0;
2888 free_frames (tls->restore_frames, tls->restore_frame_count);
2889 tls->restore_frame_count = 0;
2890 tls->restore_frames = NULL;
2896 * Suspend the current thread until the runtime is resumed. If the thread has a
2897 * pending invoke, then the invoke is executed before this function returns.
2900 suspend_current (void)
2902 DebuggerTlsData *tls;
2904 g_assert (!is_debugger_thread ());
2906 if (mono_loader_lock_is_owned_by_self ()) {
2908 * If we own the loader mutex, can't suspend until we release it, since the
2909 * whole runtime can deadlock otherwise.
2914 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2917 mono_coop_mutex_lock (&suspend_mutex);
2919 tls->suspending = FALSE;
2920 tls->really_suspended = TRUE;
2922 if (!tls->suspended) {
2923 tls->suspended = TRUE;
2924 mono_coop_sem_post (&suspend_sem);
2927 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2929 while (suspend_count - tls->resume_count > 0) {
2930 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2933 tls->suspended = FALSE;
2934 tls->really_suspended = FALSE;
2936 threads_suspend_count --;
2938 mono_coop_mutex_unlock (&suspend_mutex);
2940 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2942 if (tls->pending_invoke) {
2943 /* Save the original context */
2944 tls->pending_invoke->has_ctx = TRUE;
2945 tls->pending_invoke->ctx = tls->context.ctx;
2950 /* The frame info becomes invalid after a resume */
2951 tls->context.valid = FALSE;
2952 tls->async_state.valid = FALSE;
2953 invalidate_frames (tls);
2957 count_thread (gpointer key, gpointer value, gpointer user_data)
2959 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2961 if (!tls->suspended && !tls->terminated)
2962 *(int*)user_data = *(int*)user_data + 1;
2966 count_threads_to_wait_for (void)
2970 mono_loader_lock ();
2971 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2972 mono_loader_unlock ();
2980 * Wait until the runtime is completely suspended.
2983 wait_for_suspend (void)
2985 int nthreads, nwait, err;
2986 gboolean waited = FALSE;
2988 // FIXME: Threads starting/stopping ?
2989 mono_loader_lock ();
2990 nthreads = mono_g_hash_table_size (thread_to_tls);
2991 mono_loader_unlock ();
2994 nwait = count_threads_to_wait_for ();
2996 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2997 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2998 g_assert (err == 0);
3006 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3012 * Return whenever the runtime is suspended.
3017 return count_threads_to_wait_for () == 0;
3021 no_seq_points_found (MonoMethod *method, int offset)
3024 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3026 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3030 DebuggerTlsData *tls;
3032 } ComputeFramesUserData;
3035 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3037 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3039 MonoMethod *method, *actual_method, *api_method;
3043 if (info->type != FRAME_TYPE_MANAGED) {
3044 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3045 /* Mark the last frame as an invoke frame */
3047 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3053 method = jinfo_get_method (info->ji);
3055 method = info->method;
3056 actual_method = info->actual_method;
3057 api_method = method;
3062 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3065 if (info->il_offset == -1) {
3066 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3067 if (ud->frames == NULL) {
3068 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3069 info->il_offset = sp.il_offset;
3071 if (info->il_offset == -1)
3072 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3075 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);
3077 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3078 if (!CHECK_PROTOCOL_VERSION (2, 17))
3079 /* Older clients can't handle this flag */
3081 api_method = mono_marshal_method_from_wrapper (method);
3084 actual_method = api_method;
3085 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3088 frame = g_new0 (StackFrame, 1);
3089 frame->method = method;
3090 frame->actual_method = actual_method;
3091 frame->api_method = api_method;
3092 frame->il_offset = info->il_offset;
3093 frame->native_offset = info->native_offset;
3094 frame->flags = flags;
3095 frame->ji = info->ji;
3096 if (info->reg_locations)
3097 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3100 frame->has_ctx = TRUE;
3102 frame->domain = info->domain;
3104 ud->frames = g_slist_append (ud->frames, frame);
3110 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3112 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3115 * 'tls->filter_ctx' is the location of the throw site.
3117 * mono_walk_stack() will never actually hit the throw site, but unwind
3118 * directly from the filter to the call site; we abort stack unwinding here
3119 * once this happens and resume from the throw site.
3122 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3125 return process_frame (info, ctx, user_data);
3129 * Return a malloc-ed list of StackFrame structures.
3132 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3134 ComputeFramesUserData user_data;
3135 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3140 user_data.tls = tls;
3141 user_data.frames = NULL;
3143 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3145 nframes = g_slist_length (user_data.frames);
3146 res = g_new0 (StackFrame*, nframes);
3147 l = user_data.frames;
3148 for (i = 0; i < nframes; ++i) {
3149 res [i] = (StackFrame *)l->data;
3152 *out_nframes = nframes;
3158 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3160 ComputeFramesUserData user_data;
3162 int i, findex, new_frame_count;
3163 StackFrame **new_frames, *f;
3164 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3166 // FIXME: Locking on tls
3167 if (tls->frames && tls->frames_up_to_date)
3170 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3172 user_data.tls = tls;
3173 user_data.frames = NULL;
3174 if (tls->terminated) {
3175 tls->frame_count = 0;
3177 } if (!tls->really_suspended && tls->async_state.valid) {
3178 /* Have to use the state saved by the signal handler */
3179 process_frame (&tls->async_last_frame, NULL, &user_data);
3180 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3181 } else if (tls->filter_state.valid) {
3183 * We are inside an exception filter.
3185 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3187 if (tls->context.valid)
3188 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3190 * After that, we resume unwinding from the location where the exception has been thrown.
3192 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3193 } else if (tls->context.valid) {
3194 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3197 tls->frame_count = 0;
3201 new_frame_count = g_slist_length (user_data.frames);
3202 new_frames = g_new0 (StackFrame*, new_frame_count);
3204 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3205 f = (StackFrame *)tmp->data;
3208 * Reuse the id for already existing stack frames, so invokes don't invalidate
3209 * the still valid stack frames.
3211 for (i = 0; i < tls->frame_count; ++i) {
3212 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3213 f->id = tls->frames [i]->id;
3218 if (i >= tls->frame_count)
3219 f->id = InterlockedIncrement (&frame_id);
3221 new_frames [findex ++] = f;
3224 g_slist_free (user_data.frames);
3226 invalidate_frames (tls);
3228 tls->frames = new_frames;
3229 tls->frame_count = new_frame_count;
3230 tls->frames_up_to_date = TRUE;
3234 * GHFunc to emit an appdomain creation event
3235 * @param key Don't care
3236 * @param value A loaded appdomain
3237 * @param user_data Don't care
3240 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3242 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3243 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3247 * GHFunc to emit a thread start event
3248 * @param key A thread id
3249 * @param value A thread object
3250 * @param user_data Don't care
3253 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3255 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3256 process_profiler_event (EVENT_KIND_THREAD_START, value);
3260 * GFunc to emit an assembly load event
3261 * @param value A loaded assembly
3262 * @param user_data Don't care
3265 emit_assembly_load (gpointer value, gpointer user_data)
3267 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3271 * GFunc to emit a type load event
3272 * @param value A loaded type
3273 * @param user_data Don't care
3276 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3278 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3282 strdup_tolower (char *s)
3287 for (p = s2; *p; ++p)
3293 * Same as g_path_get_basename () but handles windows paths as well,
3294 * which can occur in .mdb files created by pdb2mdb.
3297 dbg_path_get_basename (const char *filename)
3301 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3302 return g_path_get_basename (filename);
3306 /* No separator -> filename */
3307 r = strrchr (filename, '\\');
3309 return g_strdup (filename);
3311 /* Trailing slash, remove component */
3313 char *copy = g_strdup (filename);
3314 copy [r-filename] = 0;
3315 r = strrchr (copy, '\\');
3319 return g_strdup ("/");
3321 r = g_strdup (&r[1]);
3326 return g_strdup (&r[1]);
3330 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3332 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3334 MonoCustomAttrInfo *ainfo;
3336 if (ji->dbg_attrs_inited)
3340 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3342 if (!step_through_klass)
3343 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3345 if (!non_user_klass)
3346 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3348 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3349 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3351 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3352 ji->dbg_hidden = TRUE;
3353 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3354 ji->dbg_step_through = TRUE;
3355 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3356 ji->dbg_non_user_code = TRUE;
3357 mono_custom_attrs_free (ainfo);
3360 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3361 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3363 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3364 ji->dbg_step_through = TRUE;
3365 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3366 ji->dbg_non_user_code = TRUE;
3367 mono_custom_attrs_free (ainfo);
3370 mono_memory_barrier ();
3371 ji->dbg_attrs_inited = TRUE;
3379 * create_event_list:
3381 * Return a list of event request ids matching EVENT, starting from REQS, which
3382 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3384 * We return request ids, instead of requests, to simplify threading, since
3385 * requests could be deleted anytime when the loader lock is not held.
3386 * LOCKING: Assumes the loader lock is held.
3389 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3392 GSList *events = NULL;
3394 *suspend_policy = SUSPEND_POLICY_NONE;
3397 reqs = event_requests;
3402 for (i = 0; i < reqs->len; ++i) {
3403 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3404 if (req->event_kind == event) {
3405 gboolean filtered = FALSE;
3408 for (j = 0; j < req->nmodifiers; ++j) {
3409 Modifier *mod = &req->modifiers [j];
3411 if (mod->kind == MOD_KIND_COUNT) {
3413 if (mod->data.count > 0) {
3414 if (mod->data.count > 0) {
3416 if (mod->data.count == 0)
3420 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3421 if (mod->data.thread != mono_thread_internal_current ())
3423 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3424 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3426 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3428 if (ei->caught && !mod->caught)
3430 if (!ei->caught && !mod->uncaught)
3432 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3434 gboolean found = FALSE;
3435 MonoAssembly **assemblies = mod->data.assemblies;
3438 for (k = 0; assemblies [k]; ++k)
3439 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3444 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3445 gpointer iter = NULL;
3447 MonoDebugSourceInfo *sinfo;
3448 char *source_file, *s;
3449 gboolean found = FALSE;
3451 GPtrArray *source_file_list;
3453 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3454 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3457 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3458 for (i = 0; i < source_file_list->len; ++i) {
3459 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3461 * Do a case-insesitive match by converting the file name to
3464 s = strdup_tolower (sinfo->source_file);
3465 if (g_hash_table_lookup (mod->data.source_files, s))
3468 char *s2 = dbg_path_get_basename (sinfo->source_file);
3469 char *s3 = strdup_tolower (s2);
3471 if (g_hash_table_lookup (mod->data.source_files, s3))
3478 g_ptr_array_free (source_file_list, TRUE);
3483 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3486 s = mono_type_full_name (&ei->klass->byval_arg);
3487 if (!g_hash_table_lookup (mod->data.type_names, s))
3490 } else if (mod->kind == MOD_KIND_STEP) {
3491 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3492 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3493 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3494 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3496 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3497 init_jit_info_dbg_attrs (ji);
3501 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3502 init_jit_info_dbg_attrs (ji);
3503 if (ji->dbg_step_through)
3506 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3507 init_jit_info_dbg_attrs (ji);
3508 if (ji->dbg_non_user_code)
3515 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3516 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3521 /* Send a VM START/DEATH event by default */
3522 if (event == EVENT_KIND_VM_START)
3523 events = g_slist_append (events, GINT_TO_POINTER (0));
3524 if (event == EVENT_KIND_VM_DEATH)
3525 events = g_slist_append (events, GINT_TO_POINTER (0));
3530 static G_GNUC_UNUSED const char*
3531 event_to_string (EventKind event)
3534 case EVENT_KIND_VM_START: return "VM_START";
3535 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3536 case EVENT_KIND_THREAD_START: return "THREAD_START";
3537 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3538 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3539 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3540 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3541 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3542 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3543 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3544 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3545 case EVENT_KIND_STEP: return "STEP";
3546 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3547 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3548 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3549 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3550 case EVENT_KIND_USER_LOG: return "USER_LOG";
3552 g_assert_not_reached ();
3560 * Send an event to the client, suspending the vm if needed.
3561 * LOCKING: Since this can suspend the calling thread, no locks should be held
3563 * The EVENTS list is freed by this function.
3566 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3570 MonoDomain *domain = mono_domain_get ();
3571 MonoThread *thread = NULL;
3572 MonoObject *keepalive_obj = NULL;
3573 gboolean send_success = FALSE;
3578 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3582 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3583 // FIXME: We miss those events
3584 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3588 if (vm_death_event_sent) {
3589 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3593 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3594 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3599 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3603 if (event == EVENT_KIND_KEEPALIVE)
3604 suspend_policy = SUSPEND_POLICY_NONE;
3609 if (agent_config.defer) {
3610 /* Make sure the thread id is always set when doing deferred debugging */
3611 if (is_debugger_thread ()) {
3612 /* Don't suspend on events from the debugger thread */
3613 suspend_policy = SUSPEND_POLICY_NONE;
3614 thread = mono_thread_get_main ();
3616 else thread = mono_thread_current ();
3618 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3619 // FIXME: Send these with a NULL thread, don't suspend the current thread
3624 nevents = g_slist_length (events);
3625 buffer_init (&buf, 128);
3626 buffer_add_byte (&buf, suspend_policy);
3627 buffer_add_int (&buf, nevents);
3629 for (l = events; l; l = l->next) {
3630 buffer_add_byte (&buf, event); // event kind
3631 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3635 if (event == EVENT_KIND_VM_DEATH) {
3639 thread = mono_thread_current ();
3641 if (event == EVENT_KIND_VM_START && arg != NULL)
3642 thread = (MonoThread *)arg;
3645 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3648 case EVENT_KIND_THREAD_START:
3649 case EVENT_KIND_THREAD_DEATH:
3651 case EVENT_KIND_APPDOMAIN_CREATE:
3652 case EVENT_KIND_APPDOMAIN_UNLOAD:
3653 buffer_add_domainid (&buf, (MonoDomain *)arg);
3655 case EVENT_KIND_METHOD_ENTRY:
3656 case EVENT_KIND_METHOD_EXIT:
3657 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3659 case EVENT_KIND_ASSEMBLY_LOAD:
3660 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3662 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3663 DebuggerTlsData *tls;
3665 /* The domain the assembly belonged to is not equal to the current domain */
3666 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3668 g_assert (tls->domain_unloading);
3670 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3673 case EVENT_KIND_TYPE_LOAD:
3674 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3676 case EVENT_KIND_BREAKPOINT:
3677 case EVENT_KIND_STEP:
3678 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3679 buffer_add_long (&buf, il_offset);
3681 case EVENT_KIND_VM_START:
3682 buffer_add_domainid (&buf, mono_get_root_domain ());
3684 case EVENT_KIND_VM_DEATH:
3685 if (CHECK_PROTOCOL_VERSION (2, 27))
3686 buffer_add_int (&buf, mono_environment_exitcode_get ());
3688 case EVENT_KIND_EXCEPTION: {
3689 EventInfo *ei = (EventInfo *)arg;
3690 buffer_add_objid (&buf, ei->exc);
3692 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3693 * later after the suspension. (#12494).
3695 keepalive_obj = ei->exc;
3698 case EVENT_KIND_USER_BREAK:
3700 case EVENT_KIND_USER_LOG: {
3701 EventInfo *ei = (EventInfo *)arg;
3702 buffer_add_int (&buf, ei->level);
3703 buffer_add_string (&buf, ei->category ? ei->category : "");
3704 buffer_add_string (&buf, ei->message ? ei->message : "");
3707 case EVENT_KIND_KEEPALIVE:
3708 suspend_policy = SUSPEND_POLICY_NONE;
3711 g_assert_not_reached ();
3715 if (event == EVENT_KIND_VM_START) {
3716 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3717 if (!agent_config.defer)
3718 start_debugger_thread ();
3721 if (event == EVENT_KIND_VM_DEATH) {
3722 vm_death_event_sent = TRUE;
3723 suspend_policy = SUSPEND_POLICY_NONE;
3726 if (mono_runtime_is_shutting_down ())
3727 suspend_policy = SUSPEND_POLICY_NONE;
3729 if (suspend_policy != SUSPEND_POLICY_NONE) {
3731 * Save the thread context and start suspending before sending the packet,
3732 * since we could be receiving the resume request before send_packet ()
3735 save_thread_context (ctx);
3739 /* This will keep this object alive */
3740 get_objref (keepalive_obj);
3743 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3747 g_slist_free (events);
3750 if (!send_success) {
3751 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3755 if (event == EVENT_KIND_VM_START) {
3756 vm_start_event_sent = TRUE;
3759 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);
3761 switch (suspend_policy) {
3762 case SUSPEND_POLICY_NONE:
3764 case SUSPEND_POLICY_ALL:
3767 case SUSPEND_POLICY_EVENT_THREAD:
3771 g_assert_not_reached ();
3776 process_profiler_event (EventKind event, gpointer arg)
3780 EventInfo ei, *ei_arg = NULL;
3782 if (event == EVENT_KIND_TYPE_LOAD) {
3783 ei.klass = (MonoClass *)arg;
3787 mono_loader_lock ();
3788 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3789 mono_loader_unlock ();
3791 process_event (event, arg, 0, NULL, events, suspend_policy);
3795 runtime_initialized (MonoProfiler *prof)
3797 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3798 if (agent_config.defer)
3799 start_debugger_thread ();
3803 runtime_shutdown (MonoProfiler *prof)
3805 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3807 mono_debugger_agent_cleanup ();
3811 thread_startup (MonoProfiler *prof, uintptr_t tid)
3813 MonoInternalThread *thread = mono_thread_internal_current ();
3814 MonoInternalThread *old_thread;
3815 DebuggerTlsData *tls;
3817 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3820 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3822 mono_loader_lock ();
3823 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3824 mono_loader_unlock ();
3826 if (thread == old_thread) {
3828 * For some reason, thread_startup () might be called for the same thread
3829 * multiple times (attach ?).
3831 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3835 * thread_end () might not be called for some threads, and the tid could
3838 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3839 mono_loader_lock ();
3840 mono_g_hash_table_remove (thread_to_tls, old_thread);
3841 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3842 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3843 mono_loader_unlock ();
3847 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3849 // FIXME: Free this somewhere
3850 tls = g_new0 (DebuggerTlsData, 1);
3851 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3852 tls->thread = thread;
3853 mono_native_tls_set_value (debugger_tls_id, tls);
3855 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3857 mono_loader_lock ();
3858 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3859 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3860 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3861 mono_loader_unlock ();
3863 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3866 * suspend_vm () could have missed this thread, so wait for a resume.
3872 thread_end (MonoProfiler *prof, uintptr_t tid)
3874 MonoInternalThread *thread;
3875 DebuggerTlsData *tls = NULL;
3877 mono_loader_lock ();
3878 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3880 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3881 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3883 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3884 tls->terminated = TRUE;
3885 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3886 MONO_GC_UNREGISTER_ROOT (tls->thread);
3890 mono_loader_unlock ();
3892 /* We might be called for threads started before we registered the start callback */
3894 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3896 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3897 && !mono_native_tls_get_value (debugger_tls_id)
3900 * This can happen on darwin since we deregister threads using pthread dtors.
3901 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3906 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3911 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3913 mono_loader_lock ();
3914 g_hash_table_insert (domains, domain, domain);
3915 mono_loader_unlock ();
3917 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3921 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3923 DebuggerTlsData *tls;
3925 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3926 if (is_debugger_thread ())
3930 * Remember the currently unloading appdomain as it is needed to generate
3931 * proper ids for unloading assemblies.
3933 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3935 tls->domain_unloading = domain;
3939 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3941 DebuggerTlsData *tls;
3943 if (is_debugger_thread ())
3946 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3948 tls->domain_unloading = NULL;
3950 clear_breakpoints_for_domain (domain);
3952 mono_loader_lock ();
3953 /* Invalidate each thread's frame stack */
3954 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3955 mono_loader_unlock ();
3957 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3961 * invalidate_each_thread:
3963 * A GHFunc to invalidate frames.
3964 * value must be a DebuggerTlsData*
3967 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3969 invalidate_frames ((DebuggerTlsData *)value);
3973 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3975 /* Sent later in jit_end () */
3977 g_ptr_array_add (pending_assembly_loads, assembly);
3982 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3984 if (is_debugger_thread ())
3987 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3989 clear_event_requests_for_assembly (assembly);
3990 clear_types_for_assembly (assembly);
3994 send_type_load (MonoClass *klass)
3996 gboolean type_load = FALSE;
3997 MonoDomain *domain = mono_domain_get ();
3998 AgentDomainInfo *info = NULL;
4000 info = get_agent_domain_info (domain);
4002 mono_loader_lock ();
4004 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4006 g_hash_table_insert (info->loaded_classes, klass, klass);
4009 mono_loader_unlock ();
4012 emit_type_load (klass, klass, NULL);
4016 * Emit load events for all types currently loaded in the domain.
4017 * Takes the loader and domain locks.
4018 * user_data is unused.
4021 send_types_for_domain (MonoDomain *domain, void *user_data)
4023 MonoDomain* old_domain;
4024 AgentDomainInfo *info = NULL;
4026 info = get_agent_domain_info (domain);
4029 old_domain = mono_domain_get ();
4031 mono_domain_set (domain, TRUE);
4033 mono_loader_lock ();
4034 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4035 mono_loader_unlock ();
4037 mono_domain_set (old_domain, TRUE);
4041 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4044 MonoDomain* old_domain;
4046 old_domain = mono_domain_get ();
4048 mono_domain_set (domain, TRUE);
4050 mono_domain_assemblies_lock (domain);
4051 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4052 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4053 emit_assembly_load (ass, NULL);
4055 mono_domain_assemblies_unlock (domain);
4057 mono_domain_set (old_domain, TRUE);
4061 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4064 * We emit type load events when the first method of the type is JITted,
4065 * since the class load profiler callbacks might be called with the
4066 * loader lock held. They could also occur in the debugger thread.
4067 * Same for assembly load events.
4070 MonoAssembly *assembly = NULL;
4072 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4074 if (pending_assembly_loads->len > 0) {
4075 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4076 g_ptr_array_remove_index (pending_assembly_loads, 0);
4081 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4087 send_type_load (method->klass);
4090 add_pending_breakpoints (method, jinfo);
4094 * BREAKPOINTS/SINGLE STEPPING
4098 * Contains information about an inserted breakpoint.
4101 long il_offset, native_offset;
4105 } BreakpointInstance;
4108 * Contains generic information about a breakpoint.
4112 * The method where the breakpoint is placed. Can be NULL in which case it
4113 * is inserted into every method. This is used to implement method entry/
4114 * exit events. Can be a generic method definition, in which case the
4115 * breakpoint is inserted into every instance.
4121 * A list of BreakpointInstance structures describing where the breakpoint
4122 * was inserted. There could be more than one because of
4123 * generics/appdomains/method entry/exit.
4125 GPtrArray *children;
4128 /* List of breakpoints */
4129 /* Protected by the loader lock */
4130 static GPtrArray *breakpoints;
4131 /* Maps breakpoint locations to the number of breakpoints at that location */
4132 static GHashTable *bp_locs;
4135 breakpoints_init (void)
4137 breakpoints = g_ptr_array_new ();
4138 bp_locs = g_hash_table_new (NULL, NULL);
4142 * insert_breakpoint:
4144 * Insert the breakpoint described by BP into the method described by
4148 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4151 BreakpointInstance *inst;
4152 SeqPointIterator it;
4153 gboolean it_has_sp = FALSE;
4156 mono_error_init (error);
4158 mono_seq_point_iterator_init (&it, seq_points);
4159 while (mono_seq_point_iterator_next (&it)) {
4160 if (it.seq_point.il_offset == bp->il_offset) {
4168 * The set of IL offsets with seq points doesn't completely match the
4169 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4171 mono_seq_point_iterator_init (&it, seq_points);
4172 while (mono_seq_point_iterator_next (&it)) {
4173 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4174 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4175 it.seq_point.il_offset + 1 == bp->il_offset) {
4183 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4185 mono_seq_point_iterator_init (&it, seq_points);
4186 while (mono_seq_point_iterator_next (&it))
4187 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4190 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4191 g_warning ("%s", s);
4195 g_warning ("%s", s);
4201 inst = g_new0 (BreakpointInstance, 1);
4202 inst->il_offset = it.seq_point.il_offset;
4203 inst->native_offset = it.seq_point.native_offset;
4204 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4206 inst->domain = domain;
4208 mono_loader_lock ();
4210 g_ptr_array_add (bp->children, inst);
4212 mono_loader_unlock ();
4215 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4216 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4219 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4220 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4221 } else if (count == 0) {
4222 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4223 mono_arch_set_breakpoint (ji, inst->ip);
4229 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);
4233 remove_breakpoint (BreakpointInstance *inst)
4235 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4237 MonoJitInfo *ji = inst->ji;
4238 guint8 *ip = inst->ip;
4241 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4242 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4245 g_assert (count > 0);
4247 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4248 mono_arch_clear_breakpoint (ji, ip);
4249 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4257 * This doesn't take any locks.
4259 static inline gboolean
4260 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4266 if (method == bp->method)
4268 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4271 if (bp->method->is_inflated && method->is_inflated) {
4272 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4273 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4275 /* Open generic methods should match closed generic methods of the same class */
4276 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4277 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4278 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4280 /* FIXME: Handle !mvar */
4281 if (t1->type != MONO_TYPE_MVAR)
4292 * add_pending_breakpoints:
4294 * Insert pending breakpoints into the newly JITted method METHOD.
4297 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4300 MonoSeqPointInfo *seq_points;
4302 MonoMethod *jmethod;
4307 domain = mono_domain_get ();
4309 mono_loader_lock ();
4311 for (i = 0; i < breakpoints->len; ++i) {
4312 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4313 gboolean found = FALSE;
4315 if (!bp_matches_method (bp, method))
4318 for (j = 0; j < bp->children->len; ++j) {
4319 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4326 MonoMethod *declaring = NULL;
4328 jmethod = jinfo_get_method (ji);
4329 if (jmethod->is_inflated)
4330 declaring = mono_method_get_declaring_generic_method (jmethod);
4332 mono_domain_lock (domain);
4333 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4334 if (!seq_points && declaring)
4335 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4336 mono_domain_unlock (domain);
4338 /* Could be AOT code */
4340 g_assert (seq_points);
4342 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4346 mono_loader_unlock ();
4350 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4356 mono_error_init (error);
4358 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4362 /* Might be AOTed code */
4363 mono_class_init (method->klass);
4364 code = mono_aot_get_method_checked (domain, method, &oerror);
4366 mono_error_assert_ok (&oerror);
4367 ji = mono_jit_info_table_find (domain, (char *)code);
4372 insert_breakpoint (seq_points, domain, ji, bp, error);
4376 clear_breakpoint (MonoBreakpoint *bp);
4381 * Set a breakpoint at IL_OFFSET in METHOD.
4382 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4383 * METHOD can also be a generic method definition, in which case a breakpoint
4384 * is placed in all instances of the method.
4385 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4388 static MonoBreakpoint*
4389 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4392 GHashTableIter iter, iter2;
4395 MonoSeqPointInfo *seq_points;
4397 GPtrArray *method_domains;
4398 GPtrArray *method_seq_points;
4402 mono_error_init (error);
4405 // - suspend/resume the vm to prevent code patching problems
4406 // - multiple breakpoints on the same location
4407 // - dynamic methods
4410 bp = g_new0 (MonoBreakpoint, 1);
4411 bp->method = method;
4412 bp->il_offset = il_offset;
4414 bp->children = g_ptr_array_new ();
4416 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);
4418 methods = g_ptr_array_new ();
4419 method_domains = g_ptr_array_new ();
4420 method_seq_points = g_ptr_array_new ();
4422 mono_loader_lock ();
4423 g_hash_table_iter_init (&iter, domains);
4424 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4425 mono_domain_lock (domain);
4426 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4427 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4428 if (bp_matches_method (bp, m)) {
4429 /* Save the info locally to simplify the code inside the domain lock */
4430 g_ptr_array_add (methods, m);
4431 g_ptr_array_add (method_domains, domain);
4432 g_ptr_array_add (method_seq_points, seq_points);
4435 mono_domain_unlock (domain);
4438 for (i = 0; i < methods->len; ++i) {
4439 m = (MonoMethod *)g_ptr_array_index (methods, i);
4440 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4441 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4442 set_bp_in_method (domain, m, seq_points, bp, error);
4445 g_ptr_array_add (breakpoints, bp);
4446 mono_loader_unlock ();
4448 g_ptr_array_free (methods, TRUE);
4449 g_ptr_array_free (method_domains, TRUE);
4450 g_ptr_array_free (method_seq_points, TRUE);
4452 if (error && !mono_error_ok (error)) {
4453 clear_breakpoint (bp);
4461 clear_breakpoint (MonoBreakpoint *bp)
4465 // FIXME: locking, races
4466 for (i = 0; i < bp->children->len; ++i) {
4467 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4469 remove_breakpoint (inst);
4474 mono_loader_lock ();
4475 g_ptr_array_remove (breakpoints, bp);
4476 mono_loader_unlock ();
4478 g_ptr_array_free (bp->children, TRUE);
4483 breakpoints_cleanup (void)
4487 mono_loader_lock ();
4489 while (i < event_requests->len) {
4490 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4492 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4493 clear_breakpoint ((MonoBreakpoint *)req->info);
4494 g_ptr_array_remove_index_fast (event_requests, i);
4501 for (i = 0; i < breakpoints->len; ++i)
4502 g_free (g_ptr_array_index (breakpoints, i));
4504 g_ptr_array_free (breakpoints, TRUE);
4505 g_hash_table_destroy (bp_locs);
4510 mono_loader_unlock ();
4514 * clear_breakpoints_for_domain:
4516 * Clear breakpoint instances which reference DOMAIN.
4519 clear_breakpoints_for_domain (MonoDomain *domain)
4523 /* This could be called after shutdown */
4527 mono_loader_lock ();
4528 for (i = 0; i < breakpoints->len; ++i) {
4529 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4532 while (j < bp->children->len) {
4533 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4535 if (inst->domain == domain) {
4536 remove_breakpoint (inst);
4540 g_ptr_array_remove_index_fast (bp->children, j);
4546 mono_loader_unlock ();
4550 * ss_calculate_framecount:
4552 * Ensure DebuggerTlsData fields are filled out.
4554 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4556 if (!tls->context.valid)
4557 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4558 compute_frame_info (tls->thread, tls);
4562 ensure_jit (StackFrame* frame)
4565 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4566 if (!frame->jit && frame->api_method->is_inflated)
4567 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4571 /* This could happen for aot images with no jit debug info */
4572 s = mono_method_full_name (frame->api_method, TRUE);
4573 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4584 * Return FALSE if single stepping needs to continue.
4587 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4589 MonoDebugMethodInfo *minfo;
4590 MonoDebugSourceLocation *loc = NULL;
4591 gboolean hit = TRUE;
4593 if (req->async_stepout_method == method) {
4594 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);
4598 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4600 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4602 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);
4606 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4607 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4609 ss_calculate_framecount (tls, ctx);
4611 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4612 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4613 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4614 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4615 /* Hit the breakpoint in a recursive call, don't halt */
4616 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");
4621 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4622 ss_calculate_framecount (tls, ctx);
4623 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4624 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);
4629 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4631 for (int i = 0; i < asyncMethod->num_awaits; i++)
4633 if (asyncMethod->yield_offsets[i] == sp->il_offset || asyncMethod->resume_offsets[i] == sp->il_offset) {
4634 mono_debug_free_method_async_debug_info (asyncMethod);
4638 mono_debug_free_method_async_debug_info (asyncMethod);
4641 if (req->size != STEP_SIZE_LINE)
4644 /* Have to check whenever a different source line was reached */
4645 minfo = mono_debug_lookup_method (method);
4648 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4651 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);
4652 ss_req->last_method = method;
4654 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4655 ss_calculate_framecount (tls, ctx);
4656 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4657 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4663 ss_req->last_method = method;
4664 ss_req->last_line = loc->row;
4665 mono_debug_free_source_location (loc);
4672 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4674 return bp->method && bp->method->klass->image->assembly == assembly;
4678 get_this (StackFrame *frame)
4680 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4681 MonoDebugVarInfo *var = frame->jit->this_var;
4682 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4685 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4686 addr += (gint32)var->offset;
4687 return *(MonoObject**)addr;
4690 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4691 //since thread probably changed...
4693 get_this_async_id (StackFrame *frame)
4695 return get_objid (get_this (frame));
4698 static MonoMethod* set_notification_method_cache = NULL;
4701 get_set_notification_method ()
4703 if(set_notification_method_cache != NULL)
4704 return set_notification_method_cache;
4706 MonoClass* async_builder_class = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder");
4707 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4708 mono_error_assert_ok (&error);
4709 g_assert (array->len == 1);
4710 set_notification_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4711 g_ptr_array_free (array, TRUE);
4712 return set_notification_method_cache;
4716 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4718 MonoObject* obj = get_this (frame);
4720 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4721 g_assert (builder_field);
4722 MonoObject* builder;
4724 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4725 mono_error_assert_ok (&error);
4729 gboolean arg = TRUE;
4731 mono_runtime_invoke_checked (get_set_notification_method(), mono_object_unbox (builder), args, &error);
4732 mono_error_assert_ok (&error);
4733 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4736 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4739 get_notify_debugger_of_wait_completion_method ()
4741 if (notify_debugger_of_wait_completion_method_cache != NULL)
4742 return notify_debugger_of_wait_completion_method_cache;
4744 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4745 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4746 mono_error_assert_ok (&error);
4747 g_assert (array->len == 1);
4748 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4749 g_ptr_array_free (array, TRUE);
4750 return notify_debugger_of_wait_completion_method_cache;
4754 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4758 int i, j, suspend_policy;
4759 guint32 native_offset;
4761 BreakpointInstance *inst;
4762 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4763 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4764 EventKind kind = EVENT_KIND_BREAKPOINT;
4765 MonoContext *ctx = &tls->restore_state.ctx;
4767 MonoSeqPointInfo *info;
4771 // FIXME: Speed this up
4773 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4774 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4775 g_assert (ji && !ji->is_trampoline);
4776 method = jinfo_get_method (ji);
4778 /* Compute the native offset of the breakpoint from the ip */
4779 native_offset = ip - (guint8*)ji->code_start;
4782 * Skip the instruction causing the breakpoint signal.
4785 mono_arch_skip_breakpoint (ctx, ji);
4787 if (method->wrapper_type || tls->disable_breakpoints)
4790 bp_reqs = g_ptr_array_new ();
4791 ss_reqs = g_ptr_array_new ();
4792 ss_reqs_orig = g_ptr_array_new ();
4794 mono_loader_lock ();
4797 * The ip points to the instruction causing the breakpoint event, which is after
4798 * the offset recorded in the seq point map, so find the prev seq point before ip.
4800 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4803 no_seq_points_found (method, native_offset);
4805 g_assert (found_sp);
4807 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);
4810 for (i = 0; i < breakpoints->len; ++i) {
4811 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4816 for (j = 0; j < bp->children->len; ++j) {
4817 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4818 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4819 if (bp->req->event_kind == EVENT_KIND_STEP) {
4820 g_ptr_array_add (ss_reqs_orig, bp->req);
4822 g_ptr_array_add (bp_reqs, bp->req);
4827 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4828 /* Maybe a method entry/exit event */
4829 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4830 kind = EVENT_KIND_METHOD_ENTRY;
4831 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4832 kind = EVENT_KIND_METHOD_EXIT;
4835 /* Process single step requests */
4836 for (i = 0; i < ss_reqs_orig->len; ++i) {
4837 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4838 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4841 //if we hit async_stepout_method, it's our no matter which thread
4842 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4843 //We have different thread and we don't have async stepping in progress
4844 //it's breakpoint in parallel thread, ignore it
4845 if (ss_req->async_id == 0)
4848 tls->context.valid = FALSE;
4849 tls->async_state.valid = FALSE;
4850 invalidate_frames (tls);
4851 ss_calculate_framecount(tls, ctx);
4852 //make sure we have enough data to get current async method instance id
4853 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4856 //Check method is async before calling get_this_async_id
4857 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4861 mono_debug_free_method_async_debug_info (asyncMethod);
4863 //breakpoint was hit in parallelly executing async method, ignore it
4864 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4868 //Update stepping request to new thread/frame_count that we are continuing on
4869 //so continuing with normal stepping works as expected
4870 if (ss_req->async_stepout_method || ss_req->async_id) {
4871 tls->context.valid = FALSE;
4872 tls->async_state.valid = FALSE;
4873 invalidate_frames (tls);
4874 ss_calculate_framecount (tls, ctx);
4875 ss_req->thread = mono_thread_internal_current ();
4876 ss_req->nframes = tls->frame_count;
4879 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4881 g_ptr_array_add (ss_reqs, req);
4883 /* Start single stepping again from the current sequence point */
4884 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4887 if (ss_reqs->len > 0)
4888 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4889 if (bp_reqs->len > 0)
4890 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4891 if (kind != EVENT_KIND_BREAKPOINT)
4892 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4894 mono_loader_unlock ();
4896 g_ptr_array_free (bp_reqs, TRUE);
4897 g_ptr_array_free (ss_reqs, TRUE);
4900 * FIXME: The first event will suspend, so the second will only be sent after the
4904 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4906 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4907 if (enter_leave_events)
4908 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4911 /* Process a breakpoint/single step event after resuming from a signal handler */
4913 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4915 DebuggerTlsData *tls;
4916 MonoThreadUnwindState orig_restore_state;
4919 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4920 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4921 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4922 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4926 /* This is called when resuming from a signal handler, so it shouldn't return */
4927 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4928 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4929 mono_restore_context (&ctx);
4930 g_assert_not_reached ();
4934 process_breakpoint (void)
4936 process_signal_event (process_breakpoint_inner);
4940 resume_from_signal_handler (void *sigctx, void *func)
4942 DebuggerTlsData *tls;
4945 /* Save the original context in TLS */
4946 // FIXME: This might not work on an altstack ?
4947 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4949 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4952 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4953 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4954 // clob:c could be added to op_seq_point.
4956 mono_sigctx_to_monoctx (sigctx, &ctx);
4957 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4958 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4959 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4961 MONO_CONTEXT_SET_IP (&ctx, func);
4963 mono_monoctx_to_sigctx (&ctx, sigctx);
4965 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4966 mono_ppc_set_func_into_sigctx (sigctx, func);
4971 mono_debugger_agent_breakpoint_hit (void *sigctx)
4974 * We are called from a signal handler, and running code there causes all kinds of
4975 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4976 * So set up the signal context to return to the real breakpoint handler function.
4978 resume_from_signal_handler (sigctx, process_breakpoint);
4982 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4984 if (frame->managed) {
4985 *(MonoContext*)data = *ctx;
4994 * Called by System.Diagnostics.Debugger:Break ().
4997 mono_debugger_agent_user_break (void)
4999 if (agent_config.enabled) {
5004 /* Obtain a context */
5005 MONO_CONTEXT_SET_IP (&ctx, NULL);
5006 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
5007 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
5009 mono_loader_lock ();
5010 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5011 mono_loader_unlock ();
5013 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5014 } else if (debug_options.native_debugger_break) {
5020 ss_depth_to_string (StepDepth depth)
5023 case STEP_DEPTH_OVER:
5025 case STEP_DEPTH_OUT:
5027 case STEP_DEPTH_INTO:
5030 g_assert_not_reached ();
5036 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5041 int il_offset, suspend_policy;
5044 MonoContext *ctx = &tls->restore_state.ctx;
5047 MonoSeqPointInfo *info;
5049 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5051 /* Skip the instruction causing the single step */
5053 mono_arch_skip_single_step (ctx);
5055 if (suspend_count > 0) {
5056 /* Fastpath during invokes, see in process_suspend () */
5057 if (suspend_count - tls->resume_count == 0)
5059 process_suspend (tls, ctx);
5064 // FIXME: A suspend race
5067 if (mono_thread_internal_current () != ss_req->thread)
5070 if (log_level > 0) {
5071 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5073 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);
5076 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5077 g_assert (ji && !ji->is_trampoline);
5078 method = jinfo_get_method (ji);
5081 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5086 * Stopping in memset makes half-initialized vtypes visible.
5087 * Stopping in memcpy makes half-copied vtypes visible.
5089 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5093 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5094 * hence we prefer this check here.
5096 if (ss_req->user_assemblies) {
5097 gboolean found = FALSE;
5098 for (int k = 0; ss_req->user_assemblies[k]; k++)
5099 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5109 * The ip points to the instruction causing the single step event, which is before
5110 * the offset recorded in the seq point map, so find the next seq point after ip.
5112 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
5115 il_offset = sp.il_offset;
5117 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5120 /* Start single stepping again from the current sequence point */
5121 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5123 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5124 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5125 !strcmp (method->name, ".cctor"))
5128 // FIXME: Has to lock earlier
5130 reqs = g_ptr_array_new ();
5132 mono_loader_lock ();
5134 g_ptr_array_add (reqs, ss_req->req);
5136 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5138 g_ptr_array_free (reqs, TRUE);
5140 mono_loader_unlock ();
5142 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5146 process_single_step (void)
5148 process_signal_event (process_single_step_inner);
5152 * mono_debugger_agent_single_step_event:
5154 * Called from a signal handler to handle a single step event.
5157 mono_debugger_agent_single_step_event (void *sigctx)
5159 /* Resume to process_single_step through the signal context */
5161 // FIXME: Since step out/over is implemented using step in, the step in case should
5162 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5165 if (is_debugger_thread ()) {
5167 * This could happen despite our best effors when the runtime calls
5168 * assembly/type resolve hooks.
5169 * FIXME: Breakpoints too.
5173 mono_sigctx_to_monoctx (sigctx, &ctx);
5174 mono_arch_skip_single_step (&ctx);
5175 mono_monoctx_to_sigctx (&ctx, sigctx);
5179 resume_from_signal_handler (sigctx, process_single_step);
5183 debugger_agent_single_step_from_context (MonoContext *ctx)
5185 DebuggerTlsData *tls;
5186 MonoThreadUnwindState orig_restore_state;
5188 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5189 /* Fastpath during invokes, see in process_suspend () */
5190 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5193 if (is_debugger_thread ())
5198 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5199 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5200 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5201 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5203 process_single_step_inner (tls, FALSE);
5205 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5206 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5210 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5212 DebuggerTlsData *tls;
5213 MonoThreadUnwindState orig_restore_state;
5216 if (is_debugger_thread ())
5219 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5220 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5222 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5224 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5225 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5226 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5228 process_breakpoint_inner (tls, FALSE);
5230 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5231 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5232 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5233 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5237 * start_single_stepping:
5239 * Turn on single stepping. Can be called multiple times, for example,
5240 * by a single step event request + a suspend.
5243 start_single_stepping (void)
5245 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5246 int val = InterlockedIncrement (&ss_count);
5249 mono_arch_start_single_stepping ();
5251 g_assert_not_reached ();
5256 stop_single_stepping (void)
5258 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5259 int val = InterlockedDecrement (&ss_count);
5262 mono_arch_stop_single_stepping ();
5264 g_assert_not_reached ();
5271 * Stop the single stepping operation given by SS_REQ.
5274 ss_stop (SingleStepReq *ss_req)
5279 for (l = ss_req->bps; l; l = l->next) {
5280 clear_breakpoint ((MonoBreakpoint *)l->data);
5282 g_slist_free (ss_req->bps);
5286 ss_req->async_id = 0;
5287 ss_req->async_stepout_method = NULL;
5288 if (ss_req->global) {
5289 stop_single_stepping ();
5290 ss_req->global = FALSE;
5297 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5300 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5302 if (ss_req_bp_cache) {
5303 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5304 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5306 for (GSList *l = bps; l; l = l->next) {
5307 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5308 if (bp->method == method && bp->il_offset == il_offset)
5317 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5320 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5322 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5323 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5324 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5330 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5333 ss_bp_hash (gconstpointer data)
5335 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5336 guint hash = (guint) (uintptr_t) s->method;
5337 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5338 hash ^= ((guint)s->il_offset) >> 16;
5342 #define MAX_LINEAR_SCAN_BPS 7
5347 * Create a new breakpoint and add it to a step request.
5348 * Will adjust the bp count and cache used by ss_start.
5351 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5352 MonoMethod *method, guint32 il_offset)
5354 // This list is getting too long, switch to using the hash table
5355 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5356 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5357 for (GSList *l = ss_req->bps; l; l = l->next)
5358 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5361 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5362 // Create and add breakpoint
5363 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5364 ss_req->bps = g_slist_append (ss_req->bps, bp);
5365 if (*ss_req_bp_cache)
5366 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5367 (*ss_req_bp_count)++;
5369 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);
5374 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5378 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5379 mono_seq_point_init_next (info, *sp, next);
5380 for (int i = 0; i < sp->next_len; i++) {
5381 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5382 if (!is_last_non_empty (&next [i], info)) {
5398 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5399 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5400 * belong to the same thread as CTX.
5401 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5404 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5405 gboolean step_to_catch, StackFrame **frames, int nframes)
5407 int i, j, frame_index;
5408 SeqPoint *next_sp, *parent_sp = NULL;
5409 SeqPoint local_sp, local_parent_sp;
5411 MonoSeqPointInfo *parent_info;
5412 MonoMethod *parent_sp_method = NULL;
5413 gboolean enable_global = FALSE;
5415 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5416 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5417 int ss_req_bp_count = g_slist_length (ss_req->bps);
5418 GHashTable *ss_req_bp_cache = NULL;
5420 /* Stop the previous operation */
5424 * Implement single stepping using breakpoints if possible.
5426 if (step_to_catch) {
5427 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5431 if (ctx && !frames) {
5432 /* Need parent frames */
5433 if (!tls->context.valid)
5434 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5435 compute_frame_info (tls->thread, tls);
5436 frames = tls->frames;
5437 nframes = tls->frame_count;
5440 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5442 /* Need to stop in catch clauses as well */
5443 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5444 StackFrame *frame = frames [i];
5447 MonoJitInfo *jinfo = frame->ji;
5448 for (j = 0; j < jinfo->num_clauses; ++j) {
5449 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5450 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5452 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5454 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5455 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5460 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5461 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5463 // Check if we hit yield_offset during normal stepping, because if we did...
5464 // Go into special async stepping mode which places breakpoint on resumeOffset
5465 // of this await call and sets async_id so we can distinguish it from parallel executions
5466 for (i = 0; i < asyncMethod->num_awaits; i++) {
5467 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5468 ss_req->async_id = get_this_async_id (frames [0]);
5469 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5470 if (ss_req_bp_cache)
5471 g_hash_table_destroy (ss_req_bp_cache);
5472 mono_debug_free_method_async_debug_info (asyncMethod);
5476 //If we are at end of async method and doing step-in or step-over...
5477 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5478 if (is_last_non_empty (sp, info)) {
5479 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5481 if (ss_req->depth == STEP_DEPTH_OUT) {
5482 set_set_notification_for_wait_completion_flag (frames [0]);
5483 ss_req->async_id = get_this_async_id (frames [0]);
5484 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5485 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5486 if (ss_req_bp_cache)
5487 g_hash_table_destroy (ss_req_bp_cache);
5488 mono_debug_free_method_async_debug_info (asyncMethod);
5494 mono_debug_free_method_async_debug_info (asyncMethod);
5497 * Find the first sequence point in the current or in a previous frame which
5498 * is not the last in its method.
5500 if (ss_req->depth == STEP_DEPTH_OUT) {
5501 /* Ignore seq points in current method */
5502 while (frame_index < nframes) {
5503 StackFrame *frame = frames [frame_index];
5505 method = frame->method;
5506 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5507 sp = (found_sp)? &local_sp : NULL;
5509 if (sp && sp->next_len != 0)
5512 // There could be method calls before the next seq point in the caller when using nested calls
5513 //enable_global = TRUE;
5515 if (sp && sp->next_len == 0) {
5517 while (frame_index < nframes) {
5518 StackFrame *frame = frames [frame_index];
5520 method = frame->method;
5521 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5522 sp = (found_sp)? &local_sp : NULL;
5523 if (sp && sp->next_len != 0)
5529 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5530 while (frame_index < nframes) {
5531 StackFrame *frame = frames [frame_index];
5533 parent_sp_method = frame->method;
5534 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5535 parent_sp = found_sp ? &local_parent_sp : NULL;
5536 if (found_sp && parent_sp->next_len != 0)
5544 if (sp && sp->next_len > 0) {
5545 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5547 mono_seq_point_init_next (info, *sp, next);
5548 for (i = 0; i < sp->next_len; i++) {
5551 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5557 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5559 mono_seq_point_init_next (parent_info, *parent_sp, next);
5560 for (i = 0; i < parent_sp->next_len; i++) {
5563 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5568 if (ss_req->nframes == 0)
5569 ss_req->nframes = nframes;
5571 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5572 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5574 * This is needed since if we leave managed code, and later return to it, step over
5575 * is not going to stop.
5576 * This approach is a bit ugly, since we change the step depth, but it only affects
5577 * clients who reuse the same step request, and only in this special case.
5579 ss_req->depth = STEP_DEPTH_INTO;
5582 if (ss_req->depth == STEP_DEPTH_INTO) {
5583 /* Enable global stepping so we stop at method entry too */
5584 enable_global = TRUE;
5588 * The ctx/frame info computed above will become invalid when we continue.
5590 tls->context.valid = FALSE;
5591 tls->async_state.valid = FALSE;
5592 invalidate_frames (tls);
5595 if (enable_global) {
5596 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5597 ss_req->global = TRUE;
5598 start_single_stepping ();
5599 } else if (!ss_req->bps) {
5600 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5601 ss_req->global = TRUE;
5602 start_single_stepping ();
5604 ss_req->global = FALSE;
5607 if (ss_req_bp_cache)
5608 g_hash_table_destroy (ss_req_bp_cache);
5612 * Start single stepping of thread THREAD
5615 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5617 DebuggerTlsData *tls;
5618 MonoSeqPointInfo *info = NULL;
5619 SeqPoint *sp = NULL;
5622 MonoMethod *method = NULL;
5623 MonoDebugMethodInfo *minfo;
5624 gboolean step_to_catch = FALSE;
5625 gboolean set_ip = FALSE;
5626 StackFrame **frames = NULL;
5629 if (suspend_count == 0)
5630 return ERR_NOT_SUSPENDED;
5632 wait_for_suspend ();
5634 // FIXME: Multiple requests
5636 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5637 return ERR_NOT_IMPLEMENTED;
5640 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5642 ss_req = g_new0 (SingleStepReq, 1);
5644 ss_req->thread = thread;
5645 ss_req->size = size;
5646 ss_req->depth = depth;
5647 ss_req->filter = filter;
5650 for (int i = 0; i < req->nmodifiers; i++) {
5651 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5652 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5657 mono_loader_lock ();
5658 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5659 mono_loader_unlock ();
5661 if (!tls->context.valid) {
5662 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5663 return ERR_INVALID_ARGUMENT;
5666 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5668 * Need to start single stepping from restore_state and not from the current state
5671 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5674 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5676 if (tls->catch_state.valid) {
5678 StackFrameInfo frame;
5679 MonoContext new_ctx;
5680 MonoLMF *lmf = NULL;
5683 * We are stopped at a throw site. Stepping should go to the catch site.
5686 /* Find the the jit info for the catch context */
5687 res = mono_find_jit_info_ext (
5688 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5689 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5690 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5692 g_assert (frame.type == FRAME_TYPE_MANAGED);
5695 * Find the seq point corresponding to the landing site ip, which is the first seq
5698 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5699 sp = (found_sp)? &local_sp : NULL;
5701 no_seq_points_found (frame.method, frame.native_offset);
5704 method = frame.method;
5706 step_to_catch = TRUE;
5707 /* This make sure the seq point is not skipped by process_single_step () */
5708 ss_req->last_sp = NULL;
5711 if (!step_to_catch) {
5712 StackFrame *frame = NULL;
5715 if (frames && nframes)
5718 compute_frame_info (thread, tls);
5720 if (tls->frame_count)
5721 frame = tls->frames [0];
5724 if (ss_req->size == STEP_SIZE_LINE) {
5726 ss_req->last_method = frame->method;
5727 ss_req->last_line = -1;
5729 minfo = mono_debug_lookup_method (frame->method);
5730 if (minfo && frame->il_offset != -1) {
5731 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5734 ss_req->last_line = loc->row;
5742 if (!method && frame->il_offset != -1) {
5743 /* FIXME: Sort the table and use a binary search */
5744 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5745 sp = (found_sp)? &local_sp : NULL;
5747 no_seq_points_found (frame->method, frame->native_offset);
5749 method = frame->method;
5754 ss_req->start_method = method;
5756 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5759 free_frames (frames, nframes);
5765 ss_destroy (SingleStepReq *req)
5768 g_assert (ss_req == req);
5777 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5780 gboolean found = TRUE;
5784 for (l = ss_req->bps; l; l = l->next) {
5785 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5786 clear_breakpoint ((MonoBreakpoint *)l->data);
5787 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5796 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5799 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5806 if (!agent_config.enabled)
5809 mono_loader_lock ();
5810 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5811 mono_loader_unlock ();
5816 ei.category = mono_string_to_utf8_checked (category, &error);
5817 mono_error_cleanup (&error);
5821 ei.message = mono_string_to_utf8_checked (message, &error);
5822 mono_error_cleanup (&error);
5825 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5827 g_free (ei.category);
5828 g_free (ei.message);
5832 mono_debugger_agent_debug_log_is_enabled (void)
5834 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5835 return agent_config.enabled;
5838 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5840 mono_debugger_agent_unhandled_exception (MonoException *exc)
5849 memset (&ei, 0, sizeof (EventInfo));
5850 ei.exc = (MonoObject*)exc;
5852 mono_loader_lock ();
5853 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5854 mono_loader_unlock ();
5856 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5861 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5862 MonoContext *catch_ctx)
5864 int i, j, suspend_policy;
5866 MonoJitInfo *ji, *catch_ji;
5868 DebuggerTlsData *tls = NULL;
5870 if (thread_to_tls != NULL) {
5871 MonoInternalThread *thread = mono_thread_internal_current ();
5873 mono_loader_lock ();
5874 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5875 mono_loader_unlock ();
5877 if (tls && tls->abort_requested)
5879 if (tls && tls->disable_breakpoints)
5883 memset (&ei, 0, sizeof (EventInfo));
5885 /* Just-In-Time debugging */
5887 if (agent_config.onuncaught && !inited) {
5888 finish_agent_init (FALSE);
5891 * Send an unsolicited EXCEPTION event with a dummy request id.
5893 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5894 ei.exc = (MonoObject*)exc;
5895 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5898 } else if (agent_config.onthrow && !inited) {
5900 gboolean found = FALSE;
5902 for (l = agent_config.onthrow; l; l = l->next) {
5903 char *ex_type = (char *)l->data;
5904 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5906 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5913 finish_agent_init (FALSE);
5916 * Send an unsolicited EXCEPTION event with a dummy request id.
5918 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5919 ei.exc = (MonoObject*)exc;
5920 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5928 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5930 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5934 ei.exc = (MonoObject*)exc;
5935 ei.caught = catch_ctx != NULL;
5937 mono_loader_lock ();
5939 /* Treat exceptions which are caught in non-user code as unhandled */
5940 for (i = 0; i < event_requests->len; ++i) {
5941 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5942 if (req->event_kind != EVENT_KIND_EXCEPTION)
5945 for (j = 0; j < req->nmodifiers; ++j) {
5946 Modifier *mod = &req->modifiers [j];
5948 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5950 gboolean found = FALSE;
5951 MonoAssembly **assemblies = mod->data.assemblies;
5954 for (k = 0; assemblies [k]; ++k)
5955 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5964 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5965 mono_loader_unlock ();
5967 if (tls && ei.caught && catch_ctx) {
5968 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5969 tls->catch_state.ctx = *catch_ctx;
5970 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5971 tls->catch_state.valid = TRUE;
5974 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5977 tls->catch_state.valid = FALSE;
5981 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5983 DebuggerTlsData *tls;
5988 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5993 * We're about to invoke an exception filter during the first pass of exception handling.
5995 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5996 * 'orig_ctx' is the context where the exception has been thrown.
5999 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6001 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6002 * the call site (line 37) and then continue to Main(), but it would never
6003 * include the throw site (line 32).
6005 * Since exception filters are invoked during the first pass of exception handling,
6006 * the stack frames of the throw site are still intact, so we should include them
6009 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6011 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6012 * but report the location of the 'throw' to the user.
6016 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6020 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6022 DebuggerTlsData *tls;
6027 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6031 tls->filter_state.valid = FALSE;
6035 * buffer_add_value_full:
6037 * Add the encoding of the value at ADDR described by T to the buffer.
6038 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6042 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6043 gboolean as_vtype, GHashTable *parent_vtypes)
6046 gboolean boxed_vtype = FALSE;
6049 if (!(*(void**)addr)) {
6050 /* This can happen with compiler generated locals */
6051 //printf ("%s\n", mono_type_full_name (t));
6052 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6055 g_assert (*(void**)addr);
6056 addr = *(void**)addr;
6061 case MONO_TYPE_BOOLEAN:
6064 case MONO_TYPE_CHAR:
6084 case MONO_TYPE_VOID:
6085 buffer_add_byte (buf, t->type);
6087 case MONO_TYPE_BOOLEAN:
6090 buffer_add_byte (buf, t->type);
6091 buffer_add_int (buf, *(gint8*)addr);
6093 case MONO_TYPE_CHAR:
6096 buffer_add_byte (buf, t->type);
6097 buffer_add_int (buf, *(gint16*)addr);
6102 buffer_add_byte (buf, t->type);
6103 buffer_add_int (buf, *(gint32*)addr);
6108 buffer_add_byte (buf, t->type);
6109 buffer_add_long (buf, *(gint64*)addr);
6113 /* Treat it as a vtype */
6115 case MONO_TYPE_PTR: {
6116 gssize val = *(gssize*)addr;
6118 buffer_add_byte (buf, t->type);
6119 buffer_add_long (buf, val);
6123 case MONO_TYPE_STRING:
6124 case MONO_TYPE_SZARRAY:
6125 case MONO_TYPE_OBJECT:
6126 case MONO_TYPE_CLASS:
6127 case MONO_TYPE_ARRAY:
6128 obj = *(MonoObject**)addr;
6131 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6133 if (obj->vtable->klass->valuetype) {
6134 t = &obj->vtable->klass->byval_arg;
6135 addr = mono_object_unbox (obj);
6138 } else if (obj->vtable->klass->rank) {
6139 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6140 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6141 buffer_add_byte (buf, MONO_TYPE_CLASS);
6143 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6145 buffer_add_objid (buf, obj);
6149 case MONO_TYPE_VALUETYPE:
6150 case MONO_TYPE_TYPEDBYREF: {
6154 MonoClass *klass = mono_class_from_mono_type (t);
6159 * Handle boxed vtypes recursively referencing themselves using fields.
6162 parent_vtypes = g_hash_table_new (NULL, NULL);
6163 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6165 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6166 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6167 buffer_add_int (buf, vtype_index - 1);
6169 /* The client can't handle PARENT_VTYPE */
6170 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6174 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6178 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6179 buffer_add_byte (buf, klass->enumtype);
6180 buffer_add_typeid (buf, domain, klass);
6184 while ((f = mono_class_get_fields (klass, &iter))) {
6185 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6187 if (mono_field_is_deleted (f))
6191 buffer_add_int (buf, nfields);
6194 while ((f = mono_class_get_fields (klass, &iter))) {
6195 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6197 if (mono_field_is_deleted (f))
6199 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6203 g_hash_table_remove (parent_vtypes, addr);
6204 if (g_hash_table_size (parent_vtypes) == 0) {
6205 g_hash_table_destroy (parent_vtypes);
6206 parent_vtypes = NULL;
6211 case MONO_TYPE_GENERICINST:
6212 if (mono_type_generic_inst_is_valuetype (t)) {
6224 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6226 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6230 obj_is_of_type (MonoObject *obj, MonoType *t)
6232 MonoClass *klass = obj->vtable->klass;
6233 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6234 if (mono_class_is_transparent_proxy (klass)) {
6235 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6236 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6246 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6249 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6255 gpointer iter = NULL;
6259 is_enum = decode_byte (buf, &buf, limit);
6260 /* Enums are sent as a normal vtype */
6262 return ERR_NOT_IMPLEMENTED;
6263 klass = decode_typeid (buf, &buf, limit, &d, &err);
6264 if (err != ERR_NONE)
6267 if (t && klass != mono_class_from_mono_type (t)) {
6268 char *name = mono_type_full_name (t);
6269 char *name2 = mono_type_full_name (&klass->byval_arg);
6270 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6273 return ERR_INVALID_ARGUMENT;
6276 nfields = decode_int (buf, &buf, limit);
6277 while ((f = mono_class_get_fields (klass, &iter))) {
6278 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6280 if (mono_field_is_deleted (f))
6282 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6283 if (err != ERR_NONE)
6287 g_assert (nfields == 0);
6295 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6299 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6300 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6301 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6302 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6303 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6304 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6305 char *name = mono_type_full_name (t);
6306 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6308 return ERR_INVALID_ARGUMENT;
6312 case MONO_TYPE_BOOLEAN:
6313 *(guint8*)addr = decode_int (buf, &buf, limit);
6315 case MONO_TYPE_CHAR:
6316 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6319 *(gint8*)addr = decode_int (buf, &buf, limit);
6322 *(guint8*)addr = decode_int (buf, &buf, limit);
6325 *(gint16*)addr = decode_int (buf, &buf, limit);
6328 *(guint16*)addr = decode_int (buf, &buf, limit);
6331 *(gint32*)addr = decode_int (buf, &buf, limit);
6334 *(guint32*)addr = decode_int (buf, &buf, limit);
6337 *(gint64*)addr = decode_long (buf, &buf, limit);
6340 *(guint64*)addr = decode_long (buf, &buf, limit);
6343 *(guint32*)addr = decode_int (buf, &buf, limit);
6346 *(guint64*)addr = decode_long (buf, &buf, limit);
6349 /* We send these as I8, so we get them back as such */
6350 g_assert (type == MONO_TYPE_I8);
6351 *(gssize*)addr = decode_long (buf, &buf, limit);
6353 case MONO_TYPE_GENERICINST:
6354 if (MONO_TYPE_ISSTRUCT (t)) {
6355 /* The client sends these as a valuetype */
6363 /* We send these as vtypes, so we get them back as such */
6364 g_assert (type == MONO_TYPE_VALUETYPE);
6367 case MONO_TYPE_VALUETYPE:
6368 if (type == MONO_TYPE_OBJECT) {
6370 int objid = decode_objid (buf, &buf, limit);
6374 err = get_object (objid, (MonoObject**)&obj);
6375 if (err != ERR_NONE)
6378 return ERR_INVALID_ARGUMENT;
6379 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6380 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6381 return ERR_INVALID_ARGUMENT;
6383 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6385 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6386 if (err != ERR_NONE)
6392 if (MONO_TYPE_IS_REFERENCE (t)) {
6393 if (type == MONO_TYPE_OBJECT) {
6394 int objid = decode_objid (buf, &buf, limit);
6398 err = get_object (objid, (MonoObject**)&obj);
6399 if (err != ERR_NONE)
6403 if (!obj_is_of_type (obj, t)) {
6404 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6405 return ERR_INVALID_ARGUMENT;
6408 if (obj && obj->vtable->domain != domain)
6409 return ERR_INVALID_ARGUMENT;
6411 mono_gc_wbarrier_generic_store (addr, obj);
6412 } else if (type == VALUE_TYPE_ID_NULL) {
6413 *(MonoObject**)addr = NULL;
6414 } else if (type == MONO_TYPE_VALUETYPE) {
6423 /* This can happen when round-tripping boxed vtypes */
6425 * Obtain vtype class.
6426 * Same as the beginning of the handle_vtype case above.
6429 is_enum = decode_byte (buf, &buf, limit);
6431 return ERR_NOT_IMPLEMENTED;
6432 klass = decode_typeid (buf, &buf, limit, &d, &err);
6433 if (err != ERR_NONE)
6436 /* Decode the vtype into a temporary buffer, then box it. */
6437 vtype_buf_size = mono_class_value_size (klass, NULL);
6438 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6439 g_assert (vtype_buf);
6442 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6443 if (err != ERR_NONE) {
6447 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6448 mono_error_cleanup (&error);
6451 char *name = mono_type_full_name (t);
6452 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6454 return ERR_INVALID_ARGUMENT;
6468 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6472 int type = decode_byte (buf, &buf, limit);
6474 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6475 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6476 guint8 *nullable_buf;
6479 * First try decoding it as a Nullable`1
6481 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6482 if (err == ERR_NONE)
6486 * Then try decoding as a primitive value or null.
6488 if (targ->type == type) {
6489 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6490 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6491 if (err != ERR_NONE) {
6492 g_free (nullable_buf);
6495 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6496 if (!is_ok (&error)) {
6497 mono_error_cleanup (&error);
6498 return ERR_INVALID_OBJECT;
6500 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6501 g_free (nullable_buf);
6504 } else if (type == VALUE_TYPE_ID_NULL) {
6505 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6511 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6515 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6519 guint8 *addr, *gaddr;
6522 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6523 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6526 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6527 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6529 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6531 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6532 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6533 addr += (gint32)var->offset;
6535 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6537 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6539 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6542 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6543 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6544 /* Same as regoffset, but with an indirection */
6545 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6546 addr += (gint32)var->offset;
6548 gaddr = (guint8 *)*(gpointer*)addr;
6550 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6552 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6553 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6554 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6555 MonoGSharedVtMethodRuntimeInfo *info;
6561 g_assert (info_var);
6562 g_assert (locals_var);
6564 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6565 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6566 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6567 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6568 addr += (gint32)info_var->offset;
6569 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6570 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6571 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6573 g_assert_not_reached ();
6577 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6578 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6579 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6580 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6581 addr += (gint32)locals_var->offset;
6582 locals = (guint8 *)*(gpointer*)addr;
6583 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6584 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6586 g_assert_not_reached ();
6590 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6592 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6597 g_assert_not_reached ();
6602 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6606 guint8 *addr, *gaddr;
6608 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6609 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6611 if (MONO_TYPE_IS_REFERENCE (t))
6612 size = sizeof (gpointer);
6614 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6617 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6618 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6620 gboolean is_signed = FALSE;
6623 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6626 // FIXME: Write barriers
6627 mono_gc_memmove_atomic (addr, val, size);
6632 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6637 v = is_signed ? *(gint8*)val : *(guint8*)val;
6640 v = is_signed ? *(gint16*)val : *(guint16*)val;
6643 v = is_signed ? *(gint32*)val : *(guint32*)val;
6646 v = is_signed ? *(gint64*)val : *(guint64*)val;
6649 g_assert_not_reached ();
6652 /* Set value on the stack or in the return ctx */
6653 if (reg_locations [reg]) {
6654 /* Saved on the stack */
6655 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6656 *(reg_locations [reg]) = v;
6659 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6660 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6663 // FIXME: Move these to mono-context.h/c.
6664 mono_arch_context_set_int_reg (ctx, reg, v);
6666 // FIXME: Can't set registers, so we disable linears
6671 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6672 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6673 addr += (gint32)var->offset;
6675 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6678 addr = *(guint8**)addr;
6684 // FIXME: Write barriers
6685 mono_gc_memmove_atomic (addr, val, size);
6687 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6688 /* Same as regoffset, but with an indirection */
6689 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6690 addr += (gint32)var->offset;
6692 gaddr = (guint8 *)*(gpointer*)addr;
6694 // FIXME: Write barriers
6695 mono_gc_memmove_atomic (gaddr, val, size);
6697 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6701 g_assert_not_reached ();
6706 clear_event_request (int req_id, int etype)
6710 mono_loader_lock ();
6711 for (i = 0; i < event_requests->len; ++i) {
6712 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6714 if (req->id == req_id && req->event_kind == etype) {
6715 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6716 clear_breakpoint ((MonoBreakpoint *)req->info);
6717 if (req->event_kind == EVENT_KIND_STEP)
6718 ss_destroy ((SingleStepReq *)req->info);
6719 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6720 clear_breakpoint ((MonoBreakpoint *)req->info);
6721 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6722 clear_breakpoint ((MonoBreakpoint *)req->info);
6723 g_ptr_array_remove_index_fast (event_requests, i);
6728 mono_loader_unlock ();
6732 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6736 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6737 m->kind = MOD_KIND_NONE;
6738 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6739 int count = 0, match_count = 0, pos;
6740 MonoAssembly **newassemblies;
6742 for (i = 0; m->data.assemblies [i]; ++i) {
6744 if (m->data.assemblies [i] == assembly)
6749 // +1 because we don't know length and we use last element to check for end
6750 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6753 for (i = 0; i < count; ++i)
6754 if (m->data.assemblies [i] != assembly)
6755 newassemblies [pos ++] = m->data.assemblies [i];
6756 g_assert (pos == count - match_count);
6757 g_free (m->data.assemblies);
6758 m->data.assemblies = newassemblies;
6764 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6768 for (i = 0; i < req->nmodifiers; ++i) {
6769 Modifier *m = &req->modifiers [i];
6771 clear_assembly_from_modifier (req, m, assembly);
6776 * clear_event_requests_for_assembly:
6778 * Clear all events requests which reference ASSEMBLY.
6781 clear_event_requests_for_assembly (MonoAssembly *assembly)
6786 mono_loader_lock ();
6790 for (i = 0; i < event_requests->len; ++i) {
6791 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6793 clear_assembly_from_modifiers (req, assembly);
6795 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6796 clear_event_request (req->id, req->event_kind);
6801 if (req->event_kind == EVENT_KIND_STEP)
6802 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6805 mono_loader_unlock ();
6809 * type_comes_from_assembly:
6811 * GHRFunc that returns TRUE if klass comes from assembly
6814 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6816 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6820 * clear_types_for_assembly:
6822 * Clears types from loaded_classes for a given assembly
6825 clear_types_for_assembly (MonoAssembly *assembly)
6827 MonoDomain *domain = mono_domain_get ();
6828 AgentDomainInfo *info = NULL;
6830 if (!domain || !domain_jit_info (domain))
6831 /* Can happen during shutdown */
6834 info = get_agent_domain_info (domain);
6836 mono_loader_lock ();
6837 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6838 mono_loader_unlock ();
6842 add_thread (gpointer key, gpointer value, gpointer user_data)
6844 MonoInternalThread *thread = (MonoInternalThread *)value;
6845 Buffer *buf = (Buffer *)user_data;
6847 buffer_add_objid (buf, (MonoObject*)thread);
6851 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6854 guint8 *end = invoke->endp;
6858 MonoMethodSignature *sig;
6861 MonoObject *this_arg, *res, *exc;
6864 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6867 MonoStopwatch watch;
6869 if (invoke->method) {
6871 * Invoke this method directly, currently only Environment.Exit () is supported.
6874 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>");
6876 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6877 mono_error_assert_ok (&error);
6879 g_assert_not_reached ();
6882 m = decode_methodid (p, &p, end, &domain, &err);
6883 if (err != ERR_NONE)
6885 sig = mono_method_signature (m);
6887 if (m->klass->valuetype)
6888 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6890 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6891 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6892 /* Should be null */
6893 int type = decode_byte (p, &p, end);
6894 if (type != VALUE_TYPE_ID_NULL) {
6895 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6896 return ERR_INVALID_ARGUMENT;
6898 memset (this_buf, 0, mono_class_instance_size (m->klass));
6899 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6903 int type = decode_byte (p, &tmp_p, end);
6904 if (type == VALUE_TYPE_ID_NULL) {
6905 memset (this_buf, 0, mono_class_instance_size (m->klass));
6908 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6909 if (err != ERR_NONE)
6913 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6914 if (err != ERR_NONE)
6918 if (!m->klass->valuetype)
6919 this_arg = *(MonoObject**)this_buf;
6923 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6925 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6926 return ERR_INVALID_ARGUMENT;
6928 m = mono_object_get_virtual_method (this_arg, m);
6929 /* Transform this to the format the rest of the code expects it to be */
6930 if (m->klass->valuetype) {
6931 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6932 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6934 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6936 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6937 return ERR_INVALID_ARGUMENT;
6939 m = mono_object_get_virtual_method (this_arg, m);
6940 if (m->klass->valuetype) {
6941 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6942 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6946 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>");
6948 if (this_arg && this_arg->vtable->domain != domain)
6951 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6952 if (!strcmp (m->name, ".ctor")) {
6953 if (mono_class_is_abstract (m->klass))
6954 return ERR_INVALID_ARGUMENT;
6957 this_arg = mono_object_new_checked (domain, m->klass, &error);
6958 mono_error_assert_ok (&error);
6961 return ERR_INVALID_ARGUMENT;
6965 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6966 return ERR_INVALID_ARGUMENT;
6968 nargs = decode_int (p, &p, end);
6969 if (nargs != sig->param_count)
6970 return ERR_INVALID_ARGUMENT;
6971 /* Use alloca to get gc tracking */
6972 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6973 memset (arg_buf, 0, nargs * sizeof (gpointer));
6974 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6975 for (i = 0; i < nargs; ++i) {
6976 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6977 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6978 if (err != ERR_NONE)
6980 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6983 if (sig->params [i]->byref) {
6984 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6985 *(gpointer*)arg_buf [i] = args [i];
6986 args [i] = arg_buf [i];
6989 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6990 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6991 if (err != ERR_NONE)
6993 args [i] = arg_buf [i];
7000 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7001 tls->disable_breakpoints = TRUE;
7003 tls->disable_breakpoints = FALSE;
7006 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7008 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7009 if (invoke->has_ctx) {
7012 lmf_addr = mono_get_lmf_addr ();
7015 memset (&ext, 0, sizeof (ext));
7016 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7018 ext.debugger_invoke = TRUE;
7019 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7021 mono_set_lmf ((MonoLMF*)&ext);
7025 mono_stopwatch_start (&watch);
7026 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7027 if (exc == NULL && !mono_error_ok (&error)) {
7028 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7030 mono_error_cleanup (&error); /* FIXME report error */
7032 mono_stopwatch_stop (&watch);
7033 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));
7035 buffer_add_byte (buf, 0);
7036 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7038 gboolean out_this = FALSE;
7039 gboolean out_args = FALSE;
7041 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7043 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7045 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7046 if (sig->ret->type == MONO_TYPE_VOID) {
7047 if (!strcmp (m->name, ".ctor")) {
7048 if (!m->klass->valuetype)
7049 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7051 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7053 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7055 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7056 buffer_add_value (buf, sig->ret, &res, domain);
7057 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7058 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7059 MonoClass *k = mono_class_from_mono_type (sig->ret);
7060 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7062 g_assert (nullable_buf);
7063 mono_nullable_init (nullable_buf, res, k);
7064 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7067 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7073 /* Return the new value of the receiver after the call */
7074 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7076 buffer_add_int (buf, nargs);
7077 for (i = 0; i < nargs; ++i) {
7078 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7079 buffer_add_value (buf, sig->params [i], &args [i], domain);
7080 else if (sig->params [i]->byref)
7081 /* add_value () does an indirection */
7082 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7084 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7089 tls->disable_breakpoints = FALSE;
7091 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7092 if (invoke->has_ctx)
7093 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7097 // FIXME: byref arguments
7105 * Invoke the method given by tls->pending_invoke in the current thread.
7108 invoke_method (void)
7110 DebuggerTlsData *tls;
7116 MonoContext restore_ctx;
7119 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7123 * Store the `InvokeData *' in `tls->invoke' until we're done with
7124 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7127 mono_loader_lock ();
7129 invoke = tls->pending_invoke;
7131 tls->pending_invoke = NULL;
7133 invoke->last_invoke = tls->invoke;
7134 tls->invoke = invoke;
7136 mono_loader_unlock ();
7138 tls->frames_up_to_date = FALSE;
7144 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7145 buffer_init (&buf, 128);
7148 /* Fail the other invokes as well */
7150 err = do_invoke_method (tls, &buf, invoke, p, &p);
7153 if (tls->abort_requested) {
7154 if (CHECK_PROTOCOL_VERSION (2, 42))
7155 err = ERR_INVOKE_ABORTED;
7158 /* Start suspending before sending the reply */
7159 if (mindex == invoke->nmethods - 1) {
7160 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7161 for (i = 0; i < invoke->suspend_count; ++i)
7166 send_reply_packet (id, err, &buf);
7171 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7173 if (invoke->has_ctx)
7174 save_thread_context (&restore_ctx);
7176 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7177 g_assert (tls->resume_count);
7178 tls->resume_count -= invoke->suspend_count;
7181 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7184 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7186 * It is possible that mono_thread_internal_abort () was called
7187 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7188 * because we reset the abort here.
7191 mono_loader_lock ();
7193 if (tls->abort_requested)
7194 mono_thread_internal_reset_abort (tls->thread);
7196 tls->invoke = tls->invoke->last_invoke;
7197 tls->abort_requested = FALSE;
7199 mono_loader_unlock ();
7208 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7210 MonoThread *thread = (MonoThread *)value;
7211 DebuggerTlsData *tls;
7214 mono_loader_lock ();
7215 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7217 res = tls->really_suspended;
7218 mono_loader_unlock ();
7224 get_source_files_for_type (MonoClass *klass)
7226 gpointer iter = NULL;
7228 MonoDebugSourceInfo *sinfo;
7232 files = g_ptr_array_new ();
7234 while ((method = mono_class_get_methods (klass, &iter))) {
7235 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7236 GPtrArray *source_file_list;
7239 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7240 for (j = 0; j < source_file_list->len; ++j) {
7241 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7242 for (i = 0; i < files->len; ++i)
7243 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7245 if (i == files->len)
7246 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7248 g_ptr_array_free (source_file_list, TRUE);
7256 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7259 case CMD_VM_VERSION: {
7260 char *build_info, *version;
7262 build_info = mono_get_runtime_build_info ();
7263 version = g_strdup_printf ("mono %s", build_info);
7265 buffer_add_string (buf, version); /* vm version */
7266 buffer_add_int (buf, MAJOR_VERSION);
7267 buffer_add_int (buf, MINOR_VERSION);
7268 g_free (build_info);
7272 case CMD_VM_SET_PROTOCOL_VERSION: {
7273 major_version = decode_int (p, &p, end);
7274 minor_version = decode_int (p, &p, end);
7275 protocol_version_set = TRUE;
7276 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7279 case CMD_VM_ALL_THREADS: {
7281 mono_loader_lock ();
7282 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7283 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7284 mono_loader_unlock ();
7287 case CMD_VM_SUSPEND:
7289 wait_for_suspend ();
7292 if (suspend_count == 0)
7293 return ERR_NOT_SUSPENDED;
7295 clear_suspended_objs ();
7297 case CMD_VM_DISPOSE:
7298 /* Clear all event requests */
7299 mono_loader_lock ();
7300 while (event_requests->len > 0) {
7301 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7303 clear_event_request (req->id, req->event_kind);
7305 mono_loader_unlock ();
7307 while (suspend_count > 0)
7309 disconnected = TRUE;
7310 vm_start_event_sent = FALSE;
7313 MonoInternalThread *thread;
7314 DebuggerTlsData *tls;
7315 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7316 MonoClass *env_class;
7318 MonoMethod *exit_method = NULL;
7322 exit_code = decode_int (p, &p, end);
7324 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7326 /* Have to send a reply before exiting */
7327 send_reply_packet (id, 0, buf);
7329 /* Clear all event requests */
7330 mono_loader_lock ();
7331 while (event_requests->len > 0) {
7332 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7334 clear_event_request (req->id, req->event_kind);
7336 mono_loader_unlock ();
7339 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7340 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7341 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7342 * better than doing the shutdown ourselves, since it avoids various races.
7346 wait_for_suspend ();
7348 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7349 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7351 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7354 mono_loader_lock ();
7355 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7356 mono_loader_unlock ();
7358 if (thread && exit_method) {
7359 mono_loader_lock ();
7360 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7361 mono_loader_unlock ();
7363 args = g_new0 (gpointer, 1);
7364 args [0] = g_malloc (sizeof (int));
7365 *(int*)(args [0]) = exit_code;
7367 tls->pending_invoke = g_new0 (InvokeData, 1);
7368 tls->pending_invoke->method = exit_method;
7369 tls->pending_invoke->args = args;
7370 tls->pending_invoke->nmethods = 1;
7372 while (suspend_count > 0)
7376 * No thread found, do it ourselves.
7377 * FIXME: This can race with normal shutdown etc.
7379 while (suspend_count > 0)
7382 if (!mono_runtime_try_shutdown ())
7385 mono_environment_exitcode_set (exit_code);
7387 /* Suspend all managed threads since the runtime is going away */
7388 DEBUG_PRINTF (1, "Suspending all threads...\n");
7389 mono_thread_suspend_all_other_threads ();
7390 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7391 mono_runtime_quit ();
7392 transport_close2 ();
7393 DEBUG_PRINTF (1, "Exiting...\n");
7399 case CMD_VM_INVOKE_METHOD:
7400 case CMD_VM_INVOKE_METHODS: {
7401 int objid = decode_objid (p, &p, end);
7403 DebuggerTlsData *tls;
7404 int i, count, flags, nmethods;
7407 err = get_object (objid, (MonoObject**)&thread);
7408 if (err != ERR_NONE)
7411 flags = decode_int (p, &p, end);
7413 if (command == CMD_VM_INVOKE_METHODS)
7414 nmethods = decode_int (p, &p, end);
7418 // Wait for suspending if it already started
7420 wait_for_suspend ();
7421 if (!is_suspended ())
7422 return ERR_NOT_SUSPENDED;
7424 mono_loader_lock ();
7425 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7426 mono_loader_unlock ();
7429 if (!tls->really_suspended)
7430 /* The thread is still running native code, can't do invokes */
7431 return ERR_NOT_SUSPENDED;
7434 * Store the invoke data into tls, the thread will execute it after it is
7437 if (tls->pending_invoke)
7438 return ERR_NOT_SUSPENDED;
7439 tls->pending_invoke = g_new0 (InvokeData, 1);
7440 tls->pending_invoke->id = id;
7441 tls->pending_invoke->flags = flags;
7442 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7443 memcpy (tls->pending_invoke->p, p, end - p);
7444 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7445 tls->pending_invoke->suspend_count = suspend_count;
7446 tls->pending_invoke->nmethods = nmethods;
7448 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7449 resume_thread (THREAD_TO_INTERNAL (thread));
7452 count = suspend_count;
7453 for (i = 0; i < count; ++i)
7458 case CMD_VM_ABORT_INVOKE: {
7459 int objid = decode_objid (p, &p, end);
7461 DebuggerTlsData *tls;
7465 err = get_object (objid, (MonoObject**)&thread);
7466 if (err != ERR_NONE)
7469 invoke_id = decode_int (p, &p, end);
7471 mono_loader_lock ();
7472 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7475 if (tls->abort_requested) {
7476 DEBUG_PRINTF (1, "Abort already requested.\n");
7477 mono_loader_unlock ();
7482 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7483 * actually the correct invocation.
7485 * Careful, we do not stop the thread that's doing the invocation, so we can't
7486 * inspect its stack. However, invoke_method() also acquires the loader lock
7487 * when it's done, so we're safe here.
7491 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7492 mono_loader_unlock ();
7493 return ERR_NO_INVOCATION;
7496 tls->abort_requested = TRUE;
7498 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7499 mono_loader_unlock ();
7503 case CMD_VM_SET_KEEPALIVE: {
7504 int timeout = decode_int (p, &p, end);
7505 agent_config.keepalive = timeout;
7507 #ifndef DISABLE_SOCKET_TRANSPORT
7514 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7515 GHashTableIter iter, kiter;
7520 char *fname, *basename;
7521 gboolean ignore_case;
7522 GSList *class_list, *l;
7523 GPtrArray *res_classes, *res_domains;
7525 fname = decode_string (p, &p, end);
7526 ignore_case = decode_byte (p, &p, end);
7528 basename = dbg_path_get_basename (fname);
7530 res_classes = g_ptr_array_new ();
7531 res_domains = g_ptr_array_new ();
7533 mono_loader_lock ();
7534 g_hash_table_iter_init (&iter, domains);
7535 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7536 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7538 /* Update 'source_file_to_class' cache */
7539 g_hash_table_iter_init (&kiter, info->loaded_classes);
7540 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7541 if (!g_hash_table_lookup (info->source_files, klass)) {
7542 files = get_source_files_for_type (klass);
7543 g_hash_table_insert (info->source_files, klass, files);
7545 for (i = 0; i < files->len; ++i) {
7546 char *s = (char *)g_ptr_array_index (files, i);
7547 char *s2 = dbg_path_get_basename (s);
7550 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7552 class_list = g_slist_prepend (class_list, klass);
7553 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7555 class_list = g_slist_prepend (class_list, klass);
7556 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7559 /* The _ignorecase hash contains the lowercase path */
7560 s3 = strdup_tolower (s2);
7561 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7563 class_list = g_slist_prepend (class_list, klass);
7564 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7566 class_list = g_slist_prepend (class_list, klass);
7567 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7579 s = strdup_tolower (basename);
7580 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7583 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7586 for (l = class_list; l; l = l->next) {
7587 klass = (MonoClass *)l->data;
7589 g_ptr_array_add (res_classes, klass);
7590 g_ptr_array_add (res_domains, domain);
7593 mono_loader_unlock ();
7598 buffer_add_int (buf, res_classes->len);
7599 for (i = 0; i < res_classes->len; ++i)
7600 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7601 g_ptr_array_free (res_classes, TRUE);
7602 g_ptr_array_free (res_domains, TRUE);
7605 case CMD_VM_GET_TYPES: {
7606 GHashTableIter iter;
7610 gboolean ignore_case;
7611 GPtrArray *res_classes, *res_domains;
7612 MonoTypeNameParse info;
7614 name = decode_string (p, &p, end);
7615 ignore_case = decode_byte (p, &p, end);
7617 if (!mono_reflection_parse_type (name, &info)) {
7619 mono_reflection_free_type_info (&info);
7620 return ERR_INVALID_ARGUMENT;
7623 res_classes = g_ptr_array_new ();
7624 res_domains = g_ptr_array_new ();
7626 mono_loader_lock ();
7627 g_hash_table_iter_init (&iter, domains);
7628 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7630 gboolean type_resolve;
7634 mono_domain_assemblies_lock (domain);
7635 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7636 ass = (MonoAssembly *)tmp->data;
7640 type_resolve = TRUE;
7641 /* FIXME really okay to call while holding locks? */
7642 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7643 mono_error_cleanup (&error);
7645 g_ptr_array_add (res_classes, mono_type_get_class (t));
7646 g_ptr_array_add (res_domains, domain);
7650 mono_domain_assemblies_unlock (domain);
7652 mono_loader_unlock ();
7655 mono_reflection_free_type_info (&info);
7657 buffer_add_int (buf, res_classes->len);
7658 for (i = 0; i < res_classes->len; ++i)
7659 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7660 g_ptr_array_free (res_classes, TRUE);
7661 g_ptr_array_free (res_domains, TRUE);
7664 case CMD_VM_START_BUFFERING:
7665 case CMD_VM_STOP_BUFFERING:
7666 /* Handled in the main loop */
7669 return ERR_NOT_IMPLEMENTED;
7676 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7682 case CMD_EVENT_REQUEST_SET: {
7684 int i, event_kind, suspend_policy, nmodifiers;
7688 MonoThread *step_thread;
7689 int step_thread_id = 0;
7690 StepDepth depth = STEP_DEPTH_INTO;
7691 StepSize size = STEP_SIZE_MIN;
7692 StepFilter filter = STEP_FILTER_NONE;
7696 event_kind = decode_byte (p, &p, end);
7697 suspend_policy = decode_byte (p, &p, end);
7698 nmodifiers = decode_byte (p, &p, end);
7700 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7701 req->id = InterlockedIncrement (&event_request_id);
7702 req->event_kind = event_kind;
7703 req->suspend_policy = suspend_policy;
7704 req->nmodifiers = nmodifiers;
7707 for (i = 0; i < nmodifiers; ++i) {
7708 mod = (ModifierKind)decode_byte (p, &p, end);
7710 req->modifiers [i].kind = mod;
7711 if (mod == MOD_KIND_COUNT) {
7712 req->modifiers [i].data.count = decode_int (p, &p, end);
7713 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7714 method = decode_methodid (p, &p, end, &domain, &err);
7715 if (err != ERR_NONE)
7717 location = decode_long (p, &p, end);
7718 } else if (mod == MOD_KIND_STEP) {
7719 step_thread_id = decode_id (p, &p, end);
7720 size = (StepSize)decode_int (p, &p, end);
7721 depth = (StepDepth)decode_int (p, &p, end);
7722 if (CHECK_PROTOCOL_VERSION (2, 16))
7723 filter = (StepFilter)decode_int (p, &p, end);
7724 req->modifiers [i].data.filter = filter;
7725 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7726 /* Treat STEP_THOUGH the same as HIDDEN */
7727 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7728 } else if (mod == MOD_KIND_THREAD_ONLY) {
7729 int id = decode_id (p, &p, end);
7731 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7732 if (err != ERR_NONE) {
7736 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7737 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7739 if (err != ERR_NONE)
7741 req->modifiers [i].caught = decode_byte (p, &p, end);
7742 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7743 if (CHECK_PROTOCOL_VERSION (2, 25))
7744 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7746 req->modifiers [i].subclasses = TRUE;
7747 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" : "");
7749 req->modifiers [i].data.exc_class = exc_class;
7751 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7753 return ERR_INVALID_ARGUMENT;
7756 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7757 int n = decode_int (p, &p, end);
7760 // +1 because we don't know length and we use last element to check for end
7761 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7762 for (j = 0; j < n; ++j) {
7763 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7764 if (err != ERR_NONE) {
7765 g_free (req->modifiers [i].data.assemblies);
7769 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7770 int n = decode_int (p, &p, end);
7773 modifier = &req->modifiers [i];
7774 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7775 for (j = 0; j < n; ++j) {
7776 char *s = decode_string (p, &p, end);
7780 s2 = strdup_tolower (s);
7781 g_hash_table_insert (modifier->data.source_files, s2, s2);
7785 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7786 int n = decode_int (p, &p, end);
7789 modifier = &req->modifiers [i];
7790 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7791 for (j = 0; j < n; ++j) {
7792 char *s = decode_string (p, &p, end);
7795 g_hash_table_insert (modifier->data.type_names, s, s);
7799 return ERR_NOT_IMPLEMENTED;
7803 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7806 req->info = set_breakpoint (method, location, req, &error);
7807 if (!mono_error_ok (&error)) {
7809 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7810 mono_error_cleanup (&error);
7811 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7813 } else if (req->event_kind == EVENT_KIND_STEP) {
7814 g_assert (step_thread_id);
7816 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7817 if (err != ERR_NONE) {
7822 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7823 if (err != ERR_NONE) {
7827 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7828 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7829 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7830 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7831 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7832 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7834 if (req->nmodifiers) {
7836 return ERR_NOT_IMPLEMENTED;
7840 mono_loader_lock ();
7841 g_ptr_array_add (event_requests, req);
7843 if (agent_config.defer) {
7844 /* Transmit cached data to the client on receipt of the event request */
7845 switch (req->event_kind) {
7846 case EVENT_KIND_APPDOMAIN_CREATE:
7847 /* Emit load events for currently loaded domains */
7848 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7850 case EVENT_KIND_ASSEMBLY_LOAD:
7851 /* Emit load events for currently loaded assemblies */
7852 mono_domain_foreach (send_assemblies_for_domain, NULL);
7854 case EVENT_KIND_THREAD_START:
7855 /* Emit start events for currently started threads */
7856 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7858 case EVENT_KIND_TYPE_LOAD:
7859 /* Emit type load events for currently loaded types */
7860 mono_domain_foreach (send_types_for_domain, NULL);
7866 mono_loader_unlock ();
7868 buffer_add_int (buf, req->id);
7871 case CMD_EVENT_REQUEST_CLEAR: {
7872 int etype = decode_byte (p, &p, end);
7873 int req_id = decode_int (p, &p, end);
7875 // FIXME: Make a faster mapping from req_id to request
7876 mono_loader_lock ();
7877 clear_event_request (req_id, etype);
7878 mono_loader_unlock ();
7881 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7884 mono_loader_lock ();
7886 while (i < event_requests->len) {
7887 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7889 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7890 clear_breakpoint ((MonoBreakpoint *)req->info);
7892 g_ptr_array_remove_index_fast (event_requests, i);
7898 mono_loader_unlock ();
7902 return ERR_NOT_IMPLEMENTED;
7909 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7915 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7916 buffer_add_domainid (buf, mono_get_root_domain ());
7919 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7920 domain = decode_domainid (p, &p, end, NULL, &err);
7921 if (err != ERR_NONE)
7923 buffer_add_string (buf, domain->friendly_name);
7926 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7931 domain = decode_domainid (p, &p, end, NULL, &err);
7932 if (err != ERR_NONE)
7934 mono_loader_lock ();
7936 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7939 buffer_add_int (buf, count);
7940 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7941 ass = (MonoAssembly *)tmp->data;
7942 buffer_add_assemblyid (buf, domain, ass);
7944 mono_loader_unlock ();
7947 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7948 domain = decode_domainid (p, &p, end, NULL, &err);
7949 if (err != ERR_NONE)
7952 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7955 case CMD_APPDOMAIN_GET_CORLIB: {
7956 domain = decode_domainid (p, &p, end, NULL, &err);
7957 if (err != ERR_NONE)
7960 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7963 case CMD_APPDOMAIN_CREATE_STRING: {
7967 domain = decode_domainid (p, &p, end, NULL, &err);
7968 if (err != ERR_NONE)
7970 s = decode_string (p, &p, end);
7972 o = mono_string_new (domain, s);
7973 buffer_add_objid (buf, (MonoObject*)o);
7976 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7979 MonoDomain *domain2;
7982 domain = decode_domainid (p, &p, end, NULL, &err);
7983 if (err != ERR_NONE)
7985 klass = decode_typeid (p, &p, end, &domain2, &err);
7986 if (err != ERR_NONE)
7990 g_assert (domain == domain2);
7992 o = mono_object_new_checked (domain, klass, &error);
7993 mono_error_assert_ok (&error);
7995 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7996 if (err != ERR_NONE)
7999 buffer_add_objid (buf, o);
8003 return ERR_NOT_IMPLEMENTED;
8010 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8012 HANDLE_FUNCTION_ENTER();
8013 ErrorCode err = ERR_NONE;
8014 mono_error_init (error);
8015 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8016 if (MONO_HANDLE_IS_NULL (o)) {
8017 err = ERR_INVALID_OBJECT;
8020 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8022 HANDLE_FUNCTION_RETURN_VAL (err);
8027 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8033 ass = decode_assemblyid (p, &p, end, &domain, &err);
8034 if (err != ERR_NONE)
8038 case CMD_ASSEMBLY_GET_LOCATION: {
8039 buffer_add_string (buf, mono_image_get_filename (ass->image));
8042 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8046 if (ass->image->dynamic) {
8047 buffer_add_id (buf, 0);
8049 token = mono_image_get_entry_point (ass->image);
8051 buffer_add_id (buf, 0);
8054 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8056 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8057 buffer_add_methodid (buf, domain, m);
8062 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8063 buffer_add_moduleid (buf, domain, ass->image);
8066 case CMD_ASSEMBLY_GET_OBJECT: {
8068 err = get_assembly_object_command (domain, ass, buf, &error);
8069 mono_error_cleanup (&error);
8072 case CMD_ASSEMBLY_GET_DOMAIN: {
8073 buffer_add_domainid (buf, domain);
8076 case CMD_ASSEMBLY_GET_TYPE: {
8078 char *s = decode_string (p, &p, end);
8079 gboolean ignorecase = decode_byte (p, &p, end);
8080 MonoTypeNameParse info;
8082 gboolean type_resolve, res;
8083 MonoDomain *d = mono_domain_get ();
8085 /* This is needed to be able to find referenced assemblies */
8086 res = mono_domain_set (domain, FALSE);
8089 if (!mono_reflection_parse_type (s, &info)) {
8092 if (info.assembly.name)
8094 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8095 if (!is_ok (&error)) {
8096 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8097 mono_reflection_free_type_info (&info);
8099 return ERR_INVALID_ARGUMENT;
8102 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8103 mono_reflection_free_type_info (&info);
8106 mono_domain_set (d, TRUE);
8110 case CMD_ASSEMBLY_GET_NAME: {
8112 MonoAssembly *mass = ass;
8114 name = g_strdup_printf (
8115 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8117 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8118 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8119 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8120 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8122 buffer_add_string (buf, name);
8127 return ERR_NOT_IMPLEMENTED;
8134 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8140 case CMD_MODULE_GET_INFO: {
8141 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8144 basename = g_path_get_basename (image->name);
8145 buffer_add_string (buf, basename); // name
8146 buffer_add_string (buf, image->module_name); // scopename
8147 buffer_add_string (buf, image->name); // fqname
8148 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8149 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8154 return ERR_NOT_IMPLEMENTED;
8161 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8167 case CMD_FIELD_GET_INFO: {
8168 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8170 buffer_add_string (buf, f->name);
8171 buffer_add_typeid (buf, domain, f->parent);
8172 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8173 buffer_add_int (buf, f->type->attrs);
8177 return ERR_NOT_IMPLEMENTED;
8184 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8186 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8187 /* Special case these so the client doesn't have to handle Type objects */
8189 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8190 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8191 } else if (MONO_TYPE_IS_REFERENCE (t))
8192 buffer_add_value (buf, t, &val, domain);
8194 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8198 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8204 buffer_add_int (buf, 0);
8208 for (i = 0; i < cinfo->num_attrs; ++i) {
8209 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8212 buffer_add_int (buf, nattrs);
8214 for (i = 0; i < cinfo->num_attrs; ++i) {
8215 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8216 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8217 MonoArray *typed_args, *named_args;
8219 CattrNamedArg *arginfo = NULL;
8222 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8223 if (!mono_error_ok (&error)) {
8224 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8225 mono_error_cleanup (&error);
8226 return ERR_LOADER_ERROR;
8229 buffer_add_methodid (buf, domain, attr->ctor);
8233 buffer_add_int (buf, mono_array_length (typed_args));
8234 for (j = 0; j < mono_array_length (typed_args); ++j) {
8235 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8237 t = mono_method_signature (attr->ctor)->params [j];
8239 buffer_add_cattr_arg (buf, t, domain, val);
8242 buffer_add_int (buf, 0);
8247 buffer_add_int (buf, mono_array_length (named_args));
8249 for (j = 0; j < mono_array_length (named_args); ++j) {
8250 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8252 if (arginfo [j].prop) {
8253 buffer_add_byte (buf, 0x54);
8254 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8255 } else if (arginfo [j].field) {
8256 buffer_add_byte (buf, 0x53);
8257 buffer_add_fieldid (buf, domain, arginfo [j].field);
8259 g_assert_not_reached ();
8262 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8265 buffer_add_int (buf, 0);
8274 /* FIXME: Code duplication with icall.c */
8276 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8281 mono_class_setup_interfaces (klass, error);
8282 if (!mono_error_ok (error))
8285 for (i = 0; i < klass->interface_count; i++) {
8286 ic = klass->interfaces [i];
8287 g_hash_table_insert (ifaces, ic, ic);
8289 collect_interfaces (ic, ifaces, error);
8290 if (!mono_error_ok (error))
8296 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8308 case CMD_TYPE_GET_INFO: {
8309 buffer_add_string (buf, klass->name_space);
8310 buffer_add_string (buf, klass->name);
8312 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8313 buffer_add_string (buf, name);
8315 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8316 buffer_add_moduleid (buf, domain, klass->image);
8317 buffer_add_typeid (buf, domain, klass->parent);
8318 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8319 buffer_add_typeid (buf, domain, klass->element_class);
8321 buffer_add_id (buf, 0);
8322 buffer_add_int (buf, klass->type_token);
8323 buffer_add_byte (buf, klass->rank);
8324 buffer_add_int (buf, mono_class_get_flags (klass));
8326 type = &klass->byval_arg;
8327 // FIXME: Can't decide whenever a class represents a byref type
8330 if (type->type == MONO_TYPE_PTR)
8332 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8334 if (type->type == MONO_TYPE_VALUETYPE)
8336 if (klass->enumtype)
8338 if (mono_class_is_gtd (klass))
8340 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8342 buffer_add_byte (buf, b);
8345 while ((nested = mono_class_get_nested_types (klass, &iter)))
8347 buffer_add_int (buf, nnested);
8349 while ((nested = mono_class_get_nested_types (klass, &iter)))
8350 buffer_add_typeid (buf, domain, nested);
8351 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8352 if (mono_class_is_gtd (klass))
8353 buffer_add_typeid (buf, domain, klass);
8354 else if (mono_class_is_ginst (klass))
8355 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8357 buffer_add_id (buf, 0);
8359 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8362 if (mono_class_is_ginst (klass)) {
8363 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8365 count = inst->type_argc;
8366 buffer_add_int (buf, count);
8367 for (i = 0; i < count; i++)
8368 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8369 } else if (mono_class_is_gtd (klass)) {
8370 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8373 count = container->type_argc;
8374 buffer_add_int (buf, count);
8375 for (i = 0; i < count; i++) {
8376 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8377 buffer_add_typeid (buf, domain, pklass);
8380 buffer_add_int (buf, 0);
8385 case CMD_TYPE_GET_METHODS: {
8388 gpointer iter = NULL;
8391 mono_class_setup_methods (klass);
8393 nmethods = mono_class_num_methods (klass);
8395 buffer_add_int (buf, nmethods);
8397 while ((m = mono_class_get_methods (klass, &iter))) {
8398 buffer_add_methodid (buf, domain, m);
8401 g_assert (i == nmethods);
8404 case CMD_TYPE_GET_FIELDS: {
8407 gpointer iter = NULL;
8410 nfields = mono_class_num_fields (klass);
8412 buffer_add_int (buf, nfields);
8414 while ((f = mono_class_get_fields (klass, &iter))) {
8415 buffer_add_fieldid (buf, domain, f);
8416 buffer_add_string (buf, f->name);
8417 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8418 buffer_add_int (buf, f->type->attrs);
8421 g_assert (i == nfields);
8424 case CMD_TYPE_GET_PROPERTIES: {
8427 gpointer iter = NULL;
8430 nprops = mono_class_num_properties (klass);
8432 buffer_add_int (buf, nprops);
8434 while ((p = mono_class_get_properties (klass, &iter))) {
8435 buffer_add_propertyid (buf, domain, p);
8436 buffer_add_string (buf, p->name);
8437 buffer_add_methodid (buf, domain, p->get);
8438 buffer_add_methodid (buf, domain, p->set);
8439 buffer_add_int (buf, p->attrs);
8442 g_assert (i == nprops);
8445 case CMD_TYPE_GET_CATTRS: {
8446 MonoClass *attr_klass;
8447 MonoCustomAttrInfo *cinfo;
8449 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8450 /* attr_klass can be NULL */
8451 if (err != ERR_NONE)
8454 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8455 if (!is_ok (&error)) {
8456 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8457 return ERR_LOADER_ERROR;
8460 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8461 if (err != ERR_NONE)
8465 case CMD_TYPE_GET_FIELD_CATTRS: {
8466 MonoClass *attr_klass;
8467 MonoCustomAttrInfo *cinfo;
8468 MonoClassField *field;
8470 field = decode_fieldid (p, &p, end, NULL, &err);
8471 if (err != ERR_NONE)
8473 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8474 if (err != ERR_NONE)
8477 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8478 if (!is_ok (&error)) {
8479 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8480 return ERR_LOADER_ERROR;
8483 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8484 if (err != ERR_NONE)
8488 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8489 MonoClass *attr_klass;
8490 MonoCustomAttrInfo *cinfo;
8493 prop = decode_propertyid (p, &p, end, NULL, &err);
8494 if (err != ERR_NONE)
8496 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8497 if (err != ERR_NONE)
8500 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8501 if (!is_ok (&error)) {
8502 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8503 return ERR_LOADER_ERROR;
8506 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8507 if (err != ERR_NONE)
8511 case CMD_TYPE_GET_VALUES:
8512 case CMD_TYPE_GET_VALUES_2: {
8519 MonoThread *thread_obj;
8520 MonoInternalThread *thread = NULL;
8521 guint32 special_static_type;
8523 if (command == CMD_TYPE_GET_VALUES_2) {
8524 int objid = decode_objid (p, &p, end);
8527 err = get_object (objid, (MonoObject**)&thread_obj);
8528 if (err != ERR_NONE)
8531 thread = THREAD_TO_INTERNAL (thread_obj);
8534 len = decode_int (p, &p, end);
8535 for (i = 0; i < len; ++i) {
8536 f = decode_fieldid (p, &p, end, NULL, &err);
8537 if (err != ERR_NONE)
8540 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8541 return ERR_INVALID_FIELDID;
8542 special_static_type = mono_class_field_get_special_static_type (f);
8543 if (special_static_type != SPECIAL_STATIC_NONE) {
8544 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8545 return ERR_INVALID_FIELDID;
8548 /* Check that the field belongs to the object */
8550 for (k = klass; k; k = k->parent) {
8551 if (k == f->parent) {
8557 return ERR_INVALID_FIELDID;
8559 vtable = mono_class_vtable (domain, f->parent);
8560 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8561 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8562 if (!is_ok (&error))
8563 return ERR_INVALID_FIELDID;
8564 buffer_add_value (buf, f->type, val, domain);
8569 case CMD_TYPE_SET_VALUES: {
8577 len = decode_int (p, &p, end);
8578 for (i = 0; i < len; ++i) {
8579 f = decode_fieldid (p, &p, end, NULL, &err);
8580 if (err != ERR_NONE)
8583 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8584 return ERR_INVALID_FIELDID;
8585 if (mono_class_field_is_special_static (f))
8586 return ERR_INVALID_FIELDID;
8588 /* Check that the field belongs to the object */
8590 for (k = klass; k; k = k->parent) {
8591 if (k == f->parent) {
8597 return ERR_INVALID_FIELDID;
8599 // FIXME: Check for literal/const
8601 vtable = mono_class_vtable (domain, f->parent);
8602 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8603 err = decode_value (f->type, domain, val, p, &p, end);
8604 if (err != ERR_NONE) {
8608 if (MONO_TYPE_IS_REFERENCE (f->type))
8609 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8611 mono_field_static_set_value (vtable, f, val);
8616 case CMD_TYPE_GET_OBJECT: {
8617 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8618 if (!mono_error_ok (&error)) {
8619 mono_error_cleanup (&error);
8620 return ERR_INVALID_OBJECT;
8622 buffer_add_objid (buf, o);
8625 case CMD_TYPE_GET_SOURCE_FILES:
8626 case CMD_TYPE_GET_SOURCE_FILES_2: {
8627 char *source_file, *base;
8631 files = get_source_files_for_type (klass);
8633 buffer_add_int (buf, files->len);
8634 for (i = 0; i < files->len; ++i) {
8635 source_file = (char *)g_ptr_array_index (files, i);
8636 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8637 buffer_add_string (buf, source_file);
8639 base = dbg_path_get_basename (source_file);
8640 buffer_add_string (buf, base);
8643 g_free (source_file);
8645 g_ptr_array_free (files, TRUE);
8648 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8649 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8651 if (err != ERR_NONE)
8653 if (mono_class_is_assignable_from (klass, oklass))
8654 buffer_add_byte (buf, 1);
8656 buffer_add_byte (buf, 0);
8659 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8660 char *name = decode_string (p, &p, end);
8661 int i, flags = decode_int (p, &p, end);
8665 mono_error_init (&error);
8666 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8667 if (!is_ok (&error)) {
8668 mono_error_cleanup (&error);
8669 return ERR_LOADER_ERROR;
8671 buffer_add_int (buf, array->len);
8672 for (i = 0; i < array->len; ++i) {
8673 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8674 buffer_add_methodid (buf, domain, method);
8677 g_ptr_array_free (array, TRUE);
8681 case CMD_TYPE_GET_INTERFACES: {
8683 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8684 MonoClass *tclass, *iface;
8685 GHashTableIter iter;
8689 for (parent = tclass; parent; parent = parent->parent) {
8690 mono_class_setup_interfaces (parent, &error);
8691 if (!mono_error_ok (&error))
8692 return ERR_LOADER_ERROR;
8693 collect_interfaces (parent, iface_hash, &error);
8694 if (!mono_error_ok (&error))
8695 return ERR_LOADER_ERROR;
8698 buffer_add_int (buf, g_hash_table_size (iface_hash));
8700 g_hash_table_iter_init (&iter, iface_hash);
8701 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8702 buffer_add_typeid (buf, domain, iface);
8703 g_hash_table_destroy (iface_hash);
8706 case CMD_TYPE_GET_INTERFACE_MAP: {
8707 int tindex, ioffset;
8708 gboolean variance_used;
8710 int len, nmethods, i;
8714 len = decode_int (p, &p, end);
8715 mono_class_setup_vtable (klass);
8717 for (tindex = 0; tindex < len; ++tindex) {
8718 iclass = decode_typeid (p, &p, end, NULL, &err);
8719 if (err != ERR_NONE)
8722 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8724 return ERR_INVALID_ARGUMENT;
8726 nmethods = mono_class_num_methods (iclass);
8727 buffer_add_int (buf, nmethods);
8730 while ((method = mono_class_get_methods (iclass, &iter))) {
8731 buffer_add_methodid (buf, domain, method);
8733 for (i = 0; i < nmethods; ++i)
8734 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8738 case CMD_TYPE_IS_INITIALIZED: {
8739 MonoVTable *vtable = mono_class_vtable (domain, klass);
8742 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8744 buffer_add_int (buf, 0);
8747 case CMD_TYPE_CREATE_INSTANCE: {
8751 obj = mono_object_new_checked (domain, klass, &error);
8752 mono_error_assert_ok (&error);
8753 buffer_add_objid (buf, obj);
8757 return ERR_NOT_IMPLEMENTED;
8764 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8767 MonoDomain *old_domain;
8771 klass = decode_typeid (p, &p, end, &domain, &err);
8772 if (err != ERR_NONE)
8775 old_domain = mono_domain_get ();
8777 mono_domain_set (domain, TRUE);
8779 err = type_commands_internal (command, klass, domain, p, end, buf);
8781 mono_domain_set (old_domain, TRUE);
8787 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8789 MonoMethodHeader *header;
8793 case CMD_METHOD_GET_NAME: {
8794 buffer_add_string (buf, method->name);
8797 case CMD_METHOD_GET_DECLARING_TYPE: {
8798 buffer_add_typeid (buf, domain, method->klass);
8801 case CMD_METHOD_GET_DEBUG_INFO: {
8803 MonoDebugMethodInfo *minfo;
8805 int i, j, n_il_offsets;
8807 GPtrArray *source_file_list;
8808 MonoSymSeqPoint *sym_seq_points;
8810 header = mono_method_get_header_checked (method, &error);
8812 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8813 buffer_add_int (buf, 0);
8814 buffer_add_string (buf, "");
8815 buffer_add_int (buf, 0);
8819 minfo = mono_debug_lookup_method (method);
8821 buffer_add_int (buf, header->code_size);
8822 buffer_add_string (buf, "");
8823 buffer_add_int (buf, 0);
8824 mono_metadata_free_mh (header);
8828 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8829 buffer_add_int (buf, header->code_size);
8830 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8831 buffer_add_int (buf, source_file_list->len);
8832 for (i = 0; i < source_file_list->len; ++i) {
8833 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8834 buffer_add_string (buf, sinfo->source_file);
8835 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8836 for (j = 0; j < 16; ++j)
8837 buffer_add_byte (buf, sinfo->hash [j]);
8841 buffer_add_string (buf, source_file);
8843 buffer_add_int (buf, n_il_offsets);
8844 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8845 for (i = 0; i < n_il_offsets; ++i) {
8846 MonoSymSeqPoint *sp = &sym_seq_points [i];
8847 const char *srcfile = "";
8849 if (source_files [i] != -1) {
8850 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8851 srcfile = sinfo->source_file;
8853 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);
8854 buffer_add_int (buf, sp->il_offset);
8855 buffer_add_int (buf, sp->line);
8856 if (CHECK_PROTOCOL_VERSION (2, 13))
8857 buffer_add_int (buf, source_files [i]);
8858 if (CHECK_PROTOCOL_VERSION (2, 19))
8859 buffer_add_int (buf, sp->column);
8860 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8861 buffer_add_int (buf, sp->end_line);
8862 buffer_add_int (buf, sp->end_column);
8865 g_free (source_file);
8866 g_free (source_files);
8867 g_free (sym_seq_points);
8868 g_ptr_array_free (source_file_list, TRUE);
8869 mono_metadata_free_mh (header);
8872 case CMD_METHOD_GET_PARAM_INFO: {
8873 MonoMethodSignature *sig = mono_method_signature (method);
8877 /* FIXME: mono_class_from_mono_type () and byrefs */
8879 /* FIXME: Use a smaller encoding */
8880 buffer_add_int (buf, sig->call_convention);
8881 buffer_add_int (buf, sig->param_count);
8882 buffer_add_int (buf, sig->generic_param_count);
8883 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8884 for (i = 0; i < sig->param_count; ++i) {
8886 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8889 /* Emit parameter names */
8890 names = g_new (char *, sig->param_count);
8891 mono_method_get_param_names (method, (const char **) names);
8892 for (i = 0; i < sig->param_count; ++i)
8893 buffer_add_string (buf, names [i]);
8898 case CMD_METHOD_GET_LOCALS_INFO: {
8901 MonoDebugLocalsInfo *locals;
8902 int *locals_map = NULL;
8904 header = mono_method_get_header_checked (method, &error);
8906 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8907 return ERR_INVALID_ARGUMENT;
8910 locals = mono_debug_lookup_locals (method);
8912 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8914 buffer_add_int (buf, 1);
8915 buffer_add_int (buf, 0);
8916 buffer_add_int (buf, header->code_size);
8918 buffer_add_int (buf, header->num_locals);
8920 for (i = 0; i < header->num_locals; ++i) {
8921 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8924 for (i = 0; i < header->num_locals; ++i) {
8926 sprintf (lname, "V_%d", i);
8927 buffer_add_string (buf, lname);
8930 for (i = 0; i < header->num_locals; ++i) {
8931 buffer_add_int (buf, 0);
8932 buffer_add_int (buf, header->code_size);
8935 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8937 buffer_add_int (buf, locals->num_blocks);
8939 for (i = 0; i < locals->num_blocks; ++i) {
8940 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8941 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8942 last_start = locals->code_blocks [i].start_offset;
8946 num_locals = locals->num_locals;
8947 buffer_add_int (buf, num_locals);
8950 for (i = 0; i < num_locals; ++i) {
8951 g_assert (locals->locals [i].index < header->num_locals);
8952 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8955 for (i = 0; i < num_locals; ++i)
8956 buffer_add_string (buf, locals->locals [i].name);
8958 for (i = 0; i < num_locals; ++i) {
8959 if (locals->locals [i].block) {
8960 buffer_add_int (buf, locals->locals [i].block->start_offset);
8961 buffer_add_int (buf, locals->locals [i].block->end_offset);
8963 buffer_add_int (buf, 0);
8964 buffer_add_int (buf, header->code_size);
8968 mono_metadata_free_mh (header);
8971 mono_debug_free_locals (locals);
8972 g_free (locals_map);
8976 case CMD_METHOD_GET_INFO:
8977 buffer_add_int (buf, method->flags);
8978 buffer_add_int (buf, method->iflags);
8979 buffer_add_int (buf, method->token);
8980 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8982 if (method->is_generic)
8984 if (mono_method_signature (method)->generic_param_count)
8986 buffer_add_byte (buf, attrs);
8987 if (method->is_generic || method->is_inflated) {
8990 if (method->is_generic) {
8993 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8995 result = imethod->declaring;
8996 if (imethod->context.class_inst) {
8997 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8998 /*Generic methods gets the context of the GTD.*/
8999 if (mono_class_get_context (klass)) {
9001 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
9002 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9007 buffer_add_methodid (buf, domain, result);
9009 buffer_add_id (buf, 0);
9011 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9012 if (mono_method_signature (method)->generic_param_count) {
9015 if (method->is_inflated) {
9016 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9018 count = inst->type_argc;
9019 buffer_add_int (buf, count);
9021 for (i = 0; i < count; i++)
9022 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9024 buffer_add_int (buf, 0);
9026 } else if (method->is_generic) {
9027 MonoGenericContainer *container = mono_method_get_generic_container (method);
9029 count = mono_method_signature (method)->generic_param_count;
9030 buffer_add_int (buf, count);
9031 for (i = 0; i < count; i++) {
9032 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9033 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9034 buffer_add_typeid (buf, domain, pklass);
9037 buffer_add_int (buf, 0);
9040 buffer_add_int (buf, 0);
9045 case CMD_METHOD_GET_BODY: {
9049 header = mono_method_get_header_checked (method, &error);
9051 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9052 buffer_add_int (buf, 0);
9054 if (CHECK_PROTOCOL_VERSION (2, 18))
9055 buffer_add_int (buf, 0);
9057 buffer_add_int (buf, header->code_size);
9058 for (i = 0; i < header->code_size; ++i)
9059 buffer_add_byte (buf, header->code [i]);
9061 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9062 buffer_add_int (buf, header->num_clauses);
9063 for (i = 0; i < header->num_clauses; ++i) {
9064 MonoExceptionClause *clause = &header->clauses [i];
9066 buffer_add_int (buf, clause->flags);
9067 buffer_add_int (buf, clause->try_offset);
9068 buffer_add_int (buf, clause->try_len);
9069 buffer_add_int (buf, clause->handler_offset);
9070 buffer_add_int (buf, clause->handler_len);
9071 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9072 buffer_add_typeid (buf, domain, clause->data.catch_class);
9073 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9074 buffer_add_int (buf, clause->data.filter_offset);
9078 mono_metadata_free_mh (header);
9083 case CMD_METHOD_RESOLVE_TOKEN: {
9084 guint32 token = decode_int (p, &p, end);
9087 switch (mono_metadata_token_code (token)) {
9088 case MONO_TOKEN_STRING: {
9093 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9094 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9096 s2 = mono_string_to_utf8_checked (s, &error);
9097 mono_error_assert_ok (&error);
9099 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9100 buffer_add_string (buf, s2);
9107 MonoClass *handle_class;
9109 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9110 val = mono_method_get_wrapper_data (method, token);
9111 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9113 if (handle_class == NULL) {
9114 // Can't figure out the token type
9115 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9119 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9121 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9124 if (handle_class == mono_defaults.typehandle_class) {
9125 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9126 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9127 buffer_add_typeid (buf, domain, (MonoClass *) val);
9129 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9130 } else if (handle_class == mono_defaults.fieldhandle_class) {
9131 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9132 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9133 } else if (handle_class == mono_defaults.methodhandle_class) {
9134 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9135 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9136 } else if (handle_class == mono_defaults.string_class) {
9139 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9140 mono_error_assert_ok (&error);
9141 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9142 buffer_add_string (buf, s);
9145 g_assert_not_reached ();
9152 case CMD_METHOD_GET_CATTRS: {
9154 MonoClass *attr_klass;
9155 MonoCustomAttrInfo *cinfo;
9157 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9158 /* attr_klass can be NULL */
9159 if (err != ERR_NONE)
9162 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9163 if (!is_ok (&error)) {
9164 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9165 return ERR_LOADER_ERROR;
9168 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9169 if (err != ERR_NONE)
9173 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9175 MonoType **type_argv;
9179 MonoGenericInst *ginst;
9180 MonoGenericContext tmp_context;
9181 MonoMethod *inflated;
9183 type_argc = decode_int (p, &p, end);
9184 type_argv = g_new0 (MonoType*, type_argc);
9185 for (i = 0; i < type_argc; ++i) {
9186 klass = decode_typeid (p, &p, end, &d, &err);
9187 if (err != ERR_NONE) {
9193 return ERR_INVALID_ARGUMENT;
9195 type_argv [i] = &klass->byval_arg;
9197 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9199 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9200 tmp_context.method_inst = ginst;
9202 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9203 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9204 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9205 return ERR_INVALID_ARGUMENT;
9206 buffer_add_methodid (buf, domain, inflated);
9210 return ERR_NOT_IMPLEMENTED;
9217 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9220 MonoDomain *old_domain;
9224 method = decode_methodid (p, &p, end, &domain, &err);
9225 if (err != ERR_NONE)
9228 old_domain = mono_domain_get ();
9230 mono_domain_set (domain, TRUE);
9232 err = method_commands_internal (command, method, domain, p, end, buf);
9234 mono_domain_set (old_domain, TRUE);
9240 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9242 int objid = decode_objid (p, &p, end);
9244 MonoThread *thread_obj;
9245 MonoInternalThread *thread;
9247 err = get_object (objid, (MonoObject**)&thread_obj);
9248 if (err != ERR_NONE)
9251 thread = THREAD_TO_INTERNAL (thread_obj);
9254 case CMD_THREAD_GET_NAME: {
9256 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9259 buffer_add_int (buf, 0);
9264 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9266 buffer_add_int (buf, len);
9267 buffer_add_data (buf, (guint8*)name, len);
9272 case CMD_THREAD_GET_FRAME_INFO: {
9273 DebuggerTlsData *tls;
9274 int i, start_frame, length;
9276 // Wait for suspending if it already started
9277 // FIXME: Races with suspend_count
9278 while (!is_suspended ()) {
9280 wait_for_suspend ();
9284 wait_for_suspend ();
9285 if (!is_suspended ())
9286 return ERR_NOT_SUSPENDED;
9289 start_frame = decode_int (p, &p, end);
9290 length = decode_int (p, &p, end);
9292 if (start_frame != 0 || length != -1)
9293 return ERR_NOT_IMPLEMENTED;
9295 mono_loader_lock ();
9296 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9297 mono_loader_unlock ();
9300 compute_frame_info (thread, tls);
9302 buffer_add_int (buf, tls->frame_count);
9303 for (i = 0; i < tls->frame_count; ++i) {
9304 buffer_add_int (buf, tls->frames [i]->id);
9305 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9306 buffer_add_int (buf, tls->frames [i]->il_offset);
9308 * Instead of passing the frame type directly to the client, we associate
9309 * it with the previous frame using a set of flags. This avoids lots of
9310 * conditional code in the client, since a frame whose type isn't
9311 * FRAME_TYPE_MANAGED has no method, location, etc.
9313 buffer_add_byte (buf, tls->frames [i]->flags);
9318 case CMD_THREAD_GET_STATE:
9319 buffer_add_int (buf, thread->state);
9321 case CMD_THREAD_GET_INFO:
9322 buffer_add_byte (buf, thread->threadpool_thread);
9324 case CMD_THREAD_GET_ID:
9325 buffer_add_long (buf, (guint64)(gsize)thread);
9327 case CMD_THREAD_GET_TID:
9328 buffer_add_long (buf, (guint64)thread->tid);
9330 case CMD_THREAD_SET_IP: {
9331 DebuggerTlsData *tls;
9334 MonoSeqPointInfo *seq_points;
9339 method = decode_methodid (p, &p, end, &domain, &err);
9340 if (err != ERR_NONE)
9342 il_offset = decode_long (p, &p, end);
9344 while (!is_suspended ()) {
9346 wait_for_suspend ();
9349 mono_loader_lock ();
9350 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9351 mono_loader_unlock ();
9354 compute_frame_info (thread, tls);
9355 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9356 return ERR_INVALID_ARGUMENT;
9358 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9360 g_assert (seq_points);
9363 return ERR_INVALID_ARGUMENT;
9365 // FIXME: Check that the ip change is safe
9367 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);
9368 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9372 return ERR_NOT_IMPLEMENTED;
9379 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9383 MonoThread *thread_obj;
9384 MonoInternalThread *thread;
9385 int pos, i, len, frame_idx;
9386 DebuggerTlsData *tls;
9388 MonoDebugMethodJitInfo *jit;
9389 MonoMethodSignature *sig;
9391 MonoMethodHeader *header;
9393 objid = decode_objid (p, &p, end);
9394 err = get_object (objid, (MonoObject**)&thread_obj);
9395 if (err != ERR_NONE)
9398 thread = THREAD_TO_INTERNAL (thread_obj);
9400 id = decode_id (p, &p, end);
9402 mono_loader_lock ();
9403 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9404 mono_loader_unlock ();
9407 for (i = 0; i < tls->frame_count; ++i) {
9408 if (tls->frames [i]->id == id)
9411 if (i == tls->frame_count)
9412 return ERR_INVALID_FRAMEID;
9415 frame = tls->frames [frame_idx];
9417 /* This is supported for frames without has_ctx etc. set */
9418 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9419 if (CHECK_PROTOCOL_VERSION (2, 38))
9420 buffer_add_domainid (buf, frame->domain);
9424 if (!frame->has_ctx)
9425 return ERR_ABSENT_INFORMATION;
9427 if (!ensure_jit (frame))
9428 return ERR_ABSENT_INFORMATION;
9432 sig = mono_method_signature (frame->actual_method);
9434 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9436 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9438 return ERR_ABSENT_INFORMATION;
9441 case CMD_STACK_FRAME_GET_VALUES: {
9443 len = decode_int (p, &p, end);
9444 header = mono_method_get_header_checked (frame->actual_method, &error);
9445 mono_error_assert_ok (&error); /* FIXME report error */
9447 for (i = 0; i < len; ++i) {
9448 pos = decode_int (p, &p, end);
9453 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9455 g_assert (pos >= 0 && pos < jit->num_params);
9457 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9459 MonoDebugLocalsInfo *locals;
9461 locals = mono_debug_lookup_locals (frame->method);
9463 g_assert (pos < locals->num_locals);
9464 pos = locals->locals [pos].index;
9465 mono_debug_free_locals (locals);
9467 g_assert (pos >= 0 && pos < jit->num_locals);
9469 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9471 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9474 mono_metadata_free_mh (header);
9477 case CMD_STACK_FRAME_GET_THIS: {
9478 if (frame->api_method->klass->valuetype) {
9479 if (!sig->hasthis) {
9480 MonoObject *p = NULL;
9481 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9483 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9486 if (!sig->hasthis) {
9487 MonoObject *p = NULL;
9488 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9490 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9495 case CMD_STACK_FRAME_SET_VALUES: {
9499 MonoDebugVarInfo *var;
9501 len = decode_int (p, &p, end);
9502 header = mono_method_get_header_checked (frame->actual_method, &error);
9503 mono_error_assert_ok (&error); /* FIXME report error */
9505 for (i = 0; i < len; ++i) {
9506 pos = decode_int (p, &p, end);
9511 g_assert (pos >= 0 && pos < jit->num_params);
9513 t = sig->params [pos];
9514 var = &jit->params [pos];
9516 MonoDebugLocalsInfo *locals;
9518 locals = mono_debug_lookup_locals (frame->method);
9520 g_assert (pos < locals->num_locals);
9521 pos = locals->locals [pos].index;
9522 mono_debug_free_locals (locals);
9524 g_assert (pos >= 0 && pos < jit->num_locals);
9526 t = header->locals [pos];
9527 var = &jit->locals [pos];
9530 if (MONO_TYPE_IS_REFERENCE (t))
9531 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9533 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9534 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9535 if (err != ERR_NONE)
9538 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9540 mono_metadata_free_mh (header);
9543 case CMD_STACK_FRAME_GET_DOMAIN: {
9544 if (CHECK_PROTOCOL_VERSION (2, 38))
9545 buffer_add_domainid (buf, frame->domain);
9548 case CMD_STACK_FRAME_SET_THIS: {
9551 MonoDebugVarInfo *var;
9553 t = &frame->actual_method->klass->byval_arg;
9554 /* Checked by the sender */
9555 g_assert (MONO_TYPE_ISSTRUCT (t));
9556 var = jit->this_var;
9559 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9560 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9561 if (err != ERR_NONE)
9564 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9568 return ERR_NOT_IMPLEMENTED;
9575 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9578 int objid, index, len, i, esize;
9582 objid = decode_objid (p, &p, end);
9583 err = get_object (objid, (MonoObject**)&arr);
9584 if (err != ERR_NONE)
9588 case CMD_ARRAY_REF_GET_LENGTH:
9589 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9591 buffer_add_int (buf, arr->max_length);
9592 buffer_add_int (buf, 0);
9594 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9595 buffer_add_int (buf, arr->bounds [i].length);
9596 buffer_add_int (buf, arr->bounds [i].lower_bound);
9600 case CMD_ARRAY_REF_GET_VALUES:
9601 index = decode_int (p, &p, end);
9602 len = decode_int (p, &p, end);
9604 g_assert (index >= 0 && len >= 0);
9605 // Reordered to avoid integer overflow
9606 g_assert (!(index > arr->max_length - len));
9608 esize = mono_array_element_size (arr->obj.vtable->klass);
9609 for (i = index; i < index + len; ++i) {
9610 elem = (gpointer*)((char*)arr->vector + (i * esize));
9611 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9614 case CMD_ARRAY_REF_SET_VALUES:
9615 index = decode_int (p, &p, end);
9616 len = decode_int (p, &p, end);
9618 g_assert (index >= 0 && len >= 0);
9619 // Reordered to avoid integer overflow
9620 g_assert (!(index > arr->max_length - len));
9622 esize = mono_array_element_size (arr->obj.vtable->klass);
9623 for (i = index; i < index + len; ++i) {
9624 elem = (gpointer*)((char*)arr->vector + (i * esize));
9626 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9630 return ERR_NOT_IMPLEMENTED;
9637 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9643 int i, index, length;
9645 gboolean use_utf16 = FALSE;
9647 objid = decode_objid (p, &p, end);
9648 err = get_object (objid, (MonoObject**)&str);
9649 if (err != ERR_NONE)
9653 case CMD_STRING_REF_GET_VALUE:
9654 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9655 for (i = 0; i < mono_string_length (str); ++i)
9656 if (mono_string_chars (str)[i] == 0)
9658 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9661 buffer_add_int (buf, mono_string_length (str) * 2);
9662 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9665 s = mono_string_to_utf8_checked (str, &error);
9666 mono_error_assert_ok (&error);
9667 buffer_add_string (buf, s);
9671 case CMD_STRING_REF_GET_LENGTH:
9672 buffer_add_long (buf, mono_string_length (str));
9674 case CMD_STRING_REF_GET_CHARS:
9675 index = decode_long (p, &p, end);
9676 length = decode_long (p, &p, end);
9677 if (index > mono_string_length (str) - length)
9678 return ERR_INVALID_ARGUMENT;
9679 c = mono_string_chars (str) + index;
9680 for (i = 0; i < length; ++i)
9681 buffer_add_short (buf, c [i]);
9684 return ERR_NOT_IMPLEMENTED;
9691 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9702 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9703 objid = decode_objid (p, &p, end);
9704 err = get_object (objid, &obj);
9705 if (err != ERR_NONE)
9706 buffer_add_int (buf, 1);
9708 buffer_add_int (buf, 0);
9712 objid = decode_objid (p, &p, end);
9713 err = get_object (objid, &obj);
9714 if (err != ERR_NONE)
9717 MonoClass *obj_type;
9718 gboolean remote_obj = FALSE;
9720 obj_type = obj->vtable->klass;
9721 if (mono_class_is_transparent_proxy (obj_type)) {
9722 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9726 g_assert (obj_type);
9729 case CMD_OBJECT_REF_GET_TYPE:
9730 /* This handles transparent proxies too */
9731 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9733 case CMD_OBJECT_REF_GET_VALUES:
9734 len = decode_int (p, &p, end);
9736 for (i = 0; i < len; ++i) {
9737 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9738 if (err != ERR_NONE)
9741 /* Check that the field belongs to the object */
9743 for (k = obj_type; k; k = k->parent) {
9744 if (k == f->parent) {
9750 return ERR_INVALID_FIELDID;
9752 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9756 if (mono_class_field_is_special_static (f))
9757 return ERR_INVALID_FIELDID;
9759 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9760 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9761 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9762 mono_field_static_get_value_checked (vtable, f, val, &error);
9763 if (!is_ok (&error)) {
9764 mono_error_cleanup (&error); /* FIXME report the error */
9765 return ERR_INVALID_OBJECT;
9767 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9770 guint8 *field_value = NULL;
9773 #ifndef DISABLE_REMOTING
9774 void *field_storage = NULL;
9775 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9776 if (!is_ok (&error)) {
9777 mono_error_cleanup (&error); /* FIXME report the error */
9778 return ERR_INVALID_OBJECT;
9781 g_assert_not_reached ();
9784 field_value = (guint8*)obj + f->offset;
9786 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9790 case CMD_OBJECT_REF_SET_VALUES:
9791 len = decode_int (p, &p, end);
9793 for (i = 0; i < len; ++i) {
9794 f = decode_fieldid (p, &p, end, NULL, &err);
9795 if (err != ERR_NONE)
9798 /* Check that the field belongs to the object */
9800 for (k = obj_type; k; k = k->parent) {
9801 if (k == f->parent) {
9807 return ERR_INVALID_FIELDID;
9809 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9813 if (mono_class_field_is_special_static (f))
9814 return ERR_INVALID_FIELDID;
9816 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9817 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9819 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9820 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9821 if (err != ERR_NONE) {
9825 mono_field_static_set_value (vtable, f, val);
9828 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9829 if (err != ERR_NONE)
9834 case CMD_OBJECT_REF_GET_ADDRESS:
9835 buffer_add_long (buf, (gssize)obj);
9837 case CMD_OBJECT_REF_GET_DOMAIN:
9838 buffer_add_domainid (buf, obj->vtable->domain);
9840 case CMD_OBJECT_REF_GET_INFO:
9841 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9842 buffer_add_domainid (buf, obj->vtable->domain);
9845 return ERR_NOT_IMPLEMENTED;
9852 command_set_to_string (CommandSet command_set)
9854 switch (command_set) {
9857 case CMD_SET_OBJECT_REF:
9858 return "OBJECT_REF";
9859 case CMD_SET_STRING_REF:
9860 return "STRING_REF";
9861 case CMD_SET_THREAD:
9863 case CMD_SET_ARRAY_REF:
9865 case CMD_SET_EVENT_REQUEST:
9866 return "EVENT_REQUEST";
9867 case CMD_SET_STACK_FRAME:
9868 return "STACK_FRAME";
9869 case CMD_SET_APPDOMAIN:
9871 case CMD_SET_ASSEMBLY:
9873 case CMD_SET_METHOD:
9877 case CMD_SET_MODULE:
9888 static const char* vm_cmds_str [] = {
9896 "SET_PROTOCOL_VERSION",
9899 "GET_TYPES_FOR_SOURCE_FILE",
9904 static const char* thread_cmds_str[] = {
9914 static const char* event_cmds_str[] = {
9917 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9920 static const char* appdomain_cmds_str[] = {
9922 "GET_FRIENDLY_NAME",
9924 "GET_ENTRY_ASSEMBLY",
9927 "CREATE_BOXED_VALUE"
9930 static const char* assembly_cmds_str[] = {
9933 "GET_MANIFEST_MODULE",
9940 static const char* module_cmds_str[] = {
9944 static const char* field_cmds_str[] = {
9948 static const char* method_cmds_str[] = {
9950 "GET_DECLARING_TYPE",
9958 "MAKE_GENERIC_METHOD"
9961 static const char* type_cmds_str[] = {
9969 "IS_ASSIGNABLE_FROM",
9973 "GET_PROPERTY_CATTRS",
9974 "GET_SOURCE_FILES_2",
9976 "GET_METHODS_BY_NAME_FLAGS",
9978 "GET_INTERFACE_MAP",
9982 static const char* stack_frame_cmds_str[] = {
9990 static const char* array_cmds_str[] = {
9996 static const char* string_cmds_str[] = {
10002 static const char* object_cmds_str[] = {
10013 cmd_to_string (CommandSet set, int command)
10020 cmds = vm_cmds_str;
10021 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10023 case CMD_SET_OBJECT_REF:
10024 cmds = object_cmds_str;
10025 cmds_len = G_N_ELEMENTS (object_cmds_str);
10027 case CMD_SET_STRING_REF:
10028 cmds = string_cmds_str;
10029 cmds_len = G_N_ELEMENTS (string_cmds_str);
10031 case CMD_SET_THREAD:
10032 cmds = thread_cmds_str;
10033 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10035 case CMD_SET_ARRAY_REF:
10036 cmds = array_cmds_str;
10037 cmds_len = G_N_ELEMENTS (array_cmds_str);
10039 case CMD_SET_EVENT_REQUEST:
10040 cmds = event_cmds_str;
10041 cmds_len = G_N_ELEMENTS (event_cmds_str);
10043 case CMD_SET_STACK_FRAME:
10044 cmds = stack_frame_cmds_str;
10045 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10047 case CMD_SET_APPDOMAIN:
10048 cmds = appdomain_cmds_str;
10049 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10051 case CMD_SET_ASSEMBLY:
10052 cmds = assembly_cmds_str;
10053 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10055 case CMD_SET_METHOD:
10056 cmds = method_cmds_str;
10057 cmds_len = G_N_ELEMENTS (method_cmds_str);
10060 cmds = type_cmds_str;
10061 cmds_len = G_N_ELEMENTS (type_cmds_str);
10063 case CMD_SET_MODULE:
10064 cmds = module_cmds_str;
10065 cmds_len = G_N_ELEMENTS (module_cmds_str);
10067 case CMD_SET_FIELD:
10068 cmds = field_cmds_str;
10069 cmds_len = G_N_ELEMENTS (field_cmds_str);
10071 case CMD_SET_EVENT:
10072 cmds = event_cmds_str;
10073 cmds_len = G_N_ELEMENTS (event_cmds_str);
10078 if (command > 0 && command <= cmds_len)
10079 return cmds [command - 1];
10085 wait_for_attach (void)
10087 #ifndef DISABLE_SOCKET_TRANSPORT
10088 if (listen_fd == -1) {
10089 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10093 /* Block and wait for client connection */
10094 conn_fd = socket_transport_accept (listen_fd);
10096 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10097 if (conn_fd == -1) {
10098 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10102 g_assert_not_reached ();
10106 disconnected = !transport_handshake ();
10107 if (disconnected) {
10108 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10118 * This thread handles communication with the debugger client using a JDWP
10121 static gsize WINAPI
10122 debugger_thread (void *arg)
10125 int res, len, id, flags, command = 0;
10126 CommandSet command_set = (CommandSet)0;
10127 guint8 header [HEADER_LENGTH];
10128 guint8 *data, *p, *end;
10132 gboolean attach_failed = FALSE;
10134 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10136 debugger_thread_id = mono_native_thread_id_get ();
10138 MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
10139 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, &error);
10140 mono_error_assert_ok (&error);
10142 thread->internal_thread->state |= ThreadState_Background;
10143 thread->internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10145 if (agent_config.defer) {
10146 if (!wait_for_attach ()) {
10147 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10148 attach_failed = TRUE; // Don't abort process when we can't listen
10150 mono_set_is_debugger_attached (TRUE);
10151 /* Send start event to client */
10152 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10155 mono_set_is_debugger_attached (TRUE);
10158 while (!attach_failed) {
10159 res = transport_recv (header, HEADER_LENGTH);
10161 /* This will break if the socket is closed during shutdown too */
10162 if (res != HEADER_LENGTH) {
10163 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10168 end = header + HEADER_LENGTH;
10170 len = decode_int (p, &p, end);
10171 id = decode_int (p, &p, end);
10172 flags = decode_byte (p, &p, end);
10173 command_set = (CommandSet)decode_byte (p, &p, end);
10174 command = decode_byte (p, &p, end);
10176 g_assert (flags == 0);
10179 const char *cmd_str;
10180 char cmd_num [256];
10182 cmd_str = cmd_to_string (command_set, command);
10184 sprintf (cmd_num, "%d", command);
10188 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);
10191 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10192 if (len - HEADER_LENGTH > 0)
10194 res = transport_recv (data, len - HEADER_LENGTH);
10195 if (res != len - HEADER_LENGTH) {
10196 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10202 end = data + (len - HEADER_LENGTH);
10204 buffer_init (&buf, 128);
10209 /* Process the request */
10210 switch (command_set) {
10212 err = vm_commands (command, id, p, end, &buf);
10213 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10214 /* Sent after the invoke is complete */
10217 case CMD_SET_EVENT_REQUEST:
10218 err = event_commands (command, p, end, &buf);
10220 case CMD_SET_APPDOMAIN:
10221 err = domain_commands (command, p, end, &buf);
10223 case CMD_SET_ASSEMBLY:
10224 err = assembly_commands (command, p, end, &buf);
10226 case CMD_SET_MODULE:
10227 err = module_commands (command, p, end, &buf);
10229 case CMD_SET_FIELD:
10230 err = field_commands (command, p, end, &buf);
10233 err = type_commands (command, p, end, &buf);
10235 case CMD_SET_METHOD:
10236 err = method_commands (command, p, end, &buf);
10238 case CMD_SET_THREAD:
10239 err = thread_commands (command, p, end, &buf);
10241 case CMD_SET_STACK_FRAME:
10242 err = frame_commands (command, p, end, &buf);
10244 case CMD_SET_ARRAY_REF:
10245 err = array_commands (command, p, end, &buf);
10247 case CMD_SET_STRING_REF:
10248 err = string_commands (command, p, end, &buf);
10250 case CMD_SET_OBJECT_REF:
10251 err = object_commands (command, p, end, &buf);
10254 err = ERR_NOT_IMPLEMENTED;
10257 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10258 buffer_replies = TRUE;
10262 if (buffer_replies) {
10263 buffer_reply_packet (id, err, &buf);
10265 send_reply_packet (id, err, &buf);
10266 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10270 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10271 send_buffered_reply_packets ();
10272 buffer_replies = FALSE;
10276 buffer_free (&buf);
10278 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10282 mono_set_is_debugger_attached (FALSE);
10284 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10285 debugger_thread_exited = TRUE;
10286 mono_coop_cond_signal (&debugger_thread_exited_cond);
10287 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10289 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10291 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10292 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10293 start_debugger_thread ();
10299 #else /* DISABLE_DEBUGGER_AGENT */
10302 mono_debugger_agent_parse_options (char *options)
10304 g_error ("This runtime is configured with the debugger agent disabled.");
10308 mono_debugger_agent_init (void)
10313 mono_debugger_agent_breakpoint_hit (void *sigctx)
10318 mono_debugger_agent_single_step_event (void *sigctx)
10323 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10328 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10329 MonoContext *catch_ctx)
10334 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10339 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10344 mono_debugger_agent_user_break (void)
10350 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10355 mono_debugger_agent_debug_log_is_enabled (void)
10361 mono_debugger_agent_unhandled_exception (MonoException *exc)
10363 g_assert_not_reached ();
10367 debugger_agent_single_step_from_context (MonoContext *ctx)
10369 g_assert_not_reached ();
10373 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10375 g_assert_not_reached ();