2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #ifdef HAVE_SYS_TYPES_H
17 #include <sys/types.h>
19 #ifdef HAVE_SYS_SELECT_H
20 #include <sys/select.h>
22 #ifdef HAVE_SYS_SOCKET_H
23 #include <sys/socket.h>
25 #ifdef HAVE_NETINET_TCP_H
26 #include <netinet/tcp.h>
28 #ifdef HAVE_NETINET_IN_H
29 #include <netinet/in.h>
49 #ifdef PLATFORM_ANDROID
51 #include <linux/tcp.h>
52 #include <sys/endian.h>
55 #include <mono/metadata/mono-debug.h>
56 #include <mono/metadata/mono-debug-debugger.h>
57 #include <mono/metadata/debug-mono-symfile.h>
58 #include <mono/metadata/gc-internals.h>
59 #include <mono/metadata/environment.h>
60 #include <mono/metadata/threads-types.h>
61 #include <mono/metadata/threadpool.h>
62 #include <mono/metadata/assembly.h>
63 #include <mono/metadata/runtime.h>
64 #include <mono/metadata/verify-internals.h>
65 #include <mono/metadata/reflection-internals.h>
66 #include <mono/metadata/w32socket.h>
67 #include <mono/utils/mono-coop-mutex.h>
68 #include <mono/utils/mono-coop-semaphore.h>
69 #include <mono/utils/mono-error-internals.h>
70 #include <mono/utils/mono-stack-unwinding.h>
71 #include <mono/utils/mono-time.h>
72 #include <mono/utils/mono-threads.h>
73 #include <mono/utils/networking.h>
74 #include <mono/utils/mono-proclib.h>
75 #include "debugger-agent.h"
77 #include "seq-points.h"
78 #include <mono/utils/w32api.h>
81 * On iOS we can't use System.Environment.Exit () as it will do the wrong
84 #if !defined (TARGET_IOS)
85 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
89 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
90 #define DISABLE_DEBUGGER_AGENT 1
93 #ifdef DISABLE_SOFT_DEBUG
94 #define DISABLE_DEBUGGER_AGENT 1
97 #ifndef DISABLE_DEBUGGER_AGENT
99 #include <mono/utils/mono-os-mutex.h>
101 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
124 guint32 il_offset, native_offset;
128 * If method is gshared, this is the actual instance, otherwise this is equal to
131 MonoMethod *actual_method;
133 * This is the method which is visible to debugger clients. Same as method,
134 * except for native-to-managed wrappers.
136 MonoMethod *api_method;
138 MonoDebugMethodJitInfo *jit;
141 mgreg_t *reg_locations [MONO_MAX_IREGS];
143 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
144 * the frame can become invalid.
149 typedef struct _InvokeData InvokeData;
157 /* This is the context which needs to be restored after the invoke */
161 * If this is set, invoke this method with the arguments given by ARGS.
165 guint32 suspend_count;
168 InvokeData *last_invoke;
172 MonoThreadUnwindState context;
174 /* This is computed on demand when it is requested using the wire protocol */
175 /* It is freed up when the thread is resumed */
179 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
182 gboolean frames_up_to_date;
184 * Points to data about a pending invoke which needs to be executed after the thread
187 InvokeData *pending_invoke;
189 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
194 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
195 * within a finite amount of time.
199 * Set to TRUE if this thread is suspended in suspend_current ().
201 gboolean really_suspended;
202 /* Used to pass the context to the breakpoint/single step handler */
203 MonoContext handler_ctx;
204 /* Whenever thread_stop () was called for this thread */
207 /* Whenever to disable breakpoints (used during invokes) */
208 gboolean disable_breakpoints;
211 * Number of times this thread has been resumed using resume_thread ().
213 guint32 resume_count;
215 MonoInternalThread *thread;
218 * Information about the frame which transitioned to native code for running
221 StackFrameInfo async_last_frame;
224 * The context where the stack walk can be started for running threads.
226 MonoThreadUnwindState async_state;
229 * The context used for filter clauses
231 MonoThreadUnwindState filter_state;
233 gboolean abort_requested;
236 * The current mono_runtime_invoke_checked invocation.
241 * The context where single stepping should resume while the thread is suspended because
242 * of an EXCEPTION event.
244 MonoThreadUnwindState catch_state;
247 * The context which needs to be restored after handling a single step/breakpoint
248 * event. This is the same as the ctx at step/breakpoint site, but includes changes
249 * to caller saved registers done by set_var ().
251 MonoThreadUnwindState restore_state;
252 /* Frames computed from restore_state */
253 int restore_frame_count;
254 StackFrame **restore_frames;
256 /* The currently unloading appdomain */
257 MonoDomain *domain_unloading;
262 void (*connect) (const char *address);
263 void (*close1) (void);
264 void (*close2) (void);
265 gboolean (*send) (void *buf, int len);
266 int (*recv) (void *buf, int len);
270 * Wire Protocol definitions
273 #define HEADER_LENGTH 11
275 #define MAJOR_VERSION 2
276 #define MINOR_VERSION 45
280 CMD_SET_OBJECT_REF = 9,
281 CMD_SET_STRING_REF = 10,
283 CMD_SET_ARRAY_REF = 13,
284 CMD_SET_EVENT_REQUEST = 15,
285 CMD_SET_STACK_FRAME = 16,
286 CMD_SET_APPDOMAIN = 20,
287 CMD_SET_ASSEMBLY = 21,
296 EVENT_KIND_VM_START = 0,
297 EVENT_KIND_VM_DEATH = 1,
298 EVENT_KIND_THREAD_START = 2,
299 EVENT_KIND_THREAD_DEATH = 3,
300 EVENT_KIND_APPDOMAIN_CREATE = 4,
301 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
302 EVENT_KIND_METHOD_ENTRY = 6,
303 EVENT_KIND_METHOD_EXIT = 7,
304 EVENT_KIND_ASSEMBLY_LOAD = 8,
305 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
306 EVENT_KIND_BREAKPOINT = 10,
307 EVENT_KIND_STEP = 11,
308 EVENT_KIND_TYPE_LOAD = 12,
309 EVENT_KIND_EXCEPTION = 13,
310 EVENT_KIND_KEEPALIVE = 14,
311 EVENT_KIND_USER_BREAK = 15,
312 EVENT_KIND_USER_LOG = 16
316 SUSPEND_POLICY_NONE = 0,
317 SUSPEND_POLICY_EVENT_THREAD = 1,
318 SUSPEND_POLICY_ALL = 2
323 ERR_INVALID_OBJECT = 20,
324 ERR_INVALID_FIELDID = 25,
325 ERR_INVALID_FRAMEID = 30,
326 ERR_NOT_IMPLEMENTED = 100,
327 ERR_NOT_SUSPENDED = 101,
328 ERR_INVALID_ARGUMENT = 102,
330 ERR_NO_INVOCATION = 104,
331 ERR_ABSENT_INFORMATION = 105,
332 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
333 ERR_INVOKE_ABORTED = 107,
334 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
339 MOD_KIND_THREAD_ONLY = 3,
340 MOD_KIND_LOCATION_ONLY = 7,
341 MOD_KIND_EXCEPTION_ONLY = 8,
343 MOD_KIND_ASSEMBLY_ONLY = 11,
344 MOD_KIND_SOURCE_FILE_ONLY = 12,
345 MOD_KIND_TYPE_NAME_ONLY = 13,
361 STEP_FILTER_NONE = 0,
362 STEP_FILTER_STATIC_CTOR = 1,
363 STEP_FILTER_DEBUGGER_HIDDEN = 2,
364 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
365 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
369 TOKEN_TYPE_STRING = 0,
371 TOKEN_TYPE_FIELD = 2,
372 TOKEN_TYPE_METHOD = 3,
373 TOKEN_TYPE_UNKNOWN = 4
377 VALUE_TYPE_ID_NULL = 0xf0,
378 VALUE_TYPE_ID_TYPE = 0xf1,
379 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
383 FRAME_FLAG_DEBUGGER_INVOKE = 1,
384 FRAME_FLAG_NATIVE_TRANSITION = 2
388 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
389 INVOKE_FLAG_SINGLE_THREADED = 2,
390 INVOKE_FLAG_RETURN_OUT_THIS = 4,
391 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
392 INVOKE_FLAG_VIRTUAL = 16
396 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
397 } BindingFlagsExtensions;
401 CMD_VM_ALL_THREADS = 2,
406 CMD_VM_INVOKE_METHOD = 7,
407 CMD_VM_SET_PROTOCOL_VERSION = 8,
408 CMD_VM_ABORT_INVOKE = 9,
409 CMD_VM_SET_KEEPALIVE = 10,
410 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
411 CMD_VM_GET_TYPES = 12,
412 CMD_VM_INVOKE_METHODS = 13,
413 CMD_VM_START_BUFFERING = 14,
414 CMD_VM_STOP_BUFFERING = 15
418 CMD_THREAD_GET_FRAME_INFO = 1,
419 CMD_THREAD_GET_NAME = 2,
420 CMD_THREAD_GET_STATE = 3,
421 CMD_THREAD_GET_INFO = 4,
422 CMD_THREAD_GET_ID = 5,
423 CMD_THREAD_GET_TID = 6,
424 CMD_THREAD_SET_IP = 7
428 CMD_EVENT_REQUEST_SET = 1,
429 CMD_EVENT_REQUEST_CLEAR = 2,
430 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
438 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
439 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
440 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
441 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
442 CMD_APPDOMAIN_CREATE_STRING = 5,
443 CMD_APPDOMAIN_GET_CORLIB = 6,
444 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
448 CMD_ASSEMBLY_GET_LOCATION = 1,
449 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
450 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
451 CMD_ASSEMBLY_GET_OBJECT = 4,
452 CMD_ASSEMBLY_GET_TYPE = 5,
453 CMD_ASSEMBLY_GET_NAME = 6,
454 CMD_ASSEMBLY_GET_DOMAIN = 7
458 CMD_MODULE_GET_INFO = 1,
462 CMD_FIELD_GET_INFO = 1,
466 CMD_METHOD_GET_NAME = 1,
467 CMD_METHOD_GET_DECLARING_TYPE = 2,
468 CMD_METHOD_GET_DEBUG_INFO = 3,
469 CMD_METHOD_GET_PARAM_INFO = 4,
470 CMD_METHOD_GET_LOCALS_INFO = 5,
471 CMD_METHOD_GET_INFO = 6,
472 CMD_METHOD_GET_BODY = 7,
473 CMD_METHOD_RESOLVE_TOKEN = 8,
474 CMD_METHOD_GET_CATTRS = 9,
475 CMD_METHOD_MAKE_GENERIC_METHOD = 10
479 CMD_TYPE_GET_INFO = 1,
480 CMD_TYPE_GET_METHODS = 2,
481 CMD_TYPE_GET_FIELDS = 3,
482 CMD_TYPE_GET_VALUES = 4,
483 CMD_TYPE_GET_OBJECT = 5,
484 CMD_TYPE_GET_SOURCE_FILES = 6,
485 CMD_TYPE_SET_VALUES = 7,
486 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
487 CMD_TYPE_GET_PROPERTIES = 9,
488 CMD_TYPE_GET_CATTRS = 10,
489 CMD_TYPE_GET_FIELD_CATTRS = 11,
490 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
491 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
492 CMD_TYPE_GET_VALUES_2 = 14,
493 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
494 CMD_TYPE_GET_INTERFACES = 16,
495 CMD_TYPE_GET_INTERFACE_MAP = 17,
496 CMD_TYPE_IS_INITIALIZED = 18,
497 CMD_TYPE_CREATE_INSTANCE = 19
501 CMD_STACK_FRAME_GET_VALUES = 1,
502 CMD_STACK_FRAME_GET_THIS = 2,
503 CMD_STACK_FRAME_SET_VALUES = 3,
504 CMD_STACK_FRAME_GET_DOMAIN = 4,
505 CMD_STACK_FRAME_SET_THIS = 5,
509 CMD_ARRAY_REF_GET_LENGTH = 1,
510 CMD_ARRAY_REF_GET_VALUES = 2,
511 CMD_ARRAY_REF_SET_VALUES = 3,
515 CMD_STRING_REF_GET_VALUE = 1,
516 CMD_STRING_REF_GET_LENGTH = 2,
517 CMD_STRING_REF_GET_CHARS = 3
521 CMD_OBJECT_REF_GET_TYPE = 1,
522 CMD_OBJECT_REF_GET_VALUES = 2,
523 CMD_OBJECT_REF_IS_COLLECTED = 3,
524 CMD_OBJECT_REF_GET_ADDRESS = 4,
525 CMD_OBJECT_REF_GET_DOMAIN = 5,
526 CMD_OBJECT_REF_SET_VALUES = 6,
527 CMD_OBJECT_REF_GET_INFO = 7,
533 int count; /* For kind == MOD_KIND_COUNT */
534 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
535 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
536 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
537 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
538 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
539 StepFilter filter; /* For kind == MOD_KIND_STEP */
541 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
550 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
554 * Describes a single step request.
558 MonoInternalThread *thread;
564 MonoMethod *start_method;
565 MonoMethod *last_method;
567 /* Whenever single stepping is performed using start/stop_single_stepping () */
569 /* The list of breakpoints used to implement step-over */
571 /* The number of frames at the start of a step-over */
573 /* If set, don't stop in methods that are not part of user assemblies */
574 MonoAssembly** user_assemblies;
575 /* Used to distinguish stepping breakpoint hits in parallel tasks executions */
577 /* Used to know if we are in process of async step-out and distishing from exception breakpoints */
578 MonoMethod* async_stepout_method;
582 * Contains additional information for an event
585 /* For EVENT_KIND_EXCEPTION */
587 MonoContext catch_ctx;
589 /* For EVENT_KIND_USER_LOG */
591 char *category, *message;
592 /* For EVENT_KIND_TYPE_LOAD */
596 /* Dummy structure used for the profiler callbacks */
602 guint8 *buf, *p, *end;
605 typedef struct ReplyPacket {
611 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
613 #ifdef PLATFORM_ANDROID
614 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
616 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
620 #define get_last_sock_error() WSAGetLastError()
621 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
622 #define MONO_EINTR WSAEINTR
624 #define get_last_sock_error() errno
625 #define MONO_EWOULDBLOCK EWOULDBLOCK
626 #define MONO_EINTR EINTR
629 #define CHECK_PROTOCOL_VERSION(major,minor) \
630 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
636 static AgentConfig agent_config;
639 * Whenever the agent is fully initialized.
640 * When using the onuncaught or onthrow options, only some parts of the agent are
641 * initialized on startup, and the full initialization which includes connection
642 * establishment and the startup of the agent thread is only done in response to
645 static gint32 inited;
647 #ifndef DISABLE_SOCKET_TRANSPORT
649 static int listen_fd;
652 static int packet_id = 0;
654 static int objref_id = 0;
656 static int event_request_id = 0;
658 static int frame_id = 0;
660 static GPtrArray *event_requests;
662 static MonoNativeTlsKey debugger_tls_id;
664 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
666 /* Maps MonoInternalThread -> DebuggerTlsData */
667 /* Protected by the loader lock */
668 static MonoGHashTable *thread_to_tls;
670 /* Maps tid -> MonoInternalThread */
671 /* Protected by the loader lock */
672 static MonoGHashTable *tid_to_thread;
674 /* Maps tid -> MonoThread (not MonoInternalThread) */
675 /* Protected by the loader lock */
676 static MonoGHashTable *tid_to_thread_obj;
678 static MonoNativeThreadId debugger_thread_id;
680 static MonoThreadHandle *debugger_thread_handle;
682 static int log_level;
684 static gboolean embedding;
686 static FILE *log_file;
688 /* Assemblies whose assembly load event has no been sent yet */
689 /* Protected by the dbg lock */
690 static GPtrArray *pending_assembly_loads;
692 /* Whenever the debugger thread has exited */
693 static gboolean debugger_thread_exited;
695 /* Cond variable used to wait for debugger_thread_exited becoming true */
696 static MonoCoopCond debugger_thread_exited_cond;
698 /* Mutex for the cond var above */
699 static MonoCoopMutex debugger_thread_exited_mutex;
701 static DebuggerProfiler debugger_profiler;
703 /* The single step request instance */
704 static SingleStepReq *ss_req;
706 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
707 /* Number of single stepping operations in progress */
711 /* The protocol version of the client */
712 static int major_version, minor_version;
714 /* Whenever the variables above are set by the client */
715 static gboolean protocol_version_set;
717 /* A hash table containing all active domains */
718 /* Protected by the loader lock */
719 static GHashTable *domains;
721 /* The number of times the runtime is suspended */
722 static gint32 suspend_count;
724 /* Whenever to buffer reply messages and send them together */
725 static gboolean buffer_replies;
727 /* Buffered reply packets */
728 static ReplyPacket reply_packets [128];
731 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
732 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
733 static MonoCoopMutex debug_mutex;
735 static void transport_init (void);
736 static void transport_connect (const char *address);
737 static gboolean transport_handshake (void);
738 static void register_transport (DebuggerTransport *trans);
740 static gsize WINAPI debugger_thread (void *arg);
742 static void runtime_initialized (MonoProfiler *prof);
744 static void runtime_shutdown (MonoProfiler *prof);
746 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
748 static void thread_end (MonoProfiler *prof, uintptr_t tid);
750 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
752 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
754 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
756 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
758 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
760 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
762 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
764 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
766 static void emit_assembly_load (gpointer assembly, gpointer user_data);
768 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
770 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
772 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
774 static void start_single_stepping (void);
776 static void stop_single_stepping (void);
778 static void suspend_current (void);
780 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
782 static void clear_types_for_assembly (MonoAssembly *assembly);
784 static void clear_breakpoints_for_domain (MonoDomain *domain);
786 static void process_profiler_event (EventKind event, gpointer arg);
788 /* Submodule init/cleanup */
789 static void breakpoints_init (void);
790 static void breakpoints_cleanup (void);
792 static void objrefs_init (void);
793 static void objrefs_cleanup (void);
795 static void ids_init (void);
796 static void ids_cleanup (void);
798 static void suspend_init (void);
800 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
801 StackFrame **frames, int nframes);
802 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
803 static void ss_destroy (SingleStepReq *req);
805 static void start_debugger_thread (void);
806 static void stop_debugger_thread (void);
808 static void finish_agent_init (gboolean on_startup);
810 static void process_profiler_event (EventKind event, gpointer arg);
812 static void invalidate_frames (DebuggerTlsData *tls);
814 #ifndef DISABLE_SOCKET_TRANSPORT
816 register_socket_transport (void);
819 static inline gboolean
820 is_debugger_thread (void)
822 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
826 parse_address (char *address, char **host, int *port)
828 char *pos = strchr (address, ':');
830 if (pos == NULL || pos == address)
833 size_t len = pos - address;
834 *host = (char *)g_malloc (len + 1);
835 memcpy (*host, address, len);
836 (*host) [len] = '\0';
838 *port = atoi (pos + 1);
846 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
847 fprintf (stderr, "Available options:\n");
848 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
849 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
850 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
851 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
852 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
853 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
854 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
855 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
856 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
857 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
861 parse_flag (const char *option, char *flag)
863 if (!strcmp (flag, "y"))
865 else if (!strcmp (flag, "n"))
868 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
875 mono_debugger_agent_parse_options (char *options)
882 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
883 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
887 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
889 options = g_strdup_printf ("%s,%s", options, extra);
891 agent_config.enabled = TRUE;
892 agent_config.suspend = TRUE;
893 agent_config.server = FALSE;
894 agent_config.defer = FALSE;
895 agent_config.address = NULL;
897 //agent_config.log_level = 10;
899 args = g_strsplit (options, ",", -1);
900 for (ptr = args; ptr && *ptr; ptr ++) {
903 if (strncmp (arg, "transport=", 10) == 0) {
904 agent_config.transport = g_strdup (arg + 10);
905 } else if (strncmp (arg, "address=", 8) == 0) {
906 agent_config.address = g_strdup (arg + 8);
907 } else if (strncmp (arg, "loglevel=", 9) == 0) {
908 agent_config.log_level = atoi (arg + 9);
909 } else if (strncmp (arg, "logfile=", 8) == 0) {
910 agent_config.log_file = g_strdup (arg + 8);
911 } else if (strncmp (arg, "suspend=", 8) == 0) {
912 agent_config.suspend = parse_flag ("suspend", arg + 8);
913 } else if (strncmp (arg, "server=", 7) == 0) {
914 agent_config.server = parse_flag ("server", arg + 7);
915 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
916 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
917 } else if (strncmp (arg, "onthrow=", 8) == 0) {
918 /* We support multiple onthrow= options */
919 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
920 } else if (strncmp (arg, "onthrow", 7) == 0) {
921 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
922 } else if (strncmp (arg, "help", 4) == 0) {
925 } else if (strncmp (arg, "timeout=", 8) == 0) {
926 agent_config.timeout = atoi (arg + 8);
927 } else if (strncmp (arg, "launch=", 7) == 0) {
928 agent_config.launch = g_strdup (arg + 7);
929 } else if (strncmp (arg, "embedding=", 10) == 0) {
930 agent_config.embedding = atoi (arg + 10) == 1;
931 } else if (strncmp (arg, "keepalive=", 10) == 0) {
932 agent_config.keepalive = atoi (arg + 10);
933 } else if (strncmp (arg, "setpgid=", 8) == 0) {
934 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
941 if (agent_config.server && !agent_config.suspend) {
942 /* Waiting for deferred attachment */
943 agent_config.defer = TRUE;
944 if (agent_config.address == NULL) {
945 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
949 //agent_config.log_level = 0;
951 if (agent_config.transport == NULL) {
952 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
956 if (agent_config.address == NULL && !agent_config.server) {
957 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
962 if (!strcmp (agent_config.transport, "dt_socket")) {
963 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
964 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
971 mono_debugger_agent_init (void)
973 mono_coop_mutex_init_recursive (&debug_mutex);
975 if (!agent_config.enabled)
980 /* Need to know whenever a thread has acquired the loader mutex */
981 mono_loader_lock_track_ownership (TRUE);
983 event_requests = g_ptr_array_new ();
985 mono_coop_mutex_init (&debugger_thread_exited_mutex);
986 mono_coop_cond_init (&debugger_thread_exited_cond);
988 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
989 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
990 mono_profiler_install_runtime_initialized (runtime_initialized);
991 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
992 mono_profiler_install_thread (thread_startup, thread_end);
993 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
994 mono_profiler_install_jit_end (jit_end);
996 mono_native_tls_alloc (&debugger_tls_id, NULL);
998 /* Needed by the hash_table_new_type () call below */
999 mono_gc_base_init ();
1001 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
1003 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1005 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 pending_assembly_loads = g_ptr_array_new ();
1008 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1010 log_level = agent_config.log_level;
1012 embedding = agent_config.embedding;
1013 disconnected = TRUE;
1015 if (agent_config.log_file) {
1016 log_file = fopen (agent_config.log_file, "w+");
1018 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1027 breakpoints_init ();
1030 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1032 * This is needed because currently we don't handle liveness info.
1034 mini_get_debug_options ()->mdb_optimizations = TRUE;
1036 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1037 /* This is needed because we can't set local variables in registers yet */
1038 mono_disable_optimizations (MONO_OPT_LINEARS);
1042 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1043 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1044 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1047 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1050 if (agent_config.setpgid)
1054 if (!agent_config.onuncaught && !agent_config.onthrow)
1055 finish_agent_init (TRUE);
1059 * finish_agent_init:
1061 * Finish the initialization of the agent. This involves connecting the transport
1062 * and starting the agent thread. This is either done at startup, or
1063 * in response to some event like an unhandled exception.
1066 finish_agent_init (gboolean on_startup)
1070 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1073 if (agent_config.launch) {
1076 // FIXME: Generated address
1077 // FIXME: Races with transport_connect ()
1079 argv [0] = agent_config.launch;
1080 argv [1] = agent_config.transport;
1081 argv [2] = agent_config.address;
1084 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1086 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1091 transport_connect (agent_config.address);
1094 /* Do some which is usually done after sending the VMStart () event */
1095 vm_start_event_sent = TRUE;
1096 start_debugger_thread ();
1101 mono_debugger_agent_cleanup (void)
1106 stop_debugger_thread ();
1108 breakpoints_cleanup ();
1117 #ifndef DISABLE_SOCKET_TRANSPORT
1122 * recv() + handle incomplete reads and EINTR
1125 socket_transport_recv (void *buf, int len)
1131 static gint64 last_keepalive;
1138 res = recv (fd, (char *) buf + total, len - total, flags);
1141 if (agent_config.keepalive) {
1142 gboolean need_keepalive = FALSE;
1143 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1144 need_keepalive = TRUE;
1145 } else if (res == -1) {
1146 /* This could happen if recv () is interrupted repeatedly */
1147 msecs = mono_msec_ticks ();
1148 if (msecs - last_keepalive >= agent_config.keepalive) {
1149 need_keepalive = TRUE;
1150 last_keepalive = msecs;
1153 if (need_keepalive) {
1154 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1158 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1166 set_keepalive (void)
1171 if (!agent_config.keepalive || !conn_fd)
1174 tv.tv_sec = agent_config.keepalive / 1000;
1175 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1177 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1178 g_assert (result >= 0);
1182 socket_transport_accept (int socket_fd)
1185 conn_fd = accept (socket_fd, NULL, NULL);
1188 if (conn_fd == -1) {
1189 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1191 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1198 socket_transport_send (void *data, int len)
1205 res = send (conn_fd, data, len, 0);
1206 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1217 * socket_transport_connect:
1219 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1222 socket_transport_connect (const char *address)
1224 MonoAddressInfo *result;
1225 MonoAddressEntry *rp;
1226 int sfd = -1, s, res;
1230 if (agent_config.address) {
1231 res = parse_address (agent_config.address, &host, &port);
1232 g_assert (res == 0);
1243 mono_network_init ();
1245 /* Obtain address(es) matching host/port */
1246 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1248 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1253 if (agent_config.server) {
1254 /* Wait for a connection */
1256 struct sockaddr_in addr;
1259 /* No address, generate one */
1260 sfd = socket (AF_INET, SOCK_STREAM, 0);
1263 /* This will bind the socket to a random port */
1264 res = listen (sfd, 16);
1266 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1271 addrlen = sizeof (addr);
1272 memset (&addr, 0, sizeof (addr));
1273 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1274 g_assert (res == 0);
1276 host = (char*)"127.0.0.1";
1277 port = ntohs (addr.sin_port);
1279 /* Emit the address to stdout */
1280 /* FIXME: Should print another interface, not localhost */
1281 printf ("%s:%d\n", host, port);
1283 /* Listen on the provided address */
1284 for (rp = result->entries; rp != NULL; rp = rp->next) {
1285 MonoSocketAddress sockaddr;
1289 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1291 sfd = socket (rp->family, rp->socktype,
1296 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1299 res = bind (sfd, &sockaddr.addr, sock_len);
1303 res = listen (sfd, 16);
1310 mono_free_address_info (result);
1313 if (agent_config.defer)
1316 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1318 if (agent_config.timeout) {
1323 tv.tv_usec = agent_config.timeout * 1000;
1325 FD_SET (sfd, &readfds);
1328 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1332 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1337 conn_fd = socket_transport_accept (sfd);
1341 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1343 /* Connect to the specified address */
1344 /* FIXME: Respect the timeout */
1345 for (rp = result->entries; rp != NULL; rp = rp->next) {
1346 MonoSocketAddress sockaddr;
1349 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1351 sfd = socket (rp->family, rp->socktype,
1357 res = connect (sfd, &sockaddr.addr, sock_len);
1361 break; /* Success */
1369 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1375 mono_free_address_info (result);
1378 if (!transport_handshake ())
1383 socket_transport_close1 (void)
1385 /* This will interrupt the agent thread */
1386 /* Close the read part only so it can still send back replies */
1387 /* Also shut down the connection listener so that we can exit normally */
1389 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1390 shutdown (conn_fd, SD_BOTH);
1391 shutdown (listen_fd, SD_BOTH);
1392 closesocket (listen_fd);
1394 shutdown (conn_fd, SHUT_RD);
1395 shutdown (listen_fd, SHUT_RDWR);
1403 socket_transport_close2 (void)
1406 shutdown (conn_fd, SD_BOTH);
1408 shutdown (conn_fd, SHUT_RDWR);
1413 register_socket_transport (void)
1415 DebuggerTransport trans;
1417 trans.name = "dt_socket";
1418 trans.connect = socket_transport_connect;
1419 trans.close1 = socket_transport_close1;
1420 trans.close2 = socket_transport_close2;
1421 trans.send = socket_transport_send;
1422 trans.recv = socket_transport_recv;
1424 register_transport (&trans);
1428 * socket_fd_transport_connect:
1432 socket_fd_transport_connect (const char *address)
1436 res = sscanf (address, "%d", &conn_fd);
1438 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1442 if (!transport_handshake ())
1447 register_socket_fd_transport (void)
1449 DebuggerTransport trans;
1451 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1452 trans.name = "socket-fd";
1453 trans.connect = socket_fd_transport_connect;
1454 trans.close1 = socket_transport_close1;
1455 trans.close2 = socket_transport_close2;
1456 trans.send = socket_transport_send;
1457 trans.recv = socket_transport_recv;
1459 register_transport (&trans);
1462 #endif /* DISABLE_SOCKET_TRANSPORT */
1468 #define MAX_TRANSPORTS 16
1470 static DebuggerTransport *transport;
1472 static DebuggerTransport transports [MAX_TRANSPORTS];
1473 static int ntransports;
1476 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1479 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1481 register_transport (trans);
1485 register_transport (DebuggerTransport *trans)
1487 g_assert (ntransports < MAX_TRANSPORTS);
1489 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1494 transport_init (void)
1498 #ifndef DISABLE_SOCKET_TRANSPORT
1499 register_socket_transport ();
1500 register_socket_fd_transport ();
1503 for (i = 0; i < ntransports; ++i) {
1504 if (!strcmp (agent_config.transport, transports [i].name))
1507 if (i == ntransports) {
1508 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1509 for (i = 0; i < ntransports; ++i)
1510 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1511 fprintf (stderr, "\n");
1514 transport = &transports [i];
1518 transport_connect (const char *address)
1520 transport->connect (address);
1524 transport_close1 (void)
1526 transport->close1 ();
1530 transport_close2 (void)
1532 transport->close2 ();
1536 transport_send (void *buf, int len)
1538 return transport->send (buf, len);
1542 transport_recv (void *buf, int len)
1544 return transport->recv (buf, len);
1548 mono_debugger_agent_transport_handshake (void)
1550 return transport_handshake ();
1554 transport_handshake (void)
1556 char handshake_msg [128];
1560 disconnected = TRUE;
1562 /* Write handshake message */
1563 sprintf (handshake_msg, "DWP-Handshake");
1566 res = transport_send (handshake_msg, strlen (handshake_msg));
1567 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1569 g_assert (res != -1);
1572 res = transport_recv (buf, strlen (handshake_msg));
1573 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1574 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1579 * To support older clients, the client sends its protocol version after connecting
1580 * using a command. Until that is received, default to our protocol version.
1582 major_version = MAJOR_VERSION;
1583 minor_version = MINOR_VERSION;
1584 protocol_version_set = FALSE;
1586 #ifndef DISABLE_SOCKET_TRANSPORT
1587 // FIXME: Move this somewhere else
1589 * Set TCP_NODELAY on the socket so the client receives events/command
1590 * results immediately.
1594 int result = setsockopt (conn_fd,
1599 g_assert (result >= 0);
1605 disconnected = FALSE;
1610 stop_debugger_thread (void)
1615 transport_close1 ();
1618 * Wait for the thread to exit.
1620 * If we continue with the shutdown without waiting for it, then the client might
1621 * not receive an answer to its last command like a resume.
1623 if (!is_debugger_thread ()) {
1625 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1626 if (!debugger_thread_exited)
1627 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1628 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1629 } while (!debugger_thread_exited);
1632 transport_close2 ();
1636 start_debugger_thread (void)
1638 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, NULL, NULL);
1639 g_assert (debugger_thread_handle);
1643 * Functions to decode protocol data
1647 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1650 g_assert (*endbuf <= limit);
1655 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1658 g_assert (*endbuf <= limit);
1660 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1663 static inline gint64
1664 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1666 guint32 high = decode_int (buf, &buf, limit);
1667 guint32 low = decode_int (buf, &buf, limit);
1671 return ((((guint64)high) << 32) | ((guint64)low));
1675 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1677 return decode_int (buf, endbuf, limit);
1681 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1683 int len = decode_int (buf, &buf, limit);
1691 s = (char *)g_malloc (len + 1);
1694 memcpy (s, buf, len);
1703 * Functions to encode protocol data
1707 buffer_init (Buffer *buf, int size)
1709 buf->buf = (guint8 *)g_malloc (size);
1711 buf->end = buf->buf + size;
1715 buffer_len (Buffer *buf)
1717 return buf->p - buf->buf;
1721 buffer_make_room (Buffer *buf, int size)
1723 if (buf->end - buf->p < size) {
1724 int new_size = buf->end - buf->buf + size + 32;
1725 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1726 size = buf->p - buf->buf;
1729 buf->end = buf->buf + new_size;
1734 buffer_add_byte (Buffer *buf, guint8 val)
1736 buffer_make_room (buf, 1);
1742 buffer_add_short (Buffer *buf, guint32 val)
1744 buffer_make_room (buf, 2);
1745 buf->p [0] = (val >> 8) & 0xff;
1746 buf->p [1] = (val >> 0) & 0xff;
1751 buffer_add_int (Buffer *buf, guint32 val)
1753 buffer_make_room (buf, 4);
1754 buf->p [0] = (val >> 24) & 0xff;
1755 buf->p [1] = (val >> 16) & 0xff;
1756 buf->p [2] = (val >> 8) & 0xff;
1757 buf->p [3] = (val >> 0) & 0xff;
1762 buffer_add_long (Buffer *buf, guint64 l)
1764 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1765 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1769 buffer_add_id (Buffer *buf, int id)
1771 buffer_add_int (buf, (guint64)id);
1775 buffer_add_data (Buffer *buf, guint8 *data, int len)
1777 buffer_make_room (buf, len);
1778 memcpy (buf->p, data, len);
1783 buffer_add_string (Buffer *buf, const char *str)
1788 buffer_add_int (buf, 0);
1791 buffer_add_int (buf, len);
1792 buffer_add_data (buf, (guint8*)str, len);
1797 buffer_add_buffer (Buffer *buf, Buffer *data)
1799 buffer_add_data (buf, data->buf, buffer_len (data));
1803 buffer_free (Buffer *buf)
1809 send_packet (int command_set, int command, Buffer *data)
1815 id = InterlockedIncrement (&packet_id);
1817 len = data->p - data->buf + 11;
1818 buffer_init (&buf, len);
1819 buffer_add_int (&buf, len);
1820 buffer_add_int (&buf, id);
1821 buffer_add_byte (&buf, 0); /* flags */
1822 buffer_add_byte (&buf, command_set);
1823 buffer_add_byte (&buf, command);
1824 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1826 res = transport_send (buf.buf, len);
1834 send_reply_packets (int npackets, ReplyPacket *packets)
1841 for (i = 0; i < npackets; ++i)
1842 len += buffer_len (packets [i].data) + 11;
1843 buffer_init (&buf, len);
1844 for (i = 0; i < npackets; ++i) {
1845 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1846 buffer_add_int (&buf, packets [i].id);
1847 buffer_add_byte (&buf, 0x80); /* flags */
1848 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1849 buffer_add_byte (&buf, packets [i].error);
1850 buffer_add_buffer (&buf, packets [i].data);
1853 res = transport_send (buf.buf, len);
1861 send_reply_packet (int id, int error, Buffer *data)
1865 memset (&packet, 0, sizeof (ReplyPacket));
1867 packet.error = error;
1870 return send_reply_packets (1, &packet);
1874 send_buffered_reply_packets (void)
1878 send_reply_packets (nreply_packets, reply_packets);
1879 for (i = 0; i < nreply_packets; ++i)
1880 buffer_free (reply_packets [i].data);
1881 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1886 buffer_reply_packet (int id, int error, Buffer *data)
1890 if (nreply_packets == 128)
1891 send_buffered_reply_packets ();
1893 p = &reply_packets [nreply_packets];
1896 p->data = g_new0 (Buffer, 1);
1897 buffer_init (p->data, buffer_len (data));
1898 buffer_add_buffer (p->data, data);
1907 * Represents an object accessible by the debugger client.
1910 /* Unique id used in the wire protocol to refer to objects */
1913 * A weakref gc handle pointing to the object. The gc handle is used to
1914 * detect if the object was garbage collected.
1919 /* Maps objid -> ObjRef */
1920 /* Protected by the loader lock */
1921 static GHashTable *objrefs;
1922 /* Protected by the loader lock */
1923 static GHashTable *obj_to_objref;
1924 /* Protected by the dbg lock */
1925 static MonoGHashTable *suspended_objs;
1928 free_objref (gpointer value)
1930 ObjRef *o = (ObjRef *)value;
1932 mono_gchandle_free (o->handle);
1940 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1941 obj_to_objref = g_hash_table_new (NULL, NULL);
1942 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1946 objrefs_cleanup (void)
1948 g_hash_table_destroy (objrefs);
1953 * Return an ObjRef for OBJ.
1956 get_objref (MonoObject *obj)
1959 GSList *reflist = NULL, *l;
1965 if (suspend_count) {
1967 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1970 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1974 mono_loader_lock ();
1976 /* FIXME: The tables can grow indefinitely */
1978 if (mono_gc_is_moving ()) {
1980 * Objects can move, so use a hash table mapping hash codes to lists of
1981 * ObjRef structures.
1983 hash = mono_object_hash (obj);
1985 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1986 for (l = reflist; l; l = l->next) {
1987 ref = (ObjRef *)l->data;
1988 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1989 mono_loader_unlock ();
1994 /* Use a hash table with masked pointers to internalize object references */
1995 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1996 /* ref might refer to a different object with the same addr which was GCd */
1997 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1998 mono_loader_unlock ();
2003 ref = g_new0 (ObjRef, 1);
2004 ref->id = InterlockedIncrement (&objref_id);
2005 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2007 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2009 if (mono_gc_is_moving ()) {
2010 reflist = g_slist_append (reflist, ref);
2011 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2013 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2016 mono_loader_unlock ();
2022 true_pred (gpointer key, gpointer value, gpointer user_data)
2028 clear_suspended_objs (void)
2031 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2036 get_objid (MonoObject *obj)
2041 return get_objref (obj)->id;
2045 * Set OBJ to the object identified by OBJID.
2046 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2050 get_object_allow_null (int objid, MonoObject **obj)
2060 return ERR_INVALID_OBJECT;
2062 mono_loader_lock ();
2064 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2067 *obj = mono_gchandle_get_target (ref->handle);
2068 mono_loader_unlock ();
2070 return ERR_INVALID_OBJECT;
2073 mono_loader_unlock ();
2074 return ERR_INVALID_OBJECT;
2079 get_object (int objid, MonoObject **obj)
2081 ErrorCode err = get_object_allow_null (objid, obj);
2083 if (err != ERR_NONE)
2086 return ERR_INVALID_OBJECT;
2091 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2093 return decode_id (buf, endbuf, limit);
2097 buffer_add_objid (Buffer *buf, MonoObject *o)
2099 buffer_add_id (buf, get_objid (o));
2118 * Represents a runtime structure accessible to the debugger client
2121 /* Unique id used in the wire protocol */
2123 /* Domain of the runtime structure, NULL if the domain was unloaded */
2130 MonoAssembly *assembly;
2131 MonoClassField *field;
2133 MonoProperty *property;
2138 /* Maps runtime structure -> Id */
2139 /* Protected by the dbg lock */
2140 GHashTable *val_to_id [ID_NUM];
2141 /* Classes whose class load event has been sent */
2142 /* Protected by the loader lock */
2143 GHashTable *loaded_classes;
2144 /* Maps MonoClass->GPtrArray of file names */
2145 GHashTable *source_files;
2146 /* Maps source file basename -> GSList of classes */
2147 GHashTable *source_file_to_class;
2148 /* Same with ignore-case */
2149 GHashTable *source_file_to_class_ignorecase;
2153 /* Protected by the dbg lock */
2154 static GPtrArray *ids [ID_NUM];
2161 for (i = 0; i < ID_NUM; ++i)
2162 ids [i] = g_ptr_array_new ();
2170 for (i = 0; i < ID_NUM; ++i) {
2172 for (j = 0; j < ids [i]->len; ++j)
2173 g_free (g_ptr_array_index (ids [i], j));
2174 g_ptr_array_free (ids [i], TRUE);
2181 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2183 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2185 GHashTableIter iter;
2186 GPtrArray *file_names;
2191 for (i = 0; i < ID_NUM; ++i)
2192 if (info->val_to_id [i])
2193 g_hash_table_destroy (info->val_to_id [i]);
2194 g_hash_table_destroy (info->loaded_classes);
2196 g_hash_table_iter_init (&iter, info->source_files);
2197 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2198 for (i = 0; i < file_names->len; ++i)
2199 g_free (g_ptr_array_index (file_names, i));
2200 g_ptr_array_free (file_names, TRUE);
2203 g_hash_table_iter_init (&iter, info->source_file_to_class);
2204 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2209 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2210 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2218 domain_jit_info (domain)->agent_info = NULL;
2220 /* Clear ids referencing structures in the domain */
2222 for (i = 0; i < ID_NUM; ++i) {
2224 for (j = 0; j < ids [i]->len; ++j) {
2225 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2226 if (id->domain == domain)
2233 mono_loader_lock ();
2234 g_hash_table_remove (domains, domain);
2235 mono_loader_unlock ();
2238 static AgentDomainInfo*
2239 get_agent_domain_info (MonoDomain *domain)
2241 AgentDomainInfo *info = NULL;
2243 mono_domain_lock (domain);
2245 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2247 info = g_new0 (AgentDomainInfo, 1);
2248 domain_jit_info (domain)->agent_info = info;
2249 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2250 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2251 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2252 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2255 mono_domain_unlock (domain);
2261 get_id (MonoDomain *domain, IdType type, gpointer val)
2264 AgentDomainInfo *info;
2269 info = get_agent_domain_info (domain);
2273 if (info->val_to_id [type] == NULL)
2274 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2276 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2282 id = g_new0 (Id, 1);
2284 id->id = ids [type]->len + 1;
2285 id->domain = domain;
2288 g_hash_table_insert (info->val_to_id [type], val, id);
2289 g_ptr_array_add (ids [type], id);
2296 static inline gpointer
2297 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2301 int id = decode_id (buf, endbuf, limit);
2310 // FIXME: error handling
2312 g_assert (id > 0 && id <= ids [type]->len);
2314 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2317 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2318 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2319 *err = ERR_UNLOADED;
2324 *domain = res->domain;
2326 return res->data.val;
2330 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2332 int id = get_id (domain, type, val);
2334 buffer_add_id (buf, id);
2338 static inline MonoClass*
2339 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2343 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2344 if (G_UNLIKELY (log_level >= 2) && klass) {
2347 s = mono_type_full_name (&klass->byval_arg);
2348 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2354 static inline MonoAssembly*
2355 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2357 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2360 static inline MonoImage*
2361 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2363 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2366 static inline MonoMethod*
2367 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2371 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2372 if (G_UNLIKELY (log_level >= 2) && m) {
2375 s = mono_method_full_name (m, TRUE);
2376 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2382 static inline MonoClassField*
2383 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2385 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2388 static inline MonoDomain*
2389 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2391 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2394 static inline MonoProperty*
2395 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2397 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2401 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2403 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2404 if (G_UNLIKELY (log_level >= 2) && klass) {
2407 s = mono_type_full_name (&klass->byval_arg);
2408 if (is_debugger_thread ())
2409 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2411 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2417 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2419 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2420 if (G_UNLIKELY (log_level >= 2) && method) {
2423 s = mono_method_full_name (method, 1);
2424 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2430 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2434 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2435 if (G_UNLIKELY (log_level >= 2) && assembly)
2436 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2440 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2442 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2446 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2448 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2452 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2454 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2458 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2460 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2463 static void invoke_method (void);
2470 * save_thread_context:
2472 * Set CTX as the current threads context which is used for computing stack traces.
2473 * This function is signal-safe.
2476 save_thread_context (MonoContext *ctx)
2478 DebuggerTlsData *tls;
2480 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2484 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2486 mono_thread_state_init_from_current (&tls->context);
2489 /* Number of threads suspended */
2491 * If this is equal to the size of thread_to_tls, the runtime is considered
2494 static gint32 threads_suspend_count;
2496 static MonoCoopMutex suspend_mutex;
2498 /* Cond variable used to wait for suspend_count becoming 0 */
2499 static MonoCoopCond suspend_cond;
2501 /* Semaphore used to wait for a thread becoming suspended */
2502 static MonoCoopSem suspend_sem;
2507 mono_coop_mutex_init (&suspend_mutex);
2508 mono_coop_cond_init (&suspend_cond);
2509 mono_coop_sem_init (&suspend_sem, 0);
2514 StackFrameInfo last_frame;
2515 gboolean last_frame_set;
2519 } GetLastFrameUserData;
2522 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2524 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2526 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2529 if (!data->last_frame_set) {
2530 /* Store the last frame */
2531 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2532 data->last_frame_set = TRUE;
2535 /* Store the context/lmf for the frame above the last frame */
2536 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2537 data->lmf = info->lmf;
2538 data->domain = info->domain;
2544 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2546 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2548 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2549 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2550 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2557 * Process interruption of a thread. This should be signal safe.
2559 * This always runs in the debugger thread.
2562 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2565 MonoNativeThreadId tid;
2569 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2570 tid = mono_thread_info_get_tid (info);
2572 // FIXME: Races when the thread leaves managed code before hitting a single step
2575 if (ji && !ji->is_trampoline) {
2576 /* Running managed code, will be suspended by the single step code */
2577 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2580 * Running native code, will be suspended when it returns to/enters
2581 * managed code. Treat it as already suspended.
2582 * This might interrupt the code in process_single_step_inner (), we use the
2583 * tls->suspending flag to avoid races when that happens.
2585 if (!tls->suspended && !tls->suspending) {
2586 GetLastFrameUserData data;
2588 // FIXME: printf is not signal safe, but this is only used during
2589 // debugger debugging
2591 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2592 //save_thread_context (&ctx);
2595 /* Already terminated */
2599 * We are in a difficult position: we want to be able to provide stack
2600 * traces for this thread, but we can't use the current ctx+lmf, since
2601 * the thread is still running, so it might return to managed code,
2602 * making these invalid.
2603 * So we start a stack walk and save the first frame, along with the
2604 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2605 * suspended when it returns to managed code, so the parent's ctx should
2608 data.last_frame_set = FALSE;
2609 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2610 if (data.last_frame_set) {
2611 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2613 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2615 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2616 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2618 tls->async_state.valid = FALSE;
2621 mono_memory_barrier ();
2623 tls->suspended = TRUE;
2624 mono_coop_sem_post (&suspend_sem);
2630 * reset_native_thread_suspend_state:
2632 * Reset the suspended flag and state on native threads
2635 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2637 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2639 if (!tls->really_suspended && tls->suspended) {
2640 tls->suspended = FALSE;
2642 * The thread might still be running if it was executing native code, so the state won't be invalided by
2643 * suspend_current ().
2645 tls->context.valid = FALSE;
2646 tls->async_state.valid = FALSE;
2647 invalidate_frames (tls);
2652 DebuggerTlsData *tls;
2653 gboolean valid_info;
2656 static SuspendThreadResult
2657 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2659 InterruptData *data = (InterruptData *)user_data;
2662 data->valid_info = TRUE;
2663 ji = mono_jit_info_table_find_internal (
2664 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2665 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2669 /* This is signal safe */
2670 thread_interrupt (data->tls, info, ji);
2671 return MonoResumeThread;
2677 * Notify a thread that it needs to suspend.
2680 notify_thread (gpointer key, gpointer value, gpointer user_data)
2682 MonoInternalThread *thread = (MonoInternalThread *)key;
2683 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2684 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2686 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2689 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2691 /* This is _not_ equivalent to mono_thread_internal_abort () */
2692 InterruptData interrupt_data = { 0 };
2693 interrupt_data.tls = tls;
2695 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2696 if (!interrupt_data.valid_info) {
2697 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2699 * Attached thread which died without detaching.
2701 tls->terminated = TRUE;
2706 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2708 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2712 if (mono_loader_lock_is_owned_by_self ()) {
2714 * Shortcut for the check in suspend_current (). This speeds up processing
2715 * when executing long running code inside the loader lock, i.e. assembly load
2721 if (is_debugger_thread ())
2724 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2725 if (suspend_count - tls->resume_count > 0)
2726 tls->suspending = TRUE;
2728 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2730 if (suspend_count - tls->resume_count == 0) {
2732 * We are executing a single threaded invoke but the single step for
2733 * suspending is still active.
2734 * FIXME: This slows down single threaded invokes.
2736 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2740 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2742 /* Can't suspend in these methods */
2743 method = jinfo_get_method (ji);
2744 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2747 save_thread_context (ctx);
2755 * Increase the suspend count of the VM. While the suspend count is greater
2756 * than 0, runtime threads are suspended at certain points during execution.
2761 mono_loader_lock ();
2763 mono_coop_mutex_lock (&suspend_mutex);
2767 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2769 if (suspend_count == 1) {
2770 // FIXME: Is it safe to call this inside the lock ?
2771 start_single_stepping ();
2772 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2775 mono_coop_mutex_unlock (&suspend_mutex);
2777 if (suspend_count == 1)
2779 * Suspend creation of new threadpool threads, since they cannot run
2781 mono_threadpool_suspend ();
2783 mono_loader_unlock ();
2789 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2795 g_assert (is_debugger_thread ());
2797 mono_loader_lock ();
2799 mono_coop_mutex_lock (&suspend_mutex);
2801 g_assert (suspend_count > 0);
2804 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2806 if (suspend_count == 0) {
2807 // FIXME: Is it safe to call this inside the lock ?
2808 stop_single_stepping ();
2809 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2812 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2813 mono_coop_cond_broadcast (&suspend_cond);
2815 mono_coop_mutex_unlock (&suspend_mutex);
2816 //g_assert (err == 0);
2818 if (suspend_count == 0)
2819 mono_threadpool_resume ();
2821 mono_loader_unlock ();
2827 * Resume just one thread.
2830 resume_thread (MonoInternalThread *thread)
2832 DebuggerTlsData *tls;
2834 g_assert (is_debugger_thread ());
2836 mono_loader_lock ();
2838 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2841 mono_coop_mutex_lock (&suspend_mutex);
2843 g_assert (suspend_count > 0);
2845 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2847 tls->resume_count += suspend_count;
2850 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2851 * but only the one whose resume_count field is > 0 will be resumed.
2853 mono_coop_cond_broadcast (&suspend_cond);
2855 mono_coop_mutex_unlock (&suspend_mutex);
2856 //g_assert (err == 0);
2858 mono_loader_unlock ();
2862 free_frames (StackFrame **frames, int nframes)
2866 for (i = 0; i < nframes; ++i) {
2867 if (frames [i]->jit)
2868 mono_debug_free_method_jit_info (frames [i]->jit);
2869 g_free (frames [i]);
2875 invalidate_frames (DebuggerTlsData *tls)
2878 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2881 free_frames (tls->frames, tls->frame_count);
2882 tls->frame_count = 0;
2885 free_frames (tls->restore_frames, tls->restore_frame_count);
2886 tls->restore_frame_count = 0;
2887 tls->restore_frames = NULL;
2893 * Suspend the current thread until the runtime is resumed. If the thread has a
2894 * pending invoke, then the invoke is executed before this function returns.
2897 suspend_current (void)
2899 DebuggerTlsData *tls;
2901 g_assert (!is_debugger_thread ());
2903 if (mono_loader_lock_is_owned_by_self ()) {
2905 * If we own the loader mutex, can't suspend until we release it, since the
2906 * whole runtime can deadlock otherwise.
2911 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2914 mono_coop_mutex_lock (&suspend_mutex);
2916 tls->suspending = FALSE;
2917 tls->really_suspended = TRUE;
2919 if (!tls->suspended) {
2920 tls->suspended = TRUE;
2921 mono_coop_sem_post (&suspend_sem);
2924 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2926 while (suspend_count - tls->resume_count > 0) {
2927 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2930 tls->suspended = FALSE;
2931 tls->really_suspended = FALSE;
2933 threads_suspend_count --;
2935 mono_coop_mutex_unlock (&suspend_mutex);
2937 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2939 if (tls->pending_invoke) {
2940 /* Save the original context */
2941 tls->pending_invoke->has_ctx = TRUE;
2942 tls->pending_invoke->ctx = tls->context.ctx;
2947 /* The frame info becomes invalid after a resume */
2948 tls->context.valid = FALSE;
2949 tls->async_state.valid = FALSE;
2950 invalidate_frames (tls);
2954 count_thread (gpointer key, gpointer value, gpointer user_data)
2956 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2958 if (!tls->suspended && !tls->terminated)
2959 *(int*)user_data = *(int*)user_data + 1;
2963 count_threads_to_wait_for (void)
2967 mono_loader_lock ();
2968 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2969 mono_loader_unlock ();
2977 * Wait until the runtime is completely suspended.
2980 wait_for_suspend (void)
2982 int nthreads, nwait, err;
2983 gboolean waited = FALSE;
2985 // FIXME: Threads starting/stopping ?
2986 mono_loader_lock ();
2987 nthreads = mono_g_hash_table_size (thread_to_tls);
2988 mono_loader_unlock ();
2991 nwait = count_threads_to_wait_for ();
2993 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2994 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2995 g_assert (err == 0);
3003 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3009 * Return whenever the runtime is suspended.
3014 return count_threads_to_wait_for () == 0;
3018 no_seq_points_found (MonoMethod *method, int offset)
3021 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3023 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3027 DebuggerTlsData *tls;
3029 } ComputeFramesUserData;
3032 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3034 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3036 MonoMethod *method, *actual_method, *api_method;
3040 if (info->type != FRAME_TYPE_MANAGED) {
3041 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3042 /* Mark the last frame as an invoke frame */
3044 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3050 method = jinfo_get_method (info->ji);
3052 method = info->method;
3053 actual_method = info->actual_method;
3054 api_method = method;
3059 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3062 if (info->il_offset == -1) {
3063 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3064 if (ud->frames == NULL) {
3065 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3066 info->il_offset = sp.il_offset;
3068 if (info->il_offset == -1)
3069 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3072 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);
3074 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3075 if (!CHECK_PROTOCOL_VERSION (2, 17))
3076 /* Older clients can't handle this flag */
3078 api_method = mono_marshal_method_from_wrapper (method);
3081 actual_method = api_method;
3082 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3085 frame = g_new0 (StackFrame, 1);
3086 frame->method = method;
3087 frame->actual_method = actual_method;
3088 frame->api_method = api_method;
3089 frame->il_offset = info->il_offset;
3090 frame->native_offset = info->native_offset;
3091 frame->flags = flags;
3092 frame->ji = info->ji;
3093 if (info->reg_locations)
3094 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3097 frame->has_ctx = TRUE;
3099 frame->domain = info->domain;
3101 ud->frames = g_slist_append (ud->frames, frame);
3107 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3109 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3112 * 'tls->filter_ctx' is the location of the throw site.
3114 * mono_walk_stack() will never actually hit the throw site, but unwind
3115 * directly from the filter to the call site; we abort stack unwinding here
3116 * once this happens and resume from the throw site.
3119 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3122 return process_frame (info, ctx, user_data);
3126 * Return a malloc-ed list of StackFrame structures.
3129 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3131 ComputeFramesUserData user_data;
3132 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3137 user_data.tls = tls;
3138 user_data.frames = NULL;
3140 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3142 nframes = g_slist_length (user_data.frames);
3143 res = g_new0 (StackFrame*, nframes);
3144 l = user_data.frames;
3145 for (i = 0; i < nframes; ++i) {
3146 res [i] = (StackFrame *)l->data;
3149 *out_nframes = nframes;
3155 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3157 ComputeFramesUserData user_data;
3159 int i, findex, new_frame_count;
3160 StackFrame **new_frames, *f;
3161 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3163 // FIXME: Locking on tls
3164 if (tls->frames && tls->frames_up_to_date)
3167 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3169 user_data.tls = tls;
3170 user_data.frames = NULL;
3171 if (tls->terminated) {
3172 tls->frame_count = 0;
3174 } if (!tls->really_suspended && tls->async_state.valid) {
3175 /* Have to use the state saved by the signal handler */
3176 process_frame (&tls->async_last_frame, NULL, &user_data);
3177 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3178 } else if (tls->filter_state.valid) {
3180 * We are inside an exception filter.
3182 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3184 if (tls->context.valid)
3185 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3187 * After that, we resume unwinding from the location where the exception has been thrown.
3189 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3190 } else if (tls->context.valid) {
3191 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3194 tls->frame_count = 0;
3198 new_frame_count = g_slist_length (user_data.frames);
3199 new_frames = g_new0 (StackFrame*, new_frame_count);
3201 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3202 f = (StackFrame *)tmp->data;
3205 * Reuse the id for already existing stack frames, so invokes don't invalidate
3206 * the still valid stack frames.
3208 for (i = 0; i < tls->frame_count; ++i) {
3209 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3210 f->id = tls->frames [i]->id;
3215 if (i >= tls->frame_count)
3216 f->id = InterlockedIncrement (&frame_id);
3218 new_frames [findex ++] = f;
3221 g_slist_free (user_data.frames);
3223 invalidate_frames (tls);
3225 tls->frames = new_frames;
3226 tls->frame_count = new_frame_count;
3227 tls->frames_up_to_date = TRUE;
3231 * GHFunc to emit an appdomain creation event
3232 * @param key Don't care
3233 * @param value A loaded appdomain
3234 * @param user_data Don't care
3237 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3239 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3240 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3244 * GHFunc to emit a thread start event
3245 * @param key A thread id
3246 * @param value A thread object
3247 * @param user_data Don't care
3250 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3252 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3253 process_profiler_event (EVENT_KIND_THREAD_START, value);
3257 * GFunc to emit an assembly load event
3258 * @param value A loaded assembly
3259 * @param user_data Don't care
3262 emit_assembly_load (gpointer value, gpointer user_data)
3264 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3268 * GFunc to emit a type load event
3269 * @param value A loaded type
3270 * @param user_data Don't care
3273 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3275 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3279 strdup_tolower (char *s)
3284 for (p = s2; *p; ++p)
3290 * Same as g_path_get_basename () but handles windows paths as well,
3291 * which can occur in .mdb files created by pdb2mdb.
3294 dbg_path_get_basename (const char *filename)
3298 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3299 return g_path_get_basename (filename);
3303 /* No separator -> filename */
3304 r = strrchr (filename, '\\');
3306 return g_strdup (filename);
3308 /* Trailing slash, remove component */
3310 char *copy = g_strdup (filename);
3311 copy [r-filename] = 0;
3312 r = strrchr (copy, '\\');
3316 return g_strdup ("/");
3318 r = g_strdup (&r[1]);
3323 return g_strdup (&r[1]);
3327 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3329 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3331 MonoCustomAttrInfo *ainfo;
3333 if (ji->dbg_attrs_inited)
3337 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3339 if (!step_through_klass)
3340 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3342 if (!non_user_klass)
3343 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3345 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3346 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3348 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3349 ji->dbg_hidden = TRUE;
3350 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3351 ji->dbg_step_through = TRUE;
3352 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3353 ji->dbg_non_user_code = TRUE;
3354 mono_custom_attrs_free (ainfo);
3357 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3358 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3360 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3361 ji->dbg_step_through = TRUE;
3362 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3363 ji->dbg_non_user_code = TRUE;
3364 mono_custom_attrs_free (ainfo);
3367 mono_memory_barrier ();
3368 ji->dbg_attrs_inited = TRUE;
3376 * create_event_list:
3378 * Return a list of event request ids matching EVENT, starting from REQS, which
3379 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3381 * We return request ids, instead of requests, to simplify threading, since
3382 * requests could be deleted anytime when the loader lock is not held.
3383 * LOCKING: Assumes the loader lock is held.
3386 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3389 GSList *events = NULL;
3391 *suspend_policy = SUSPEND_POLICY_NONE;
3394 reqs = event_requests;
3399 for (i = 0; i < reqs->len; ++i) {
3400 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3401 if (req->event_kind == event) {
3402 gboolean filtered = FALSE;
3405 for (j = 0; j < req->nmodifiers; ++j) {
3406 Modifier *mod = &req->modifiers [j];
3408 if (mod->kind == MOD_KIND_COUNT) {
3410 if (mod->data.count > 0) {
3411 if (mod->data.count > 0) {
3413 if (mod->data.count == 0)
3417 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3418 if (mod->data.thread != mono_thread_internal_current ())
3420 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3421 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3423 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3425 if (ei->caught && !mod->caught)
3427 if (!ei->caught && !mod->uncaught)
3429 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3431 gboolean found = FALSE;
3432 MonoAssembly **assemblies = mod->data.assemblies;
3435 for (k = 0; assemblies [k]; ++k)
3436 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3441 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3442 gpointer iter = NULL;
3444 MonoDebugSourceInfo *sinfo;
3445 char *source_file, *s;
3446 gboolean found = FALSE;
3448 GPtrArray *source_file_list;
3450 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3451 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3454 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3455 for (i = 0; i < source_file_list->len; ++i) {
3456 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3458 * Do a case-insesitive match by converting the file name to
3461 s = strdup_tolower (sinfo->source_file);
3462 if (g_hash_table_lookup (mod->data.source_files, s))
3465 char *s2 = dbg_path_get_basename (sinfo->source_file);
3466 char *s3 = strdup_tolower (s2);
3468 if (g_hash_table_lookup (mod->data.source_files, s3))
3475 g_ptr_array_free (source_file_list, TRUE);
3480 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3483 s = mono_type_full_name (&ei->klass->byval_arg);
3484 if (!g_hash_table_lookup (mod->data.type_names, s))
3487 } else if (mod->kind == MOD_KIND_STEP) {
3488 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3489 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3490 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3491 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3493 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3494 init_jit_info_dbg_attrs (ji);
3498 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3499 init_jit_info_dbg_attrs (ji);
3500 if (ji->dbg_step_through)
3503 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3504 init_jit_info_dbg_attrs (ji);
3505 if (ji->dbg_non_user_code)
3512 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3513 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3518 /* Send a VM START/DEATH event by default */
3519 if (event == EVENT_KIND_VM_START)
3520 events = g_slist_append (events, GINT_TO_POINTER (0));
3521 if (event == EVENT_KIND_VM_DEATH)
3522 events = g_slist_append (events, GINT_TO_POINTER (0));
3527 static G_GNUC_UNUSED const char*
3528 event_to_string (EventKind event)
3531 case EVENT_KIND_VM_START: return "VM_START";
3532 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3533 case EVENT_KIND_THREAD_START: return "THREAD_START";
3534 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3535 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3536 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3537 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3538 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3539 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3540 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3541 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3542 case EVENT_KIND_STEP: return "STEP";
3543 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3544 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3545 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3546 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3547 case EVENT_KIND_USER_LOG: return "USER_LOG";
3549 g_assert_not_reached ();
3557 * Send an event to the client, suspending the vm if needed.
3558 * LOCKING: Since this can suspend the calling thread, no locks should be held
3560 * The EVENTS list is freed by this function.
3563 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3567 MonoDomain *domain = mono_domain_get ();
3568 MonoThread *thread = NULL;
3569 MonoObject *keepalive_obj = NULL;
3570 gboolean send_success = FALSE;
3575 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3579 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3580 // FIXME: We miss those events
3581 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3585 if (vm_death_event_sent) {
3586 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3590 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3591 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3596 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3600 if (event == EVENT_KIND_KEEPALIVE)
3601 suspend_policy = SUSPEND_POLICY_NONE;
3606 if (agent_config.defer) {
3607 /* Make sure the thread id is always set when doing deferred debugging */
3608 if (is_debugger_thread ()) {
3609 /* Don't suspend on events from the debugger thread */
3610 suspend_policy = SUSPEND_POLICY_NONE;
3611 thread = mono_thread_get_main ();
3613 else thread = mono_thread_current ();
3615 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3616 // FIXME: Send these with a NULL thread, don't suspend the current thread
3621 nevents = g_slist_length (events);
3622 buffer_init (&buf, 128);
3623 buffer_add_byte (&buf, suspend_policy);
3624 buffer_add_int (&buf, nevents);
3626 for (l = events; l; l = l->next) {
3627 buffer_add_byte (&buf, event); // event kind
3628 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3632 if (event == EVENT_KIND_VM_DEATH) {
3636 thread = mono_thread_current ();
3638 if (event == EVENT_KIND_VM_START && arg != NULL)
3639 thread = (MonoThread *)arg;
3642 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3645 case EVENT_KIND_THREAD_START:
3646 case EVENT_KIND_THREAD_DEATH:
3648 case EVENT_KIND_APPDOMAIN_CREATE:
3649 case EVENT_KIND_APPDOMAIN_UNLOAD:
3650 buffer_add_domainid (&buf, (MonoDomain *)arg);
3652 case EVENT_KIND_METHOD_ENTRY:
3653 case EVENT_KIND_METHOD_EXIT:
3654 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3656 case EVENT_KIND_ASSEMBLY_LOAD:
3657 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3659 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3660 DebuggerTlsData *tls;
3662 /* The domain the assembly belonged to is not equal to the current domain */
3663 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3665 g_assert (tls->domain_unloading);
3667 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3670 case EVENT_KIND_TYPE_LOAD:
3671 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3673 case EVENT_KIND_BREAKPOINT:
3674 case EVENT_KIND_STEP:
3675 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3676 buffer_add_long (&buf, il_offset);
3678 case EVENT_KIND_VM_START:
3679 buffer_add_domainid (&buf, mono_get_root_domain ());
3681 case EVENT_KIND_VM_DEATH:
3682 if (CHECK_PROTOCOL_VERSION (2, 27))
3683 buffer_add_int (&buf, mono_environment_exitcode_get ());
3685 case EVENT_KIND_EXCEPTION: {
3686 EventInfo *ei = (EventInfo *)arg;
3687 buffer_add_objid (&buf, ei->exc);
3689 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3690 * later after the suspension. (#12494).
3692 keepalive_obj = ei->exc;
3695 case EVENT_KIND_USER_BREAK:
3697 case EVENT_KIND_USER_LOG: {
3698 EventInfo *ei = (EventInfo *)arg;
3699 buffer_add_int (&buf, ei->level);
3700 buffer_add_string (&buf, ei->category ? ei->category : "");
3701 buffer_add_string (&buf, ei->message ? ei->message : "");
3704 case EVENT_KIND_KEEPALIVE:
3705 suspend_policy = SUSPEND_POLICY_NONE;
3708 g_assert_not_reached ();
3712 if (event == EVENT_KIND_VM_START) {
3713 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3714 if (!agent_config.defer)
3715 start_debugger_thread ();
3718 if (event == EVENT_KIND_VM_DEATH) {
3719 vm_death_event_sent = TRUE;
3720 suspend_policy = SUSPEND_POLICY_NONE;
3723 if (mono_runtime_is_shutting_down ())
3724 suspend_policy = SUSPEND_POLICY_NONE;
3726 if (suspend_policy != SUSPEND_POLICY_NONE) {
3728 * Save the thread context and start suspending before sending the packet,
3729 * since we could be receiving the resume request before send_packet ()
3732 save_thread_context (ctx);
3736 /* This will keep this object alive */
3737 get_objref (keepalive_obj);
3740 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3744 g_slist_free (events);
3747 if (!send_success) {
3748 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3752 if (event == EVENT_KIND_VM_START) {
3753 vm_start_event_sent = TRUE;
3756 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);
3758 switch (suspend_policy) {
3759 case SUSPEND_POLICY_NONE:
3761 case SUSPEND_POLICY_ALL:
3764 case SUSPEND_POLICY_EVENT_THREAD:
3768 g_assert_not_reached ();
3773 process_profiler_event (EventKind event, gpointer arg)
3777 EventInfo ei, *ei_arg = NULL;
3779 if (event == EVENT_KIND_TYPE_LOAD) {
3780 ei.klass = (MonoClass *)arg;
3784 mono_loader_lock ();
3785 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3786 mono_loader_unlock ();
3788 process_event (event, arg, 0, NULL, events, suspend_policy);
3792 runtime_initialized (MonoProfiler *prof)
3794 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3795 if (agent_config.defer)
3796 start_debugger_thread ();
3800 runtime_shutdown (MonoProfiler *prof)
3802 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3804 mono_debugger_agent_cleanup ();
3808 thread_startup (MonoProfiler *prof, uintptr_t tid)
3810 MonoInternalThread *thread = mono_thread_internal_current ();
3811 MonoInternalThread *old_thread;
3812 DebuggerTlsData *tls;
3814 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3817 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3819 mono_loader_lock ();
3820 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3821 mono_loader_unlock ();
3823 if (thread == old_thread) {
3825 * For some reason, thread_startup () might be called for the same thread
3826 * multiple times (attach ?).
3828 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3832 * thread_end () might not be called for some threads, and the tid could
3835 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3836 mono_loader_lock ();
3837 mono_g_hash_table_remove (thread_to_tls, old_thread);
3838 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3839 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3840 mono_loader_unlock ();
3844 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3846 // FIXME: Free this somewhere
3847 tls = g_new0 (DebuggerTlsData, 1);
3848 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3849 tls->thread = thread;
3850 mono_native_tls_set_value (debugger_tls_id, tls);
3852 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3854 mono_loader_lock ();
3855 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3856 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3857 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3858 mono_loader_unlock ();
3860 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3863 * suspend_vm () could have missed this thread, so wait for a resume.
3869 thread_end (MonoProfiler *prof, uintptr_t tid)
3871 MonoInternalThread *thread;
3872 DebuggerTlsData *tls = NULL;
3874 mono_loader_lock ();
3875 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3877 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3878 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3880 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3881 tls->terminated = TRUE;
3882 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3883 MONO_GC_UNREGISTER_ROOT (tls->thread);
3887 mono_loader_unlock ();
3889 /* We might be called for threads started before we registered the start callback */
3891 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3893 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3894 && !mono_native_tls_get_value (debugger_tls_id)
3897 * This can happen on darwin since we deregister threads using pthread dtors.
3898 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3903 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3908 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3910 mono_loader_lock ();
3911 g_hash_table_insert (domains, domain, domain);
3912 mono_loader_unlock ();
3914 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3918 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3920 DebuggerTlsData *tls;
3922 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3923 if (is_debugger_thread ())
3927 * Remember the currently unloading appdomain as it is needed to generate
3928 * proper ids for unloading assemblies.
3930 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3932 tls->domain_unloading = domain;
3936 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3938 DebuggerTlsData *tls;
3940 if (is_debugger_thread ())
3943 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3945 tls->domain_unloading = NULL;
3947 clear_breakpoints_for_domain (domain);
3949 mono_loader_lock ();
3950 /* Invalidate each thread's frame stack */
3951 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3952 mono_loader_unlock ();
3954 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3958 * invalidate_each_thread:
3960 * A GHFunc to invalidate frames.
3961 * value must be a DebuggerTlsData*
3964 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3966 invalidate_frames ((DebuggerTlsData *)value);
3970 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3972 /* Sent later in jit_end () */
3974 g_ptr_array_add (pending_assembly_loads, assembly);
3979 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3981 if (is_debugger_thread ())
3984 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3986 clear_event_requests_for_assembly (assembly);
3987 clear_types_for_assembly (assembly);
3991 send_type_load (MonoClass *klass)
3993 gboolean type_load = FALSE;
3994 MonoDomain *domain = mono_domain_get ();
3995 AgentDomainInfo *info = NULL;
3997 info = get_agent_domain_info (domain);
3999 mono_loader_lock ();
4001 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4003 g_hash_table_insert (info->loaded_classes, klass, klass);
4006 mono_loader_unlock ();
4009 emit_type_load (klass, klass, NULL);
4013 * Emit load events for all types currently loaded in the domain.
4014 * Takes the loader and domain locks.
4015 * user_data is unused.
4018 send_types_for_domain (MonoDomain *domain, void *user_data)
4020 MonoDomain* old_domain;
4021 AgentDomainInfo *info = NULL;
4023 info = get_agent_domain_info (domain);
4026 old_domain = mono_domain_get ();
4028 mono_domain_set (domain, TRUE);
4030 mono_loader_lock ();
4031 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4032 mono_loader_unlock ();
4034 mono_domain_set (old_domain, TRUE);
4038 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4041 MonoDomain* old_domain;
4043 old_domain = mono_domain_get ();
4045 mono_domain_set (domain, TRUE);
4047 mono_domain_assemblies_lock (domain);
4048 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4049 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4050 emit_assembly_load (ass, NULL);
4052 mono_domain_assemblies_unlock (domain);
4054 mono_domain_set (old_domain, TRUE);
4058 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4061 * We emit type load events when the first method of the type is JITted,
4062 * since the class load profiler callbacks might be called with the
4063 * loader lock held. They could also occur in the debugger thread.
4064 * Same for assembly load events.
4067 MonoAssembly *assembly = NULL;
4069 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4071 if (pending_assembly_loads->len > 0) {
4072 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4073 g_ptr_array_remove_index (pending_assembly_loads, 0);
4078 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4084 send_type_load (method->klass);
4087 add_pending_breakpoints (method, jinfo);
4091 * BREAKPOINTS/SINGLE STEPPING
4095 * Contains information about an inserted breakpoint.
4098 long il_offset, native_offset;
4102 } BreakpointInstance;
4105 * Contains generic information about a breakpoint.
4109 * The method where the breakpoint is placed. Can be NULL in which case it
4110 * is inserted into every method. This is used to implement method entry/
4111 * exit events. Can be a generic method definition, in which case the
4112 * breakpoint is inserted into every instance.
4118 * A list of BreakpointInstance structures describing where the breakpoint
4119 * was inserted. There could be more than one because of
4120 * generics/appdomains/method entry/exit.
4122 GPtrArray *children;
4125 /* List of breakpoints */
4126 /* Protected by the loader lock */
4127 static GPtrArray *breakpoints;
4128 /* Maps breakpoint locations to the number of breakpoints at that location */
4129 static GHashTable *bp_locs;
4132 breakpoints_init (void)
4134 breakpoints = g_ptr_array_new ();
4135 bp_locs = g_hash_table_new (NULL, NULL);
4139 * insert_breakpoint:
4141 * Insert the breakpoint described by BP into the method described by
4145 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4148 BreakpointInstance *inst;
4149 SeqPointIterator it;
4150 gboolean it_has_sp = FALSE;
4153 mono_error_init (error);
4155 mono_seq_point_iterator_init (&it, seq_points);
4156 while (mono_seq_point_iterator_next (&it)) {
4157 if (it.seq_point.il_offset == bp->il_offset) {
4165 * The set of IL offsets with seq points doesn't completely match the
4166 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4168 mono_seq_point_iterator_init (&it, seq_points);
4169 while (mono_seq_point_iterator_next (&it)) {
4170 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4171 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4172 it.seq_point.il_offset + 1 == bp->il_offset) {
4180 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4182 mono_seq_point_iterator_init (&it, seq_points);
4183 while (mono_seq_point_iterator_next (&it))
4184 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4187 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4188 g_warning ("%s", s);
4192 g_warning ("%s", s);
4198 inst = g_new0 (BreakpointInstance, 1);
4199 inst->il_offset = it.seq_point.il_offset;
4200 inst->native_offset = it.seq_point.native_offset;
4201 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4203 inst->domain = domain;
4205 mono_loader_lock ();
4207 g_ptr_array_add (bp->children, inst);
4209 mono_loader_unlock ();
4212 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4213 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4216 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4217 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4218 } else if (count == 0) {
4219 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4220 mono_arch_set_breakpoint (ji, inst->ip);
4226 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);
4230 remove_breakpoint (BreakpointInstance *inst)
4232 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4234 MonoJitInfo *ji = inst->ji;
4235 guint8 *ip = inst->ip;
4238 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4239 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4242 g_assert (count > 0);
4244 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4245 mono_arch_clear_breakpoint (ji, ip);
4246 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4254 * This doesn't take any locks.
4256 static inline gboolean
4257 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4263 if (method == bp->method)
4265 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4268 if (bp->method->is_inflated && method->is_inflated) {
4269 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4270 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4272 /* Open generic methods should match closed generic methods of the same class */
4273 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4274 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4275 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4277 /* FIXME: Handle !mvar */
4278 if (t1->type != MONO_TYPE_MVAR)
4289 * add_pending_breakpoints:
4291 * Insert pending breakpoints into the newly JITted method METHOD.
4294 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4297 MonoSeqPointInfo *seq_points;
4299 MonoMethod *jmethod;
4304 domain = mono_domain_get ();
4306 mono_loader_lock ();
4308 for (i = 0; i < breakpoints->len; ++i) {
4309 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4310 gboolean found = FALSE;
4312 if (!bp_matches_method (bp, method))
4315 for (j = 0; j < bp->children->len; ++j) {
4316 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4323 MonoMethod *declaring = NULL;
4325 jmethod = jinfo_get_method (ji);
4326 if (jmethod->is_inflated)
4327 declaring = mono_method_get_declaring_generic_method (jmethod);
4329 mono_domain_lock (domain);
4330 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4331 if (!seq_points && declaring)
4332 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4333 mono_domain_unlock (domain);
4335 /* Could be AOT code */
4337 g_assert (seq_points);
4339 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4343 mono_loader_unlock ();
4347 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4353 mono_error_init (error);
4355 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4359 /* Might be AOTed code */
4360 mono_class_init (method->klass);
4361 code = mono_aot_get_method_checked (domain, method, &oerror);
4363 mono_error_assert_ok (&oerror);
4364 ji = mono_jit_info_table_find (domain, (char *)code);
4369 insert_breakpoint (seq_points, domain, ji, bp, error);
4373 clear_breakpoint (MonoBreakpoint *bp);
4378 * Set a breakpoint at IL_OFFSET in METHOD.
4379 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4380 * METHOD can also be a generic method definition, in which case a breakpoint
4381 * is placed in all instances of the method.
4382 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4385 static MonoBreakpoint*
4386 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4389 GHashTableIter iter, iter2;
4392 MonoSeqPointInfo *seq_points;
4394 GPtrArray *method_domains;
4395 GPtrArray *method_seq_points;
4399 mono_error_init (error);
4402 // - suspend/resume the vm to prevent code patching problems
4403 // - multiple breakpoints on the same location
4404 // - dynamic methods
4407 bp = g_new0 (MonoBreakpoint, 1);
4408 bp->method = method;
4409 bp->il_offset = il_offset;
4411 bp->children = g_ptr_array_new ();
4413 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);
4415 methods = g_ptr_array_new ();
4416 method_domains = g_ptr_array_new ();
4417 method_seq_points = g_ptr_array_new ();
4419 mono_loader_lock ();
4420 g_hash_table_iter_init (&iter, domains);
4421 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4422 mono_domain_lock (domain);
4423 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4424 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4425 if (bp_matches_method (bp, m)) {
4426 /* Save the info locally to simplify the code inside the domain lock */
4427 g_ptr_array_add (methods, m);
4428 g_ptr_array_add (method_domains, domain);
4429 g_ptr_array_add (method_seq_points, seq_points);
4432 mono_domain_unlock (domain);
4435 for (i = 0; i < methods->len; ++i) {
4436 m = (MonoMethod *)g_ptr_array_index (methods, i);
4437 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4438 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4439 set_bp_in_method (domain, m, seq_points, bp, error);
4442 g_ptr_array_add (breakpoints, bp);
4443 mono_loader_unlock ();
4445 g_ptr_array_free (methods, TRUE);
4446 g_ptr_array_free (method_domains, TRUE);
4447 g_ptr_array_free (method_seq_points, TRUE);
4449 if (error && !mono_error_ok (error)) {
4450 clear_breakpoint (bp);
4458 clear_breakpoint (MonoBreakpoint *bp)
4462 // FIXME: locking, races
4463 for (i = 0; i < bp->children->len; ++i) {
4464 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4466 remove_breakpoint (inst);
4471 mono_loader_lock ();
4472 g_ptr_array_remove (breakpoints, bp);
4473 mono_loader_unlock ();
4475 g_ptr_array_free (bp->children, TRUE);
4480 breakpoints_cleanup (void)
4484 mono_loader_lock ();
4486 while (i < event_requests->len) {
4487 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4489 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4490 clear_breakpoint ((MonoBreakpoint *)req->info);
4491 g_ptr_array_remove_index_fast (event_requests, i);
4498 for (i = 0; i < breakpoints->len; ++i)
4499 g_free (g_ptr_array_index (breakpoints, i));
4501 g_ptr_array_free (breakpoints, TRUE);
4502 g_hash_table_destroy (bp_locs);
4507 mono_loader_unlock ();
4511 * clear_breakpoints_for_domain:
4513 * Clear breakpoint instances which reference DOMAIN.
4516 clear_breakpoints_for_domain (MonoDomain *domain)
4520 /* This could be called after shutdown */
4524 mono_loader_lock ();
4525 for (i = 0; i < breakpoints->len; ++i) {
4526 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4529 while (j < bp->children->len) {
4530 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4532 if (inst->domain == domain) {
4533 remove_breakpoint (inst);
4537 g_ptr_array_remove_index_fast (bp->children, j);
4543 mono_loader_unlock ();
4547 * ss_calculate_framecount:
4549 * Ensure DebuggerTlsData fields are filled out.
4551 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4553 if (!tls->context.valid)
4554 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4555 compute_frame_info (tls->thread, tls);
4559 ensure_jit (StackFrame* frame)
4562 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4563 if (!frame->jit && frame->api_method->is_inflated)
4564 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4568 /* This could happen for aot images with no jit debug info */
4569 s = mono_method_full_name (frame->api_method, TRUE);
4570 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4581 * Return FALSE if single stepping needs to continue.
4584 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4586 MonoDebugMethodInfo *minfo;
4587 MonoDebugSourceLocation *loc = NULL;
4588 gboolean hit = TRUE;
4590 if (req->async_stepout_method == method) {
4591 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);
4595 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4597 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4599 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);
4603 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4604 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4606 ss_calculate_framecount (tls, ctx);
4608 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4609 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4610 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4611 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4612 /* Hit the breakpoint in a recursive call, don't halt */
4613 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");
4618 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4619 ss_calculate_framecount (tls, ctx);
4620 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4621 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);
4626 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4628 for (int i = 0; i < asyncMethod->num_awaits; i++)
4630 if (asyncMethod->yield_offsets[i] == sp->il_offset || asyncMethod->resume_offsets[i] == sp->il_offset) {
4631 mono_debug_free_method_async_debug_info (asyncMethod);
4635 mono_debug_free_method_async_debug_info (asyncMethod);
4638 if (req->size != STEP_SIZE_LINE)
4641 /* Have to check whenever a different source line was reached */
4642 minfo = mono_debug_lookup_method (method);
4645 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4648 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);
4649 ss_req->last_method = method;
4651 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4652 ss_calculate_framecount (tls, ctx);
4653 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4654 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4660 ss_req->last_method = method;
4661 ss_req->last_line = loc->row;
4662 mono_debug_free_source_location (loc);
4669 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4671 return bp->method && bp->method->klass->image->assembly == assembly;
4675 get_this (StackFrame *frame)
4677 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4678 MonoDebugVarInfo *var = frame->jit->this_var;
4679 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4682 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4683 addr += (gint32)var->offset;
4684 return *(MonoObject**)addr;
4687 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4688 //since thread probably changed...
4690 get_this_async_id (StackFrame *frame)
4692 return get_objid (get_this (frame));
4695 static MonoMethod* set_notification_method_cache = NULL;
4698 get_set_notification_method ()
4700 if(set_notification_method_cache != NULL)
4701 return set_notification_method_cache;
4703 MonoClass* async_builder_class = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder");
4704 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4705 mono_error_assert_ok (&error);
4706 g_assert (array->len == 1);
4707 set_notification_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4708 g_ptr_array_free (array, TRUE);
4709 return set_notification_method_cache;
4713 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4715 MonoObject* obj = get_this (frame);
4717 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4718 g_assert (builder_field);
4719 MonoObject* builder;
4721 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4722 mono_error_assert_ok (&error);
4726 gboolean arg = TRUE;
4728 mono_runtime_invoke_checked (get_set_notification_method(), mono_object_unbox (builder), args, &error);
4729 mono_error_assert_ok (&error);
4730 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4733 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4736 get_notify_debugger_of_wait_completion_method ()
4738 if (notify_debugger_of_wait_completion_method_cache != NULL)
4739 return notify_debugger_of_wait_completion_method_cache;
4741 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4742 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4743 mono_error_assert_ok (&error);
4744 g_assert (array->len == 1);
4745 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4746 g_ptr_array_free (array, TRUE);
4747 return notify_debugger_of_wait_completion_method_cache;
4751 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4755 int i, j, suspend_policy;
4756 guint32 native_offset;
4758 BreakpointInstance *inst;
4759 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4760 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4761 EventKind kind = EVENT_KIND_BREAKPOINT;
4762 MonoContext *ctx = &tls->restore_state.ctx;
4764 MonoSeqPointInfo *info;
4768 // FIXME: Speed this up
4770 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4771 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4772 g_assert (ji && !ji->is_trampoline);
4773 method = jinfo_get_method (ji);
4775 /* Compute the native offset of the breakpoint from the ip */
4776 native_offset = ip - (guint8*)ji->code_start;
4779 * Skip the instruction causing the breakpoint signal.
4782 mono_arch_skip_breakpoint (ctx, ji);
4784 if (method->wrapper_type || tls->disable_breakpoints)
4787 bp_reqs = g_ptr_array_new ();
4788 ss_reqs = g_ptr_array_new ();
4789 ss_reqs_orig = g_ptr_array_new ();
4791 mono_loader_lock ();
4794 * The ip points to the instruction causing the breakpoint event, which is after
4795 * the offset recorded in the seq point map, so find the prev seq point before ip.
4797 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4800 no_seq_points_found (method, native_offset);
4802 g_assert (found_sp);
4804 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);
4807 for (i = 0; i < breakpoints->len; ++i) {
4808 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4813 for (j = 0; j < bp->children->len; ++j) {
4814 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4815 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4816 if (bp->req->event_kind == EVENT_KIND_STEP) {
4817 g_ptr_array_add (ss_reqs_orig, bp->req);
4819 g_ptr_array_add (bp_reqs, bp->req);
4824 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4825 /* Maybe a method entry/exit event */
4826 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4827 kind = EVENT_KIND_METHOD_ENTRY;
4828 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4829 kind = EVENT_KIND_METHOD_EXIT;
4832 /* Process single step requests */
4833 for (i = 0; i < ss_reqs_orig->len; ++i) {
4834 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4835 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4838 //if we hit async_stepout_method, it's our no matter which thread
4839 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4840 //We have different thread and we don't have async stepping in progress
4841 //it's breakpoint in parallel thread, ignore it
4842 if (ss_req->async_id == 0)
4845 tls->context.valid = FALSE;
4846 tls->async_state.valid = FALSE;
4847 invalidate_frames (tls);
4848 ss_calculate_framecount(tls, ctx);
4849 //make sure we have enough data to get current async method instance id
4850 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4853 //Check method is async before calling get_this_async_id
4854 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4858 mono_debug_free_method_async_debug_info (asyncMethod);
4860 //breakpoint was hit in parallelly executing async method, ignore it
4861 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4865 //Update stepping request to new thread/frame_count that we are continuing on
4866 //so continuing with normal stepping works as expected
4867 if (ss_req->async_stepout_method || ss_req->async_id) {
4868 tls->context.valid = FALSE;
4869 tls->async_state.valid = FALSE;
4870 invalidate_frames (tls);
4871 ss_calculate_framecount (tls, ctx);
4872 ss_req->thread = mono_thread_internal_current ();
4873 ss_req->nframes = tls->frame_count;
4876 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4878 g_ptr_array_add (ss_reqs, req);
4880 /* Start single stepping again from the current sequence point */
4881 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4884 if (ss_reqs->len > 0)
4885 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4886 if (bp_reqs->len > 0)
4887 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4888 if (kind != EVENT_KIND_BREAKPOINT)
4889 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4891 mono_loader_unlock ();
4893 g_ptr_array_free (bp_reqs, TRUE);
4894 g_ptr_array_free (ss_reqs, TRUE);
4897 * FIXME: The first event will suspend, so the second will only be sent after the
4901 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4903 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4904 if (enter_leave_events)
4905 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4908 /* Process a breakpoint/single step event after resuming from a signal handler */
4910 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4912 DebuggerTlsData *tls;
4913 MonoThreadUnwindState orig_restore_state;
4916 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4917 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4918 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4919 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4923 /* This is called when resuming from a signal handler, so it shouldn't return */
4924 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4925 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4926 mono_restore_context (&ctx);
4927 g_assert_not_reached ();
4931 process_breakpoint (void)
4933 process_signal_event (process_breakpoint_inner);
4937 resume_from_signal_handler (void *sigctx, void *func)
4939 DebuggerTlsData *tls;
4942 /* Save the original context in TLS */
4943 // FIXME: This might not work on an altstack ?
4944 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4946 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4949 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4950 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4951 // clob:c could be added to op_seq_point.
4953 mono_sigctx_to_monoctx (sigctx, &ctx);
4954 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4955 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4956 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4958 MONO_CONTEXT_SET_IP (&ctx, func);
4960 mono_monoctx_to_sigctx (&ctx, sigctx);
4962 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4963 mono_ppc_set_func_into_sigctx (sigctx, func);
4968 mono_debugger_agent_breakpoint_hit (void *sigctx)
4971 * We are called from a signal handler, and running code there causes all kinds of
4972 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4973 * So set up the signal context to return to the real breakpoint handler function.
4975 resume_from_signal_handler (sigctx, process_breakpoint);
4979 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4981 if (frame->managed) {
4982 *(MonoContext*)data = *ctx;
4991 * Called by System.Diagnostics.Debugger:Break ().
4994 mono_debugger_agent_user_break (void)
4996 if (agent_config.enabled) {
5001 /* Obtain a context */
5002 MONO_CONTEXT_SET_IP (&ctx, NULL);
5003 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
5004 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
5006 mono_loader_lock ();
5007 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5008 mono_loader_unlock ();
5010 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5011 } else if (debug_options.native_debugger_break) {
5017 ss_depth_to_string (StepDepth depth)
5020 case STEP_DEPTH_OVER:
5022 case STEP_DEPTH_OUT:
5024 case STEP_DEPTH_INTO:
5027 g_assert_not_reached ();
5033 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5038 int il_offset, suspend_policy;
5041 MonoContext *ctx = &tls->restore_state.ctx;
5044 MonoSeqPointInfo *info;
5046 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5048 /* Skip the instruction causing the single step */
5050 mono_arch_skip_single_step (ctx);
5052 if (suspend_count > 0) {
5053 /* Fastpath during invokes, see in process_suspend () */
5054 if (suspend_count - tls->resume_count == 0)
5056 process_suspend (tls, ctx);
5061 // FIXME: A suspend race
5064 if (mono_thread_internal_current () != ss_req->thread)
5067 if (log_level > 0) {
5068 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5070 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);
5073 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5074 g_assert (ji && !ji->is_trampoline);
5075 method = jinfo_get_method (ji);
5078 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5083 * Stopping in memset makes half-initialized vtypes visible.
5084 * Stopping in memcpy makes half-copied vtypes visible.
5086 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5090 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5091 * hence we prefer this check here.
5093 if (ss_req->user_assemblies) {
5094 gboolean found = FALSE;
5095 for (int k = 0; ss_req->user_assemblies[k]; k++)
5096 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5106 * The ip points to the instruction causing the single step event, which is before
5107 * the offset recorded in the seq point map, so find the next seq point after ip.
5109 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
5112 il_offset = sp.il_offset;
5114 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5117 /* Start single stepping again from the current sequence point */
5118 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5120 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5121 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5122 !strcmp (method->name, ".cctor"))
5125 // FIXME: Has to lock earlier
5127 reqs = g_ptr_array_new ();
5129 mono_loader_lock ();
5131 g_ptr_array_add (reqs, ss_req->req);
5133 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5135 g_ptr_array_free (reqs, TRUE);
5137 mono_loader_unlock ();
5139 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5143 process_single_step (void)
5145 process_signal_event (process_single_step_inner);
5149 * mono_debugger_agent_single_step_event:
5151 * Called from a signal handler to handle a single step event.
5154 mono_debugger_agent_single_step_event (void *sigctx)
5156 /* Resume to process_single_step through the signal context */
5158 // FIXME: Since step out/over is implemented using step in, the step in case should
5159 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5162 if (is_debugger_thread ()) {
5164 * This could happen despite our best effors when the runtime calls
5165 * assembly/type resolve hooks.
5166 * FIXME: Breakpoints too.
5170 mono_sigctx_to_monoctx (sigctx, &ctx);
5171 mono_arch_skip_single_step (&ctx);
5172 mono_monoctx_to_sigctx (&ctx, sigctx);
5176 resume_from_signal_handler (sigctx, process_single_step);
5180 debugger_agent_single_step_from_context (MonoContext *ctx)
5182 DebuggerTlsData *tls;
5183 MonoThreadUnwindState orig_restore_state;
5185 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5186 /* Fastpath during invokes, see in process_suspend () */
5187 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5190 if (is_debugger_thread ())
5195 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5196 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5197 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5198 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5200 process_single_step_inner (tls, FALSE);
5202 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5203 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5207 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5209 DebuggerTlsData *tls;
5210 MonoThreadUnwindState orig_restore_state;
5213 if (is_debugger_thread ())
5216 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5217 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5219 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5221 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5222 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5223 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5225 process_breakpoint_inner (tls, FALSE);
5227 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5228 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5229 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5230 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5234 * start_single_stepping:
5236 * Turn on single stepping. Can be called multiple times, for example,
5237 * by a single step event request + a suspend.
5240 start_single_stepping (void)
5242 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5243 int val = InterlockedIncrement (&ss_count);
5246 mono_arch_start_single_stepping ();
5248 g_assert_not_reached ();
5253 stop_single_stepping (void)
5255 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5256 int val = InterlockedDecrement (&ss_count);
5259 mono_arch_stop_single_stepping ();
5261 g_assert_not_reached ();
5268 * Stop the single stepping operation given by SS_REQ.
5271 ss_stop (SingleStepReq *ss_req)
5276 for (l = ss_req->bps; l; l = l->next) {
5277 clear_breakpoint ((MonoBreakpoint *)l->data);
5279 g_slist_free (ss_req->bps);
5283 ss_req->async_id = 0;
5284 ss_req->async_stepout_method = NULL;
5285 if (ss_req->global) {
5286 stop_single_stepping ();
5287 ss_req->global = FALSE;
5294 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5297 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5299 if (ss_req_bp_cache) {
5300 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5301 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5303 for (GSList *l = bps; l; l = l->next) {
5304 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5305 if (bp->method == method && bp->il_offset == il_offset)
5314 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5317 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5319 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5320 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5321 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5327 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5330 ss_bp_hash (gconstpointer data)
5332 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5333 guint hash = (guint) (uintptr_t) s->method;
5334 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5335 hash ^= ((guint)s->il_offset) >> 16;
5339 #define MAX_LINEAR_SCAN_BPS 7
5344 * Create a new breakpoint and add it to a step request.
5345 * Will adjust the bp count and cache used by ss_start.
5348 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5349 MonoMethod *method, guint32 il_offset)
5351 // This list is getting too long, switch to using the hash table
5352 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5353 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5354 for (GSList *l = ss_req->bps; l; l = l->next)
5355 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5358 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5359 // Create and add breakpoint
5360 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5361 ss_req->bps = g_slist_append (ss_req->bps, bp);
5362 if (*ss_req_bp_cache)
5363 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5364 (*ss_req_bp_count)++;
5366 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);
5371 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5375 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5376 mono_seq_point_init_next (info, *sp, next);
5377 for (int i = 0; i < sp->next_len; i++) {
5378 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5379 if (!is_last_non_empty (&next [i], info)) {
5395 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5396 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5397 * belong to the same thread as CTX.
5398 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5401 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5402 gboolean step_to_catch, StackFrame **frames, int nframes)
5404 int i, j, frame_index;
5405 SeqPoint *next_sp, *parent_sp = NULL;
5406 SeqPoint local_sp, local_parent_sp;
5408 MonoSeqPointInfo *parent_info;
5409 MonoMethod *parent_sp_method = NULL;
5410 gboolean enable_global = FALSE;
5412 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5413 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5414 int ss_req_bp_count = g_slist_length (ss_req->bps);
5415 GHashTable *ss_req_bp_cache = NULL;
5417 /* Stop the previous operation */
5421 * Implement single stepping using breakpoints if possible.
5423 if (step_to_catch) {
5424 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5428 if (ctx && !frames) {
5429 /* Need parent frames */
5430 if (!tls->context.valid)
5431 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5432 compute_frame_info (tls->thread, tls);
5433 frames = tls->frames;
5434 nframes = tls->frame_count;
5437 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5439 /* Need to stop in catch clauses as well */
5440 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5441 StackFrame *frame = frames [i];
5444 MonoJitInfo *jinfo = frame->ji;
5445 for (j = 0; j < jinfo->num_clauses; ++j) {
5446 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5447 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5449 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5451 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5452 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5457 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5458 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5460 // Check if we hit yield_offset during normal stepping, because if we did...
5461 // Go into special async stepping mode which places breakpoint on resumeOffset
5462 // of this await call and sets async_id so we can distinguish it from parallel executions
5463 for (i = 0; i < asyncMethod->num_awaits; i++) {
5464 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5465 ss_req->async_id = get_this_async_id (frames [0]);
5466 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5467 if (ss_req_bp_cache)
5468 g_hash_table_destroy (ss_req_bp_cache);
5469 mono_debug_free_method_async_debug_info (asyncMethod);
5473 //If we are at end of async method and doing step-in or step-over...
5474 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5475 if (is_last_non_empty (sp, info)) {
5476 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5478 if (ss_req->depth == STEP_DEPTH_OUT) {
5479 set_set_notification_for_wait_completion_flag (frames [0]);
5480 ss_req->async_id = get_this_async_id (frames [0]);
5481 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5482 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5483 if (ss_req_bp_cache)
5484 g_hash_table_destroy (ss_req_bp_cache);
5485 mono_debug_free_method_async_debug_info (asyncMethod);
5491 mono_debug_free_method_async_debug_info (asyncMethod);
5494 * Find the first sequence point in the current or in a previous frame which
5495 * is not the last in its method.
5497 if (ss_req->depth == STEP_DEPTH_OUT) {
5498 /* Ignore seq points in current method */
5499 while (frame_index < nframes) {
5500 StackFrame *frame = frames [frame_index];
5502 method = frame->method;
5503 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5504 sp = (found_sp)? &local_sp : NULL;
5506 if (sp && sp->next_len != 0)
5509 // There could be method calls before the next seq point in the caller when using nested calls
5510 //enable_global = TRUE;
5512 if (sp && sp->next_len == 0) {
5514 while (frame_index < nframes) {
5515 StackFrame *frame = frames [frame_index];
5517 method = frame->method;
5518 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5519 sp = (found_sp)? &local_sp : NULL;
5520 if (sp && sp->next_len != 0)
5526 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5527 while (frame_index < nframes) {
5528 StackFrame *frame = frames [frame_index];
5530 parent_sp_method = frame->method;
5531 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5532 parent_sp = found_sp ? &local_parent_sp : NULL;
5533 if (found_sp && parent_sp->next_len != 0)
5541 if (sp && sp->next_len > 0) {
5542 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5544 mono_seq_point_init_next (info, *sp, next);
5545 for (i = 0; i < sp->next_len; i++) {
5548 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5554 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5556 mono_seq_point_init_next (parent_info, *parent_sp, next);
5557 for (i = 0; i < parent_sp->next_len; i++) {
5560 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5565 if (ss_req->nframes == 0)
5566 ss_req->nframes = nframes;
5568 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5569 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5571 * This is needed since if we leave managed code, and later return to it, step over
5572 * is not going to stop.
5573 * This approach is a bit ugly, since we change the step depth, but it only affects
5574 * clients who reuse the same step request, and only in this special case.
5576 ss_req->depth = STEP_DEPTH_INTO;
5579 if (ss_req->depth == STEP_DEPTH_INTO) {
5580 /* Enable global stepping so we stop at method entry too */
5581 enable_global = TRUE;
5585 * The ctx/frame info computed above will become invalid when we continue.
5587 tls->context.valid = FALSE;
5588 tls->async_state.valid = FALSE;
5589 invalidate_frames (tls);
5592 if (enable_global) {
5593 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5594 ss_req->global = TRUE;
5595 start_single_stepping ();
5596 } else if (!ss_req->bps) {
5597 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5598 ss_req->global = TRUE;
5599 start_single_stepping ();
5601 ss_req->global = FALSE;
5604 if (ss_req_bp_cache)
5605 g_hash_table_destroy (ss_req_bp_cache);
5609 * Start single stepping of thread THREAD
5612 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5614 DebuggerTlsData *tls;
5615 MonoSeqPointInfo *info = NULL;
5616 SeqPoint *sp = NULL;
5619 MonoMethod *method = NULL;
5620 MonoDebugMethodInfo *minfo;
5621 gboolean step_to_catch = FALSE;
5622 gboolean set_ip = FALSE;
5623 StackFrame **frames = NULL;
5626 if (suspend_count == 0)
5627 return ERR_NOT_SUSPENDED;
5629 wait_for_suspend ();
5631 // FIXME: Multiple requests
5633 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5634 return ERR_NOT_IMPLEMENTED;
5637 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5639 ss_req = g_new0 (SingleStepReq, 1);
5641 ss_req->thread = thread;
5642 ss_req->size = size;
5643 ss_req->depth = depth;
5644 ss_req->filter = filter;
5647 for (int i = 0; i < req->nmodifiers; i++) {
5648 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5649 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5654 mono_loader_lock ();
5655 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5656 mono_loader_unlock ();
5658 if (!tls->context.valid) {
5659 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5660 return ERR_INVALID_ARGUMENT;
5663 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5665 * Need to start single stepping from restore_state and not from the current state
5668 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5671 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5673 if (tls->catch_state.valid) {
5675 StackFrameInfo frame;
5676 MonoContext new_ctx;
5677 MonoLMF *lmf = NULL;
5680 * We are stopped at a throw site. Stepping should go to the catch site.
5683 /* Find the the jit info for the catch context */
5684 res = mono_find_jit_info_ext (
5685 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5686 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5687 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5689 g_assert (frame.type == FRAME_TYPE_MANAGED);
5692 * Find the seq point corresponding to the landing site ip, which is the first seq
5695 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5696 sp = (found_sp)? &local_sp : NULL;
5698 no_seq_points_found (frame.method, frame.native_offset);
5701 method = frame.method;
5703 step_to_catch = TRUE;
5704 /* This make sure the seq point is not skipped by process_single_step () */
5705 ss_req->last_sp = NULL;
5708 if (!step_to_catch) {
5709 StackFrame *frame = NULL;
5712 if (frames && nframes)
5715 compute_frame_info (thread, tls);
5717 if (tls->frame_count)
5718 frame = tls->frames [0];
5721 if (ss_req->size == STEP_SIZE_LINE) {
5723 ss_req->last_method = frame->method;
5724 ss_req->last_line = -1;
5726 minfo = mono_debug_lookup_method (frame->method);
5727 if (minfo && frame->il_offset != -1) {
5728 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5731 ss_req->last_line = loc->row;
5739 if (!method && frame->il_offset != -1) {
5740 /* FIXME: Sort the table and use a binary search */
5741 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5742 sp = (found_sp)? &local_sp : NULL;
5744 no_seq_points_found (frame->method, frame->native_offset);
5746 method = frame->method;
5751 ss_req->start_method = method;
5753 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5756 free_frames (frames, nframes);
5762 ss_destroy (SingleStepReq *req)
5765 g_assert (ss_req == req);
5774 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5777 gboolean found = TRUE;
5781 for (l = ss_req->bps; l; l = l->next) {
5782 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5783 clear_breakpoint ((MonoBreakpoint *)l->data);
5784 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5793 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5796 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5803 if (!agent_config.enabled)
5806 mono_loader_lock ();
5807 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5808 mono_loader_unlock ();
5813 ei.category = mono_string_to_utf8_checked (category, &error);
5814 mono_error_cleanup (&error);
5818 ei.message = mono_string_to_utf8_checked (message, &error);
5819 mono_error_cleanup (&error);
5822 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5824 g_free (ei.category);
5825 g_free (ei.message);
5829 mono_debugger_agent_debug_log_is_enabled (void)
5831 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5832 return agent_config.enabled;
5835 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5837 mono_debugger_agent_unhandled_exception (MonoException *exc)
5846 memset (&ei, 0, sizeof (EventInfo));
5847 ei.exc = (MonoObject*)exc;
5849 mono_loader_lock ();
5850 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5851 mono_loader_unlock ();
5853 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5858 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5859 MonoContext *catch_ctx)
5861 int i, j, suspend_policy;
5863 MonoJitInfo *ji, *catch_ji;
5865 DebuggerTlsData *tls = NULL;
5867 if (thread_to_tls != NULL) {
5868 MonoInternalThread *thread = mono_thread_internal_current ();
5870 mono_loader_lock ();
5871 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5872 mono_loader_unlock ();
5874 if (tls && tls->abort_requested)
5876 if (tls && tls->disable_breakpoints)
5880 memset (&ei, 0, sizeof (EventInfo));
5882 /* Just-In-Time debugging */
5884 if (agent_config.onuncaught && !inited) {
5885 finish_agent_init (FALSE);
5888 * Send an unsolicited EXCEPTION event with a dummy request id.
5890 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5891 ei.exc = (MonoObject*)exc;
5892 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5895 } else if (agent_config.onthrow && !inited) {
5897 gboolean found = FALSE;
5899 for (l = agent_config.onthrow; l; l = l->next) {
5900 char *ex_type = (char *)l->data;
5901 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5903 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5910 finish_agent_init (FALSE);
5913 * Send an unsolicited EXCEPTION event with a dummy request id.
5915 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5916 ei.exc = (MonoObject*)exc;
5917 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5925 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5927 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5931 ei.exc = (MonoObject*)exc;
5932 ei.caught = catch_ctx != NULL;
5934 mono_loader_lock ();
5936 /* Treat exceptions which are caught in non-user code as unhandled */
5937 for (i = 0; i < event_requests->len; ++i) {
5938 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5939 if (req->event_kind != EVENT_KIND_EXCEPTION)
5942 for (j = 0; j < req->nmodifiers; ++j) {
5943 Modifier *mod = &req->modifiers [j];
5945 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5947 gboolean found = FALSE;
5948 MonoAssembly **assemblies = mod->data.assemblies;
5951 for (k = 0; assemblies [k]; ++k)
5952 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5961 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5962 mono_loader_unlock ();
5964 if (tls && ei.caught && catch_ctx) {
5965 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5966 tls->catch_state.ctx = *catch_ctx;
5967 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5968 tls->catch_state.valid = TRUE;
5971 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5974 tls->catch_state.valid = FALSE;
5978 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5980 DebuggerTlsData *tls;
5985 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5990 * We're about to invoke an exception filter during the first pass of exception handling.
5992 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5993 * 'orig_ctx' is the context where the exception has been thrown.
5996 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5998 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5999 * the call site (line 37) and then continue to Main(), but it would never
6000 * include the throw site (line 32).
6002 * Since exception filters are invoked during the first pass of exception handling,
6003 * the stack frames of the throw site are still intact, so we should include them
6006 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6008 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6009 * but report the location of the 'throw' to the user.
6013 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6017 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6019 DebuggerTlsData *tls;
6024 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6028 tls->filter_state.valid = FALSE;
6032 * buffer_add_value_full:
6034 * Add the encoding of the value at ADDR described by T to the buffer.
6035 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6039 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6040 gboolean as_vtype, GHashTable *parent_vtypes)
6043 gboolean boxed_vtype = FALSE;
6046 if (!(*(void**)addr)) {
6047 /* This can happen with compiler generated locals */
6048 //printf ("%s\n", mono_type_full_name (t));
6049 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6052 g_assert (*(void**)addr);
6053 addr = *(void**)addr;
6058 case MONO_TYPE_BOOLEAN:
6061 case MONO_TYPE_CHAR:
6081 case MONO_TYPE_VOID:
6082 buffer_add_byte (buf, t->type);
6084 case MONO_TYPE_BOOLEAN:
6087 buffer_add_byte (buf, t->type);
6088 buffer_add_int (buf, *(gint8*)addr);
6090 case MONO_TYPE_CHAR:
6093 buffer_add_byte (buf, t->type);
6094 buffer_add_int (buf, *(gint16*)addr);
6099 buffer_add_byte (buf, t->type);
6100 buffer_add_int (buf, *(gint32*)addr);
6105 buffer_add_byte (buf, t->type);
6106 buffer_add_long (buf, *(gint64*)addr);
6110 /* Treat it as a vtype */
6112 case MONO_TYPE_PTR: {
6113 gssize val = *(gssize*)addr;
6115 buffer_add_byte (buf, t->type);
6116 buffer_add_long (buf, val);
6120 case MONO_TYPE_STRING:
6121 case MONO_TYPE_SZARRAY:
6122 case MONO_TYPE_OBJECT:
6123 case MONO_TYPE_CLASS:
6124 case MONO_TYPE_ARRAY:
6125 obj = *(MonoObject**)addr;
6128 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6130 if (obj->vtable->klass->valuetype) {
6131 t = &obj->vtable->klass->byval_arg;
6132 addr = mono_object_unbox (obj);
6135 } else if (obj->vtable->klass->rank) {
6136 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6137 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6138 buffer_add_byte (buf, MONO_TYPE_CLASS);
6140 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6142 buffer_add_objid (buf, obj);
6146 case MONO_TYPE_VALUETYPE:
6147 case MONO_TYPE_TYPEDBYREF: {
6151 MonoClass *klass = mono_class_from_mono_type (t);
6156 * Handle boxed vtypes recursively referencing themselves using fields.
6159 parent_vtypes = g_hash_table_new (NULL, NULL);
6160 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6162 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6163 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6164 buffer_add_int (buf, vtype_index - 1);
6166 /* The client can't handle PARENT_VTYPE */
6167 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6171 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6175 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6176 buffer_add_byte (buf, klass->enumtype);
6177 buffer_add_typeid (buf, domain, klass);
6181 while ((f = mono_class_get_fields (klass, &iter))) {
6182 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6184 if (mono_field_is_deleted (f))
6188 buffer_add_int (buf, nfields);
6191 while ((f = mono_class_get_fields (klass, &iter))) {
6192 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6194 if (mono_field_is_deleted (f))
6196 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6200 g_hash_table_remove (parent_vtypes, addr);
6201 if (g_hash_table_size (parent_vtypes) == 0) {
6202 g_hash_table_destroy (parent_vtypes);
6203 parent_vtypes = NULL;
6208 case MONO_TYPE_GENERICINST:
6209 if (mono_type_generic_inst_is_valuetype (t)) {
6221 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6223 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6227 obj_is_of_type (MonoObject *obj, MonoType *t)
6229 MonoClass *klass = obj->vtable->klass;
6230 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6231 if (mono_class_is_transparent_proxy (klass)) {
6232 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6233 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6243 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6246 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6252 gpointer iter = NULL;
6256 is_enum = decode_byte (buf, &buf, limit);
6257 /* Enums are sent as a normal vtype */
6259 return ERR_NOT_IMPLEMENTED;
6260 klass = decode_typeid (buf, &buf, limit, &d, &err);
6261 if (err != ERR_NONE)
6264 if (t && klass != mono_class_from_mono_type (t)) {
6265 char *name = mono_type_full_name (t);
6266 char *name2 = mono_type_full_name (&klass->byval_arg);
6267 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6270 return ERR_INVALID_ARGUMENT;
6273 nfields = decode_int (buf, &buf, limit);
6274 while ((f = mono_class_get_fields (klass, &iter))) {
6275 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6277 if (mono_field_is_deleted (f))
6279 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6280 if (err != ERR_NONE)
6284 g_assert (nfields == 0);
6292 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6296 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6297 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6298 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6299 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6300 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6301 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6302 char *name = mono_type_full_name (t);
6303 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6305 return ERR_INVALID_ARGUMENT;
6309 case MONO_TYPE_BOOLEAN:
6310 *(guint8*)addr = decode_int (buf, &buf, limit);
6312 case MONO_TYPE_CHAR:
6313 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6316 *(gint8*)addr = decode_int (buf, &buf, limit);
6319 *(guint8*)addr = decode_int (buf, &buf, limit);
6322 *(gint16*)addr = decode_int (buf, &buf, limit);
6325 *(guint16*)addr = decode_int (buf, &buf, limit);
6328 *(gint32*)addr = decode_int (buf, &buf, limit);
6331 *(guint32*)addr = decode_int (buf, &buf, limit);
6334 *(gint64*)addr = decode_long (buf, &buf, limit);
6337 *(guint64*)addr = decode_long (buf, &buf, limit);
6340 *(guint32*)addr = decode_int (buf, &buf, limit);
6343 *(guint64*)addr = decode_long (buf, &buf, limit);
6346 /* We send these as I8, so we get them back as such */
6347 g_assert (type == MONO_TYPE_I8);
6348 *(gssize*)addr = decode_long (buf, &buf, limit);
6350 case MONO_TYPE_GENERICINST:
6351 if (MONO_TYPE_ISSTRUCT (t)) {
6352 /* The client sends these as a valuetype */
6360 /* We send these as vtypes, so we get them back as such */
6361 g_assert (type == MONO_TYPE_VALUETYPE);
6364 case MONO_TYPE_VALUETYPE:
6365 if (type == MONO_TYPE_OBJECT) {
6367 int objid = decode_objid (buf, &buf, limit);
6371 err = get_object (objid, (MonoObject**)&obj);
6372 if (err != ERR_NONE)
6375 return ERR_INVALID_ARGUMENT;
6376 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6377 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6378 return ERR_INVALID_ARGUMENT;
6380 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6382 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6383 if (err != ERR_NONE)
6389 if (MONO_TYPE_IS_REFERENCE (t)) {
6390 if (type == MONO_TYPE_OBJECT) {
6391 int objid = decode_objid (buf, &buf, limit);
6395 err = get_object (objid, (MonoObject**)&obj);
6396 if (err != ERR_NONE)
6400 if (!obj_is_of_type (obj, t)) {
6401 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6402 return ERR_INVALID_ARGUMENT;
6405 if (obj && obj->vtable->domain != domain)
6406 return ERR_INVALID_ARGUMENT;
6408 mono_gc_wbarrier_generic_store (addr, obj);
6409 } else if (type == VALUE_TYPE_ID_NULL) {
6410 *(MonoObject**)addr = NULL;
6411 } else if (type == MONO_TYPE_VALUETYPE) {
6420 /* This can happen when round-tripping boxed vtypes */
6422 * Obtain vtype class.
6423 * Same as the beginning of the handle_vtype case above.
6426 is_enum = decode_byte (buf, &buf, limit);
6428 return ERR_NOT_IMPLEMENTED;
6429 klass = decode_typeid (buf, &buf, limit, &d, &err);
6430 if (err != ERR_NONE)
6433 /* Decode the vtype into a temporary buffer, then box it. */
6434 vtype_buf_size = mono_class_value_size (klass, NULL);
6435 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6436 g_assert (vtype_buf);
6439 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6440 if (err != ERR_NONE) {
6444 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6445 mono_error_cleanup (&error);
6448 char *name = mono_type_full_name (t);
6449 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6451 return ERR_INVALID_ARGUMENT;
6465 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6469 int type = decode_byte (buf, &buf, limit);
6471 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6472 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6473 guint8 *nullable_buf;
6476 * First try decoding it as a Nullable`1
6478 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6479 if (err == ERR_NONE)
6483 * Then try decoding as a primitive value or null.
6485 if (targ->type == type) {
6486 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6487 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6488 if (err != ERR_NONE) {
6489 g_free (nullable_buf);
6492 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6493 if (!is_ok (&error)) {
6494 mono_error_cleanup (&error);
6495 return ERR_INVALID_OBJECT;
6497 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6498 g_free (nullable_buf);
6501 } else if (type == VALUE_TYPE_ID_NULL) {
6502 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6508 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6512 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6516 guint8 *addr, *gaddr;
6519 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6520 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6523 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6524 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6526 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6528 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6529 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6530 addr += (gint32)var->offset;
6532 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6534 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6536 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6539 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6540 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6541 /* Same as regoffset, but with an indirection */
6542 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6543 addr += (gint32)var->offset;
6545 gaddr = (guint8 *)*(gpointer*)addr;
6547 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6549 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6550 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6551 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6552 MonoGSharedVtMethodRuntimeInfo *info;
6558 g_assert (info_var);
6559 g_assert (locals_var);
6561 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6562 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6563 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6564 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6565 addr += (gint32)info_var->offset;
6566 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6567 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6568 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6570 g_assert_not_reached ();
6574 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6575 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6576 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6577 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6578 addr += (gint32)locals_var->offset;
6579 locals = (guint8 *)*(gpointer*)addr;
6580 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6581 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6583 g_assert_not_reached ();
6587 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6589 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6594 g_assert_not_reached ();
6599 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6603 guint8 *addr, *gaddr;
6605 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6606 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6608 if (MONO_TYPE_IS_REFERENCE (t))
6609 size = sizeof (gpointer);
6611 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6614 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6615 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6617 gboolean is_signed = FALSE;
6620 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6623 // FIXME: Write barriers
6624 mono_gc_memmove_atomic (addr, val, size);
6629 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6634 v = is_signed ? *(gint8*)val : *(guint8*)val;
6637 v = is_signed ? *(gint16*)val : *(guint16*)val;
6640 v = is_signed ? *(gint32*)val : *(guint32*)val;
6643 v = is_signed ? *(gint64*)val : *(guint64*)val;
6646 g_assert_not_reached ();
6649 /* Set value on the stack or in the return ctx */
6650 if (reg_locations [reg]) {
6651 /* Saved on the stack */
6652 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6653 *(reg_locations [reg]) = v;
6656 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6657 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6660 // FIXME: Move these to mono-context.h/c.
6661 mono_arch_context_set_int_reg (ctx, reg, v);
6663 // FIXME: Can't set registers, so we disable linears
6668 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6669 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6670 addr += (gint32)var->offset;
6672 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6675 addr = *(guint8**)addr;
6681 // FIXME: Write barriers
6682 mono_gc_memmove_atomic (addr, val, size);
6684 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6685 /* Same as regoffset, but with an indirection */
6686 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6687 addr += (gint32)var->offset;
6689 gaddr = (guint8 *)*(gpointer*)addr;
6691 // FIXME: Write barriers
6692 mono_gc_memmove_atomic (gaddr, val, size);
6694 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6698 g_assert_not_reached ();
6703 clear_event_request (int req_id, int etype)
6707 mono_loader_lock ();
6708 for (i = 0; i < event_requests->len; ++i) {
6709 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6711 if (req->id == req_id && req->event_kind == etype) {
6712 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6713 clear_breakpoint ((MonoBreakpoint *)req->info);
6714 if (req->event_kind == EVENT_KIND_STEP)
6715 ss_destroy ((SingleStepReq *)req->info);
6716 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6717 clear_breakpoint ((MonoBreakpoint *)req->info);
6718 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6719 clear_breakpoint ((MonoBreakpoint *)req->info);
6720 g_ptr_array_remove_index_fast (event_requests, i);
6725 mono_loader_unlock ();
6729 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6733 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6734 m->kind = MOD_KIND_NONE;
6735 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6736 int count = 0, match_count = 0, pos;
6737 MonoAssembly **newassemblies;
6739 for (i = 0; m->data.assemblies [i]; ++i) {
6741 if (m->data.assemblies [i] == assembly)
6746 // +1 because we don't know length and we use last element to check for end
6747 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6750 for (i = 0; i < count; ++i)
6751 if (m->data.assemblies [i] != assembly)
6752 newassemblies [pos ++] = m->data.assemblies [i];
6753 g_assert (pos == count - match_count);
6754 g_free (m->data.assemblies);
6755 m->data.assemblies = newassemblies;
6761 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6765 for (i = 0; i < req->nmodifiers; ++i) {
6766 Modifier *m = &req->modifiers [i];
6768 clear_assembly_from_modifier (req, m, assembly);
6773 * clear_event_requests_for_assembly:
6775 * Clear all events requests which reference ASSEMBLY.
6778 clear_event_requests_for_assembly (MonoAssembly *assembly)
6783 mono_loader_lock ();
6787 for (i = 0; i < event_requests->len; ++i) {
6788 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6790 clear_assembly_from_modifiers (req, assembly);
6792 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6793 clear_event_request (req->id, req->event_kind);
6798 if (req->event_kind == EVENT_KIND_STEP)
6799 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6802 mono_loader_unlock ();
6806 * type_comes_from_assembly:
6808 * GHRFunc that returns TRUE if klass comes from assembly
6811 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6813 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6817 * clear_types_for_assembly:
6819 * Clears types from loaded_classes for a given assembly
6822 clear_types_for_assembly (MonoAssembly *assembly)
6824 MonoDomain *domain = mono_domain_get ();
6825 AgentDomainInfo *info = NULL;
6827 if (!domain || !domain_jit_info (domain))
6828 /* Can happen during shutdown */
6831 info = get_agent_domain_info (domain);
6833 mono_loader_lock ();
6834 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6835 mono_loader_unlock ();
6839 add_thread (gpointer key, gpointer value, gpointer user_data)
6841 MonoInternalThread *thread = (MonoInternalThread *)value;
6842 Buffer *buf = (Buffer *)user_data;
6844 buffer_add_objid (buf, (MonoObject*)thread);
6848 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6851 guint8 *end = invoke->endp;
6855 MonoMethodSignature *sig;
6858 MonoObject *this_arg, *res, *exc;
6861 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6864 MonoStopwatch watch;
6866 if (invoke->method) {
6868 * Invoke this method directly, currently only Environment.Exit () is supported.
6871 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>");
6873 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6874 mono_error_assert_ok (&error);
6876 g_assert_not_reached ();
6879 m = decode_methodid (p, &p, end, &domain, &err);
6880 if (err != ERR_NONE)
6882 sig = mono_method_signature (m);
6884 if (m->klass->valuetype)
6885 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6887 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6888 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6889 /* Should be null */
6890 int type = decode_byte (p, &p, end);
6891 if (type != VALUE_TYPE_ID_NULL) {
6892 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6893 return ERR_INVALID_ARGUMENT;
6895 memset (this_buf, 0, mono_class_instance_size (m->klass));
6896 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6900 int type = decode_byte (p, &tmp_p, end);
6901 if (type == VALUE_TYPE_ID_NULL) {
6902 memset (this_buf, 0, mono_class_instance_size (m->klass));
6905 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6906 if (err != ERR_NONE)
6910 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6911 if (err != ERR_NONE)
6915 if (!m->klass->valuetype)
6916 this_arg = *(MonoObject**)this_buf;
6920 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6922 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6923 return ERR_INVALID_ARGUMENT;
6925 m = mono_object_get_virtual_method (this_arg, m);
6926 /* Transform this to the format the rest of the code expects it to be */
6927 if (m->klass->valuetype) {
6928 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6929 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6931 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6933 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6934 return ERR_INVALID_ARGUMENT;
6936 m = mono_object_get_virtual_method (this_arg, m);
6937 if (m->klass->valuetype) {
6938 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6939 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6943 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>");
6945 if (this_arg && this_arg->vtable->domain != domain)
6948 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6949 if (!strcmp (m->name, ".ctor")) {
6950 if (mono_class_is_abstract (m->klass))
6951 return ERR_INVALID_ARGUMENT;
6954 this_arg = mono_object_new_checked (domain, m->klass, &error);
6955 mono_error_assert_ok (&error);
6958 return ERR_INVALID_ARGUMENT;
6962 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6963 return ERR_INVALID_ARGUMENT;
6965 nargs = decode_int (p, &p, end);
6966 if (nargs != sig->param_count)
6967 return ERR_INVALID_ARGUMENT;
6968 /* Use alloca to get gc tracking */
6969 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6970 memset (arg_buf, 0, nargs * sizeof (gpointer));
6971 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6972 for (i = 0; i < nargs; ++i) {
6973 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6974 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6975 if (err != ERR_NONE)
6977 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6980 if (sig->params [i]->byref) {
6981 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6982 *(gpointer*)arg_buf [i] = args [i];
6983 args [i] = arg_buf [i];
6986 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6987 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6988 if (err != ERR_NONE)
6990 args [i] = arg_buf [i];
6997 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6998 tls->disable_breakpoints = TRUE;
7000 tls->disable_breakpoints = FALSE;
7003 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7005 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7006 if (invoke->has_ctx) {
7009 lmf_addr = mono_get_lmf_addr ();
7012 memset (&ext, 0, sizeof (ext));
7013 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7015 ext.debugger_invoke = TRUE;
7016 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7018 mono_set_lmf ((MonoLMF*)&ext);
7022 mono_stopwatch_start (&watch);
7023 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7024 if (exc == NULL && !mono_error_ok (&error)) {
7025 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7027 mono_error_cleanup (&error); /* FIXME report error */
7029 mono_stopwatch_stop (&watch);
7030 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));
7032 buffer_add_byte (buf, 0);
7033 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7035 gboolean out_this = FALSE;
7036 gboolean out_args = FALSE;
7038 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7040 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7042 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7043 if (sig->ret->type == MONO_TYPE_VOID) {
7044 if (!strcmp (m->name, ".ctor")) {
7045 if (!m->klass->valuetype)
7046 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7048 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7050 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7052 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7053 buffer_add_value (buf, sig->ret, &res, domain);
7054 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7055 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7056 MonoClass *k = mono_class_from_mono_type (sig->ret);
7057 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7059 g_assert (nullable_buf);
7060 mono_nullable_init (nullable_buf, res, k);
7061 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7064 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7070 /* Return the new value of the receiver after the call */
7071 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7073 buffer_add_int (buf, nargs);
7074 for (i = 0; i < nargs; ++i) {
7075 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7076 buffer_add_value (buf, sig->params [i], &args [i], domain);
7077 else if (sig->params [i]->byref)
7078 /* add_value () does an indirection */
7079 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7081 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7086 tls->disable_breakpoints = FALSE;
7088 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7089 if (invoke->has_ctx)
7090 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7094 // FIXME: byref arguments
7102 * Invoke the method given by tls->pending_invoke in the current thread.
7105 invoke_method (void)
7107 DebuggerTlsData *tls;
7113 MonoContext restore_ctx;
7116 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7120 * Store the `InvokeData *' in `tls->invoke' until we're done with
7121 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7124 mono_loader_lock ();
7126 invoke = tls->pending_invoke;
7128 tls->pending_invoke = NULL;
7130 invoke->last_invoke = tls->invoke;
7131 tls->invoke = invoke;
7133 mono_loader_unlock ();
7135 tls->frames_up_to_date = FALSE;
7141 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7142 buffer_init (&buf, 128);
7145 /* Fail the other invokes as well */
7147 err = do_invoke_method (tls, &buf, invoke, p, &p);
7150 if (tls->abort_requested) {
7151 if (CHECK_PROTOCOL_VERSION (2, 42))
7152 err = ERR_INVOKE_ABORTED;
7155 /* Start suspending before sending the reply */
7156 if (mindex == invoke->nmethods - 1) {
7157 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7158 for (i = 0; i < invoke->suspend_count; ++i)
7163 send_reply_packet (id, err, &buf);
7168 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7170 if (invoke->has_ctx)
7171 save_thread_context (&restore_ctx);
7173 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7174 g_assert (tls->resume_count);
7175 tls->resume_count -= invoke->suspend_count;
7178 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7181 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7183 * It is possible that mono_thread_internal_abort () was called
7184 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7185 * because we reset the abort here.
7188 mono_loader_lock ();
7190 if (tls->abort_requested)
7191 mono_thread_internal_reset_abort (tls->thread);
7193 tls->invoke = tls->invoke->last_invoke;
7194 tls->abort_requested = FALSE;
7196 mono_loader_unlock ();
7205 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7207 MonoThread *thread = (MonoThread *)value;
7208 DebuggerTlsData *tls;
7211 mono_loader_lock ();
7212 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7214 res = tls->really_suspended;
7215 mono_loader_unlock ();
7221 get_source_files_for_type (MonoClass *klass)
7223 gpointer iter = NULL;
7225 MonoDebugSourceInfo *sinfo;
7229 files = g_ptr_array_new ();
7231 while ((method = mono_class_get_methods (klass, &iter))) {
7232 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7233 GPtrArray *source_file_list;
7236 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7237 for (j = 0; j < source_file_list->len; ++j) {
7238 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7239 for (i = 0; i < files->len; ++i)
7240 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7242 if (i == files->len)
7243 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7245 g_ptr_array_free (source_file_list, TRUE);
7253 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7256 case CMD_VM_VERSION: {
7257 char *build_info, *version;
7259 build_info = mono_get_runtime_build_info ();
7260 version = g_strdup_printf ("mono %s", build_info);
7262 buffer_add_string (buf, version); /* vm version */
7263 buffer_add_int (buf, MAJOR_VERSION);
7264 buffer_add_int (buf, MINOR_VERSION);
7265 g_free (build_info);
7269 case CMD_VM_SET_PROTOCOL_VERSION: {
7270 major_version = decode_int (p, &p, end);
7271 minor_version = decode_int (p, &p, end);
7272 protocol_version_set = TRUE;
7273 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7276 case CMD_VM_ALL_THREADS: {
7278 mono_loader_lock ();
7279 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7280 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7281 mono_loader_unlock ();
7284 case CMD_VM_SUSPEND:
7286 wait_for_suspend ();
7289 if (suspend_count == 0)
7290 return ERR_NOT_SUSPENDED;
7292 clear_suspended_objs ();
7294 case CMD_VM_DISPOSE:
7295 /* Clear all event requests */
7296 mono_loader_lock ();
7297 while (event_requests->len > 0) {
7298 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7300 clear_event_request (req->id, req->event_kind);
7302 mono_loader_unlock ();
7304 while (suspend_count > 0)
7306 disconnected = TRUE;
7307 vm_start_event_sent = FALSE;
7310 MonoInternalThread *thread;
7311 DebuggerTlsData *tls;
7312 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7313 MonoClass *env_class;
7315 MonoMethod *exit_method = NULL;
7319 exit_code = decode_int (p, &p, end);
7321 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7323 /* Have to send a reply before exiting */
7324 send_reply_packet (id, 0, buf);
7326 /* Clear all event requests */
7327 mono_loader_lock ();
7328 while (event_requests->len > 0) {
7329 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7331 clear_event_request (req->id, req->event_kind);
7333 mono_loader_unlock ();
7336 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7337 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7338 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7339 * better than doing the shutdown ourselves, since it avoids various races.
7343 wait_for_suspend ();
7345 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7346 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7348 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7351 mono_loader_lock ();
7352 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7353 mono_loader_unlock ();
7355 if (thread && exit_method) {
7356 mono_loader_lock ();
7357 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7358 mono_loader_unlock ();
7360 args = g_new0 (gpointer, 1);
7361 args [0] = g_malloc (sizeof (int));
7362 *(int*)(args [0]) = exit_code;
7364 tls->pending_invoke = g_new0 (InvokeData, 1);
7365 tls->pending_invoke->method = exit_method;
7366 tls->pending_invoke->args = args;
7367 tls->pending_invoke->nmethods = 1;
7369 while (suspend_count > 0)
7373 * No thread found, do it ourselves.
7374 * FIXME: This can race with normal shutdown etc.
7376 while (suspend_count > 0)
7379 if (!mono_runtime_try_shutdown ())
7382 mono_environment_exitcode_set (exit_code);
7384 /* Suspend all managed threads since the runtime is going away */
7385 DEBUG_PRINTF (1, "Suspending all threads...\n");
7386 mono_thread_suspend_all_other_threads ();
7387 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7388 mono_runtime_quit ();
7389 transport_close2 ();
7390 DEBUG_PRINTF (1, "Exiting...\n");
7396 case CMD_VM_INVOKE_METHOD:
7397 case CMD_VM_INVOKE_METHODS: {
7398 int objid = decode_objid (p, &p, end);
7400 DebuggerTlsData *tls;
7401 int i, count, flags, nmethods;
7404 err = get_object (objid, (MonoObject**)&thread);
7405 if (err != ERR_NONE)
7408 flags = decode_int (p, &p, end);
7410 if (command == CMD_VM_INVOKE_METHODS)
7411 nmethods = decode_int (p, &p, end);
7415 // Wait for suspending if it already started
7417 wait_for_suspend ();
7418 if (!is_suspended ())
7419 return ERR_NOT_SUSPENDED;
7421 mono_loader_lock ();
7422 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7423 mono_loader_unlock ();
7426 if (!tls->really_suspended)
7427 /* The thread is still running native code, can't do invokes */
7428 return ERR_NOT_SUSPENDED;
7431 * Store the invoke data into tls, the thread will execute it after it is
7434 if (tls->pending_invoke)
7435 return ERR_NOT_SUSPENDED;
7436 tls->pending_invoke = g_new0 (InvokeData, 1);
7437 tls->pending_invoke->id = id;
7438 tls->pending_invoke->flags = flags;
7439 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7440 memcpy (tls->pending_invoke->p, p, end - p);
7441 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7442 tls->pending_invoke->suspend_count = suspend_count;
7443 tls->pending_invoke->nmethods = nmethods;
7445 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7446 resume_thread (THREAD_TO_INTERNAL (thread));
7449 count = suspend_count;
7450 for (i = 0; i < count; ++i)
7455 case CMD_VM_ABORT_INVOKE: {
7456 int objid = decode_objid (p, &p, end);
7458 DebuggerTlsData *tls;
7462 err = get_object (objid, (MonoObject**)&thread);
7463 if (err != ERR_NONE)
7466 invoke_id = decode_int (p, &p, end);
7468 mono_loader_lock ();
7469 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7472 if (tls->abort_requested) {
7473 DEBUG_PRINTF (1, "Abort already requested.\n");
7474 mono_loader_unlock ();
7479 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7480 * actually the correct invocation.
7482 * Careful, we do not stop the thread that's doing the invocation, so we can't
7483 * inspect its stack. However, invoke_method() also acquires the loader lock
7484 * when it's done, so we're safe here.
7488 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7489 mono_loader_unlock ();
7490 return ERR_NO_INVOCATION;
7493 tls->abort_requested = TRUE;
7495 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7496 mono_loader_unlock ();
7500 case CMD_VM_SET_KEEPALIVE: {
7501 int timeout = decode_int (p, &p, end);
7502 agent_config.keepalive = timeout;
7504 #ifndef DISABLE_SOCKET_TRANSPORT
7511 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7512 GHashTableIter iter, kiter;
7517 char *fname, *basename;
7518 gboolean ignore_case;
7519 GSList *class_list, *l;
7520 GPtrArray *res_classes, *res_domains;
7522 fname = decode_string (p, &p, end);
7523 ignore_case = decode_byte (p, &p, end);
7525 basename = dbg_path_get_basename (fname);
7527 res_classes = g_ptr_array_new ();
7528 res_domains = g_ptr_array_new ();
7530 mono_loader_lock ();
7531 g_hash_table_iter_init (&iter, domains);
7532 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7533 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7535 /* Update 'source_file_to_class' cache */
7536 g_hash_table_iter_init (&kiter, info->loaded_classes);
7537 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7538 if (!g_hash_table_lookup (info->source_files, klass)) {
7539 files = get_source_files_for_type (klass);
7540 g_hash_table_insert (info->source_files, klass, files);
7542 for (i = 0; i < files->len; ++i) {
7543 char *s = (char *)g_ptr_array_index (files, i);
7544 char *s2 = dbg_path_get_basename (s);
7547 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7549 class_list = g_slist_prepend (class_list, klass);
7550 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7552 class_list = g_slist_prepend (class_list, klass);
7553 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7556 /* The _ignorecase hash contains the lowercase path */
7557 s3 = strdup_tolower (s2);
7558 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7560 class_list = g_slist_prepend (class_list, klass);
7561 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7563 class_list = g_slist_prepend (class_list, klass);
7564 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7576 s = strdup_tolower (basename);
7577 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7580 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7583 for (l = class_list; l; l = l->next) {
7584 klass = (MonoClass *)l->data;
7586 g_ptr_array_add (res_classes, klass);
7587 g_ptr_array_add (res_domains, domain);
7590 mono_loader_unlock ();
7595 buffer_add_int (buf, res_classes->len);
7596 for (i = 0; i < res_classes->len; ++i)
7597 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7598 g_ptr_array_free (res_classes, TRUE);
7599 g_ptr_array_free (res_domains, TRUE);
7602 case CMD_VM_GET_TYPES: {
7603 GHashTableIter iter;
7607 gboolean ignore_case;
7608 GPtrArray *res_classes, *res_domains;
7609 MonoTypeNameParse info;
7611 name = decode_string (p, &p, end);
7612 ignore_case = decode_byte (p, &p, end);
7614 if (!mono_reflection_parse_type (name, &info)) {
7616 mono_reflection_free_type_info (&info);
7617 return ERR_INVALID_ARGUMENT;
7620 res_classes = g_ptr_array_new ();
7621 res_domains = g_ptr_array_new ();
7623 mono_loader_lock ();
7624 g_hash_table_iter_init (&iter, domains);
7625 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7627 gboolean type_resolve;
7631 mono_domain_assemblies_lock (domain);
7632 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7633 ass = (MonoAssembly *)tmp->data;
7637 type_resolve = TRUE;
7638 /* FIXME really okay to call while holding locks? */
7639 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7640 mono_error_cleanup (&error);
7642 g_ptr_array_add (res_classes, mono_type_get_class (t));
7643 g_ptr_array_add (res_domains, domain);
7647 mono_domain_assemblies_unlock (domain);
7649 mono_loader_unlock ();
7652 mono_reflection_free_type_info (&info);
7654 buffer_add_int (buf, res_classes->len);
7655 for (i = 0; i < res_classes->len; ++i)
7656 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7657 g_ptr_array_free (res_classes, TRUE);
7658 g_ptr_array_free (res_domains, TRUE);
7661 case CMD_VM_START_BUFFERING:
7662 case CMD_VM_STOP_BUFFERING:
7663 /* Handled in the main loop */
7666 return ERR_NOT_IMPLEMENTED;
7673 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7679 case CMD_EVENT_REQUEST_SET: {
7681 int i, event_kind, suspend_policy, nmodifiers;
7685 MonoThread *step_thread;
7686 int step_thread_id = 0;
7687 StepDepth depth = STEP_DEPTH_INTO;
7688 StepSize size = STEP_SIZE_MIN;
7689 StepFilter filter = STEP_FILTER_NONE;
7693 event_kind = decode_byte (p, &p, end);
7694 suspend_policy = decode_byte (p, &p, end);
7695 nmodifiers = decode_byte (p, &p, end);
7697 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7698 req->id = InterlockedIncrement (&event_request_id);
7699 req->event_kind = event_kind;
7700 req->suspend_policy = suspend_policy;
7701 req->nmodifiers = nmodifiers;
7704 for (i = 0; i < nmodifiers; ++i) {
7705 mod = (ModifierKind)decode_byte (p, &p, end);
7707 req->modifiers [i].kind = mod;
7708 if (mod == MOD_KIND_COUNT) {
7709 req->modifiers [i].data.count = decode_int (p, &p, end);
7710 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7711 method = decode_methodid (p, &p, end, &domain, &err);
7712 if (err != ERR_NONE)
7714 location = decode_long (p, &p, end);
7715 } else if (mod == MOD_KIND_STEP) {
7716 step_thread_id = decode_id (p, &p, end);
7717 size = (StepSize)decode_int (p, &p, end);
7718 depth = (StepDepth)decode_int (p, &p, end);
7719 if (CHECK_PROTOCOL_VERSION (2, 16))
7720 filter = (StepFilter)decode_int (p, &p, end);
7721 req->modifiers [i].data.filter = filter;
7722 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7723 /* Treat STEP_THOUGH the same as HIDDEN */
7724 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7725 } else if (mod == MOD_KIND_THREAD_ONLY) {
7726 int id = decode_id (p, &p, end);
7728 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7729 if (err != ERR_NONE) {
7733 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7734 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7736 if (err != ERR_NONE)
7738 req->modifiers [i].caught = decode_byte (p, &p, end);
7739 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7740 if (CHECK_PROTOCOL_VERSION (2, 25))
7741 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7743 req->modifiers [i].subclasses = TRUE;
7744 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" : "");
7746 req->modifiers [i].data.exc_class = exc_class;
7748 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7750 return ERR_INVALID_ARGUMENT;
7753 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7754 int n = decode_int (p, &p, end);
7757 // +1 because we don't know length and we use last element to check for end
7758 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7759 for (j = 0; j < n; ++j) {
7760 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7761 if (err != ERR_NONE) {
7762 g_free (req->modifiers [i].data.assemblies);
7766 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7767 int n = decode_int (p, &p, end);
7770 modifier = &req->modifiers [i];
7771 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7772 for (j = 0; j < n; ++j) {
7773 char *s = decode_string (p, &p, end);
7777 s2 = strdup_tolower (s);
7778 g_hash_table_insert (modifier->data.source_files, s2, s2);
7782 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7783 int n = decode_int (p, &p, end);
7786 modifier = &req->modifiers [i];
7787 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7788 for (j = 0; j < n; ++j) {
7789 char *s = decode_string (p, &p, end);
7792 g_hash_table_insert (modifier->data.type_names, s, s);
7796 return ERR_NOT_IMPLEMENTED;
7800 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7803 req->info = set_breakpoint (method, location, req, &error);
7804 if (!mono_error_ok (&error)) {
7806 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7807 mono_error_cleanup (&error);
7808 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7810 } else if (req->event_kind == EVENT_KIND_STEP) {
7811 g_assert (step_thread_id);
7813 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7814 if (err != ERR_NONE) {
7819 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7820 if (err != ERR_NONE) {
7824 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7825 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7826 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7827 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7828 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7829 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7831 if (req->nmodifiers) {
7833 return ERR_NOT_IMPLEMENTED;
7837 mono_loader_lock ();
7838 g_ptr_array_add (event_requests, req);
7840 if (agent_config.defer) {
7841 /* Transmit cached data to the client on receipt of the event request */
7842 switch (req->event_kind) {
7843 case EVENT_KIND_APPDOMAIN_CREATE:
7844 /* Emit load events for currently loaded domains */
7845 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7847 case EVENT_KIND_ASSEMBLY_LOAD:
7848 /* Emit load events for currently loaded assemblies */
7849 mono_domain_foreach (send_assemblies_for_domain, NULL);
7851 case EVENT_KIND_THREAD_START:
7852 /* Emit start events for currently started threads */
7853 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7855 case EVENT_KIND_TYPE_LOAD:
7856 /* Emit type load events for currently loaded types */
7857 mono_domain_foreach (send_types_for_domain, NULL);
7863 mono_loader_unlock ();
7865 buffer_add_int (buf, req->id);
7868 case CMD_EVENT_REQUEST_CLEAR: {
7869 int etype = decode_byte (p, &p, end);
7870 int req_id = decode_int (p, &p, end);
7872 // FIXME: Make a faster mapping from req_id to request
7873 mono_loader_lock ();
7874 clear_event_request (req_id, etype);
7875 mono_loader_unlock ();
7878 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7881 mono_loader_lock ();
7883 while (i < event_requests->len) {
7884 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7886 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7887 clear_breakpoint ((MonoBreakpoint *)req->info);
7889 g_ptr_array_remove_index_fast (event_requests, i);
7895 mono_loader_unlock ();
7899 return ERR_NOT_IMPLEMENTED;
7906 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7912 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7913 buffer_add_domainid (buf, mono_get_root_domain ());
7916 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7917 domain = decode_domainid (p, &p, end, NULL, &err);
7918 if (err != ERR_NONE)
7920 buffer_add_string (buf, domain->friendly_name);
7923 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7928 domain = decode_domainid (p, &p, end, NULL, &err);
7929 if (err != ERR_NONE)
7931 mono_loader_lock ();
7933 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7936 buffer_add_int (buf, count);
7937 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7938 ass = (MonoAssembly *)tmp->data;
7939 buffer_add_assemblyid (buf, domain, ass);
7941 mono_loader_unlock ();
7944 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7945 domain = decode_domainid (p, &p, end, NULL, &err);
7946 if (err != ERR_NONE)
7949 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7952 case CMD_APPDOMAIN_GET_CORLIB: {
7953 domain = decode_domainid (p, &p, end, NULL, &err);
7954 if (err != ERR_NONE)
7957 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7960 case CMD_APPDOMAIN_CREATE_STRING: {
7964 domain = decode_domainid (p, &p, end, NULL, &err);
7965 if (err != ERR_NONE)
7967 s = decode_string (p, &p, end);
7969 o = mono_string_new (domain, s);
7970 buffer_add_objid (buf, (MonoObject*)o);
7973 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7976 MonoDomain *domain2;
7979 domain = decode_domainid (p, &p, end, NULL, &err);
7980 if (err != ERR_NONE)
7982 klass = decode_typeid (p, &p, end, &domain2, &err);
7983 if (err != ERR_NONE)
7987 g_assert (domain == domain2);
7989 o = mono_object_new_checked (domain, klass, &error);
7990 mono_error_assert_ok (&error);
7992 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7993 if (err != ERR_NONE)
7996 buffer_add_objid (buf, o);
8000 return ERR_NOT_IMPLEMENTED;
8007 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8009 HANDLE_FUNCTION_ENTER();
8010 ErrorCode err = ERR_NONE;
8011 mono_error_init (error);
8012 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8013 if (MONO_HANDLE_IS_NULL (o)) {
8014 err = ERR_INVALID_OBJECT;
8017 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8019 HANDLE_FUNCTION_RETURN_VAL (err);
8024 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8030 ass = decode_assemblyid (p, &p, end, &domain, &err);
8031 if (err != ERR_NONE)
8035 case CMD_ASSEMBLY_GET_LOCATION: {
8036 buffer_add_string (buf, mono_image_get_filename (ass->image));
8039 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8043 if (ass->image->dynamic) {
8044 buffer_add_id (buf, 0);
8046 token = mono_image_get_entry_point (ass->image);
8048 buffer_add_id (buf, 0);
8051 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8053 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8054 buffer_add_methodid (buf, domain, m);
8059 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8060 buffer_add_moduleid (buf, domain, ass->image);
8063 case CMD_ASSEMBLY_GET_OBJECT: {
8065 err = get_assembly_object_command (domain, ass, buf, &error);
8066 mono_error_cleanup (&error);
8069 case CMD_ASSEMBLY_GET_DOMAIN: {
8070 buffer_add_domainid (buf, domain);
8073 case CMD_ASSEMBLY_GET_TYPE: {
8075 char *s = decode_string (p, &p, end);
8076 gboolean ignorecase = decode_byte (p, &p, end);
8077 MonoTypeNameParse info;
8079 gboolean type_resolve, res;
8080 MonoDomain *d = mono_domain_get ();
8082 /* This is needed to be able to find referenced assemblies */
8083 res = mono_domain_set (domain, FALSE);
8086 if (!mono_reflection_parse_type (s, &info)) {
8089 if (info.assembly.name)
8091 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8092 if (!is_ok (&error)) {
8093 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8094 mono_reflection_free_type_info (&info);
8096 return ERR_INVALID_ARGUMENT;
8099 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8100 mono_reflection_free_type_info (&info);
8103 mono_domain_set (d, TRUE);
8107 case CMD_ASSEMBLY_GET_NAME: {
8109 MonoAssembly *mass = ass;
8111 name = g_strdup_printf (
8112 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8114 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8115 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8116 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8117 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8119 buffer_add_string (buf, name);
8124 return ERR_NOT_IMPLEMENTED;
8131 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8137 case CMD_MODULE_GET_INFO: {
8138 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8141 basename = g_path_get_basename (image->name);
8142 buffer_add_string (buf, basename); // name
8143 buffer_add_string (buf, image->module_name); // scopename
8144 buffer_add_string (buf, image->name); // fqname
8145 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8146 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8151 return ERR_NOT_IMPLEMENTED;
8158 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8164 case CMD_FIELD_GET_INFO: {
8165 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8167 buffer_add_string (buf, f->name);
8168 buffer_add_typeid (buf, domain, f->parent);
8169 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8170 buffer_add_int (buf, f->type->attrs);
8174 return ERR_NOT_IMPLEMENTED;
8181 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8183 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8184 /* Special case these so the client doesn't have to handle Type objects */
8186 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8187 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8188 } else if (MONO_TYPE_IS_REFERENCE (t))
8189 buffer_add_value (buf, t, &val, domain);
8191 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8195 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8201 buffer_add_int (buf, 0);
8205 for (i = 0; i < cinfo->num_attrs; ++i) {
8206 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8209 buffer_add_int (buf, nattrs);
8211 for (i = 0; i < cinfo->num_attrs; ++i) {
8212 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8213 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8214 MonoArray *typed_args, *named_args;
8216 CattrNamedArg *arginfo = NULL;
8219 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8220 if (!mono_error_ok (&error)) {
8221 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8222 mono_error_cleanup (&error);
8223 return ERR_LOADER_ERROR;
8226 buffer_add_methodid (buf, domain, attr->ctor);
8230 buffer_add_int (buf, mono_array_length (typed_args));
8231 for (j = 0; j < mono_array_length (typed_args); ++j) {
8232 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8234 t = mono_method_signature (attr->ctor)->params [j];
8236 buffer_add_cattr_arg (buf, t, domain, val);
8239 buffer_add_int (buf, 0);
8244 buffer_add_int (buf, mono_array_length (named_args));
8246 for (j = 0; j < mono_array_length (named_args); ++j) {
8247 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8249 if (arginfo [j].prop) {
8250 buffer_add_byte (buf, 0x54);
8251 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8252 } else if (arginfo [j].field) {
8253 buffer_add_byte (buf, 0x53);
8254 buffer_add_fieldid (buf, domain, arginfo [j].field);
8256 g_assert_not_reached ();
8259 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8262 buffer_add_int (buf, 0);
8271 /* FIXME: Code duplication with icall.c */
8273 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8278 mono_class_setup_interfaces (klass, error);
8279 if (!mono_error_ok (error))
8282 for (i = 0; i < klass->interface_count; i++) {
8283 ic = klass->interfaces [i];
8284 g_hash_table_insert (ifaces, ic, ic);
8286 collect_interfaces (ic, ifaces, error);
8287 if (!mono_error_ok (error))
8293 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8305 case CMD_TYPE_GET_INFO: {
8306 buffer_add_string (buf, klass->name_space);
8307 buffer_add_string (buf, klass->name);
8309 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8310 buffer_add_string (buf, name);
8312 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8313 buffer_add_moduleid (buf, domain, klass->image);
8314 buffer_add_typeid (buf, domain, klass->parent);
8315 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8316 buffer_add_typeid (buf, domain, klass->element_class);
8318 buffer_add_id (buf, 0);
8319 buffer_add_int (buf, klass->type_token);
8320 buffer_add_byte (buf, klass->rank);
8321 buffer_add_int (buf, mono_class_get_flags (klass));
8323 type = &klass->byval_arg;
8324 // FIXME: Can't decide whenever a class represents a byref type
8327 if (type->type == MONO_TYPE_PTR)
8329 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8331 if (type->type == MONO_TYPE_VALUETYPE)
8333 if (klass->enumtype)
8335 if (mono_class_is_gtd (klass))
8337 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8339 buffer_add_byte (buf, b);
8342 while ((nested = mono_class_get_nested_types (klass, &iter)))
8344 buffer_add_int (buf, nnested);
8346 while ((nested = mono_class_get_nested_types (klass, &iter)))
8347 buffer_add_typeid (buf, domain, nested);
8348 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8349 if (mono_class_is_gtd (klass))
8350 buffer_add_typeid (buf, domain, klass);
8351 else if (mono_class_is_ginst (klass))
8352 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8354 buffer_add_id (buf, 0);
8356 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8359 if (mono_class_is_ginst (klass)) {
8360 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8362 count = inst->type_argc;
8363 buffer_add_int (buf, count);
8364 for (i = 0; i < count; i++)
8365 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8366 } else if (mono_class_is_gtd (klass)) {
8367 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8370 count = container->type_argc;
8371 buffer_add_int (buf, count);
8372 for (i = 0; i < count; i++) {
8373 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8374 buffer_add_typeid (buf, domain, pklass);
8377 buffer_add_int (buf, 0);
8382 case CMD_TYPE_GET_METHODS: {
8385 gpointer iter = NULL;
8388 mono_class_setup_methods (klass);
8390 nmethods = mono_class_num_methods (klass);
8392 buffer_add_int (buf, nmethods);
8394 while ((m = mono_class_get_methods (klass, &iter))) {
8395 buffer_add_methodid (buf, domain, m);
8398 g_assert (i == nmethods);
8401 case CMD_TYPE_GET_FIELDS: {
8404 gpointer iter = NULL;
8407 nfields = mono_class_num_fields (klass);
8409 buffer_add_int (buf, nfields);
8411 while ((f = mono_class_get_fields (klass, &iter))) {
8412 buffer_add_fieldid (buf, domain, f);
8413 buffer_add_string (buf, f->name);
8414 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8415 buffer_add_int (buf, f->type->attrs);
8418 g_assert (i == nfields);
8421 case CMD_TYPE_GET_PROPERTIES: {
8424 gpointer iter = NULL;
8427 nprops = mono_class_num_properties (klass);
8429 buffer_add_int (buf, nprops);
8431 while ((p = mono_class_get_properties (klass, &iter))) {
8432 buffer_add_propertyid (buf, domain, p);
8433 buffer_add_string (buf, p->name);
8434 buffer_add_methodid (buf, domain, p->get);
8435 buffer_add_methodid (buf, domain, p->set);
8436 buffer_add_int (buf, p->attrs);
8439 g_assert (i == nprops);
8442 case CMD_TYPE_GET_CATTRS: {
8443 MonoClass *attr_klass;
8444 MonoCustomAttrInfo *cinfo;
8446 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8447 /* attr_klass can be NULL */
8448 if (err != ERR_NONE)
8451 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8452 if (!is_ok (&error)) {
8453 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8454 return ERR_LOADER_ERROR;
8457 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8458 if (err != ERR_NONE)
8462 case CMD_TYPE_GET_FIELD_CATTRS: {
8463 MonoClass *attr_klass;
8464 MonoCustomAttrInfo *cinfo;
8465 MonoClassField *field;
8467 field = decode_fieldid (p, &p, end, NULL, &err);
8468 if (err != ERR_NONE)
8470 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8471 if (err != ERR_NONE)
8474 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8475 if (!is_ok (&error)) {
8476 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8477 return ERR_LOADER_ERROR;
8480 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8481 if (err != ERR_NONE)
8485 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8486 MonoClass *attr_klass;
8487 MonoCustomAttrInfo *cinfo;
8490 prop = decode_propertyid (p, &p, end, NULL, &err);
8491 if (err != ERR_NONE)
8493 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8494 if (err != ERR_NONE)
8497 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8498 if (!is_ok (&error)) {
8499 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8500 return ERR_LOADER_ERROR;
8503 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8504 if (err != ERR_NONE)
8508 case CMD_TYPE_GET_VALUES:
8509 case CMD_TYPE_GET_VALUES_2: {
8516 MonoThread *thread_obj;
8517 MonoInternalThread *thread = NULL;
8518 guint32 special_static_type;
8520 if (command == CMD_TYPE_GET_VALUES_2) {
8521 int objid = decode_objid (p, &p, end);
8524 err = get_object (objid, (MonoObject**)&thread_obj);
8525 if (err != ERR_NONE)
8528 thread = THREAD_TO_INTERNAL (thread_obj);
8531 len = decode_int (p, &p, end);
8532 for (i = 0; i < len; ++i) {
8533 f = decode_fieldid (p, &p, end, NULL, &err);
8534 if (err != ERR_NONE)
8537 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8538 return ERR_INVALID_FIELDID;
8539 special_static_type = mono_class_field_get_special_static_type (f);
8540 if (special_static_type != SPECIAL_STATIC_NONE) {
8541 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8542 return ERR_INVALID_FIELDID;
8545 /* Check that the field belongs to the object */
8547 for (k = klass; k; k = k->parent) {
8548 if (k == f->parent) {
8554 return ERR_INVALID_FIELDID;
8556 vtable = mono_class_vtable (domain, f->parent);
8557 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8558 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8559 if (!is_ok (&error))
8560 return ERR_INVALID_FIELDID;
8561 buffer_add_value (buf, f->type, val, domain);
8566 case CMD_TYPE_SET_VALUES: {
8574 len = decode_int (p, &p, end);
8575 for (i = 0; i < len; ++i) {
8576 f = decode_fieldid (p, &p, end, NULL, &err);
8577 if (err != ERR_NONE)
8580 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8581 return ERR_INVALID_FIELDID;
8582 if (mono_class_field_is_special_static (f))
8583 return ERR_INVALID_FIELDID;
8585 /* Check that the field belongs to the object */
8587 for (k = klass; k; k = k->parent) {
8588 if (k == f->parent) {
8594 return ERR_INVALID_FIELDID;
8596 // FIXME: Check for literal/const
8598 vtable = mono_class_vtable (domain, f->parent);
8599 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8600 err = decode_value (f->type, domain, val, p, &p, end);
8601 if (err != ERR_NONE) {
8605 if (MONO_TYPE_IS_REFERENCE (f->type))
8606 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8608 mono_field_static_set_value (vtable, f, val);
8613 case CMD_TYPE_GET_OBJECT: {
8614 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8615 if (!mono_error_ok (&error)) {
8616 mono_error_cleanup (&error);
8617 return ERR_INVALID_OBJECT;
8619 buffer_add_objid (buf, o);
8622 case CMD_TYPE_GET_SOURCE_FILES:
8623 case CMD_TYPE_GET_SOURCE_FILES_2: {
8624 char *source_file, *base;
8628 files = get_source_files_for_type (klass);
8630 buffer_add_int (buf, files->len);
8631 for (i = 0; i < files->len; ++i) {
8632 source_file = (char *)g_ptr_array_index (files, i);
8633 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8634 buffer_add_string (buf, source_file);
8636 base = dbg_path_get_basename (source_file);
8637 buffer_add_string (buf, base);
8640 g_free (source_file);
8642 g_ptr_array_free (files, TRUE);
8645 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8646 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8648 if (err != ERR_NONE)
8650 if (mono_class_is_assignable_from (klass, oklass))
8651 buffer_add_byte (buf, 1);
8653 buffer_add_byte (buf, 0);
8656 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8657 char *name = decode_string (p, &p, end);
8658 int i, flags = decode_int (p, &p, end);
8662 mono_error_init (&error);
8663 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8664 if (!is_ok (&error)) {
8665 mono_error_cleanup (&error);
8666 return ERR_LOADER_ERROR;
8668 buffer_add_int (buf, array->len);
8669 for (i = 0; i < array->len; ++i) {
8670 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8671 buffer_add_methodid (buf, domain, method);
8674 g_ptr_array_free (array, TRUE);
8678 case CMD_TYPE_GET_INTERFACES: {
8680 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8681 MonoClass *tclass, *iface;
8682 GHashTableIter iter;
8686 for (parent = tclass; parent; parent = parent->parent) {
8687 mono_class_setup_interfaces (parent, &error);
8688 if (!mono_error_ok (&error))
8689 return ERR_LOADER_ERROR;
8690 collect_interfaces (parent, iface_hash, &error);
8691 if (!mono_error_ok (&error))
8692 return ERR_LOADER_ERROR;
8695 buffer_add_int (buf, g_hash_table_size (iface_hash));
8697 g_hash_table_iter_init (&iter, iface_hash);
8698 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8699 buffer_add_typeid (buf, domain, iface);
8700 g_hash_table_destroy (iface_hash);
8703 case CMD_TYPE_GET_INTERFACE_MAP: {
8704 int tindex, ioffset;
8705 gboolean variance_used;
8707 int len, nmethods, i;
8711 len = decode_int (p, &p, end);
8712 mono_class_setup_vtable (klass);
8714 for (tindex = 0; tindex < len; ++tindex) {
8715 iclass = decode_typeid (p, &p, end, NULL, &err);
8716 if (err != ERR_NONE)
8719 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8721 return ERR_INVALID_ARGUMENT;
8723 nmethods = mono_class_num_methods (iclass);
8724 buffer_add_int (buf, nmethods);
8727 while ((method = mono_class_get_methods (iclass, &iter))) {
8728 buffer_add_methodid (buf, domain, method);
8730 for (i = 0; i < nmethods; ++i)
8731 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8735 case CMD_TYPE_IS_INITIALIZED: {
8736 MonoVTable *vtable = mono_class_vtable (domain, klass);
8739 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8741 buffer_add_int (buf, 0);
8744 case CMD_TYPE_CREATE_INSTANCE: {
8748 obj = mono_object_new_checked (domain, klass, &error);
8749 mono_error_assert_ok (&error);
8750 buffer_add_objid (buf, obj);
8754 return ERR_NOT_IMPLEMENTED;
8761 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8764 MonoDomain *old_domain;
8768 klass = decode_typeid (p, &p, end, &domain, &err);
8769 if (err != ERR_NONE)
8772 old_domain = mono_domain_get ();
8774 mono_domain_set (domain, TRUE);
8776 err = type_commands_internal (command, klass, domain, p, end, buf);
8778 mono_domain_set (old_domain, TRUE);
8784 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8786 MonoMethodHeader *header;
8790 case CMD_METHOD_GET_NAME: {
8791 buffer_add_string (buf, method->name);
8794 case CMD_METHOD_GET_DECLARING_TYPE: {
8795 buffer_add_typeid (buf, domain, method->klass);
8798 case CMD_METHOD_GET_DEBUG_INFO: {
8800 MonoDebugMethodInfo *minfo;
8802 int i, j, n_il_offsets;
8804 GPtrArray *source_file_list;
8805 MonoSymSeqPoint *sym_seq_points;
8807 header = mono_method_get_header_checked (method, &error);
8809 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8810 buffer_add_int (buf, 0);
8811 buffer_add_string (buf, "");
8812 buffer_add_int (buf, 0);
8816 minfo = mono_debug_lookup_method (method);
8818 buffer_add_int (buf, header->code_size);
8819 buffer_add_string (buf, "");
8820 buffer_add_int (buf, 0);
8821 mono_metadata_free_mh (header);
8825 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8826 buffer_add_int (buf, header->code_size);
8827 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8828 buffer_add_int (buf, source_file_list->len);
8829 for (i = 0; i < source_file_list->len; ++i) {
8830 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8831 buffer_add_string (buf, sinfo->source_file);
8832 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8833 for (j = 0; j < 16; ++j)
8834 buffer_add_byte (buf, sinfo->hash [j]);
8838 buffer_add_string (buf, source_file);
8840 buffer_add_int (buf, n_il_offsets);
8841 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8842 for (i = 0; i < n_il_offsets; ++i) {
8843 MonoSymSeqPoint *sp = &sym_seq_points [i];
8844 const char *srcfile = "";
8846 if (source_files [i] != -1) {
8847 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8848 srcfile = sinfo->source_file;
8850 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);
8851 buffer_add_int (buf, sp->il_offset);
8852 buffer_add_int (buf, sp->line);
8853 if (CHECK_PROTOCOL_VERSION (2, 13))
8854 buffer_add_int (buf, source_files [i]);
8855 if (CHECK_PROTOCOL_VERSION (2, 19))
8856 buffer_add_int (buf, sp->column);
8857 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8858 buffer_add_int (buf, sp->end_line);
8859 buffer_add_int (buf, sp->end_column);
8862 g_free (source_file);
8863 g_free (source_files);
8864 g_free (sym_seq_points);
8865 g_ptr_array_free (source_file_list, TRUE);
8866 mono_metadata_free_mh (header);
8869 case CMD_METHOD_GET_PARAM_INFO: {
8870 MonoMethodSignature *sig = mono_method_signature (method);
8874 /* FIXME: mono_class_from_mono_type () and byrefs */
8876 /* FIXME: Use a smaller encoding */
8877 buffer_add_int (buf, sig->call_convention);
8878 buffer_add_int (buf, sig->param_count);
8879 buffer_add_int (buf, sig->generic_param_count);
8880 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8881 for (i = 0; i < sig->param_count; ++i) {
8883 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8886 /* Emit parameter names */
8887 names = g_new (char *, sig->param_count);
8888 mono_method_get_param_names (method, (const char **) names);
8889 for (i = 0; i < sig->param_count; ++i)
8890 buffer_add_string (buf, names [i]);
8895 case CMD_METHOD_GET_LOCALS_INFO: {
8898 MonoDebugLocalsInfo *locals;
8899 int *locals_map = NULL;
8901 header = mono_method_get_header_checked (method, &error);
8903 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8904 return ERR_INVALID_ARGUMENT;
8907 locals = mono_debug_lookup_locals (method);
8909 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8911 buffer_add_int (buf, 1);
8912 buffer_add_int (buf, 0);
8913 buffer_add_int (buf, header->code_size);
8915 buffer_add_int (buf, header->num_locals);
8917 for (i = 0; i < header->num_locals; ++i) {
8918 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8921 for (i = 0; i < header->num_locals; ++i) {
8923 sprintf (lname, "V_%d", i);
8924 buffer_add_string (buf, lname);
8927 for (i = 0; i < header->num_locals; ++i) {
8928 buffer_add_int (buf, 0);
8929 buffer_add_int (buf, header->code_size);
8932 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8934 buffer_add_int (buf, locals->num_blocks);
8936 for (i = 0; i < locals->num_blocks; ++i) {
8937 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8938 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8939 last_start = locals->code_blocks [i].start_offset;
8943 num_locals = locals->num_locals;
8944 buffer_add_int (buf, num_locals);
8947 for (i = 0; i < num_locals; ++i) {
8948 g_assert (locals->locals [i].index < header->num_locals);
8949 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8952 for (i = 0; i < num_locals; ++i)
8953 buffer_add_string (buf, locals->locals [i].name);
8955 for (i = 0; i < num_locals; ++i) {
8956 if (locals->locals [i].block) {
8957 buffer_add_int (buf, locals->locals [i].block->start_offset);
8958 buffer_add_int (buf, locals->locals [i].block->end_offset);
8960 buffer_add_int (buf, 0);
8961 buffer_add_int (buf, header->code_size);
8965 mono_metadata_free_mh (header);
8968 mono_debug_free_locals (locals);
8969 g_free (locals_map);
8973 case CMD_METHOD_GET_INFO:
8974 buffer_add_int (buf, method->flags);
8975 buffer_add_int (buf, method->iflags);
8976 buffer_add_int (buf, method->token);
8977 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8979 if (method->is_generic)
8981 if (mono_method_signature (method)->generic_param_count)
8983 buffer_add_byte (buf, attrs);
8984 if (method->is_generic || method->is_inflated) {
8987 if (method->is_generic) {
8990 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8992 result = imethod->declaring;
8993 if (imethod->context.class_inst) {
8994 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8995 /*Generic methods gets the context of the GTD.*/
8996 if (mono_class_get_context (klass)) {
8998 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8999 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9004 buffer_add_methodid (buf, domain, result);
9006 buffer_add_id (buf, 0);
9008 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9009 if (mono_method_signature (method)->generic_param_count) {
9012 if (method->is_inflated) {
9013 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9015 count = inst->type_argc;
9016 buffer_add_int (buf, count);
9018 for (i = 0; i < count; i++)
9019 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9021 buffer_add_int (buf, 0);
9023 } else if (method->is_generic) {
9024 MonoGenericContainer *container = mono_method_get_generic_container (method);
9026 count = mono_method_signature (method)->generic_param_count;
9027 buffer_add_int (buf, count);
9028 for (i = 0; i < count; i++) {
9029 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9030 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9031 buffer_add_typeid (buf, domain, pklass);
9034 buffer_add_int (buf, 0);
9037 buffer_add_int (buf, 0);
9042 case CMD_METHOD_GET_BODY: {
9046 header = mono_method_get_header_checked (method, &error);
9048 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9049 buffer_add_int (buf, 0);
9051 if (CHECK_PROTOCOL_VERSION (2, 18))
9052 buffer_add_int (buf, 0);
9054 buffer_add_int (buf, header->code_size);
9055 for (i = 0; i < header->code_size; ++i)
9056 buffer_add_byte (buf, header->code [i]);
9058 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9059 buffer_add_int (buf, header->num_clauses);
9060 for (i = 0; i < header->num_clauses; ++i) {
9061 MonoExceptionClause *clause = &header->clauses [i];
9063 buffer_add_int (buf, clause->flags);
9064 buffer_add_int (buf, clause->try_offset);
9065 buffer_add_int (buf, clause->try_len);
9066 buffer_add_int (buf, clause->handler_offset);
9067 buffer_add_int (buf, clause->handler_len);
9068 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9069 buffer_add_typeid (buf, domain, clause->data.catch_class);
9070 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9071 buffer_add_int (buf, clause->data.filter_offset);
9075 mono_metadata_free_mh (header);
9080 case CMD_METHOD_RESOLVE_TOKEN: {
9081 guint32 token = decode_int (p, &p, end);
9084 switch (mono_metadata_token_code (token)) {
9085 case MONO_TOKEN_STRING: {
9090 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9091 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9093 s2 = mono_string_to_utf8_checked (s, &error);
9094 mono_error_assert_ok (&error);
9096 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9097 buffer_add_string (buf, s2);
9104 MonoClass *handle_class;
9106 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9107 val = mono_method_get_wrapper_data (method, token);
9108 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9110 if (handle_class == NULL) {
9111 // Can't figure out the token type
9112 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9116 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9118 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9121 if (handle_class == mono_defaults.typehandle_class) {
9122 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9123 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9124 buffer_add_typeid (buf, domain, (MonoClass *) val);
9126 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9127 } else if (handle_class == mono_defaults.fieldhandle_class) {
9128 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9129 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9130 } else if (handle_class == mono_defaults.methodhandle_class) {
9131 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9132 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9133 } else if (handle_class == mono_defaults.string_class) {
9136 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9137 mono_error_assert_ok (&error);
9138 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9139 buffer_add_string (buf, s);
9142 g_assert_not_reached ();
9149 case CMD_METHOD_GET_CATTRS: {
9151 MonoClass *attr_klass;
9152 MonoCustomAttrInfo *cinfo;
9154 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9155 /* attr_klass can be NULL */
9156 if (err != ERR_NONE)
9159 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9160 if (!is_ok (&error)) {
9161 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9162 return ERR_LOADER_ERROR;
9165 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9166 if (err != ERR_NONE)
9170 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9172 MonoType **type_argv;
9176 MonoGenericInst *ginst;
9177 MonoGenericContext tmp_context;
9178 MonoMethod *inflated;
9180 type_argc = decode_int (p, &p, end);
9181 type_argv = g_new0 (MonoType*, type_argc);
9182 for (i = 0; i < type_argc; ++i) {
9183 klass = decode_typeid (p, &p, end, &d, &err);
9184 if (err != ERR_NONE) {
9190 return ERR_INVALID_ARGUMENT;
9192 type_argv [i] = &klass->byval_arg;
9194 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9196 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9197 tmp_context.method_inst = ginst;
9199 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9200 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9201 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9202 return ERR_INVALID_ARGUMENT;
9203 buffer_add_methodid (buf, domain, inflated);
9207 return ERR_NOT_IMPLEMENTED;
9214 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9217 MonoDomain *old_domain;
9221 method = decode_methodid (p, &p, end, &domain, &err);
9222 if (err != ERR_NONE)
9225 old_domain = mono_domain_get ();
9227 mono_domain_set (domain, TRUE);
9229 err = method_commands_internal (command, method, domain, p, end, buf);
9231 mono_domain_set (old_domain, TRUE);
9237 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9239 int objid = decode_objid (p, &p, end);
9241 MonoThread *thread_obj;
9242 MonoInternalThread *thread;
9244 err = get_object (objid, (MonoObject**)&thread_obj);
9245 if (err != ERR_NONE)
9248 thread = THREAD_TO_INTERNAL (thread_obj);
9251 case CMD_THREAD_GET_NAME: {
9253 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9256 buffer_add_int (buf, 0);
9261 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9263 buffer_add_int (buf, len);
9264 buffer_add_data (buf, (guint8*)name, len);
9269 case CMD_THREAD_GET_FRAME_INFO: {
9270 DebuggerTlsData *tls;
9271 int i, start_frame, length;
9273 // Wait for suspending if it already started
9274 // FIXME: Races with suspend_count
9275 while (!is_suspended ()) {
9277 wait_for_suspend ();
9281 wait_for_suspend ();
9282 if (!is_suspended ())
9283 return ERR_NOT_SUSPENDED;
9286 start_frame = decode_int (p, &p, end);
9287 length = decode_int (p, &p, end);
9289 if (start_frame != 0 || length != -1)
9290 return ERR_NOT_IMPLEMENTED;
9292 mono_loader_lock ();
9293 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9294 mono_loader_unlock ();
9297 compute_frame_info (thread, tls);
9299 buffer_add_int (buf, tls->frame_count);
9300 for (i = 0; i < tls->frame_count; ++i) {
9301 buffer_add_int (buf, tls->frames [i]->id);
9302 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9303 buffer_add_int (buf, tls->frames [i]->il_offset);
9305 * Instead of passing the frame type directly to the client, we associate
9306 * it with the previous frame using a set of flags. This avoids lots of
9307 * conditional code in the client, since a frame whose type isn't
9308 * FRAME_TYPE_MANAGED has no method, location, etc.
9310 buffer_add_byte (buf, tls->frames [i]->flags);
9315 case CMD_THREAD_GET_STATE:
9316 buffer_add_int (buf, thread->state);
9318 case CMD_THREAD_GET_INFO:
9319 buffer_add_byte (buf, thread->threadpool_thread);
9321 case CMD_THREAD_GET_ID:
9322 buffer_add_long (buf, (guint64)(gsize)thread);
9324 case CMD_THREAD_GET_TID:
9325 buffer_add_long (buf, (guint64)thread->tid);
9327 case CMD_THREAD_SET_IP: {
9328 DebuggerTlsData *tls;
9331 MonoSeqPointInfo *seq_points;
9336 method = decode_methodid (p, &p, end, &domain, &err);
9337 if (err != ERR_NONE)
9339 il_offset = decode_long (p, &p, end);
9341 while (!is_suspended ()) {
9343 wait_for_suspend ();
9346 mono_loader_lock ();
9347 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9348 mono_loader_unlock ();
9351 compute_frame_info (thread, tls);
9352 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9353 return ERR_INVALID_ARGUMENT;
9355 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9357 g_assert (seq_points);
9360 return ERR_INVALID_ARGUMENT;
9362 // FIXME: Check that the ip change is safe
9364 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);
9365 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9369 return ERR_NOT_IMPLEMENTED;
9376 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9380 MonoThread *thread_obj;
9381 MonoInternalThread *thread;
9382 int pos, i, len, frame_idx;
9383 DebuggerTlsData *tls;
9385 MonoDebugMethodJitInfo *jit;
9386 MonoMethodSignature *sig;
9388 MonoMethodHeader *header;
9390 objid = decode_objid (p, &p, end);
9391 err = get_object (objid, (MonoObject**)&thread_obj);
9392 if (err != ERR_NONE)
9395 thread = THREAD_TO_INTERNAL (thread_obj);
9397 id = decode_id (p, &p, end);
9399 mono_loader_lock ();
9400 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9401 mono_loader_unlock ();
9404 for (i = 0; i < tls->frame_count; ++i) {
9405 if (tls->frames [i]->id == id)
9408 if (i == tls->frame_count)
9409 return ERR_INVALID_FRAMEID;
9412 frame = tls->frames [frame_idx];
9414 /* This is supported for frames without has_ctx etc. set */
9415 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9416 if (CHECK_PROTOCOL_VERSION (2, 38))
9417 buffer_add_domainid (buf, frame->domain);
9421 if (!frame->has_ctx)
9422 return ERR_ABSENT_INFORMATION;
9424 if (!ensure_jit (frame))
9425 return ERR_ABSENT_INFORMATION;
9429 sig = mono_method_signature (frame->actual_method);
9431 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9433 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9435 return ERR_ABSENT_INFORMATION;
9438 case CMD_STACK_FRAME_GET_VALUES: {
9440 len = decode_int (p, &p, end);
9441 header = mono_method_get_header_checked (frame->actual_method, &error);
9442 mono_error_assert_ok (&error); /* FIXME report error */
9444 for (i = 0; i < len; ++i) {
9445 pos = decode_int (p, &p, end);
9450 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9452 g_assert (pos >= 0 && pos < jit->num_params);
9454 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9456 MonoDebugLocalsInfo *locals;
9458 locals = mono_debug_lookup_locals (frame->method);
9460 g_assert (pos < locals->num_locals);
9461 pos = locals->locals [pos].index;
9462 mono_debug_free_locals (locals);
9464 g_assert (pos >= 0 && pos < jit->num_locals);
9466 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9468 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9471 mono_metadata_free_mh (header);
9474 case CMD_STACK_FRAME_GET_THIS: {
9475 if (frame->api_method->klass->valuetype) {
9476 if (!sig->hasthis) {
9477 MonoObject *p = NULL;
9478 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9480 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9483 if (!sig->hasthis) {
9484 MonoObject *p = NULL;
9485 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9487 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9492 case CMD_STACK_FRAME_SET_VALUES: {
9496 MonoDebugVarInfo *var;
9498 len = decode_int (p, &p, end);
9499 header = mono_method_get_header_checked (frame->actual_method, &error);
9500 mono_error_assert_ok (&error); /* FIXME report error */
9502 for (i = 0; i < len; ++i) {
9503 pos = decode_int (p, &p, end);
9508 g_assert (pos >= 0 && pos < jit->num_params);
9510 t = sig->params [pos];
9511 var = &jit->params [pos];
9513 MonoDebugLocalsInfo *locals;
9515 locals = mono_debug_lookup_locals (frame->method);
9517 g_assert (pos < locals->num_locals);
9518 pos = locals->locals [pos].index;
9519 mono_debug_free_locals (locals);
9521 g_assert (pos >= 0 && pos < jit->num_locals);
9523 t = header->locals [pos];
9524 var = &jit->locals [pos];
9527 if (MONO_TYPE_IS_REFERENCE (t))
9528 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9530 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9531 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9532 if (err != ERR_NONE)
9535 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9537 mono_metadata_free_mh (header);
9540 case CMD_STACK_FRAME_GET_DOMAIN: {
9541 if (CHECK_PROTOCOL_VERSION (2, 38))
9542 buffer_add_domainid (buf, frame->domain);
9545 case CMD_STACK_FRAME_SET_THIS: {
9548 MonoDebugVarInfo *var;
9550 t = &frame->actual_method->klass->byval_arg;
9551 /* Checked by the sender */
9552 g_assert (MONO_TYPE_ISSTRUCT (t));
9553 var = jit->this_var;
9556 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9557 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9558 if (err != ERR_NONE)
9561 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9565 return ERR_NOT_IMPLEMENTED;
9572 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9575 int objid, index, len, i, esize;
9579 objid = decode_objid (p, &p, end);
9580 err = get_object (objid, (MonoObject**)&arr);
9581 if (err != ERR_NONE)
9585 case CMD_ARRAY_REF_GET_LENGTH:
9586 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9588 buffer_add_int (buf, arr->max_length);
9589 buffer_add_int (buf, 0);
9591 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9592 buffer_add_int (buf, arr->bounds [i].length);
9593 buffer_add_int (buf, arr->bounds [i].lower_bound);
9597 case CMD_ARRAY_REF_GET_VALUES:
9598 index = decode_int (p, &p, end);
9599 len = decode_int (p, &p, end);
9601 g_assert (index >= 0 && len >= 0);
9602 // Reordered to avoid integer overflow
9603 g_assert (!(index > arr->max_length - len));
9605 esize = mono_array_element_size (arr->obj.vtable->klass);
9606 for (i = index; i < index + len; ++i) {
9607 elem = (gpointer*)((char*)arr->vector + (i * esize));
9608 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9611 case CMD_ARRAY_REF_SET_VALUES:
9612 index = decode_int (p, &p, end);
9613 len = decode_int (p, &p, end);
9615 g_assert (index >= 0 && len >= 0);
9616 // Reordered to avoid integer overflow
9617 g_assert (!(index > arr->max_length - len));
9619 esize = mono_array_element_size (arr->obj.vtable->klass);
9620 for (i = index; i < index + len; ++i) {
9621 elem = (gpointer*)((char*)arr->vector + (i * esize));
9623 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9627 return ERR_NOT_IMPLEMENTED;
9634 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9640 int i, index, length;
9642 gboolean use_utf16 = FALSE;
9644 objid = decode_objid (p, &p, end);
9645 err = get_object (objid, (MonoObject**)&str);
9646 if (err != ERR_NONE)
9650 case CMD_STRING_REF_GET_VALUE:
9651 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9652 for (i = 0; i < mono_string_length (str); ++i)
9653 if (mono_string_chars (str)[i] == 0)
9655 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9658 buffer_add_int (buf, mono_string_length (str) * 2);
9659 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9662 s = mono_string_to_utf8_checked (str, &error);
9663 mono_error_assert_ok (&error);
9664 buffer_add_string (buf, s);
9668 case CMD_STRING_REF_GET_LENGTH:
9669 buffer_add_long (buf, mono_string_length (str));
9671 case CMD_STRING_REF_GET_CHARS:
9672 index = decode_long (p, &p, end);
9673 length = decode_long (p, &p, end);
9674 if (index > mono_string_length (str) - length)
9675 return ERR_INVALID_ARGUMENT;
9676 c = mono_string_chars (str) + index;
9677 for (i = 0; i < length; ++i)
9678 buffer_add_short (buf, c [i]);
9681 return ERR_NOT_IMPLEMENTED;
9688 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9699 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9700 objid = decode_objid (p, &p, end);
9701 err = get_object (objid, &obj);
9702 if (err != ERR_NONE)
9703 buffer_add_int (buf, 1);
9705 buffer_add_int (buf, 0);
9709 objid = decode_objid (p, &p, end);
9710 err = get_object (objid, &obj);
9711 if (err != ERR_NONE)
9714 MonoClass *obj_type;
9715 gboolean remote_obj = FALSE;
9717 obj_type = obj->vtable->klass;
9718 if (mono_class_is_transparent_proxy (obj_type)) {
9719 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9723 g_assert (obj_type);
9726 case CMD_OBJECT_REF_GET_TYPE:
9727 /* This handles transparent proxies too */
9728 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9730 case CMD_OBJECT_REF_GET_VALUES:
9731 len = decode_int (p, &p, end);
9733 for (i = 0; i < len; ++i) {
9734 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9735 if (err != ERR_NONE)
9738 /* Check that the field belongs to the object */
9740 for (k = obj_type; k; k = k->parent) {
9741 if (k == f->parent) {
9747 return ERR_INVALID_FIELDID;
9749 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9753 if (mono_class_field_is_special_static (f))
9754 return ERR_INVALID_FIELDID;
9756 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9757 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9758 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9759 mono_field_static_get_value_checked (vtable, f, val, &error);
9760 if (!is_ok (&error)) {
9761 mono_error_cleanup (&error); /* FIXME report the error */
9762 return ERR_INVALID_OBJECT;
9764 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9767 guint8 *field_value = NULL;
9770 #ifndef DISABLE_REMOTING
9771 void *field_storage = NULL;
9772 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9773 if (!is_ok (&error)) {
9774 mono_error_cleanup (&error); /* FIXME report the error */
9775 return ERR_INVALID_OBJECT;
9778 g_assert_not_reached ();
9781 field_value = (guint8*)obj + f->offset;
9783 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9787 case CMD_OBJECT_REF_SET_VALUES:
9788 len = decode_int (p, &p, end);
9790 for (i = 0; i < len; ++i) {
9791 f = decode_fieldid (p, &p, end, NULL, &err);
9792 if (err != ERR_NONE)
9795 /* Check that the field belongs to the object */
9797 for (k = obj_type; k; k = k->parent) {
9798 if (k == f->parent) {
9804 return ERR_INVALID_FIELDID;
9806 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9810 if (mono_class_field_is_special_static (f))
9811 return ERR_INVALID_FIELDID;
9813 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9814 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9816 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9817 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9818 if (err != ERR_NONE) {
9822 mono_field_static_set_value (vtable, f, val);
9825 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9826 if (err != ERR_NONE)
9831 case CMD_OBJECT_REF_GET_ADDRESS:
9832 buffer_add_long (buf, (gssize)obj);
9834 case CMD_OBJECT_REF_GET_DOMAIN:
9835 buffer_add_domainid (buf, obj->vtable->domain);
9837 case CMD_OBJECT_REF_GET_INFO:
9838 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9839 buffer_add_domainid (buf, obj->vtable->domain);
9842 return ERR_NOT_IMPLEMENTED;
9849 command_set_to_string (CommandSet command_set)
9851 switch (command_set) {
9854 case CMD_SET_OBJECT_REF:
9855 return "OBJECT_REF";
9856 case CMD_SET_STRING_REF:
9857 return "STRING_REF";
9858 case CMD_SET_THREAD:
9860 case CMD_SET_ARRAY_REF:
9862 case CMD_SET_EVENT_REQUEST:
9863 return "EVENT_REQUEST";
9864 case CMD_SET_STACK_FRAME:
9865 return "STACK_FRAME";
9866 case CMD_SET_APPDOMAIN:
9868 case CMD_SET_ASSEMBLY:
9870 case CMD_SET_METHOD:
9874 case CMD_SET_MODULE:
9885 static const char* vm_cmds_str [] = {
9893 "SET_PROTOCOL_VERSION",
9896 "GET_TYPES_FOR_SOURCE_FILE",
9901 static const char* thread_cmds_str[] = {
9911 static const char* event_cmds_str[] = {
9914 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9917 static const char* appdomain_cmds_str[] = {
9919 "GET_FRIENDLY_NAME",
9921 "GET_ENTRY_ASSEMBLY",
9924 "CREATE_BOXED_VALUE"
9927 static const char* assembly_cmds_str[] = {
9930 "GET_MANIFEST_MODULE",
9937 static const char* module_cmds_str[] = {
9941 static const char* field_cmds_str[] = {
9945 static const char* method_cmds_str[] = {
9947 "GET_DECLARING_TYPE",
9955 "MAKE_GENERIC_METHOD"
9958 static const char* type_cmds_str[] = {
9966 "IS_ASSIGNABLE_FROM",
9970 "GET_PROPERTY_CATTRS",
9971 "GET_SOURCE_FILES_2",
9973 "GET_METHODS_BY_NAME_FLAGS",
9975 "GET_INTERFACE_MAP",
9979 static const char* stack_frame_cmds_str[] = {
9987 static const char* array_cmds_str[] = {
9993 static const char* string_cmds_str[] = {
9999 static const char* object_cmds_str[] = {
10010 cmd_to_string (CommandSet set, int command)
10017 cmds = vm_cmds_str;
10018 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10020 case CMD_SET_OBJECT_REF:
10021 cmds = object_cmds_str;
10022 cmds_len = G_N_ELEMENTS (object_cmds_str);
10024 case CMD_SET_STRING_REF:
10025 cmds = string_cmds_str;
10026 cmds_len = G_N_ELEMENTS (string_cmds_str);
10028 case CMD_SET_THREAD:
10029 cmds = thread_cmds_str;
10030 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10032 case CMD_SET_ARRAY_REF:
10033 cmds = array_cmds_str;
10034 cmds_len = G_N_ELEMENTS (array_cmds_str);
10036 case CMD_SET_EVENT_REQUEST:
10037 cmds = event_cmds_str;
10038 cmds_len = G_N_ELEMENTS (event_cmds_str);
10040 case CMD_SET_STACK_FRAME:
10041 cmds = stack_frame_cmds_str;
10042 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10044 case CMD_SET_APPDOMAIN:
10045 cmds = appdomain_cmds_str;
10046 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10048 case CMD_SET_ASSEMBLY:
10049 cmds = assembly_cmds_str;
10050 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10052 case CMD_SET_METHOD:
10053 cmds = method_cmds_str;
10054 cmds_len = G_N_ELEMENTS (method_cmds_str);
10057 cmds = type_cmds_str;
10058 cmds_len = G_N_ELEMENTS (type_cmds_str);
10060 case CMD_SET_MODULE:
10061 cmds = module_cmds_str;
10062 cmds_len = G_N_ELEMENTS (module_cmds_str);
10064 case CMD_SET_FIELD:
10065 cmds = field_cmds_str;
10066 cmds_len = G_N_ELEMENTS (field_cmds_str);
10068 case CMD_SET_EVENT:
10069 cmds = event_cmds_str;
10070 cmds_len = G_N_ELEMENTS (event_cmds_str);
10075 if (command > 0 && command <= cmds_len)
10076 return cmds [command - 1];
10082 wait_for_attach (void)
10084 #ifndef DISABLE_SOCKET_TRANSPORT
10085 if (listen_fd == -1) {
10086 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10090 /* Block and wait for client connection */
10091 conn_fd = socket_transport_accept (listen_fd);
10093 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10094 if (conn_fd == -1) {
10095 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10099 g_assert_not_reached ();
10103 disconnected = !transport_handshake ();
10104 if (disconnected) {
10105 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10115 * This thread handles communication with the debugger client using a JDWP
10118 static gsize WINAPI
10119 debugger_thread (void *arg)
10122 int res, len, id, flags, command = 0;
10123 CommandSet command_set = (CommandSet)0;
10124 guint8 header [HEADER_LENGTH];
10125 guint8 *data, *p, *end;
10129 gboolean attach_failed = FALSE;
10131 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10133 debugger_thread_id = mono_native_thread_id_get ();
10135 MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
10136 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, FALSE, &error);
10137 mono_error_assert_ok (&error);
10139 thread->internal_thread->state |= ThreadState_Background;
10140 thread->internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10142 if (agent_config.defer) {
10143 if (!wait_for_attach ()) {
10144 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10145 attach_failed = TRUE; // Don't abort process when we can't listen
10147 mono_set_is_debugger_attached (TRUE);
10148 /* Send start event to client */
10149 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10152 mono_set_is_debugger_attached (TRUE);
10155 while (!attach_failed) {
10156 res = transport_recv (header, HEADER_LENGTH);
10158 /* This will break if the socket is closed during shutdown too */
10159 if (res != HEADER_LENGTH) {
10160 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10165 end = header + HEADER_LENGTH;
10167 len = decode_int (p, &p, end);
10168 id = decode_int (p, &p, end);
10169 flags = decode_byte (p, &p, end);
10170 command_set = (CommandSet)decode_byte (p, &p, end);
10171 command = decode_byte (p, &p, end);
10173 g_assert (flags == 0);
10176 const char *cmd_str;
10177 char cmd_num [256];
10179 cmd_str = cmd_to_string (command_set, command);
10181 sprintf (cmd_num, "%d", command);
10185 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);
10188 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10189 if (len - HEADER_LENGTH > 0)
10191 res = transport_recv (data, len - HEADER_LENGTH);
10192 if (res != len - HEADER_LENGTH) {
10193 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10199 end = data + (len - HEADER_LENGTH);
10201 buffer_init (&buf, 128);
10206 /* Process the request */
10207 switch (command_set) {
10209 err = vm_commands (command, id, p, end, &buf);
10210 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10211 /* Sent after the invoke is complete */
10214 case CMD_SET_EVENT_REQUEST:
10215 err = event_commands (command, p, end, &buf);
10217 case CMD_SET_APPDOMAIN:
10218 err = domain_commands (command, p, end, &buf);
10220 case CMD_SET_ASSEMBLY:
10221 err = assembly_commands (command, p, end, &buf);
10223 case CMD_SET_MODULE:
10224 err = module_commands (command, p, end, &buf);
10226 case CMD_SET_FIELD:
10227 err = field_commands (command, p, end, &buf);
10230 err = type_commands (command, p, end, &buf);
10232 case CMD_SET_METHOD:
10233 err = method_commands (command, p, end, &buf);
10235 case CMD_SET_THREAD:
10236 err = thread_commands (command, p, end, &buf);
10238 case CMD_SET_STACK_FRAME:
10239 err = frame_commands (command, p, end, &buf);
10241 case CMD_SET_ARRAY_REF:
10242 err = array_commands (command, p, end, &buf);
10244 case CMD_SET_STRING_REF:
10245 err = string_commands (command, p, end, &buf);
10247 case CMD_SET_OBJECT_REF:
10248 err = object_commands (command, p, end, &buf);
10251 err = ERR_NOT_IMPLEMENTED;
10254 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10255 buffer_replies = TRUE;
10259 if (buffer_replies) {
10260 buffer_reply_packet (id, err, &buf);
10262 send_reply_packet (id, err, &buf);
10263 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10267 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10268 send_buffered_reply_packets ();
10269 buffer_replies = FALSE;
10273 buffer_free (&buf);
10275 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10279 mono_set_is_debugger_attached (FALSE);
10281 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10282 debugger_thread_exited = TRUE;
10283 mono_coop_cond_signal (&debugger_thread_exited_cond);
10284 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10286 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10288 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10289 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10290 start_debugger_thread ();
10296 #else /* DISABLE_DEBUGGER_AGENT */
10299 mono_debugger_agent_parse_options (char *options)
10301 g_error ("This runtime is configured with the debugger agent disabled.");
10305 mono_debugger_agent_init (void)
10310 mono_debugger_agent_breakpoint_hit (void *sigctx)
10315 mono_debugger_agent_single_step_event (void *sigctx)
10320 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10325 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10326 MonoContext *catch_ctx)
10331 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10336 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10341 mono_debugger_agent_user_break (void)
10347 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10352 mono_debugger_agent_debug_log_is_enabled (void)
10358 mono_debugger_agent_unhandled_exception (MonoException *exc)
10360 g_assert_not_reached ();
10364 debugger_agent_single_step_from_context (MonoContext *ctx)
10366 g_assert_not_reached ();
10370 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10372 g_assert_not_reached ();