3 * Soft Debugger back-end module
6 * Zoltan Varga (vargaz@gmail.com)
8 * Copyright 2009-2010 Novell, Inc.
9 * Copyright 2011 Xamarin Inc.
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
17 #ifdef HAVE_SYS_TYPES_H
18 #include <sys/types.h>
20 #ifdef HAVE_SYS_SELECT_H
21 #include <sys/select.h>
23 #ifdef HAVE_SYS_SOCKET_H
24 #include <sys/socket.h>
26 #ifdef HAVE_NETINET_TCP_H
27 #include <netinet/tcp.h>
29 #ifdef HAVE_NETINET_IN_H
30 #include <netinet/in.h>
50 #ifdef PLATFORM_ANDROID
52 #include <linux/tcp.h>
53 #include <sys/endian.h>
56 #include <mono/metadata/mono-debug.h>
57 #include <mono/metadata/debug-internals.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 MonoInternalThread *internal;
824 internal = mono_thread_internal_current ();
828 return internal->debugger_thread;
832 parse_address (char *address, char **host, int *port)
834 char *pos = strchr (address, ':');
836 if (pos == NULL || pos == address)
839 size_t len = pos - address;
840 *host = (char *)g_malloc (len + 1);
841 memcpy (*host, address, len);
842 (*host) [len] = '\0';
844 *port = atoi (pos + 1);
852 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
853 fprintf (stderr, "Available options:\n");
854 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
855 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
856 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
857 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
858 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
859 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
860 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
861 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
862 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
863 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
867 parse_flag (const char *option, char *flag)
869 if (!strcmp (flag, "y"))
871 else if (!strcmp (flag, "n"))
874 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
881 mono_debugger_agent_parse_options (char *options)
888 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
889 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
893 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
895 options = g_strdup_printf ("%s,%s", options, extra);
897 agent_config.enabled = TRUE;
898 agent_config.suspend = TRUE;
899 agent_config.server = FALSE;
900 agent_config.defer = FALSE;
901 agent_config.address = NULL;
903 //agent_config.log_level = 10;
905 args = g_strsplit (options, ",", -1);
906 for (ptr = args; ptr && *ptr; ptr ++) {
909 if (strncmp (arg, "transport=", 10) == 0) {
910 agent_config.transport = g_strdup (arg + 10);
911 } else if (strncmp (arg, "address=", 8) == 0) {
912 agent_config.address = g_strdup (arg + 8);
913 } else if (strncmp (arg, "loglevel=", 9) == 0) {
914 agent_config.log_level = atoi (arg + 9);
915 } else if (strncmp (arg, "logfile=", 8) == 0) {
916 agent_config.log_file = g_strdup (arg + 8);
917 } else if (strncmp (arg, "suspend=", 8) == 0) {
918 agent_config.suspend = parse_flag ("suspend", arg + 8);
919 } else if (strncmp (arg, "server=", 7) == 0) {
920 agent_config.server = parse_flag ("server", arg + 7);
921 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
922 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
923 } else if (strncmp (arg, "onthrow=", 8) == 0) {
924 /* We support multiple onthrow= options */
925 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
926 } else if (strncmp (arg, "onthrow", 7) == 0) {
927 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
928 } else if (strncmp (arg, "help", 4) == 0) {
931 } else if (strncmp (arg, "timeout=", 8) == 0) {
932 agent_config.timeout = atoi (arg + 8);
933 } else if (strncmp (arg, "launch=", 7) == 0) {
934 agent_config.launch = g_strdup (arg + 7);
935 } else if (strncmp (arg, "embedding=", 10) == 0) {
936 agent_config.embedding = atoi (arg + 10) == 1;
937 } else if (strncmp (arg, "keepalive=", 10) == 0) {
938 agent_config.keepalive = atoi (arg + 10);
939 } else if (strncmp (arg, "setpgid=", 8) == 0) {
940 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
947 if (agent_config.server && !agent_config.suspend) {
948 /* Waiting for deferred attachment */
949 agent_config.defer = TRUE;
950 if (agent_config.address == NULL) {
951 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
955 //agent_config.log_level = 0;
957 if (agent_config.transport == NULL) {
958 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
962 if (agent_config.address == NULL && !agent_config.server) {
963 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
968 if (!strcmp (agent_config.transport, "dt_socket")) {
969 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
970 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
977 mono_debugger_agent_init (void)
979 mono_coop_mutex_init_recursive (&debug_mutex);
981 if (!agent_config.enabled)
986 /* Need to know whenever a thread has acquired the loader mutex */
987 mono_loader_lock_track_ownership (TRUE);
989 event_requests = g_ptr_array_new ();
991 mono_coop_mutex_init (&debugger_thread_exited_mutex);
992 mono_coop_cond_init (&debugger_thread_exited_cond);
994 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
995 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
996 mono_profiler_install_runtime_initialized (runtime_initialized);
997 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
998 mono_profiler_install_thread (thread_startup, thread_end);
999 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
1000 mono_profiler_install_jit_end (jit_end);
1002 mono_native_tls_alloc (&debugger_tls_id, NULL);
1004 /* Needed by the hash_table_new_type () call below */
1005 mono_gc_base_init ();
1007 thread_to_tls = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
1009 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1011 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");
1013 pending_assembly_loads = g_ptr_array_new ();
1014 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1016 log_level = agent_config.log_level;
1018 embedding = agent_config.embedding;
1019 disconnected = TRUE;
1021 if (agent_config.log_file) {
1022 log_file = fopen (agent_config.log_file, "w+");
1024 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1033 breakpoints_init ();
1036 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1038 * This is needed because currently we don't handle liveness info.
1040 mini_get_debug_options ()->mdb_optimizations = TRUE;
1042 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1043 /* This is needed because we can't set local variables in registers yet */
1044 mono_disable_optimizations (MONO_OPT_LINEARS);
1048 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1049 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1050 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1053 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1056 if (agent_config.setpgid)
1060 if (!agent_config.onuncaught && !agent_config.onthrow)
1061 finish_agent_init (TRUE);
1065 * finish_agent_init:
1067 * Finish the initialization of the agent. This involves connecting the transport
1068 * and starting the agent thread. This is either done at startup, or
1069 * in response to some event like an unhandled exception.
1072 finish_agent_init (gboolean on_startup)
1076 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1079 if (agent_config.launch) {
1082 // FIXME: Generated address
1083 // FIXME: Races with transport_connect ()
1085 argv [0] = agent_config.launch;
1086 argv [1] = agent_config.transport;
1087 argv [2] = agent_config.address;
1090 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1092 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1097 transport_connect (agent_config.address);
1100 /* Do some which is usually done after sending the VMStart () event */
1101 vm_start_event_sent = TRUE;
1102 start_debugger_thread ();
1107 mono_debugger_agent_cleanup (void)
1112 stop_debugger_thread ();
1114 breakpoints_cleanup ();
1123 #ifndef DISABLE_SOCKET_TRANSPORT
1128 * recv() + handle incomplete reads and EINTR
1131 socket_transport_recv (void *buf, int len)
1137 static gint64 last_keepalive;
1144 res = recv (fd, (char *) buf + total, len - total, flags);
1147 if (agent_config.keepalive) {
1148 gboolean need_keepalive = FALSE;
1149 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1150 need_keepalive = TRUE;
1151 } else if (res == -1) {
1152 /* This could happen if recv () is interrupted repeatedly */
1153 msecs = mono_msec_ticks ();
1154 if (msecs - last_keepalive >= agent_config.keepalive) {
1155 need_keepalive = TRUE;
1156 last_keepalive = msecs;
1159 if (need_keepalive) {
1160 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1164 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1172 set_keepalive (void)
1177 if (!agent_config.keepalive || !conn_fd)
1180 tv.tv_sec = agent_config.keepalive / 1000;
1181 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1183 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1184 g_assert (result >= 0);
1188 socket_transport_accept (int socket_fd)
1191 conn_fd = accept (socket_fd, NULL, NULL);
1194 if (conn_fd == -1) {
1195 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1197 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1204 socket_transport_send (void *data, int len)
1211 res = send (conn_fd, data, len, 0);
1212 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1223 * socket_transport_connect:
1225 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1228 socket_transport_connect (const char *address)
1230 MonoAddressInfo *result;
1231 MonoAddressEntry *rp;
1232 int sfd = -1, s, res;
1236 if (agent_config.address) {
1237 res = parse_address (agent_config.address, &host, &port);
1238 g_assert (res == 0);
1249 mono_network_init ();
1251 /* Obtain address(es) matching host/port */
1252 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1254 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1259 if (agent_config.server) {
1260 /* Wait for a connection */
1262 struct sockaddr_in addr;
1265 /* No address, generate one */
1266 sfd = socket (AF_INET, SOCK_STREAM, 0);
1269 /* This will bind the socket to a random port */
1270 res = listen (sfd, 16);
1272 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1277 addrlen = sizeof (addr);
1278 memset (&addr, 0, sizeof (addr));
1279 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1280 g_assert (res == 0);
1282 host = (char*)"127.0.0.1";
1283 port = ntohs (addr.sin_port);
1285 /* Emit the address to stdout */
1286 /* FIXME: Should print another interface, not localhost */
1287 printf ("%s:%d\n", host, port);
1289 /* Listen on the provided address */
1290 for (rp = result->entries; rp != NULL; rp = rp->next) {
1291 MonoSocketAddress sockaddr;
1295 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1297 sfd = socket (rp->family, rp->socktype,
1302 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1305 res = bind (sfd, &sockaddr.addr, sock_len);
1309 res = listen (sfd, 16);
1316 mono_free_address_info (result);
1319 if (agent_config.defer)
1322 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1324 if (agent_config.timeout) {
1329 tv.tv_usec = agent_config.timeout * 1000;
1331 FD_SET (sfd, &readfds);
1334 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1338 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1343 conn_fd = socket_transport_accept (sfd);
1347 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1349 /* Connect to the specified address */
1350 /* FIXME: Respect the timeout */
1351 for (rp = result->entries; rp != NULL; rp = rp->next) {
1352 MonoSocketAddress sockaddr;
1355 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1357 sfd = socket (rp->family, rp->socktype,
1363 res = connect (sfd, &sockaddr.addr, sock_len);
1367 break; /* Success */
1375 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1381 mono_free_address_info (result);
1384 if (!transport_handshake ())
1389 socket_transport_close1 (void)
1391 /* This will interrupt the agent thread */
1392 /* Close the read part only so it can still send back replies */
1393 /* Also shut down the connection listener so that we can exit normally */
1395 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1396 shutdown (conn_fd, SD_BOTH);
1397 shutdown (listen_fd, SD_BOTH);
1398 closesocket (listen_fd);
1400 shutdown (conn_fd, SHUT_RD);
1401 shutdown (listen_fd, SHUT_RDWR);
1409 socket_transport_close2 (void)
1412 shutdown (conn_fd, SD_BOTH);
1414 shutdown (conn_fd, SHUT_RDWR);
1419 register_socket_transport (void)
1421 DebuggerTransport trans;
1423 trans.name = "dt_socket";
1424 trans.connect = socket_transport_connect;
1425 trans.close1 = socket_transport_close1;
1426 trans.close2 = socket_transport_close2;
1427 trans.send = socket_transport_send;
1428 trans.recv = socket_transport_recv;
1430 register_transport (&trans);
1434 * socket_fd_transport_connect:
1438 socket_fd_transport_connect (const char *address)
1442 res = sscanf (address, "%d", &conn_fd);
1444 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1448 if (!transport_handshake ())
1453 register_socket_fd_transport (void)
1455 DebuggerTransport trans;
1457 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1458 trans.name = "socket-fd";
1459 trans.connect = socket_fd_transport_connect;
1460 trans.close1 = socket_transport_close1;
1461 trans.close2 = socket_transport_close2;
1462 trans.send = socket_transport_send;
1463 trans.recv = socket_transport_recv;
1465 register_transport (&trans);
1468 #endif /* DISABLE_SOCKET_TRANSPORT */
1474 #define MAX_TRANSPORTS 16
1476 static DebuggerTransport *transport;
1478 static DebuggerTransport transports [MAX_TRANSPORTS];
1479 static int ntransports;
1482 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1485 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1487 register_transport (trans);
1491 register_transport (DebuggerTransport *trans)
1493 g_assert (ntransports < MAX_TRANSPORTS);
1495 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1500 transport_init (void)
1504 #ifndef DISABLE_SOCKET_TRANSPORT
1505 register_socket_transport ();
1506 register_socket_fd_transport ();
1509 for (i = 0; i < ntransports; ++i) {
1510 if (!strcmp (agent_config.transport, transports [i].name))
1513 if (i == ntransports) {
1514 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1515 for (i = 0; i < ntransports; ++i)
1516 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1517 fprintf (stderr, "\n");
1520 transport = &transports [i];
1524 transport_connect (const char *address)
1526 transport->connect (address);
1530 transport_close1 (void)
1532 transport->close1 ();
1536 transport_close2 (void)
1538 transport->close2 ();
1542 transport_send (void *buf, int len)
1544 return transport->send (buf, len);
1548 transport_recv (void *buf, int len)
1550 return transport->recv (buf, len);
1554 mono_debugger_agent_transport_handshake (void)
1556 return transport_handshake ();
1560 transport_handshake (void)
1562 char handshake_msg [128];
1566 disconnected = TRUE;
1568 /* Write handshake message */
1569 sprintf (handshake_msg, "DWP-Handshake");
1572 res = transport_send (handshake_msg, strlen (handshake_msg));
1573 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1575 g_assert (res != -1);
1578 res = transport_recv (buf, strlen (handshake_msg));
1579 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1580 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1585 * To support older clients, the client sends its protocol version after connecting
1586 * using a command. Until that is received, default to our protocol version.
1588 major_version = MAJOR_VERSION;
1589 minor_version = MINOR_VERSION;
1590 protocol_version_set = FALSE;
1592 #ifndef DISABLE_SOCKET_TRANSPORT
1593 // FIXME: Move this somewhere else
1595 * Set TCP_NODELAY on the socket so the client receives events/command
1596 * results immediately.
1600 int result = setsockopt (conn_fd,
1605 g_assert (result >= 0);
1611 disconnected = FALSE;
1616 stop_debugger_thread (void)
1621 transport_close1 ();
1624 * Wait for the thread to exit.
1626 * If we continue with the shutdown without waiting for it, then the client might
1627 * not receive an answer to its last command like a resume.
1629 if (!is_debugger_thread ()) {
1631 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1632 if (!debugger_thread_exited)
1633 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1634 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1635 } while (!debugger_thread_exited);
1638 transport_close2 ();
1642 start_debugger_thread (void)
1645 MonoInternalThread *thread;
1647 thread = mono_thread_create_internal (mono_get_root_domain (), debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, &error);
1648 mono_error_assert_ok (&error);
1650 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1651 g_assert (debugger_thread_handle);
1655 * Functions to decode protocol data
1659 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1662 g_assert (*endbuf <= limit);
1667 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1670 g_assert (*endbuf <= limit);
1672 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1675 static inline gint64
1676 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1678 guint32 high = decode_int (buf, &buf, limit);
1679 guint32 low = decode_int (buf, &buf, limit);
1683 return ((((guint64)high) << 32) | ((guint64)low));
1687 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1689 return decode_int (buf, endbuf, limit);
1693 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1695 int len = decode_int (buf, &buf, limit);
1703 s = (char *)g_malloc (len + 1);
1706 memcpy (s, buf, len);
1715 * Functions to encode protocol data
1719 buffer_init (Buffer *buf, int size)
1721 buf->buf = (guint8 *)g_malloc (size);
1723 buf->end = buf->buf + size;
1727 buffer_len (Buffer *buf)
1729 return buf->p - buf->buf;
1733 buffer_make_room (Buffer *buf, int size)
1735 if (buf->end - buf->p < size) {
1736 int new_size = buf->end - buf->buf + size + 32;
1737 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1738 size = buf->p - buf->buf;
1741 buf->end = buf->buf + new_size;
1746 buffer_add_byte (Buffer *buf, guint8 val)
1748 buffer_make_room (buf, 1);
1754 buffer_add_short (Buffer *buf, guint32 val)
1756 buffer_make_room (buf, 2);
1757 buf->p [0] = (val >> 8) & 0xff;
1758 buf->p [1] = (val >> 0) & 0xff;
1763 buffer_add_int (Buffer *buf, guint32 val)
1765 buffer_make_room (buf, 4);
1766 buf->p [0] = (val >> 24) & 0xff;
1767 buf->p [1] = (val >> 16) & 0xff;
1768 buf->p [2] = (val >> 8) & 0xff;
1769 buf->p [3] = (val >> 0) & 0xff;
1774 buffer_add_long (Buffer *buf, guint64 l)
1776 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1777 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1781 buffer_add_id (Buffer *buf, int id)
1783 buffer_add_int (buf, (guint64)id);
1787 buffer_add_data (Buffer *buf, guint8 *data, int len)
1789 buffer_make_room (buf, len);
1790 memcpy (buf->p, data, len);
1795 buffer_add_string (Buffer *buf, const char *str)
1800 buffer_add_int (buf, 0);
1803 buffer_add_int (buf, len);
1804 buffer_add_data (buf, (guint8*)str, len);
1809 buffer_add_buffer (Buffer *buf, Buffer *data)
1811 buffer_add_data (buf, data->buf, buffer_len (data));
1815 buffer_free (Buffer *buf)
1821 send_packet (int command_set, int command, Buffer *data)
1827 id = InterlockedIncrement (&packet_id);
1829 len = data->p - data->buf + 11;
1830 buffer_init (&buf, len);
1831 buffer_add_int (&buf, len);
1832 buffer_add_int (&buf, id);
1833 buffer_add_byte (&buf, 0); /* flags */
1834 buffer_add_byte (&buf, command_set);
1835 buffer_add_byte (&buf, command);
1836 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1838 res = transport_send (buf.buf, len);
1846 send_reply_packets (int npackets, ReplyPacket *packets)
1853 for (i = 0; i < npackets; ++i)
1854 len += buffer_len (packets [i].data) + 11;
1855 buffer_init (&buf, len);
1856 for (i = 0; i < npackets; ++i) {
1857 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1858 buffer_add_int (&buf, packets [i].id);
1859 buffer_add_byte (&buf, 0x80); /* flags */
1860 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1861 buffer_add_byte (&buf, packets [i].error);
1862 buffer_add_buffer (&buf, packets [i].data);
1865 res = transport_send (buf.buf, len);
1873 send_reply_packet (int id, int error, Buffer *data)
1877 memset (&packet, 0, sizeof (ReplyPacket));
1879 packet.error = error;
1882 return send_reply_packets (1, &packet);
1886 send_buffered_reply_packets (void)
1890 send_reply_packets (nreply_packets, reply_packets);
1891 for (i = 0; i < nreply_packets; ++i)
1892 buffer_free (reply_packets [i].data);
1893 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1898 buffer_reply_packet (int id, int error, Buffer *data)
1902 if (nreply_packets == 128)
1903 send_buffered_reply_packets ();
1905 p = &reply_packets [nreply_packets];
1908 p->data = g_new0 (Buffer, 1);
1909 buffer_init (p->data, buffer_len (data));
1910 buffer_add_buffer (p->data, data);
1919 * Represents an object accessible by the debugger client.
1922 /* Unique id used in the wire protocol to refer to objects */
1925 * A weakref gc handle pointing to the object. The gc handle is used to
1926 * detect if the object was garbage collected.
1931 /* Maps objid -> ObjRef */
1932 /* Protected by the loader lock */
1933 static GHashTable *objrefs;
1934 /* Protected by the loader lock */
1935 static GHashTable *obj_to_objref;
1936 /* Protected by the dbg lock */
1937 static MonoGHashTable *suspended_objs;
1940 free_objref (gpointer value)
1942 ObjRef *o = (ObjRef *)value;
1944 mono_gchandle_free (o->handle);
1952 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1953 obj_to_objref = g_hash_table_new (NULL, NULL);
1954 suspended_objs = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1958 objrefs_cleanup (void)
1960 g_hash_table_destroy (objrefs);
1965 * Return an ObjRef for OBJ.
1968 get_objref (MonoObject *obj)
1971 GSList *reflist = NULL, *l;
1977 if (suspend_count) {
1979 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1982 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1986 mono_loader_lock ();
1988 /* FIXME: The tables can grow indefinitely */
1990 if (mono_gc_is_moving ()) {
1992 * Objects can move, so use a hash table mapping hash codes to lists of
1993 * ObjRef structures.
1995 hash = mono_object_hash (obj);
1997 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1998 for (l = reflist; l; l = l->next) {
1999 ref = (ObjRef *)l->data;
2000 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2001 mono_loader_unlock ();
2006 /* Use a hash table with masked pointers to internalize object references */
2007 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2008 /* ref might refer to a different object with the same addr which was GCd */
2009 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2010 mono_loader_unlock ();
2015 ref = g_new0 (ObjRef, 1);
2016 ref->id = InterlockedIncrement (&objref_id);
2017 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2019 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2021 if (mono_gc_is_moving ()) {
2022 reflist = g_slist_append (reflist, ref);
2023 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2025 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2028 mono_loader_unlock ();
2034 true_pred (gpointer key, gpointer value, gpointer user_data)
2040 clear_suspended_objs (void)
2043 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2048 get_objid (MonoObject *obj)
2053 return get_objref (obj)->id;
2057 * Set OBJ to the object identified by OBJID.
2058 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2062 get_object_allow_null (int objid, MonoObject **obj)
2072 return ERR_INVALID_OBJECT;
2074 mono_loader_lock ();
2076 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2079 *obj = mono_gchandle_get_target (ref->handle);
2080 mono_loader_unlock ();
2082 return ERR_INVALID_OBJECT;
2085 mono_loader_unlock ();
2086 return ERR_INVALID_OBJECT;
2091 get_object (int objid, MonoObject **obj)
2093 ErrorCode err = get_object_allow_null (objid, obj);
2095 if (err != ERR_NONE)
2098 return ERR_INVALID_OBJECT;
2103 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2105 return decode_id (buf, endbuf, limit);
2109 buffer_add_objid (Buffer *buf, MonoObject *o)
2111 buffer_add_id (buf, get_objid (o));
2130 * Represents a runtime structure accessible to the debugger client
2133 /* Unique id used in the wire protocol */
2135 /* Domain of the runtime structure, NULL if the domain was unloaded */
2142 MonoAssembly *assembly;
2143 MonoClassField *field;
2145 MonoProperty *property;
2150 /* Maps runtime structure -> Id */
2151 /* Protected by the dbg lock */
2152 GHashTable *val_to_id [ID_NUM];
2153 /* Classes whose class load event has been sent */
2154 /* Protected by the loader lock */
2155 GHashTable *loaded_classes;
2156 /* Maps MonoClass->GPtrArray of file names */
2157 GHashTable *source_files;
2158 /* Maps source file basename -> GSList of classes */
2159 GHashTable *source_file_to_class;
2160 /* Same with ignore-case */
2161 GHashTable *source_file_to_class_ignorecase;
2165 /* Protected by the dbg lock */
2166 static GPtrArray *ids [ID_NUM];
2173 for (i = 0; i < ID_NUM; ++i)
2174 ids [i] = g_ptr_array_new ();
2182 for (i = 0; i < ID_NUM; ++i) {
2184 for (j = 0; j < ids [i]->len; ++j)
2185 g_free (g_ptr_array_index (ids [i], j));
2186 g_ptr_array_free (ids [i], TRUE);
2193 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2195 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2197 GHashTableIter iter;
2198 GPtrArray *file_names;
2203 for (i = 0; i < ID_NUM; ++i)
2204 if (info->val_to_id [i])
2205 g_hash_table_destroy (info->val_to_id [i]);
2206 g_hash_table_destroy (info->loaded_classes);
2208 g_hash_table_iter_init (&iter, info->source_files);
2209 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2210 for (i = 0; i < file_names->len; ++i)
2211 g_free (g_ptr_array_index (file_names, i));
2212 g_ptr_array_free (file_names, TRUE);
2215 g_hash_table_iter_init (&iter, info->source_file_to_class);
2216 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2221 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2222 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2230 domain_jit_info (domain)->agent_info = NULL;
2232 /* Clear ids referencing structures in the domain */
2234 for (i = 0; i < ID_NUM; ++i) {
2236 for (j = 0; j < ids [i]->len; ++j) {
2237 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2238 if (id->domain == domain)
2245 mono_loader_lock ();
2246 g_hash_table_remove (domains, domain);
2247 mono_loader_unlock ();
2250 static AgentDomainInfo*
2251 get_agent_domain_info (MonoDomain *domain)
2253 AgentDomainInfo *info = NULL;
2255 mono_domain_lock (domain);
2257 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2259 info = g_new0 (AgentDomainInfo, 1);
2260 domain_jit_info (domain)->agent_info = info;
2261 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2262 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2263 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2264 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2267 mono_domain_unlock (domain);
2273 get_id (MonoDomain *domain, IdType type, gpointer val)
2276 AgentDomainInfo *info;
2281 info = get_agent_domain_info (domain);
2285 if (info->val_to_id [type] == NULL)
2286 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2288 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2294 id = g_new0 (Id, 1);
2296 id->id = ids [type]->len + 1;
2297 id->domain = domain;
2300 g_hash_table_insert (info->val_to_id [type], val, id);
2301 g_ptr_array_add (ids [type], id);
2308 static inline gpointer
2309 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2313 int id = decode_id (buf, endbuf, limit);
2322 // FIXME: error handling
2324 g_assert (id > 0 && id <= ids [type]->len);
2326 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2329 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2330 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2331 *err = ERR_UNLOADED;
2336 *domain = res->domain;
2338 return res->data.val;
2342 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2344 int id = get_id (domain, type, val);
2346 buffer_add_id (buf, id);
2350 static inline MonoClass*
2351 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2355 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2356 if (G_UNLIKELY (log_level >= 2) && klass) {
2359 s = mono_type_full_name (&klass->byval_arg);
2360 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2366 static inline MonoAssembly*
2367 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2369 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2372 static inline MonoImage*
2373 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2375 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2378 static inline MonoMethod*
2379 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2383 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2384 if (G_UNLIKELY (log_level >= 2) && m) {
2387 s = mono_method_full_name (m, TRUE);
2388 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2394 static inline MonoClassField*
2395 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2397 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2400 static inline MonoDomain*
2401 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2403 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2406 static inline MonoProperty*
2407 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2409 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2413 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2415 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2416 if (G_UNLIKELY (log_level >= 2) && klass) {
2419 s = mono_type_full_name (&klass->byval_arg);
2420 if (is_debugger_thread ())
2421 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2423 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2429 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2431 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2432 if (G_UNLIKELY (log_level >= 2) && method) {
2435 s = mono_method_full_name (method, 1);
2436 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2442 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2446 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2447 if (G_UNLIKELY (log_level >= 2) && assembly)
2448 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2452 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2454 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2458 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2460 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2464 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2466 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2470 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2472 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2475 static void invoke_method (void);
2482 * save_thread_context:
2484 * Set CTX as the current threads context which is used for computing stack traces.
2485 * This function is signal-safe.
2488 save_thread_context (MonoContext *ctx)
2490 DebuggerTlsData *tls;
2492 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2496 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2498 mono_thread_state_init_from_current (&tls->context);
2501 /* Number of threads suspended */
2503 * If this is equal to the size of thread_to_tls, the runtime is considered
2506 static gint32 threads_suspend_count;
2508 static MonoCoopMutex suspend_mutex;
2510 /* Cond variable used to wait for suspend_count becoming 0 */
2511 static MonoCoopCond suspend_cond;
2513 /* Semaphore used to wait for a thread becoming suspended */
2514 static MonoCoopSem suspend_sem;
2519 mono_coop_mutex_init (&suspend_mutex);
2520 mono_coop_cond_init (&suspend_cond);
2521 mono_coop_sem_init (&suspend_sem, 0);
2526 StackFrameInfo last_frame;
2527 gboolean last_frame_set;
2531 } GetLastFrameUserData;
2534 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2536 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2538 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2541 if (!data->last_frame_set) {
2542 /* Store the last frame */
2543 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2544 data->last_frame_set = TRUE;
2547 /* Store the context/lmf for the frame above the last frame */
2548 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2549 data->lmf = info->lmf;
2550 data->domain = info->domain;
2556 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2558 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2560 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2561 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2562 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2569 * Process interruption of a thread. This should be signal safe.
2571 * This always runs in the debugger thread.
2574 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2577 MonoNativeThreadId tid;
2581 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2582 tid = mono_thread_info_get_tid (info);
2584 // FIXME: Races when the thread leaves managed code before hitting a single step
2587 if (ji && !ji->is_trampoline) {
2588 /* Running managed code, will be suspended by the single step code */
2589 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2592 * Running native code, will be suspended when it returns to/enters
2593 * managed code. Treat it as already suspended.
2594 * This might interrupt the code in process_single_step_inner (), we use the
2595 * tls->suspending flag to avoid races when that happens.
2597 if (!tls->suspended && !tls->suspending) {
2598 GetLastFrameUserData data;
2600 // FIXME: printf is not signal safe, but this is only used during
2601 // debugger debugging
2603 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2604 //save_thread_context (&ctx);
2607 /* Already terminated */
2611 * We are in a difficult position: we want to be able to provide stack
2612 * traces for this thread, but we can't use the current ctx+lmf, since
2613 * the thread is still running, so it might return to managed code,
2614 * making these invalid.
2615 * So we start a stack walk and save the first frame, along with the
2616 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2617 * suspended when it returns to managed code, so the parent's ctx should
2620 data.last_frame_set = FALSE;
2621 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2622 if (data.last_frame_set) {
2623 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2625 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2627 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2628 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2630 tls->async_state.valid = FALSE;
2633 mono_memory_barrier ();
2635 tls->suspended = TRUE;
2636 mono_coop_sem_post (&suspend_sem);
2642 * reset_native_thread_suspend_state:
2644 * Reset the suspended flag and state on native threads
2647 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2649 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2651 if (!tls->really_suspended && tls->suspended) {
2652 tls->suspended = FALSE;
2654 * The thread might still be running if it was executing native code, so the state won't be invalided by
2655 * suspend_current ().
2657 tls->context.valid = FALSE;
2658 tls->async_state.valid = FALSE;
2659 invalidate_frames (tls);
2664 DebuggerTlsData *tls;
2665 gboolean valid_info;
2668 static SuspendThreadResult
2669 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2671 InterruptData *data = (InterruptData *)user_data;
2674 data->valid_info = TRUE;
2675 ji = mono_jit_info_table_find_internal (
2676 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2677 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2681 /* This is signal safe */
2682 thread_interrupt (data->tls, info, ji);
2683 return MonoResumeThread;
2689 * Notify a thread that it needs to suspend.
2692 notify_thread (gpointer key, gpointer value, gpointer user_data)
2694 MonoInternalThread *thread = (MonoInternalThread *)key;
2695 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2696 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2698 if (mono_thread_internal_is_current (thread) || tls->terminated)
2701 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2703 /* This is _not_ equivalent to mono_thread_internal_abort () */
2704 InterruptData interrupt_data = { 0 };
2705 interrupt_data.tls = tls;
2707 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2708 if (!interrupt_data.valid_info) {
2709 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2711 * Attached thread which died without detaching.
2713 tls->terminated = TRUE;
2718 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2720 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2724 if (mono_loader_lock_is_owned_by_self ()) {
2726 * Shortcut for the check in suspend_current (). This speeds up processing
2727 * when executing long running code inside the loader lock, i.e. assembly load
2733 if (is_debugger_thread ())
2736 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2737 if (suspend_count - tls->resume_count > 0)
2738 tls->suspending = TRUE;
2740 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2742 if (suspend_count - tls->resume_count == 0) {
2744 * We are executing a single threaded invoke but the single step for
2745 * suspending is still active.
2746 * FIXME: This slows down single threaded invokes.
2748 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2752 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2754 /* Can't suspend in these methods */
2755 method = jinfo_get_method (ji);
2756 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2759 save_thread_context (ctx);
2767 * Increase the suspend count of the VM. While the suspend count is greater
2768 * than 0, runtime threads are suspended at certain points during execution.
2773 mono_loader_lock ();
2775 mono_coop_mutex_lock (&suspend_mutex);
2779 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2781 if (suspend_count == 1) {
2782 // FIXME: Is it safe to call this inside the lock ?
2783 start_single_stepping ();
2784 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2787 mono_coop_mutex_unlock (&suspend_mutex);
2789 if (suspend_count == 1)
2791 * Suspend creation of new threadpool threads, since they cannot run
2793 mono_threadpool_suspend ();
2795 mono_loader_unlock ();
2801 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2807 g_assert (is_debugger_thread ());
2809 mono_loader_lock ();
2811 mono_coop_mutex_lock (&suspend_mutex);
2813 g_assert (suspend_count > 0);
2816 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2818 if (suspend_count == 0) {
2819 // FIXME: Is it safe to call this inside the lock ?
2820 stop_single_stepping ();
2821 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2824 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2825 mono_coop_cond_broadcast (&suspend_cond);
2827 mono_coop_mutex_unlock (&suspend_mutex);
2828 //g_assert (err == 0);
2830 if (suspend_count == 0)
2831 mono_threadpool_resume ();
2833 mono_loader_unlock ();
2839 * Resume just one thread.
2842 resume_thread (MonoInternalThread *thread)
2844 DebuggerTlsData *tls;
2846 g_assert (is_debugger_thread ());
2848 mono_loader_lock ();
2850 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2853 mono_coop_mutex_lock (&suspend_mutex);
2855 g_assert (suspend_count > 0);
2857 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2859 tls->resume_count += suspend_count;
2862 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2863 * but only the one whose resume_count field is > 0 will be resumed.
2865 mono_coop_cond_broadcast (&suspend_cond);
2867 mono_coop_mutex_unlock (&suspend_mutex);
2868 //g_assert (err == 0);
2870 mono_loader_unlock ();
2874 free_frames (StackFrame **frames, int nframes)
2878 for (i = 0; i < nframes; ++i) {
2879 if (frames [i]->jit)
2880 mono_debug_free_method_jit_info (frames [i]->jit);
2881 g_free (frames [i]);
2887 invalidate_frames (DebuggerTlsData *tls)
2890 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2893 free_frames (tls->frames, tls->frame_count);
2894 tls->frame_count = 0;
2897 free_frames (tls->restore_frames, tls->restore_frame_count);
2898 tls->restore_frame_count = 0;
2899 tls->restore_frames = NULL;
2905 * Suspend the current thread until the runtime is resumed. If the thread has a
2906 * pending invoke, then the invoke is executed before this function returns.
2909 suspend_current (void)
2911 DebuggerTlsData *tls;
2913 g_assert (!is_debugger_thread ());
2915 if (mono_loader_lock_is_owned_by_self ()) {
2917 * If we own the loader mutex, can't suspend until we release it, since the
2918 * whole runtime can deadlock otherwise.
2923 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2926 mono_coop_mutex_lock (&suspend_mutex);
2928 tls->suspending = FALSE;
2929 tls->really_suspended = TRUE;
2931 if (!tls->suspended) {
2932 tls->suspended = TRUE;
2933 mono_coop_sem_post (&suspend_sem);
2936 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2938 while (suspend_count - tls->resume_count > 0) {
2939 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2942 tls->suspended = FALSE;
2943 tls->really_suspended = FALSE;
2945 threads_suspend_count --;
2947 mono_coop_mutex_unlock (&suspend_mutex);
2949 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2951 if (tls->pending_invoke) {
2952 /* Save the original context */
2953 tls->pending_invoke->has_ctx = TRUE;
2954 tls->pending_invoke->ctx = tls->context.ctx;
2959 /* The frame info becomes invalid after a resume */
2960 tls->context.valid = FALSE;
2961 tls->async_state.valid = FALSE;
2962 invalidate_frames (tls);
2966 count_thread (gpointer key, gpointer value, gpointer user_data)
2968 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2970 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
2971 *(int*)user_data = *(int*)user_data + 1;
2975 count_threads_to_wait_for (void)
2979 mono_loader_lock ();
2980 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2981 mono_loader_unlock ();
2989 * Wait until the runtime is completely suspended.
2992 wait_for_suspend (void)
2994 int nthreads, nwait, err;
2995 gboolean waited = FALSE;
2997 // FIXME: Threads starting/stopping ?
2998 mono_loader_lock ();
2999 nthreads = mono_g_hash_table_size (thread_to_tls);
3000 mono_loader_unlock ();
3003 nwait = count_threads_to_wait_for ();
3005 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3006 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3007 g_assert (err == 0);
3015 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3021 * Return whenever the runtime is suspended.
3026 return count_threads_to_wait_for () == 0;
3030 no_seq_points_found (MonoMethod *method, int offset)
3033 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3035 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3039 DebuggerTlsData *tls;
3041 } ComputeFramesUserData;
3044 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3046 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3048 MonoMethod *method, *actual_method, *api_method;
3052 if (info->type != FRAME_TYPE_MANAGED) {
3053 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3054 /* Mark the last frame as an invoke frame */
3056 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3062 method = jinfo_get_method (info->ji);
3064 method = info->method;
3065 actual_method = info->actual_method;
3066 api_method = method;
3071 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3074 if (info->il_offset == -1) {
3075 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3076 if (ud->frames == NULL) {
3077 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3078 info->il_offset = sp.il_offset;
3080 if (info->il_offset == -1)
3081 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3084 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);
3086 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3087 if (!CHECK_PROTOCOL_VERSION (2, 17))
3088 /* Older clients can't handle this flag */
3090 api_method = mono_marshal_method_from_wrapper (method);
3093 actual_method = api_method;
3094 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3097 frame = g_new0 (StackFrame, 1);
3098 frame->method = method;
3099 frame->actual_method = actual_method;
3100 frame->api_method = api_method;
3101 frame->il_offset = info->il_offset;
3102 frame->native_offset = info->native_offset;
3103 frame->flags = flags;
3104 frame->ji = info->ji;
3105 if (info->reg_locations)
3106 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3109 frame->has_ctx = TRUE;
3111 frame->domain = info->domain;
3113 ud->frames = g_slist_append (ud->frames, frame);
3119 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3121 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3124 * 'tls->filter_ctx' is the location of the throw site.
3126 * mono_walk_stack() will never actually hit the throw site, but unwind
3127 * directly from the filter to the call site; we abort stack unwinding here
3128 * once this happens and resume from the throw site.
3131 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3134 return process_frame (info, ctx, user_data);
3138 * Return a malloc-ed list of StackFrame structures.
3141 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3143 ComputeFramesUserData user_data;
3144 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3149 user_data.tls = tls;
3150 user_data.frames = NULL;
3152 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3154 nframes = g_slist_length (user_data.frames);
3155 res = g_new0 (StackFrame*, nframes);
3156 l = user_data.frames;
3157 for (i = 0; i < nframes; ++i) {
3158 res [i] = (StackFrame *)l->data;
3161 *out_nframes = nframes;
3167 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3169 ComputeFramesUserData user_data;
3171 int i, findex, new_frame_count;
3172 StackFrame **new_frames, *f;
3173 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3175 // FIXME: Locking on tls
3176 if (tls->frames && tls->frames_up_to_date)
3179 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3181 user_data.tls = tls;
3182 user_data.frames = NULL;
3183 if (tls->terminated) {
3184 tls->frame_count = 0;
3186 } if (!tls->really_suspended && tls->async_state.valid) {
3187 /* Have to use the state saved by the signal handler */
3188 process_frame (&tls->async_last_frame, NULL, &user_data);
3189 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3190 } else if (tls->filter_state.valid) {
3192 * We are inside an exception filter.
3194 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3196 if (tls->context.valid)
3197 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3199 * After that, we resume unwinding from the location where the exception has been thrown.
3201 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3202 } else if (tls->context.valid) {
3203 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3206 tls->frame_count = 0;
3210 new_frame_count = g_slist_length (user_data.frames);
3211 new_frames = g_new0 (StackFrame*, new_frame_count);
3213 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3214 f = (StackFrame *)tmp->data;
3217 * Reuse the id for already existing stack frames, so invokes don't invalidate
3218 * the still valid stack frames.
3220 for (i = 0; i < tls->frame_count; ++i) {
3221 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3222 f->id = tls->frames [i]->id;
3227 if (i >= tls->frame_count)
3228 f->id = InterlockedIncrement (&frame_id);
3230 new_frames [findex ++] = f;
3233 g_slist_free (user_data.frames);
3235 invalidate_frames (tls);
3237 tls->frames = new_frames;
3238 tls->frame_count = new_frame_count;
3239 tls->frames_up_to_date = TRUE;
3243 * GHFunc to emit an appdomain creation event
3244 * @param key Don't care
3245 * @param value A loaded appdomain
3246 * @param user_data Don't care
3249 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3251 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3252 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3256 * GHFunc to emit a thread start event
3257 * @param key A thread id
3258 * @param value A thread object
3259 * @param user_data Don't care
3262 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3264 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3265 process_profiler_event (EVENT_KIND_THREAD_START, value);
3269 * GFunc to emit an assembly load event
3270 * @param value A loaded assembly
3271 * @param user_data Don't care
3274 emit_assembly_load (gpointer value, gpointer user_data)
3276 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3280 * GFunc to emit a type load event
3281 * @param value A loaded type
3282 * @param user_data Don't care
3285 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3287 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3291 strdup_tolower (char *s)
3296 for (p = s2; *p; ++p)
3302 * Same as g_path_get_basename () but handles windows paths as well,
3303 * which can occur in .mdb files created by pdb2mdb.
3306 dbg_path_get_basename (const char *filename)
3310 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3311 return g_path_get_basename (filename);
3315 /* No separator -> filename */
3316 r = strrchr (filename, '\\');
3318 return g_strdup (filename);
3320 /* Trailing slash, remove component */
3322 char *copy = g_strdup (filename);
3323 copy [r-filename] = 0;
3324 r = strrchr (copy, '\\');
3328 return g_strdup ("/");
3330 r = g_strdup (&r[1]);
3335 return g_strdup (&r[1]);
3339 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3341 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3343 MonoCustomAttrInfo *ainfo;
3345 if (ji->dbg_attrs_inited)
3349 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3351 if (!step_through_klass)
3352 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3354 if (!non_user_klass)
3355 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3357 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3358 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3360 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3361 ji->dbg_hidden = TRUE;
3362 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3363 ji->dbg_step_through = TRUE;
3364 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3365 ji->dbg_non_user_code = TRUE;
3366 mono_custom_attrs_free (ainfo);
3369 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3370 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3372 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3373 ji->dbg_step_through = TRUE;
3374 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3375 ji->dbg_non_user_code = TRUE;
3376 mono_custom_attrs_free (ainfo);
3379 mono_memory_barrier ();
3380 ji->dbg_attrs_inited = TRUE;
3388 * create_event_list:
3390 * Return a list of event request ids matching EVENT, starting from REQS, which
3391 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3393 * We return request ids, instead of requests, to simplify threading, since
3394 * requests could be deleted anytime when the loader lock is not held.
3395 * LOCKING: Assumes the loader lock is held.
3398 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3401 GSList *events = NULL;
3403 *suspend_policy = SUSPEND_POLICY_NONE;
3406 reqs = event_requests;
3411 for (i = 0; i < reqs->len; ++i) {
3412 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3413 if (req->event_kind == event) {
3414 gboolean filtered = FALSE;
3417 for (j = 0; j < req->nmodifiers; ++j) {
3418 Modifier *mod = &req->modifiers [j];
3420 if (mod->kind == MOD_KIND_COUNT) {
3422 if (mod->data.count > 0) {
3423 if (mod->data.count > 0) {
3425 if (mod->data.count == 0)
3429 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3430 if (mod->data.thread != mono_thread_internal_current ())
3432 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3433 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3435 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3437 if (ei->caught && !mod->caught)
3439 if (!ei->caught && !mod->uncaught)
3441 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3443 gboolean found = FALSE;
3444 MonoAssembly **assemblies = mod->data.assemblies;
3447 for (k = 0; assemblies [k]; ++k)
3448 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3453 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3454 gpointer iter = NULL;
3456 MonoDebugSourceInfo *sinfo;
3457 char *source_file, *s;
3458 gboolean found = FALSE;
3460 GPtrArray *source_file_list;
3462 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3463 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3466 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3467 for (i = 0; i < source_file_list->len; ++i) {
3468 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3470 * Do a case-insesitive match by converting the file name to
3473 s = strdup_tolower (sinfo->source_file);
3474 if (g_hash_table_lookup (mod->data.source_files, s))
3477 char *s2 = dbg_path_get_basename (sinfo->source_file);
3478 char *s3 = strdup_tolower (s2);
3480 if (g_hash_table_lookup (mod->data.source_files, s3))
3487 g_ptr_array_free (source_file_list, TRUE);
3492 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3495 s = mono_type_full_name (&ei->klass->byval_arg);
3496 if (!g_hash_table_lookup (mod->data.type_names, s))
3499 } else if (mod->kind == MOD_KIND_STEP) {
3500 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3501 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3502 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3503 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3505 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3506 init_jit_info_dbg_attrs (ji);
3510 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3511 init_jit_info_dbg_attrs (ji);
3512 if (ji->dbg_step_through)
3515 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3516 init_jit_info_dbg_attrs (ji);
3517 if (ji->dbg_non_user_code)
3524 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3525 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3530 /* Send a VM START/DEATH event by default */
3531 if (event == EVENT_KIND_VM_START)
3532 events = g_slist_append (events, GINT_TO_POINTER (0));
3533 if (event == EVENT_KIND_VM_DEATH)
3534 events = g_slist_append (events, GINT_TO_POINTER (0));
3539 static G_GNUC_UNUSED const char*
3540 event_to_string (EventKind event)
3543 case EVENT_KIND_VM_START: return "VM_START";
3544 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3545 case EVENT_KIND_THREAD_START: return "THREAD_START";
3546 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3547 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3548 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3549 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3550 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3551 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3552 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3553 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3554 case EVENT_KIND_STEP: return "STEP";
3555 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3556 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3557 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3558 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3559 case EVENT_KIND_USER_LOG: return "USER_LOG";
3561 g_assert_not_reached ();
3569 * Send an event to the client, suspending the vm if needed.
3570 * LOCKING: Since this can suspend the calling thread, no locks should be held
3572 * The EVENTS list is freed by this function.
3575 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3579 MonoDomain *domain = mono_domain_get ();
3580 MonoThread *thread = NULL;
3581 MonoObject *keepalive_obj = NULL;
3582 gboolean send_success = FALSE;
3587 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3591 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3592 // FIXME: We miss those events
3593 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3597 if (vm_death_event_sent) {
3598 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3602 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3603 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3608 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3612 if (event == EVENT_KIND_KEEPALIVE)
3613 suspend_policy = SUSPEND_POLICY_NONE;
3618 if (agent_config.defer) {
3619 /* Make sure the thread id is always set when doing deferred debugging */
3620 if (is_debugger_thread ()) {
3621 /* Don't suspend on events from the debugger thread */
3622 suspend_policy = SUSPEND_POLICY_NONE;
3623 thread = mono_thread_get_main ();
3625 else thread = mono_thread_current ();
3627 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3628 // FIXME: Send these with a NULL thread, don't suspend the current thread
3633 nevents = g_slist_length (events);
3634 buffer_init (&buf, 128);
3635 buffer_add_byte (&buf, suspend_policy);
3636 buffer_add_int (&buf, nevents);
3638 for (l = events; l; l = l->next) {
3639 buffer_add_byte (&buf, event); // event kind
3640 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3644 if (event == EVENT_KIND_VM_DEATH) {
3648 thread = mono_thread_current ();
3650 if (event == EVENT_KIND_VM_START && arg != NULL)
3651 thread = (MonoThread *)arg;
3654 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3657 case EVENT_KIND_THREAD_START:
3658 case EVENT_KIND_THREAD_DEATH:
3660 case EVENT_KIND_APPDOMAIN_CREATE:
3661 case EVENT_KIND_APPDOMAIN_UNLOAD:
3662 buffer_add_domainid (&buf, (MonoDomain *)arg);
3664 case EVENT_KIND_METHOD_ENTRY:
3665 case EVENT_KIND_METHOD_EXIT:
3666 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3668 case EVENT_KIND_ASSEMBLY_LOAD:
3669 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3671 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3672 DebuggerTlsData *tls;
3674 /* The domain the assembly belonged to is not equal to the current domain */
3675 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3677 g_assert (tls->domain_unloading);
3679 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3682 case EVENT_KIND_TYPE_LOAD:
3683 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3685 case EVENT_KIND_BREAKPOINT:
3686 case EVENT_KIND_STEP:
3687 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3688 buffer_add_long (&buf, il_offset);
3690 case EVENT_KIND_VM_START:
3691 buffer_add_domainid (&buf, mono_get_root_domain ());
3693 case EVENT_KIND_VM_DEATH:
3694 if (CHECK_PROTOCOL_VERSION (2, 27))
3695 buffer_add_int (&buf, mono_environment_exitcode_get ());
3697 case EVENT_KIND_EXCEPTION: {
3698 EventInfo *ei = (EventInfo *)arg;
3699 buffer_add_objid (&buf, ei->exc);
3701 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3702 * later after the suspension. (#12494).
3704 keepalive_obj = ei->exc;
3707 case EVENT_KIND_USER_BREAK:
3709 case EVENT_KIND_USER_LOG: {
3710 EventInfo *ei = (EventInfo *)arg;
3711 buffer_add_int (&buf, ei->level);
3712 buffer_add_string (&buf, ei->category ? ei->category : "");
3713 buffer_add_string (&buf, ei->message ? ei->message : "");
3716 case EVENT_KIND_KEEPALIVE:
3717 suspend_policy = SUSPEND_POLICY_NONE;
3720 g_assert_not_reached ();
3724 if (event == EVENT_KIND_VM_START) {
3725 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3726 if (!agent_config.defer)
3727 start_debugger_thread ();
3730 if (event == EVENT_KIND_VM_DEATH) {
3731 vm_death_event_sent = TRUE;
3732 suspend_policy = SUSPEND_POLICY_NONE;
3735 if (mono_runtime_is_shutting_down ())
3736 suspend_policy = SUSPEND_POLICY_NONE;
3738 if (suspend_policy != SUSPEND_POLICY_NONE) {
3740 * Save the thread context and start suspending before sending the packet,
3741 * since we could be receiving the resume request before send_packet ()
3744 save_thread_context (ctx);
3748 /* This will keep this object alive */
3749 get_objref (keepalive_obj);
3752 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3756 g_slist_free (events);
3759 if (!send_success) {
3760 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3764 if (event == EVENT_KIND_VM_START) {
3765 vm_start_event_sent = TRUE;
3768 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);
3770 switch (suspend_policy) {
3771 case SUSPEND_POLICY_NONE:
3773 case SUSPEND_POLICY_ALL:
3776 case SUSPEND_POLICY_EVENT_THREAD:
3780 g_assert_not_reached ();
3785 process_profiler_event (EventKind event, gpointer arg)
3789 EventInfo ei, *ei_arg = NULL;
3791 if (event == EVENT_KIND_TYPE_LOAD) {
3792 ei.klass = (MonoClass *)arg;
3796 mono_loader_lock ();
3797 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3798 mono_loader_unlock ();
3800 process_event (event, arg, 0, NULL, events, suspend_policy);
3804 runtime_initialized (MonoProfiler *prof)
3806 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3807 if (agent_config.defer)
3808 start_debugger_thread ();
3812 runtime_shutdown (MonoProfiler *prof)
3814 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3816 mono_debugger_agent_cleanup ();
3820 thread_startup (MonoProfiler *prof, uintptr_t tid)
3822 MonoInternalThread *thread = mono_thread_internal_current ();
3823 MonoInternalThread *old_thread;
3824 DebuggerTlsData *tls;
3826 if (is_debugger_thread ())
3829 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3831 mono_loader_lock ();
3832 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3833 mono_loader_unlock ();
3835 if (thread == old_thread) {
3837 * For some reason, thread_startup () might be called for the same thread
3838 * multiple times (attach ?).
3840 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3844 * thread_end () might not be called for some threads, and the tid could
3847 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3848 mono_loader_lock ();
3849 mono_g_hash_table_remove (thread_to_tls, old_thread);
3850 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3851 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3852 mono_loader_unlock ();
3856 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3858 // FIXME: Free this somewhere
3859 tls = g_new0 (DebuggerTlsData, 1);
3860 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3861 tls->thread = thread;
3862 mono_native_tls_set_value (debugger_tls_id, tls);
3864 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3866 mono_loader_lock ();
3867 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3868 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3869 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3870 mono_loader_unlock ();
3872 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3875 * suspend_vm () could have missed this thread, so wait for a resume.
3881 thread_end (MonoProfiler *prof, uintptr_t tid)
3883 MonoInternalThread *thread;
3884 DebuggerTlsData *tls = NULL;
3886 mono_loader_lock ();
3887 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3889 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3890 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3892 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3893 tls->terminated = TRUE;
3894 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3895 MONO_GC_UNREGISTER_ROOT (tls->thread);
3899 mono_loader_unlock ();
3901 /* We might be called for threads started before we registered the start callback */
3903 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3905 if (mono_thread_internal_is_current (thread) && !mono_native_tls_get_value (debugger_tls_id)
3908 * This can happen on darwin since we deregister threads using pthread dtors.
3909 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3914 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3919 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3921 mono_loader_lock ();
3922 g_hash_table_insert (domains, domain, domain);
3923 mono_loader_unlock ();
3925 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3929 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3931 DebuggerTlsData *tls;
3933 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3934 if (is_debugger_thread ())
3938 * Remember the currently unloading appdomain as it is needed to generate
3939 * proper ids for unloading assemblies.
3941 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3943 tls->domain_unloading = domain;
3947 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3949 DebuggerTlsData *tls;
3951 if (is_debugger_thread ())
3954 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3956 tls->domain_unloading = NULL;
3958 clear_breakpoints_for_domain (domain);
3960 mono_loader_lock ();
3961 /* Invalidate each thread's frame stack */
3962 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3963 mono_loader_unlock ();
3965 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3969 * invalidate_each_thread:
3971 * A GHFunc to invalidate frames.
3972 * value must be a DebuggerTlsData*
3975 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3977 invalidate_frames ((DebuggerTlsData *)value);
3981 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3983 /* Sent later in jit_end () */
3985 g_ptr_array_add (pending_assembly_loads, assembly);
3990 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3992 if (is_debugger_thread ())
3995 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3997 clear_event_requests_for_assembly (assembly);
3998 clear_types_for_assembly (assembly);
4002 send_type_load (MonoClass *klass)
4004 gboolean type_load = FALSE;
4005 MonoDomain *domain = mono_domain_get ();
4006 AgentDomainInfo *info = NULL;
4008 info = get_agent_domain_info (domain);
4010 mono_loader_lock ();
4012 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4014 g_hash_table_insert (info->loaded_classes, klass, klass);
4017 mono_loader_unlock ();
4020 emit_type_load (klass, klass, NULL);
4024 * Emit load events for all types currently loaded in the domain.
4025 * Takes the loader and domain locks.
4026 * user_data is unused.
4029 send_types_for_domain (MonoDomain *domain, void *user_data)
4031 MonoDomain* old_domain;
4032 AgentDomainInfo *info = NULL;
4034 info = get_agent_domain_info (domain);
4037 old_domain = mono_domain_get ();
4039 mono_domain_set (domain, TRUE);
4041 mono_loader_lock ();
4042 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4043 mono_loader_unlock ();
4045 mono_domain_set (old_domain, TRUE);
4049 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4052 MonoDomain* old_domain;
4054 old_domain = mono_domain_get ();
4056 mono_domain_set (domain, TRUE);
4058 mono_domain_assemblies_lock (domain);
4059 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4060 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4061 emit_assembly_load (ass, NULL);
4063 mono_domain_assemblies_unlock (domain);
4065 mono_domain_set (old_domain, TRUE);
4069 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4072 * We emit type load events when the first method of the type is JITted,
4073 * since the class load profiler callbacks might be called with the
4074 * loader lock held. They could also occur in the debugger thread.
4075 * Same for assembly load events.
4078 MonoAssembly *assembly = NULL;
4080 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4082 if (pending_assembly_loads->len > 0) {
4083 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4084 g_ptr_array_remove_index (pending_assembly_loads, 0);
4089 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4095 send_type_load (method->klass);
4098 add_pending_breakpoints (method, jinfo);
4102 * BREAKPOINTS/SINGLE STEPPING
4106 * Contains information about an inserted breakpoint.
4109 long il_offset, native_offset;
4113 } BreakpointInstance;
4116 * Contains generic information about a breakpoint.
4120 * The method where the breakpoint is placed. Can be NULL in which case it
4121 * is inserted into every method. This is used to implement method entry/
4122 * exit events. Can be a generic method definition, in which case the
4123 * breakpoint is inserted into every instance.
4129 * A list of BreakpointInstance structures describing where the breakpoint
4130 * was inserted. There could be more than one because of
4131 * generics/appdomains/method entry/exit.
4133 GPtrArray *children;
4136 /* List of breakpoints */
4137 /* Protected by the loader lock */
4138 static GPtrArray *breakpoints;
4139 /* Maps breakpoint locations to the number of breakpoints at that location */
4140 static GHashTable *bp_locs;
4143 breakpoints_init (void)
4145 breakpoints = g_ptr_array_new ();
4146 bp_locs = g_hash_table_new (NULL, NULL);
4150 * insert_breakpoint:
4152 * Insert the breakpoint described by BP into the method described by
4156 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4159 BreakpointInstance *inst;
4160 SeqPointIterator it;
4161 gboolean it_has_sp = FALSE;
4166 mono_seq_point_iterator_init (&it, seq_points);
4167 while (mono_seq_point_iterator_next (&it)) {
4168 if (it.seq_point.il_offset == bp->il_offset) {
4176 * The set of IL offsets with seq points doesn't completely match the
4177 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4179 mono_seq_point_iterator_init (&it, seq_points);
4180 while (mono_seq_point_iterator_next (&it)) {
4181 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4182 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4183 it.seq_point.il_offset + 1 == bp->il_offset) {
4191 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4193 mono_seq_point_iterator_init (&it, seq_points);
4194 while (mono_seq_point_iterator_next (&it))
4195 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4198 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4199 g_warning ("%s", s);
4203 g_warning ("%s", s);
4209 inst = g_new0 (BreakpointInstance, 1);
4210 inst->il_offset = it.seq_point.il_offset;
4211 inst->native_offset = it.seq_point.native_offset;
4212 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4214 inst->domain = domain;
4216 mono_loader_lock ();
4218 g_ptr_array_add (bp->children, inst);
4220 mono_loader_unlock ();
4223 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4224 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4227 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4228 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4229 } else if (count == 0) {
4230 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4231 mono_arch_set_breakpoint (ji, inst->ip);
4237 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);
4241 remove_breakpoint (BreakpointInstance *inst)
4243 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4245 MonoJitInfo *ji = inst->ji;
4246 guint8 *ip = inst->ip;
4249 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4250 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4253 g_assert (count > 0);
4255 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4256 mono_arch_clear_breakpoint (ji, ip);
4257 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4265 * This doesn't take any locks.
4267 static inline gboolean
4268 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4274 if (method == bp->method)
4276 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4279 if (bp->method->is_inflated && method->is_inflated) {
4280 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4281 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4283 /* Open generic methods should match closed generic methods of the same class */
4284 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4285 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4286 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4288 /* FIXME: Handle !mvar */
4289 if (t1->type != MONO_TYPE_MVAR)
4300 * add_pending_breakpoints:
4302 * Insert pending breakpoints into the newly JITted method METHOD.
4305 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4308 MonoSeqPointInfo *seq_points;
4310 MonoMethod *jmethod;
4315 domain = mono_domain_get ();
4317 mono_loader_lock ();
4319 for (i = 0; i < breakpoints->len; ++i) {
4320 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4321 gboolean found = FALSE;
4323 if (!bp_matches_method (bp, method))
4326 for (j = 0; j < bp->children->len; ++j) {
4327 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4334 MonoMethod *declaring = NULL;
4336 jmethod = jinfo_get_method (ji);
4337 if (jmethod->is_inflated)
4338 declaring = mono_method_get_declaring_generic_method (jmethod);
4340 mono_domain_lock (domain);
4341 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4342 if (!seq_points && declaring)
4343 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4344 mono_domain_unlock (domain);
4346 /* Could be AOT code */
4348 g_assert (seq_points);
4350 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4354 mono_loader_unlock ();
4358 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4366 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4370 /* Might be AOTed code */
4371 mono_class_init (method->klass);
4372 code = mono_aot_get_method_checked (domain, method, &oerror);
4374 mono_error_assert_ok (&oerror);
4375 ji = mono_jit_info_table_find (domain, (char *)code);
4380 insert_breakpoint (seq_points, domain, ji, bp, error);
4384 clear_breakpoint (MonoBreakpoint *bp);
4389 * Set a breakpoint at IL_OFFSET in METHOD.
4390 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4391 * METHOD can also be a generic method definition, in which case a breakpoint
4392 * is placed in all instances of the method.
4393 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4396 static MonoBreakpoint*
4397 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4400 GHashTableIter iter, iter2;
4403 MonoSeqPointInfo *seq_points;
4405 GPtrArray *method_domains;
4406 GPtrArray *method_seq_points;
4413 // - suspend/resume the vm to prevent code patching problems
4414 // - multiple breakpoints on the same location
4415 // - dynamic methods
4418 bp = g_new0 (MonoBreakpoint, 1);
4419 bp->method = method;
4420 bp->il_offset = il_offset;
4422 bp->children = g_ptr_array_new ();
4424 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);
4426 methods = g_ptr_array_new ();
4427 method_domains = g_ptr_array_new ();
4428 method_seq_points = g_ptr_array_new ();
4430 mono_loader_lock ();
4431 g_hash_table_iter_init (&iter, domains);
4432 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4433 mono_domain_lock (domain);
4434 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4435 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4436 if (bp_matches_method (bp, m)) {
4437 /* Save the info locally to simplify the code inside the domain lock */
4438 g_ptr_array_add (methods, m);
4439 g_ptr_array_add (method_domains, domain);
4440 g_ptr_array_add (method_seq_points, seq_points);
4443 mono_domain_unlock (domain);
4446 for (i = 0; i < methods->len; ++i) {
4447 m = (MonoMethod *)g_ptr_array_index (methods, i);
4448 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4449 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4450 set_bp_in_method (domain, m, seq_points, bp, error);
4453 g_ptr_array_add (breakpoints, bp);
4454 mono_loader_unlock ();
4456 g_ptr_array_free (methods, TRUE);
4457 g_ptr_array_free (method_domains, TRUE);
4458 g_ptr_array_free (method_seq_points, TRUE);
4460 if (error && !mono_error_ok (error)) {
4461 clear_breakpoint (bp);
4469 clear_breakpoint (MonoBreakpoint *bp)
4473 // FIXME: locking, races
4474 for (i = 0; i < bp->children->len; ++i) {
4475 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4477 remove_breakpoint (inst);
4482 mono_loader_lock ();
4483 g_ptr_array_remove (breakpoints, bp);
4484 mono_loader_unlock ();
4486 g_ptr_array_free (bp->children, TRUE);
4491 breakpoints_cleanup (void)
4495 mono_loader_lock ();
4497 while (i < event_requests->len) {
4498 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4500 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4501 clear_breakpoint ((MonoBreakpoint *)req->info);
4502 g_ptr_array_remove_index_fast (event_requests, i);
4509 for (i = 0; i < breakpoints->len; ++i)
4510 g_free (g_ptr_array_index (breakpoints, i));
4512 g_ptr_array_free (breakpoints, TRUE);
4513 g_hash_table_destroy (bp_locs);
4518 mono_loader_unlock ();
4522 * clear_breakpoints_for_domain:
4524 * Clear breakpoint instances which reference DOMAIN.
4527 clear_breakpoints_for_domain (MonoDomain *domain)
4531 /* This could be called after shutdown */
4535 mono_loader_lock ();
4536 for (i = 0; i < breakpoints->len; ++i) {
4537 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4540 while (j < bp->children->len) {
4541 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4543 if (inst->domain == domain) {
4544 remove_breakpoint (inst);
4548 g_ptr_array_remove_index_fast (bp->children, j);
4554 mono_loader_unlock ();
4558 * ss_calculate_framecount:
4560 * Ensure DebuggerTlsData fields are filled out.
4562 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4564 if (!tls->context.valid)
4565 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4566 compute_frame_info (tls->thread, tls);
4570 ensure_jit (StackFrame* frame)
4573 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4574 if (!frame->jit && frame->api_method->is_inflated)
4575 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4579 /* This could happen for aot images with no jit debug info */
4580 s = mono_method_full_name (frame->api_method, TRUE);
4581 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4592 * Return FALSE if single stepping needs to continue.
4595 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4597 MonoDebugMethodInfo *minfo;
4598 MonoDebugSourceLocation *loc = NULL;
4599 gboolean hit = TRUE;
4601 if (req->async_stepout_method == method) {
4602 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);
4606 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4608 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4610 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);
4614 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4615 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4617 ss_calculate_framecount (tls, ctx);
4619 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4620 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4621 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4622 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4623 /* Hit the breakpoint in a recursive call, don't halt */
4624 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");
4629 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4630 ss_calculate_framecount (tls, ctx);
4631 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4632 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);
4637 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4639 for (int i = 0; i < asyncMethod->num_awaits; i++)
4641 if (asyncMethod->yield_offsets[i] == sp->il_offset || asyncMethod->resume_offsets[i] == sp->il_offset) {
4642 mono_debug_free_method_async_debug_info (asyncMethod);
4646 mono_debug_free_method_async_debug_info (asyncMethod);
4649 if (req->size != STEP_SIZE_LINE)
4652 /* Have to check whenever a different source line was reached */
4653 minfo = mono_debug_lookup_method (method);
4656 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4659 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);
4660 ss_req->last_method = method;
4662 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4663 ss_calculate_framecount (tls, ctx);
4664 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4665 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4671 ss_req->last_method = method;
4672 ss_req->last_line = loc->row;
4673 mono_debug_free_source_location (loc);
4680 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4682 return bp->method && bp->method->klass->image->assembly == assembly;
4686 get_this (StackFrame *frame)
4688 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4689 MonoDebugVarInfo *var = frame->jit->this_var;
4690 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4693 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4694 addr += (gint32)var->offset;
4695 return *(MonoObject**)addr;
4698 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4699 //since thread probably changed...
4701 get_this_async_id (StackFrame *frame)
4703 return get_objid (get_this (frame));
4706 static MonoMethod* set_notification_method_cache = NULL;
4709 get_set_notification_method ()
4711 if(set_notification_method_cache != NULL)
4712 return set_notification_method_cache;
4714 MonoClass* async_builder_class = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder");
4715 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4716 mono_error_assert_ok (&error);
4717 g_assert (array->len == 1);
4718 set_notification_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4719 g_ptr_array_free (array, TRUE);
4720 return set_notification_method_cache;
4724 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4726 MonoObject* obj = get_this (frame);
4728 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4729 g_assert (builder_field);
4730 MonoObject* builder;
4732 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4733 mono_error_assert_ok (&error);
4737 gboolean arg = TRUE;
4739 mono_runtime_invoke_checked (get_set_notification_method(), mono_object_unbox (builder), args, &error);
4740 mono_error_assert_ok (&error);
4741 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4744 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4747 get_notify_debugger_of_wait_completion_method ()
4749 if (notify_debugger_of_wait_completion_method_cache != NULL)
4750 return notify_debugger_of_wait_completion_method_cache;
4752 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4753 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4754 mono_error_assert_ok (&error);
4755 g_assert (array->len == 1);
4756 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4757 g_ptr_array_free (array, TRUE);
4758 return notify_debugger_of_wait_completion_method_cache;
4762 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4766 int i, j, suspend_policy;
4767 guint32 native_offset;
4769 BreakpointInstance *inst;
4770 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4771 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4772 EventKind kind = EVENT_KIND_BREAKPOINT;
4773 MonoContext *ctx = &tls->restore_state.ctx;
4775 MonoSeqPointInfo *info;
4779 // FIXME: Speed this up
4781 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4782 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4783 g_assert (ji && !ji->is_trampoline);
4784 method = jinfo_get_method (ji);
4786 /* Compute the native offset of the breakpoint from the ip */
4787 native_offset = ip - (guint8*)ji->code_start;
4790 * Skip the instruction causing the breakpoint signal.
4793 mono_arch_skip_breakpoint (ctx, ji);
4795 if (method->wrapper_type || tls->disable_breakpoints)
4798 bp_reqs = g_ptr_array_new ();
4799 ss_reqs = g_ptr_array_new ();
4800 ss_reqs_orig = g_ptr_array_new ();
4802 mono_loader_lock ();
4805 * The ip points to the instruction causing the breakpoint event, which is after
4806 * the offset recorded in the seq point map, so find the prev seq point before ip.
4808 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4811 no_seq_points_found (method, native_offset);
4813 g_assert (found_sp);
4815 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);
4818 for (i = 0; i < breakpoints->len; ++i) {
4819 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4824 for (j = 0; j < bp->children->len; ++j) {
4825 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4826 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4827 if (bp->req->event_kind == EVENT_KIND_STEP) {
4828 g_ptr_array_add (ss_reqs_orig, bp->req);
4830 g_ptr_array_add (bp_reqs, bp->req);
4835 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4836 /* Maybe a method entry/exit event */
4837 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4838 kind = EVENT_KIND_METHOD_ENTRY;
4839 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4840 kind = EVENT_KIND_METHOD_EXIT;
4843 /* Process single step requests */
4844 for (i = 0; i < ss_reqs_orig->len; ++i) {
4845 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4846 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4849 //if we hit async_stepout_method, it's our no matter which thread
4850 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4851 //We have different thread and we don't have async stepping in progress
4852 //it's breakpoint in parallel thread, ignore it
4853 if (ss_req->async_id == 0)
4856 tls->context.valid = FALSE;
4857 tls->async_state.valid = FALSE;
4858 invalidate_frames (tls);
4859 ss_calculate_framecount(tls, ctx);
4860 //make sure we have enough data to get current async method instance id
4861 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4864 //Check method is async before calling get_this_async_id
4865 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4869 mono_debug_free_method_async_debug_info (asyncMethod);
4871 //breakpoint was hit in parallelly executing async method, ignore it
4872 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4876 //Update stepping request to new thread/frame_count that we are continuing on
4877 //so continuing with normal stepping works as expected
4878 if (ss_req->async_stepout_method || ss_req->async_id) {
4879 tls->context.valid = FALSE;
4880 tls->async_state.valid = FALSE;
4881 invalidate_frames (tls);
4882 ss_calculate_framecount (tls, ctx);
4883 ss_req->thread = mono_thread_internal_current ();
4884 ss_req->nframes = tls->frame_count;
4887 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4889 g_ptr_array_add (ss_reqs, req);
4891 /* Start single stepping again from the current sequence point */
4892 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4895 if (ss_reqs->len > 0)
4896 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4897 if (bp_reqs->len > 0)
4898 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4899 if (kind != EVENT_KIND_BREAKPOINT)
4900 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4902 mono_loader_unlock ();
4904 g_ptr_array_free (bp_reqs, TRUE);
4905 g_ptr_array_free (ss_reqs, TRUE);
4908 * FIXME: The first event will suspend, so the second will only be sent after the
4912 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4914 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4915 if (enter_leave_events)
4916 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4919 /* Process a breakpoint/single step event after resuming from a signal handler */
4921 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4923 DebuggerTlsData *tls;
4924 MonoThreadUnwindState orig_restore_state;
4927 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4928 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4929 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4930 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4934 /* This is called when resuming from a signal handler, so it shouldn't return */
4935 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4936 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4937 mono_restore_context (&ctx);
4938 g_assert_not_reached ();
4942 process_breakpoint (void)
4944 process_signal_event (process_breakpoint_inner);
4948 resume_from_signal_handler (void *sigctx, void *func)
4950 DebuggerTlsData *tls;
4953 /* Save the original context in TLS */
4954 // FIXME: This might not work on an altstack ?
4955 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4957 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4960 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4961 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4962 // clob:c could be added to op_seq_point.
4964 mono_sigctx_to_monoctx (sigctx, &ctx);
4965 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4966 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4967 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4969 MONO_CONTEXT_SET_IP (&ctx, func);
4971 mono_monoctx_to_sigctx (&ctx, sigctx);
4973 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4974 mono_ppc_set_func_into_sigctx (sigctx, func);
4979 mono_debugger_agent_breakpoint_hit (void *sigctx)
4982 * We are called from a signal handler, and running code there causes all kinds of
4983 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4984 * So set up the signal context to return to the real breakpoint handler function.
4986 resume_from_signal_handler (sigctx, process_breakpoint);
4990 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4992 if (frame->managed) {
4993 *(MonoContext*)data = *ctx;
5002 * Called by System.Diagnostics.Debugger:Break ().
5005 mono_debugger_agent_user_break (void)
5007 if (agent_config.enabled) {
5012 /* Obtain a context */
5013 MONO_CONTEXT_SET_IP (&ctx, NULL);
5014 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
5015 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
5017 mono_loader_lock ();
5018 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5019 mono_loader_unlock ();
5021 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5022 } else if (debug_options.native_debugger_break) {
5028 ss_depth_to_string (StepDepth depth)
5031 case STEP_DEPTH_OVER:
5033 case STEP_DEPTH_OUT:
5035 case STEP_DEPTH_INTO:
5038 g_assert_not_reached ();
5044 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5049 int il_offset, suspend_policy;
5052 MonoContext *ctx = &tls->restore_state.ctx;
5055 MonoSeqPointInfo *info;
5057 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5059 /* Skip the instruction causing the single step */
5061 mono_arch_skip_single_step (ctx);
5063 if (suspend_count > 0) {
5064 /* Fastpath during invokes, see in process_suspend () */
5065 if (suspend_count - tls->resume_count == 0)
5067 process_suspend (tls, ctx);
5072 // FIXME: A suspend race
5075 if (mono_thread_internal_current () != ss_req->thread)
5078 if (log_level > 0) {
5079 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5081 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);
5084 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5085 g_assert (ji && !ji->is_trampoline);
5086 method = jinfo_get_method (ji);
5089 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5094 * Stopping in memset makes half-initialized vtypes visible.
5095 * Stopping in memcpy makes half-copied vtypes visible.
5097 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5101 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5102 * hence we prefer this check here.
5104 if (ss_req->user_assemblies) {
5105 gboolean found = FALSE;
5106 for (int k = 0; ss_req->user_assemblies[k]; k++)
5107 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5117 * The ip points to the instruction causing the single step event, which is before
5118 * the offset recorded in the seq point map, so find the next seq point after ip.
5120 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
5123 il_offset = sp.il_offset;
5125 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5128 /* Start single stepping again from the current sequence point */
5129 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5131 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5132 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5133 !strcmp (method->name, ".cctor"))
5136 // FIXME: Has to lock earlier
5138 reqs = g_ptr_array_new ();
5140 mono_loader_lock ();
5142 g_ptr_array_add (reqs, ss_req->req);
5144 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5146 g_ptr_array_free (reqs, TRUE);
5148 mono_loader_unlock ();
5150 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5154 process_single_step (void)
5156 process_signal_event (process_single_step_inner);
5160 * mono_debugger_agent_single_step_event:
5162 * Called from a signal handler to handle a single step event.
5165 mono_debugger_agent_single_step_event (void *sigctx)
5167 /* Resume to process_single_step through the signal context */
5169 // FIXME: Since step out/over is implemented using step in, the step in case should
5170 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5173 if (is_debugger_thread ()) {
5175 * This could happen despite our best effors when the runtime calls
5176 * assembly/type resolve hooks.
5177 * FIXME: Breakpoints too.
5181 mono_sigctx_to_monoctx (sigctx, &ctx);
5182 mono_arch_skip_single_step (&ctx);
5183 mono_monoctx_to_sigctx (&ctx, sigctx);
5187 resume_from_signal_handler (sigctx, process_single_step);
5191 debugger_agent_single_step_from_context (MonoContext *ctx)
5193 DebuggerTlsData *tls;
5194 MonoThreadUnwindState orig_restore_state;
5196 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5197 /* Fastpath during invokes, see in process_suspend () */
5198 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5201 if (is_debugger_thread ())
5206 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5207 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5208 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5209 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5211 process_single_step_inner (tls, FALSE);
5213 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5214 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5218 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5220 DebuggerTlsData *tls;
5221 MonoThreadUnwindState orig_restore_state;
5224 if (is_debugger_thread ())
5227 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5228 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5230 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5232 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5233 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5234 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5236 process_breakpoint_inner (tls, FALSE);
5238 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5239 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5240 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5241 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5245 * start_single_stepping:
5247 * Turn on single stepping. Can be called multiple times, for example,
5248 * by a single step event request + a suspend.
5251 start_single_stepping (void)
5253 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5254 int val = InterlockedIncrement (&ss_count);
5257 mono_arch_start_single_stepping ();
5259 g_assert_not_reached ();
5264 stop_single_stepping (void)
5266 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5267 int val = InterlockedDecrement (&ss_count);
5270 mono_arch_stop_single_stepping ();
5272 g_assert_not_reached ();
5279 * Stop the single stepping operation given by SS_REQ.
5282 ss_stop (SingleStepReq *ss_req)
5287 for (l = ss_req->bps; l; l = l->next) {
5288 clear_breakpoint ((MonoBreakpoint *)l->data);
5290 g_slist_free (ss_req->bps);
5294 ss_req->async_id = 0;
5295 ss_req->async_stepout_method = NULL;
5296 if (ss_req->global) {
5297 stop_single_stepping ();
5298 ss_req->global = FALSE;
5305 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5308 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5310 if (ss_req_bp_cache) {
5311 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5312 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5314 for (GSList *l = bps; l; l = l->next) {
5315 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5316 if (bp->method == method && bp->il_offset == il_offset)
5325 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5328 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5330 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5331 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5332 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5338 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5341 ss_bp_hash (gconstpointer data)
5343 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5344 guint hash = (guint) (uintptr_t) s->method;
5345 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5346 hash ^= ((guint)s->il_offset) >> 16;
5350 #define MAX_LINEAR_SCAN_BPS 7
5355 * Create a new breakpoint and add it to a step request.
5356 * Will adjust the bp count and cache used by ss_start.
5359 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5360 MonoMethod *method, guint32 il_offset)
5362 // This list is getting too long, switch to using the hash table
5363 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5364 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5365 for (GSList *l = ss_req->bps; l; l = l->next)
5366 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5369 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5370 // Create and add breakpoint
5371 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5372 ss_req->bps = g_slist_append (ss_req->bps, bp);
5373 if (*ss_req_bp_cache)
5374 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5375 (*ss_req_bp_count)++;
5377 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);
5382 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5386 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5387 mono_seq_point_init_next (info, *sp, next);
5388 for (int i = 0; i < sp->next_len; i++) {
5389 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5390 if (!is_last_non_empty (&next [i], info)) {
5406 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5407 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5408 * belong to the same thread as CTX.
5409 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5412 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5413 gboolean step_to_catch, StackFrame **frames, int nframes)
5415 int i, j, frame_index;
5416 SeqPoint *next_sp, *parent_sp = NULL;
5417 SeqPoint local_sp, local_parent_sp;
5419 MonoSeqPointInfo *parent_info;
5420 MonoMethod *parent_sp_method = NULL;
5421 gboolean enable_global = FALSE;
5423 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5424 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5425 int ss_req_bp_count = g_slist_length (ss_req->bps);
5426 GHashTable *ss_req_bp_cache = NULL;
5428 /* Stop the previous operation */
5432 * Implement single stepping using breakpoints if possible.
5434 if (step_to_catch) {
5435 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5439 if (ctx && !frames) {
5440 /* Need parent frames */
5441 if (!tls->context.valid)
5442 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5443 compute_frame_info (tls->thread, tls);
5444 frames = tls->frames;
5445 nframes = tls->frame_count;
5448 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5450 /* Need to stop in catch clauses as well */
5451 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5452 StackFrame *frame = frames [i];
5455 MonoJitInfo *jinfo = frame->ji;
5456 for (j = 0; j < jinfo->num_clauses; ++j) {
5457 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5458 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5460 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5462 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5463 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5468 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5469 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5471 // Check if we hit yield_offset during normal stepping, because if we did...
5472 // Go into special async stepping mode which places breakpoint on resumeOffset
5473 // of this await call and sets async_id so we can distinguish it from parallel executions
5474 for (i = 0; i < asyncMethod->num_awaits; i++) {
5475 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5476 ss_req->async_id = get_this_async_id (frames [0]);
5477 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5478 if (ss_req_bp_cache)
5479 g_hash_table_destroy (ss_req_bp_cache);
5480 mono_debug_free_method_async_debug_info (asyncMethod);
5484 //If we are at end of async method and doing step-in or step-over...
5485 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5486 if (is_last_non_empty (sp, info)) {
5487 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5489 if (ss_req->depth == STEP_DEPTH_OUT) {
5490 set_set_notification_for_wait_completion_flag (frames [0]);
5491 ss_req->async_id = get_this_async_id (frames [0]);
5492 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5493 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5494 if (ss_req_bp_cache)
5495 g_hash_table_destroy (ss_req_bp_cache);
5496 mono_debug_free_method_async_debug_info (asyncMethod);
5502 mono_debug_free_method_async_debug_info (asyncMethod);
5505 * Find the first sequence point in the current or in a previous frame which
5506 * is not the last in its method.
5508 if (ss_req->depth == STEP_DEPTH_OUT) {
5509 /* Ignore seq points in current method */
5510 while (frame_index < nframes) {
5511 StackFrame *frame = frames [frame_index];
5513 method = frame->method;
5514 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5515 sp = (found_sp)? &local_sp : NULL;
5517 if (sp && sp->next_len != 0)
5520 // There could be method calls before the next seq point in the caller when using nested calls
5521 //enable_global = TRUE;
5523 if (sp && sp->next_len == 0) {
5525 while (frame_index < nframes) {
5526 StackFrame *frame = frames [frame_index];
5528 method = frame->method;
5529 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5530 sp = (found_sp)? &local_sp : NULL;
5531 if (sp && sp->next_len != 0)
5537 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5538 while (frame_index < nframes) {
5539 StackFrame *frame = frames [frame_index];
5541 parent_sp_method = frame->method;
5542 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5543 parent_sp = found_sp ? &local_parent_sp : NULL;
5544 if (found_sp && parent_sp->next_len != 0)
5552 if (sp && sp->next_len > 0) {
5553 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5555 mono_seq_point_init_next (info, *sp, next);
5556 for (i = 0; i < sp->next_len; i++) {
5559 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5565 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5567 mono_seq_point_init_next (parent_info, *parent_sp, next);
5568 for (i = 0; i < parent_sp->next_len; i++) {
5571 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5576 if (ss_req->nframes == 0)
5577 ss_req->nframes = nframes;
5579 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5580 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5582 * This is needed since if we leave managed code, and later return to it, step over
5583 * is not going to stop.
5584 * This approach is a bit ugly, since we change the step depth, but it only affects
5585 * clients who reuse the same step request, and only in this special case.
5587 ss_req->depth = STEP_DEPTH_INTO;
5590 if (ss_req->depth == STEP_DEPTH_INTO) {
5591 /* Enable global stepping so we stop at method entry too */
5592 enable_global = TRUE;
5596 * The ctx/frame info computed above will become invalid when we continue.
5598 tls->context.valid = FALSE;
5599 tls->async_state.valid = FALSE;
5600 invalidate_frames (tls);
5603 if (enable_global) {
5604 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5605 ss_req->global = TRUE;
5606 start_single_stepping ();
5607 } else if (!ss_req->bps) {
5608 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5609 ss_req->global = TRUE;
5610 start_single_stepping ();
5612 ss_req->global = FALSE;
5615 if (ss_req_bp_cache)
5616 g_hash_table_destroy (ss_req_bp_cache);
5620 * Start single stepping of thread THREAD
5623 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5625 DebuggerTlsData *tls;
5626 MonoSeqPointInfo *info = NULL;
5627 SeqPoint *sp = NULL;
5630 MonoMethod *method = NULL;
5631 MonoDebugMethodInfo *minfo;
5632 gboolean step_to_catch = FALSE;
5633 gboolean set_ip = FALSE;
5634 StackFrame **frames = NULL;
5637 if (suspend_count == 0)
5638 return ERR_NOT_SUSPENDED;
5640 wait_for_suspend ();
5642 // FIXME: Multiple requests
5644 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5645 return ERR_NOT_IMPLEMENTED;
5648 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5650 ss_req = g_new0 (SingleStepReq, 1);
5652 ss_req->thread = thread;
5653 ss_req->size = size;
5654 ss_req->depth = depth;
5655 ss_req->filter = filter;
5658 for (int i = 0; i < req->nmodifiers; i++) {
5659 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5660 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5665 mono_loader_lock ();
5666 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5667 mono_loader_unlock ();
5669 if (!tls->context.valid) {
5670 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5671 return ERR_INVALID_ARGUMENT;
5674 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5676 * Need to start single stepping from restore_state and not from the current state
5679 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5682 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5684 if (tls->catch_state.valid) {
5686 StackFrameInfo frame;
5687 MonoContext new_ctx;
5688 MonoLMF *lmf = NULL;
5691 * We are stopped at a throw site. Stepping should go to the catch site.
5694 /* Find the the jit info for the catch context */
5695 res = mono_find_jit_info_ext (
5696 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5697 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5698 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5700 g_assert (frame.type == FRAME_TYPE_MANAGED);
5703 * Find the seq point corresponding to the landing site ip, which is the first seq
5706 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5707 sp = (found_sp)? &local_sp : NULL;
5709 no_seq_points_found (frame.method, frame.native_offset);
5712 method = frame.method;
5714 step_to_catch = TRUE;
5715 /* This make sure the seq point is not skipped by process_single_step () */
5716 ss_req->last_sp = NULL;
5719 if (!step_to_catch) {
5720 StackFrame *frame = NULL;
5723 if (frames && nframes)
5726 compute_frame_info (thread, tls);
5728 if (tls->frame_count)
5729 frame = tls->frames [0];
5732 if (ss_req->size == STEP_SIZE_LINE) {
5734 ss_req->last_method = frame->method;
5735 ss_req->last_line = -1;
5737 minfo = mono_debug_lookup_method (frame->method);
5738 if (minfo && frame->il_offset != -1) {
5739 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5742 ss_req->last_line = loc->row;
5750 if (!method && frame->il_offset != -1) {
5751 /* FIXME: Sort the table and use a binary search */
5752 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5753 sp = (found_sp)? &local_sp : NULL;
5755 no_seq_points_found (frame->method, frame->native_offset);
5757 method = frame->method;
5762 ss_req->start_method = method;
5764 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5767 free_frames (frames, nframes);
5773 ss_destroy (SingleStepReq *req)
5776 g_assert (ss_req == req);
5785 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5788 gboolean found = TRUE;
5792 for (l = ss_req->bps; l; l = l->next) {
5793 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5794 clear_breakpoint ((MonoBreakpoint *)l->data);
5795 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5804 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5807 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5814 if (!agent_config.enabled)
5817 mono_loader_lock ();
5818 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5819 mono_loader_unlock ();
5824 ei.category = mono_string_to_utf8_checked (category, &error);
5825 mono_error_cleanup (&error);
5829 ei.message = mono_string_to_utf8_checked (message, &error);
5830 mono_error_cleanup (&error);
5833 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5835 g_free (ei.category);
5836 g_free (ei.message);
5840 mono_debugger_agent_debug_log_is_enabled (void)
5842 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5843 return agent_config.enabled;
5846 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5848 mono_debugger_agent_unhandled_exception (MonoException *exc)
5857 memset (&ei, 0, sizeof (EventInfo));
5858 ei.exc = (MonoObject*)exc;
5860 mono_loader_lock ();
5861 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5862 mono_loader_unlock ();
5864 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5869 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5870 MonoContext *catch_ctx)
5872 int i, j, suspend_policy;
5874 MonoJitInfo *ji, *catch_ji;
5876 DebuggerTlsData *tls = NULL;
5878 if (thread_to_tls != NULL) {
5879 MonoInternalThread *thread = mono_thread_internal_current ();
5881 mono_loader_lock ();
5882 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5883 mono_loader_unlock ();
5885 if (tls && tls->abort_requested)
5887 if (tls && tls->disable_breakpoints)
5891 memset (&ei, 0, sizeof (EventInfo));
5893 /* Just-In-Time debugging */
5895 if (agent_config.onuncaught && !inited) {
5896 finish_agent_init (FALSE);
5899 * Send an unsolicited EXCEPTION event with a dummy request id.
5901 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5902 ei.exc = (MonoObject*)exc;
5903 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5906 } else if (agent_config.onthrow && !inited) {
5908 gboolean found = FALSE;
5910 for (l = agent_config.onthrow; l; l = l->next) {
5911 char *ex_type = (char *)l->data;
5912 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5914 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5921 finish_agent_init (FALSE);
5924 * Send an unsolicited EXCEPTION event with a dummy request id.
5926 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5927 ei.exc = (MonoObject*)exc;
5928 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5936 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5938 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5942 ei.exc = (MonoObject*)exc;
5943 ei.caught = catch_ctx != NULL;
5945 mono_loader_lock ();
5947 /* Treat exceptions which are caught in non-user code as unhandled */
5948 for (i = 0; i < event_requests->len; ++i) {
5949 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5950 if (req->event_kind != EVENT_KIND_EXCEPTION)
5953 for (j = 0; j < req->nmodifiers; ++j) {
5954 Modifier *mod = &req->modifiers [j];
5956 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5958 gboolean found = FALSE;
5959 MonoAssembly **assemblies = mod->data.assemblies;
5962 for (k = 0; assemblies [k]; ++k)
5963 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5972 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5973 mono_loader_unlock ();
5975 if (tls && ei.caught && catch_ctx) {
5976 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5977 tls->catch_state.ctx = *catch_ctx;
5978 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5979 tls->catch_state.valid = TRUE;
5982 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5985 tls->catch_state.valid = FALSE;
5989 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5991 DebuggerTlsData *tls;
5996 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6001 * We're about to invoke an exception filter during the first pass of exception handling.
6003 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
6004 * 'orig_ctx' is the context where the exception has been thrown.
6007 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6009 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6010 * the call site (line 37) and then continue to Main(), but it would never
6011 * include the throw site (line 32).
6013 * Since exception filters are invoked during the first pass of exception handling,
6014 * the stack frames of the throw site are still intact, so we should include them
6017 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6019 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6020 * but report the location of the 'throw' to the user.
6024 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6028 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6030 DebuggerTlsData *tls;
6035 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6039 tls->filter_state.valid = FALSE;
6043 * buffer_add_value_full:
6045 * Add the encoding of the value at ADDR described by T to the buffer.
6046 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6050 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6051 gboolean as_vtype, GHashTable *parent_vtypes)
6054 gboolean boxed_vtype = FALSE;
6057 if (!(*(void**)addr)) {
6058 /* This can happen with compiler generated locals */
6059 //printf ("%s\n", mono_type_full_name (t));
6060 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6063 g_assert (*(void**)addr);
6064 addr = *(void**)addr;
6069 case MONO_TYPE_BOOLEAN:
6072 case MONO_TYPE_CHAR:
6092 case MONO_TYPE_VOID:
6093 buffer_add_byte (buf, t->type);
6095 case MONO_TYPE_BOOLEAN:
6098 buffer_add_byte (buf, t->type);
6099 buffer_add_int (buf, *(gint8*)addr);
6101 case MONO_TYPE_CHAR:
6104 buffer_add_byte (buf, t->type);
6105 buffer_add_int (buf, *(gint16*)addr);
6110 buffer_add_byte (buf, t->type);
6111 buffer_add_int (buf, *(gint32*)addr);
6116 buffer_add_byte (buf, t->type);
6117 buffer_add_long (buf, *(gint64*)addr);
6121 /* Treat it as a vtype */
6123 case MONO_TYPE_PTR: {
6124 gssize val = *(gssize*)addr;
6126 buffer_add_byte (buf, t->type);
6127 buffer_add_long (buf, val);
6131 case MONO_TYPE_STRING:
6132 case MONO_TYPE_SZARRAY:
6133 case MONO_TYPE_OBJECT:
6134 case MONO_TYPE_CLASS:
6135 case MONO_TYPE_ARRAY:
6136 obj = *(MonoObject**)addr;
6139 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6141 if (obj->vtable->klass->valuetype) {
6142 t = &obj->vtable->klass->byval_arg;
6143 addr = mono_object_unbox (obj);
6146 } else if (obj->vtable->klass->rank) {
6147 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6148 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6149 buffer_add_byte (buf, MONO_TYPE_CLASS);
6151 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6153 buffer_add_objid (buf, obj);
6157 case MONO_TYPE_VALUETYPE:
6158 case MONO_TYPE_TYPEDBYREF: {
6162 MonoClass *klass = mono_class_from_mono_type (t);
6167 * Handle boxed vtypes recursively referencing themselves using fields.
6170 parent_vtypes = g_hash_table_new (NULL, NULL);
6171 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6173 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6174 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6175 buffer_add_int (buf, vtype_index - 1);
6177 /* The client can't handle PARENT_VTYPE */
6178 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6182 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6186 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6187 buffer_add_byte (buf, klass->enumtype);
6188 buffer_add_typeid (buf, domain, klass);
6192 while ((f = mono_class_get_fields (klass, &iter))) {
6193 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6195 if (mono_field_is_deleted (f))
6199 buffer_add_int (buf, nfields);
6202 while ((f = mono_class_get_fields (klass, &iter))) {
6203 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6205 if (mono_field_is_deleted (f))
6207 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6211 g_hash_table_remove (parent_vtypes, addr);
6212 if (g_hash_table_size (parent_vtypes) == 0) {
6213 g_hash_table_destroy (parent_vtypes);
6214 parent_vtypes = NULL;
6219 case MONO_TYPE_GENERICINST:
6220 if (mono_type_generic_inst_is_valuetype (t)) {
6232 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6234 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6238 obj_is_of_type (MonoObject *obj, MonoType *t)
6240 MonoClass *klass = obj->vtable->klass;
6241 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6242 if (mono_class_is_transparent_proxy (klass)) {
6243 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6244 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6254 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6257 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6263 gpointer iter = NULL;
6267 is_enum = decode_byte (buf, &buf, limit);
6268 /* Enums are sent as a normal vtype */
6270 return ERR_NOT_IMPLEMENTED;
6271 klass = decode_typeid (buf, &buf, limit, &d, &err);
6272 if (err != ERR_NONE)
6275 if (t && klass != mono_class_from_mono_type (t)) {
6276 char *name = mono_type_full_name (t);
6277 char *name2 = mono_type_full_name (&klass->byval_arg);
6278 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6281 return ERR_INVALID_ARGUMENT;
6284 nfields = decode_int (buf, &buf, limit);
6285 while ((f = mono_class_get_fields (klass, &iter))) {
6286 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6288 if (mono_field_is_deleted (f))
6290 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6291 if (err != ERR_NONE)
6295 g_assert (nfields == 0);
6303 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6307 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6308 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6309 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6310 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6311 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6312 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6313 char *name = mono_type_full_name (t);
6314 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6316 return ERR_INVALID_ARGUMENT;
6320 case MONO_TYPE_BOOLEAN:
6321 *(guint8*)addr = decode_int (buf, &buf, limit);
6323 case MONO_TYPE_CHAR:
6324 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6327 *(gint8*)addr = decode_int (buf, &buf, limit);
6330 *(guint8*)addr = decode_int (buf, &buf, limit);
6333 *(gint16*)addr = decode_int (buf, &buf, limit);
6336 *(guint16*)addr = decode_int (buf, &buf, limit);
6339 *(gint32*)addr = decode_int (buf, &buf, limit);
6342 *(guint32*)addr = decode_int (buf, &buf, limit);
6345 *(gint64*)addr = decode_long (buf, &buf, limit);
6348 *(guint64*)addr = decode_long (buf, &buf, limit);
6351 *(guint32*)addr = decode_int (buf, &buf, limit);
6354 *(guint64*)addr = decode_long (buf, &buf, limit);
6357 /* We send these as I8, so we get them back as such */
6358 g_assert (type == MONO_TYPE_I8);
6359 *(gssize*)addr = decode_long (buf, &buf, limit);
6361 case MONO_TYPE_GENERICINST:
6362 if (MONO_TYPE_ISSTRUCT (t)) {
6363 /* The client sends these as a valuetype */
6371 /* We send these as vtypes, so we get them back as such */
6372 g_assert (type == MONO_TYPE_VALUETYPE);
6375 case MONO_TYPE_VALUETYPE:
6376 if (type == MONO_TYPE_OBJECT) {
6378 int objid = decode_objid (buf, &buf, limit);
6382 err = get_object (objid, (MonoObject**)&obj);
6383 if (err != ERR_NONE)
6386 return ERR_INVALID_ARGUMENT;
6387 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6388 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6389 return ERR_INVALID_ARGUMENT;
6391 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6393 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6394 if (err != ERR_NONE)
6400 if (MONO_TYPE_IS_REFERENCE (t)) {
6401 if (type == MONO_TYPE_OBJECT) {
6402 int objid = decode_objid (buf, &buf, limit);
6406 err = get_object (objid, (MonoObject**)&obj);
6407 if (err != ERR_NONE)
6411 if (!obj_is_of_type (obj, t)) {
6412 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6413 return ERR_INVALID_ARGUMENT;
6416 if (obj && obj->vtable->domain != domain)
6417 return ERR_INVALID_ARGUMENT;
6419 mono_gc_wbarrier_generic_store (addr, obj);
6420 } else if (type == VALUE_TYPE_ID_NULL) {
6421 *(MonoObject**)addr = NULL;
6422 } else if (type == MONO_TYPE_VALUETYPE) {
6431 /* This can happen when round-tripping boxed vtypes */
6433 * Obtain vtype class.
6434 * Same as the beginning of the handle_vtype case above.
6437 is_enum = decode_byte (buf, &buf, limit);
6439 return ERR_NOT_IMPLEMENTED;
6440 klass = decode_typeid (buf, &buf, limit, &d, &err);
6441 if (err != ERR_NONE)
6444 /* Decode the vtype into a temporary buffer, then box it. */
6445 vtype_buf_size = mono_class_value_size (klass, NULL);
6446 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6447 g_assert (vtype_buf);
6450 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6451 if (err != ERR_NONE) {
6455 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6456 mono_error_cleanup (&error);
6459 char *name = mono_type_full_name (t);
6460 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6462 return ERR_INVALID_ARGUMENT;
6476 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6480 int type = decode_byte (buf, &buf, limit);
6482 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6483 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6484 guint8 *nullable_buf;
6487 * First try decoding it as a Nullable`1
6489 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6490 if (err == ERR_NONE)
6494 * Then try decoding as a primitive value or null.
6496 if (targ->type == type) {
6497 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6498 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6499 if (err != ERR_NONE) {
6500 g_free (nullable_buf);
6503 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6504 if (!is_ok (&error)) {
6505 mono_error_cleanup (&error);
6506 return ERR_INVALID_OBJECT;
6508 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6509 g_free (nullable_buf);
6512 } else if (type == VALUE_TYPE_ID_NULL) {
6513 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6519 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6523 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6527 guint8 *addr, *gaddr;
6530 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6531 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6534 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6535 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6537 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6539 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6540 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6541 addr += (gint32)var->offset;
6543 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6545 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6547 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6550 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6551 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6552 /* Same as regoffset, but with an indirection */
6553 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6554 addr += (gint32)var->offset;
6556 gaddr = (guint8 *)*(gpointer*)addr;
6558 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6560 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6561 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6562 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6563 MonoGSharedVtMethodRuntimeInfo *info;
6569 g_assert (info_var);
6570 g_assert (locals_var);
6572 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6573 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6574 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6575 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6576 addr += (gint32)info_var->offset;
6577 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6578 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6579 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6581 g_assert_not_reached ();
6585 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6586 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6587 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6588 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6589 addr += (gint32)locals_var->offset;
6590 locals = (guint8 *)*(gpointer*)addr;
6591 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6592 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6594 g_assert_not_reached ();
6598 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6600 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6605 g_assert_not_reached ();
6610 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6614 guint8 *addr, *gaddr;
6616 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6617 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6619 if (MONO_TYPE_IS_REFERENCE (t))
6620 size = sizeof (gpointer);
6622 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6625 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6626 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6628 gboolean is_signed = FALSE;
6631 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6634 // FIXME: Write barriers
6635 mono_gc_memmove_atomic (addr, val, size);
6640 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6645 v = is_signed ? *(gint8*)val : *(guint8*)val;
6648 v = is_signed ? *(gint16*)val : *(guint16*)val;
6651 v = is_signed ? *(gint32*)val : *(guint32*)val;
6654 v = is_signed ? *(gint64*)val : *(guint64*)val;
6657 g_assert_not_reached ();
6660 /* Set value on the stack or in the return ctx */
6661 if (reg_locations [reg]) {
6662 /* Saved on the stack */
6663 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6664 *(reg_locations [reg]) = v;
6667 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6668 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6671 // FIXME: Move these to mono-context.h/c.
6672 mono_arch_context_set_int_reg (ctx, reg, v);
6674 // FIXME: Can't set registers, so we disable linears
6679 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6680 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6681 addr += (gint32)var->offset;
6683 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6686 addr = *(guint8**)addr;
6692 // FIXME: Write barriers
6693 mono_gc_memmove_atomic (addr, val, size);
6695 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6696 /* Same as regoffset, but with an indirection */
6697 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6698 addr += (gint32)var->offset;
6700 gaddr = (guint8 *)*(gpointer*)addr;
6702 // FIXME: Write barriers
6703 mono_gc_memmove_atomic (gaddr, val, size);
6705 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6709 g_assert_not_reached ();
6714 clear_event_request (int req_id, int etype)
6718 mono_loader_lock ();
6719 for (i = 0; i < event_requests->len; ++i) {
6720 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6722 if (req->id == req_id && req->event_kind == etype) {
6723 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6724 clear_breakpoint ((MonoBreakpoint *)req->info);
6725 if (req->event_kind == EVENT_KIND_STEP)
6726 ss_destroy ((SingleStepReq *)req->info);
6727 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6728 clear_breakpoint ((MonoBreakpoint *)req->info);
6729 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6730 clear_breakpoint ((MonoBreakpoint *)req->info);
6731 g_ptr_array_remove_index_fast (event_requests, i);
6736 mono_loader_unlock ();
6740 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6744 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6745 m->kind = MOD_KIND_NONE;
6746 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6747 int count = 0, match_count = 0, pos;
6748 MonoAssembly **newassemblies;
6750 for (i = 0; m->data.assemblies [i]; ++i) {
6752 if (m->data.assemblies [i] == assembly)
6757 // +1 because we don't know length and we use last element to check for end
6758 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6761 for (i = 0; i < count; ++i)
6762 if (m->data.assemblies [i] != assembly)
6763 newassemblies [pos ++] = m->data.assemblies [i];
6764 g_assert (pos == count - match_count);
6765 g_free (m->data.assemblies);
6766 m->data.assemblies = newassemblies;
6772 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6776 for (i = 0; i < req->nmodifiers; ++i) {
6777 Modifier *m = &req->modifiers [i];
6779 clear_assembly_from_modifier (req, m, assembly);
6784 * clear_event_requests_for_assembly:
6786 * Clear all events requests which reference ASSEMBLY.
6789 clear_event_requests_for_assembly (MonoAssembly *assembly)
6794 mono_loader_lock ();
6798 for (i = 0; i < event_requests->len; ++i) {
6799 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6801 clear_assembly_from_modifiers (req, assembly);
6803 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6804 clear_event_request (req->id, req->event_kind);
6809 if (req->event_kind == EVENT_KIND_STEP)
6810 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6813 mono_loader_unlock ();
6817 * type_comes_from_assembly:
6819 * GHRFunc that returns TRUE if klass comes from assembly
6822 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6824 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6828 * clear_types_for_assembly:
6830 * Clears types from loaded_classes for a given assembly
6833 clear_types_for_assembly (MonoAssembly *assembly)
6835 MonoDomain *domain = mono_domain_get ();
6836 AgentDomainInfo *info = NULL;
6838 if (!domain || !domain_jit_info (domain))
6839 /* Can happen during shutdown */
6842 info = get_agent_domain_info (domain);
6844 mono_loader_lock ();
6845 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6846 mono_loader_unlock ();
6850 add_thread (gpointer key, gpointer value, gpointer user_data)
6852 MonoInternalThread *thread = (MonoInternalThread *)value;
6853 Buffer *buf = (Buffer *)user_data;
6855 buffer_add_objid (buf, (MonoObject*)thread);
6859 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6862 guint8 *end = invoke->endp;
6866 MonoMethodSignature *sig;
6869 MonoObject *this_arg, *res, *exc;
6872 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6875 MonoStopwatch watch;
6877 if (invoke->method) {
6879 * Invoke this method directly, currently only Environment.Exit () is supported.
6882 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>");
6884 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6885 mono_error_assert_ok (&error);
6887 g_assert_not_reached ();
6890 m = decode_methodid (p, &p, end, &domain, &err);
6891 if (err != ERR_NONE)
6893 sig = mono_method_signature (m);
6895 if (m->klass->valuetype)
6896 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6898 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6899 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6900 /* Should be null */
6901 int type = decode_byte (p, &p, end);
6902 if (type != VALUE_TYPE_ID_NULL) {
6903 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6904 return ERR_INVALID_ARGUMENT;
6906 memset (this_buf, 0, mono_class_instance_size (m->klass));
6907 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6911 int type = decode_byte (p, &tmp_p, end);
6912 if (type == VALUE_TYPE_ID_NULL) {
6913 memset (this_buf, 0, mono_class_instance_size (m->klass));
6916 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6917 if (err != ERR_NONE)
6921 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6922 if (err != ERR_NONE)
6926 if (!m->klass->valuetype)
6927 this_arg = *(MonoObject**)this_buf;
6931 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6933 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked 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 /* Transform this to the format the rest of the code expects it to be */
6938 if (m->klass->valuetype) {
6939 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6940 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6942 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6944 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6945 return ERR_INVALID_ARGUMENT;
6947 m = mono_object_get_virtual_method (this_arg, m);
6948 if (m->klass->valuetype) {
6949 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6950 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6954 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>");
6956 if (this_arg && this_arg->vtable->domain != domain)
6959 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6960 if (!strcmp (m->name, ".ctor")) {
6961 if (mono_class_is_abstract (m->klass))
6962 return ERR_INVALID_ARGUMENT;
6965 this_arg = mono_object_new_checked (domain, m->klass, &error);
6966 mono_error_assert_ok (&error);
6969 return ERR_INVALID_ARGUMENT;
6973 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6974 return ERR_INVALID_ARGUMENT;
6976 nargs = decode_int (p, &p, end);
6977 if (nargs != sig->param_count)
6978 return ERR_INVALID_ARGUMENT;
6979 /* Use alloca to get gc tracking */
6980 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6981 memset (arg_buf, 0, nargs * sizeof (gpointer));
6982 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6983 for (i = 0; i < nargs; ++i) {
6984 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6985 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6986 if (err != ERR_NONE)
6988 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6991 if (sig->params [i]->byref) {
6992 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6993 *(gpointer*)arg_buf [i] = args [i];
6994 args [i] = arg_buf [i];
6997 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6998 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6999 if (err != ERR_NONE)
7001 args [i] = arg_buf [i];
7008 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7009 tls->disable_breakpoints = TRUE;
7011 tls->disable_breakpoints = FALSE;
7014 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7016 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7017 if (invoke->has_ctx) {
7020 lmf_addr = mono_get_lmf_addr ();
7023 memset (&ext, 0, sizeof (ext));
7024 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7026 ext.debugger_invoke = TRUE;
7027 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7029 mono_set_lmf ((MonoLMF*)&ext);
7033 mono_stopwatch_start (&watch);
7034 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7035 if (exc == NULL && !mono_error_ok (&error)) {
7036 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7038 mono_error_cleanup (&error); /* FIXME report error */
7040 mono_stopwatch_stop (&watch);
7041 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));
7043 buffer_add_byte (buf, 0);
7044 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7046 gboolean out_this = FALSE;
7047 gboolean out_args = FALSE;
7049 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7051 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7053 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7054 if (sig->ret->type == MONO_TYPE_VOID) {
7055 if (!strcmp (m->name, ".ctor")) {
7056 if (!m->klass->valuetype)
7057 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7059 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7061 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7063 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7064 buffer_add_value (buf, sig->ret, &res, domain);
7065 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7066 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7067 MonoClass *k = mono_class_from_mono_type (sig->ret);
7068 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7070 g_assert (nullable_buf);
7071 mono_nullable_init (nullable_buf, res, k);
7072 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7075 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7081 /* Return the new value of the receiver after the call */
7082 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7084 buffer_add_int (buf, nargs);
7085 for (i = 0; i < nargs; ++i) {
7086 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7087 buffer_add_value (buf, sig->params [i], &args [i], domain);
7088 else if (sig->params [i]->byref)
7089 /* add_value () does an indirection */
7090 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7092 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7097 tls->disable_breakpoints = FALSE;
7099 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7100 if (invoke->has_ctx)
7101 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7105 // FIXME: byref arguments
7113 * Invoke the method given by tls->pending_invoke in the current thread.
7116 invoke_method (void)
7118 DebuggerTlsData *tls;
7124 MonoContext restore_ctx;
7127 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7131 * Store the `InvokeData *' in `tls->invoke' until we're done with
7132 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7135 mono_loader_lock ();
7137 invoke = tls->pending_invoke;
7139 tls->pending_invoke = NULL;
7141 invoke->last_invoke = tls->invoke;
7142 tls->invoke = invoke;
7144 mono_loader_unlock ();
7146 tls->frames_up_to_date = FALSE;
7152 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7153 buffer_init (&buf, 128);
7156 /* Fail the other invokes as well */
7158 err = do_invoke_method (tls, &buf, invoke, p, &p);
7161 if (tls->abort_requested) {
7162 if (CHECK_PROTOCOL_VERSION (2, 42))
7163 err = ERR_INVOKE_ABORTED;
7166 /* Start suspending before sending the reply */
7167 if (mindex == invoke->nmethods - 1) {
7168 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7169 for (i = 0; i < invoke->suspend_count; ++i)
7174 send_reply_packet (id, err, &buf);
7179 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7181 if (invoke->has_ctx)
7182 save_thread_context (&restore_ctx);
7184 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7185 g_assert (tls->resume_count);
7186 tls->resume_count -= invoke->suspend_count;
7189 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7192 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7194 * It is possible that mono_thread_internal_abort () was called
7195 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7196 * because we reset the abort here.
7199 mono_loader_lock ();
7201 if (tls->abort_requested)
7202 mono_thread_internal_reset_abort (tls->thread);
7204 tls->invoke = tls->invoke->last_invoke;
7205 tls->abort_requested = FALSE;
7207 mono_loader_unlock ();
7216 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7218 MonoThread *thread = (MonoThread *)value;
7219 DebuggerTlsData *tls;
7222 mono_loader_lock ();
7223 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7225 res = tls->really_suspended;
7226 mono_loader_unlock ();
7232 get_source_files_for_type (MonoClass *klass)
7234 gpointer iter = NULL;
7236 MonoDebugSourceInfo *sinfo;
7240 files = g_ptr_array_new ();
7242 while ((method = mono_class_get_methods (klass, &iter))) {
7243 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7244 GPtrArray *source_file_list;
7247 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7248 for (j = 0; j < source_file_list->len; ++j) {
7249 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7250 for (i = 0; i < files->len; ++i)
7251 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7253 if (i == files->len)
7254 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7256 g_ptr_array_free (source_file_list, TRUE);
7264 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7267 case CMD_VM_VERSION: {
7268 char *build_info, *version;
7270 build_info = mono_get_runtime_build_info ();
7271 version = g_strdup_printf ("mono %s", build_info);
7273 buffer_add_string (buf, version); /* vm version */
7274 buffer_add_int (buf, MAJOR_VERSION);
7275 buffer_add_int (buf, MINOR_VERSION);
7276 g_free (build_info);
7280 case CMD_VM_SET_PROTOCOL_VERSION: {
7281 major_version = decode_int (p, &p, end);
7282 minor_version = decode_int (p, &p, end);
7283 protocol_version_set = TRUE;
7284 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7287 case CMD_VM_ALL_THREADS: {
7289 mono_loader_lock ();
7290 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7291 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7292 mono_loader_unlock ();
7295 case CMD_VM_SUSPEND:
7297 wait_for_suspend ();
7300 if (suspend_count == 0)
7301 return ERR_NOT_SUSPENDED;
7303 clear_suspended_objs ();
7305 case CMD_VM_DISPOSE:
7306 /* Clear all event requests */
7307 mono_loader_lock ();
7308 while (event_requests->len > 0) {
7309 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7311 clear_event_request (req->id, req->event_kind);
7313 mono_loader_unlock ();
7315 while (suspend_count > 0)
7317 disconnected = TRUE;
7318 vm_start_event_sent = FALSE;
7321 MonoInternalThread *thread;
7322 DebuggerTlsData *tls;
7323 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7324 MonoClass *env_class;
7326 MonoMethod *exit_method = NULL;
7330 exit_code = decode_int (p, &p, end);
7332 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7334 /* Have to send a reply before exiting */
7335 send_reply_packet (id, 0, buf);
7337 /* Clear all event requests */
7338 mono_loader_lock ();
7339 while (event_requests->len > 0) {
7340 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7342 clear_event_request (req->id, req->event_kind);
7344 mono_loader_unlock ();
7347 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7348 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7349 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7350 * better than doing the shutdown ourselves, since it avoids various races.
7354 wait_for_suspend ();
7356 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7357 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7359 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7362 mono_loader_lock ();
7363 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7364 mono_loader_unlock ();
7366 if (thread && exit_method) {
7367 mono_loader_lock ();
7368 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7369 mono_loader_unlock ();
7371 args = g_new0 (gpointer, 1);
7372 args [0] = g_malloc (sizeof (int));
7373 *(int*)(args [0]) = exit_code;
7375 tls->pending_invoke = g_new0 (InvokeData, 1);
7376 tls->pending_invoke->method = exit_method;
7377 tls->pending_invoke->args = args;
7378 tls->pending_invoke->nmethods = 1;
7380 while (suspend_count > 0)
7384 * No thread found, do it ourselves.
7385 * FIXME: This can race with normal shutdown etc.
7387 while (suspend_count > 0)
7390 if (!mono_runtime_try_shutdown ())
7393 mono_environment_exitcode_set (exit_code);
7395 /* Suspend all managed threads since the runtime is going away */
7396 DEBUG_PRINTF (1, "Suspending all threads...\n");
7397 mono_thread_suspend_all_other_threads ();
7398 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7399 mono_runtime_quit ();
7400 transport_close2 ();
7401 DEBUG_PRINTF (1, "Exiting...\n");
7407 case CMD_VM_INVOKE_METHOD:
7408 case CMD_VM_INVOKE_METHODS: {
7409 int objid = decode_objid (p, &p, end);
7411 DebuggerTlsData *tls;
7412 int i, count, flags, nmethods;
7415 err = get_object (objid, (MonoObject**)&thread);
7416 if (err != ERR_NONE)
7419 flags = decode_int (p, &p, end);
7421 if (command == CMD_VM_INVOKE_METHODS)
7422 nmethods = decode_int (p, &p, end);
7426 // Wait for suspending if it already started
7428 wait_for_suspend ();
7429 if (!is_suspended ())
7430 return ERR_NOT_SUSPENDED;
7432 mono_loader_lock ();
7433 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7434 mono_loader_unlock ();
7437 if (!tls->really_suspended)
7438 /* The thread is still running native code, can't do invokes */
7439 return ERR_NOT_SUSPENDED;
7442 * Store the invoke data into tls, the thread will execute it after it is
7445 if (tls->pending_invoke)
7446 return ERR_NOT_SUSPENDED;
7447 tls->pending_invoke = g_new0 (InvokeData, 1);
7448 tls->pending_invoke->id = id;
7449 tls->pending_invoke->flags = flags;
7450 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7451 memcpy (tls->pending_invoke->p, p, end - p);
7452 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7453 tls->pending_invoke->suspend_count = suspend_count;
7454 tls->pending_invoke->nmethods = nmethods;
7456 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7457 resume_thread (THREAD_TO_INTERNAL (thread));
7460 count = suspend_count;
7461 for (i = 0; i < count; ++i)
7466 case CMD_VM_ABORT_INVOKE: {
7467 int objid = decode_objid (p, &p, end);
7469 DebuggerTlsData *tls;
7473 err = get_object (objid, (MonoObject**)&thread);
7474 if (err != ERR_NONE)
7477 invoke_id = decode_int (p, &p, end);
7479 mono_loader_lock ();
7480 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7483 if (tls->abort_requested) {
7484 DEBUG_PRINTF (1, "Abort already requested.\n");
7485 mono_loader_unlock ();
7490 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7491 * actually the correct invocation.
7493 * Careful, we do not stop the thread that's doing the invocation, so we can't
7494 * inspect its stack. However, invoke_method() also acquires the loader lock
7495 * when it's done, so we're safe here.
7499 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7500 mono_loader_unlock ();
7501 return ERR_NO_INVOCATION;
7504 tls->abort_requested = TRUE;
7506 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7507 mono_loader_unlock ();
7511 case CMD_VM_SET_KEEPALIVE: {
7512 int timeout = decode_int (p, &p, end);
7513 agent_config.keepalive = timeout;
7515 #ifndef DISABLE_SOCKET_TRANSPORT
7522 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7523 GHashTableIter iter, kiter;
7528 char *fname, *basename;
7529 gboolean ignore_case;
7530 GSList *class_list, *l;
7531 GPtrArray *res_classes, *res_domains;
7533 fname = decode_string (p, &p, end);
7534 ignore_case = decode_byte (p, &p, end);
7536 basename = dbg_path_get_basename (fname);
7538 res_classes = g_ptr_array_new ();
7539 res_domains = g_ptr_array_new ();
7541 mono_loader_lock ();
7542 g_hash_table_iter_init (&iter, domains);
7543 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7544 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7546 /* Update 'source_file_to_class' cache */
7547 g_hash_table_iter_init (&kiter, info->loaded_classes);
7548 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7549 if (!g_hash_table_lookup (info->source_files, klass)) {
7550 files = get_source_files_for_type (klass);
7551 g_hash_table_insert (info->source_files, klass, files);
7553 for (i = 0; i < files->len; ++i) {
7554 char *s = (char *)g_ptr_array_index (files, i);
7555 char *s2 = dbg_path_get_basename (s);
7558 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7560 class_list = g_slist_prepend (class_list, klass);
7561 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7563 class_list = g_slist_prepend (class_list, klass);
7564 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7567 /* The _ignorecase hash contains the lowercase path */
7568 s3 = strdup_tolower (s2);
7569 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7571 class_list = g_slist_prepend (class_list, klass);
7572 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7574 class_list = g_slist_prepend (class_list, klass);
7575 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7587 s = strdup_tolower (basename);
7588 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7591 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7594 for (l = class_list; l; l = l->next) {
7595 klass = (MonoClass *)l->data;
7597 g_ptr_array_add (res_classes, klass);
7598 g_ptr_array_add (res_domains, domain);
7601 mono_loader_unlock ();
7606 buffer_add_int (buf, res_classes->len);
7607 for (i = 0; i < res_classes->len; ++i)
7608 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7609 g_ptr_array_free (res_classes, TRUE);
7610 g_ptr_array_free (res_domains, TRUE);
7613 case CMD_VM_GET_TYPES: {
7614 GHashTableIter iter;
7618 gboolean ignore_case;
7619 GPtrArray *res_classes, *res_domains;
7620 MonoTypeNameParse info;
7622 name = decode_string (p, &p, end);
7623 ignore_case = decode_byte (p, &p, end);
7625 if (!mono_reflection_parse_type (name, &info)) {
7627 mono_reflection_free_type_info (&info);
7628 return ERR_INVALID_ARGUMENT;
7631 res_classes = g_ptr_array_new ();
7632 res_domains = g_ptr_array_new ();
7634 mono_loader_lock ();
7635 g_hash_table_iter_init (&iter, domains);
7636 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7638 gboolean type_resolve;
7642 mono_domain_assemblies_lock (domain);
7643 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7644 ass = (MonoAssembly *)tmp->data;
7648 type_resolve = TRUE;
7649 /* FIXME really okay to call while holding locks? */
7650 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7651 mono_error_cleanup (&error);
7653 g_ptr_array_add (res_classes, mono_type_get_class (t));
7654 g_ptr_array_add (res_domains, domain);
7658 mono_domain_assemblies_unlock (domain);
7660 mono_loader_unlock ();
7663 mono_reflection_free_type_info (&info);
7665 buffer_add_int (buf, res_classes->len);
7666 for (i = 0; i < res_classes->len; ++i)
7667 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7668 g_ptr_array_free (res_classes, TRUE);
7669 g_ptr_array_free (res_domains, TRUE);
7672 case CMD_VM_START_BUFFERING:
7673 case CMD_VM_STOP_BUFFERING:
7674 /* Handled in the main loop */
7677 return ERR_NOT_IMPLEMENTED;
7684 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7690 case CMD_EVENT_REQUEST_SET: {
7692 int i, event_kind, suspend_policy, nmodifiers;
7696 MonoThread *step_thread;
7697 int step_thread_id = 0;
7698 StepDepth depth = STEP_DEPTH_INTO;
7699 StepSize size = STEP_SIZE_MIN;
7700 StepFilter filter = STEP_FILTER_NONE;
7704 event_kind = decode_byte (p, &p, end);
7705 suspend_policy = decode_byte (p, &p, end);
7706 nmodifiers = decode_byte (p, &p, end);
7708 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7709 req->id = InterlockedIncrement (&event_request_id);
7710 req->event_kind = event_kind;
7711 req->suspend_policy = suspend_policy;
7712 req->nmodifiers = nmodifiers;
7715 for (i = 0; i < nmodifiers; ++i) {
7716 mod = (ModifierKind)decode_byte (p, &p, end);
7718 req->modifiers [i].kind = mod;
7719 if (mod == MOD_KIND_COUNT) {
7720 req->modifiers [i].data.count = decode_int (p, &p, end);
7721 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7722 method = decode_methodid (p, &p, end, &domain, &err);
7723 if (err != ERR_NONE)
7725 location = decode_long (p, &p, end);
7726 } else if (mod == MOD_KIND_STEP) {
7727 step_thread_id = decode_id (p, &p, end);
7728 size = (StepSize)decode_int (p, &p, end);
7729 depth = (StepDepth)decode_int (p, &p, end);
7730 if (CHECK_PROTOCOL_VERSION (2, 16))
7731 filter = (StepFilter)decode_int (p, &p, end);
7732 req->modifiers [i].data.filter = filter;
7733 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7734 /* Treat STEP_THOUGH the same as HIDDEN */
7735 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7736 } else if (mod == MOD_KIND_THREAD_ONLY) {
7737 int id = decode_id (p, &p, end);
7739 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7740 if (err != ERR_NONE) {
7744 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7745 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7747 if (err != ERR_NONE)
7749 req->modifiers [i].caught = decode_byte (p, &p, end);
7750 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7751 if (CHECK_PROTOCOL_VERSION (2, 25))
7752 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7754 req->modifiers [i].subclasses = TRUE;
7755 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" : "");
7757 req->modifiers [i].data.exc_class = exc_class;
7759 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7761 return ERR_INVALID_ARGUMENT;
7764 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7765 int n = decode_int (p, &p, end);
7768 // +1 because we don't know length and we use last element to check for end
7769 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7770 for (j = 0; j < n; ++j) {
7771 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7772 if (err != ERR_NONE) {
7773 g_free (req->modifiers [i].data.assemblies);
7777 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7778 int n = decode_int (p, &p, end);
7781 modifier = &req->modifiers [i];
7782 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7783 for (j = 0; j < n; ++j) {
7784 char *s = decode_string (p, &p, end);
7788 s2 = strdup_tolower (s);
7789 g_hash_table_insert (modifier->data.source_files, s2, s2);
7793 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7794 int n = decode_int (p, &p, end);
7797 modifier = &req->modifiers [i];
7798 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7799 for (j = 0; j < n; ++j) {
7800 char *s = decode_string (p, &p, end);
7803 g_hash_table_insert (modifier->data.type_names, s, s);
7807 return ERR_NOT_IMPLEMENTED;
7811 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7814 req->info = set_breakpoint (method, location, req, &error);
7815 if (!mono_error_ok (&error)) {
7817 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7818 mono_error_cleanup (&error);
7819 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7821 } else if (req->event_kind == EVENT_KIND_STEP) {
7822 g_assert (step_thread_id);
7824 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7825 if (err != ERR_NONE) {
7830 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7831 if (err != ERR_NONE) {
7835 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7836 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7837 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7838 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7839 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7840 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7842 if (req->nmodifiers) {
7844 return ERR_NOT_IMPLEMENTED;
7848 mono_loader_lock ();
7849 g_ptr_array_add (event_requests, req);
7851 if (agent_config.defer) {
7852 /* Transmit cached data to the client on receipt of the event request */
7853 switch (req->event_kind) {
7854 case EVENT_KIND_APPDOMAIN_CREATE:
7855 /* Emit load events for currently loaded domains */
7856 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7858 case EVENT_KIND_ASSEMBLY_LOAD:
7859 /* Emit load events for currently loaded assemblies */
7860 mono_domain_foreach (send_assemblies_for_domain, NULL);
7862 case EVENT_KIND_THREAD_START:
7863 /* Emit start events for currently started threads */
7864 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7866 case EVENT_KIND_TYPE_LOAD:
7867 /* Emit type load events for currently loaded types */
7868 mono_domain_foreach (send_types_for_domain, NULL);
7874 mono_loader_unlock ();
7876 buffer_add_int (buf, req->id);
7879 case CMD_EVENT_REQUEST_CLEAR: {
7880 int etype = decode_byte (p, &p, end);
7881 int req_id = decode_int (p, &p, end);
7883 // FIXME: Make a faster mapping from req_id to request
7884 mono_loader_lock ();
7885 clear_event_request (req_id, etype);
7886 mono_loader_unlock ();
7889 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7892 mono_loader_lock ();
7894 while (i < event_requests->len) {
7895 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7897 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7898 clear_breakpoint ((MonoBreakpoint *)req->info);
7900 g_ptr_array_remove_index_fast (event_requests, i);
7906 mono_loader_unlock ();
7910 return ERR_NOT_IMPLEMENTED;
7917 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7923 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7924 buffer_add_domainid (buf, mono_get_root_domain ());
7927 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7928 domain = decode_domainid (p, &p, end, NULL, &err);
7929 if (err != ERR_NONE)
7931 buffer_add_string (buf, domain->friendly_name);
7934 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7939 domain = decode_domainid (p, &p, end, NULL, &err);
7940 if (err != ERR_NONE)
7942 mono_loader_lock ();
7944 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7947 buffer_add_int (buf, count);
7948 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7949 ass = (MonoAssembly *)tmp->data;
7950 buffer_add_assemblyid (buf, domain, ass);
7952 mono_loader_unlock ();
7955 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7956 domain = decode_domainid (p, &p, end, NULL, &err);
7957 if (err != ERR_NONE)
7960 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7963 case CMD_APPDOMAIN_GET_CORLIB: {
7964 domain = decode_domainid (p, &p, end, NULL, &err);
7965 if (err != ERR_NONE)
7968 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7971 case CMD_APPDOMAIN_CREATE_STRING: {
7975 domain = decode_domainid (p, &p, end, NULL, &err);
7976 if (err != ERR_NONE)
7978 s = decode_string (p, &p, end);
7980 o = mono_string_new (domain, s);
7981 buffer_add_objid (buf, (MonoObject*)o);
7984 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7987 MonoDomain *domain2;
7990 domain = decode_domainid (p, &p, end, NULL, &err);
7991 if (err != ERR_NONE)
7993 klass = decode_typeid (p, &p, end, &domain2, &err);
7994 if (err != ERR_NONE)
7998 g_assert (domain == domain2);
8000 o = mono_object_new_checked (domain, klass, &error);
8001 mono_error_assert_ok (&error);
8003 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
8004 if (err != ERR_NONE)
8007 buffer_add_objid (buf, o);
8011 return ERR_NOT_IMPLEMENTED;
8018 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8020 HANDLE_FUNCTION_ENTER();
8021 ErrorCode err = ERR_NONE;
8023 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8024 if (MONO_HANDLE_IS_NULL (o)) {
8025 err = ERR_INVALID_OBJECT;
8028 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8030 HANDLE_FUNCTION_RETURN_VAL (err);
8035 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8041 ass = decode_assemblyid (p, &p, end, &domain, &err);
8042 if (err != ERR_NONE)
8046 case CMD_ASSEMBLY_GET_LOCATION: {
8047 buffer_add_string (buf, mono_image_get_filename (ass->image));
8050 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8054 if (ass->image->dynamic) {
8055 buffer_add_id (buf, 0);
8057 token = mono_image_get_entry_point (ass->image);
8059 buffer_add_id (buf, 0);
8062 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8064 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8065 buffer_add_methodid (buf, domain, m);
8070 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8071 buffer_add_moduleid (buf, domain, ass->image);
8074 case CMD_ASSEMBLY_GET_OBJECT: {
8076 err = get_assembly_object_command (domain, ass, buf, &error);
8077 mono_error_cleanup (&error);
8080 case CMD_ASSEMBLY_GET_DOMAIN: {
8081 buffer_add_domainid (buf, domain);
8084 case CMD_ASSEMBLY_GET_TYPE: {
8086 char *s = decode_string (p, &p, end);
8087 gboolean ignorecase = decode_byte (p, &p, end);
8088 MonoTypeNameParse info;
8090 gboolean type_resolve, res;
8091 MonoDomain *d = mono_domain_get ();
8093 /* This is needed to be able to find referenced assemblies */
8094 res = mono_domain_set (domain, FALSE);
8097 if (!mono_reflection_parse_type (s, &info)) {
8100 if (info.assembly.name)
8102 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8103 if (!is_ok (&error)) {
8104 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8105 mono_reflection_free_type_info (&info);
8107 return ERR_INVALID_ARGUMENT;
8110 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8111 mono_reflection_free_type_info (&info);
8114 mono_domain_set (d, TRUE);
8118 case CMD_ASSEMBLY_GET_NAME: {
8120 MonoAssembly *mass = ass;
8122 name = g_strdup_printf (
8123 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8125 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8126 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8127 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8128 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8130 buffer_add_string (buf, name);
8135 return ERR_NOT_IMPLEMENTED;
8142 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8148 case CMD_MODULE_GET_INFO: {
8149 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8152 basename = g_path_get_basename (image->name);
8153 buffer_add_string (buf, basename); // name
8154 buffer_add_string (buf, image->module_name); // scopename
8155 buffer_add_string (buf, image->name); // fqname
8156 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8157 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8162 return ERR_NOT_IMPLEMENTED;
8169 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8175 case CMD_FIELD_GET_INFO: {
8176 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8178 buffer_add_string (buf, f->name);
8179 buffer_add_typeid (buf, domain, f->parent);
8180 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8181 buffer_add_int (buf, f->type->attrs);
8185 return ERR_NOT_IMPLEMENTED;
8192 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8194 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8195 /* Special case these so the client doesn't have to handle Type objects */
8197 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8198 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8199 } else if (MONO_TYPE_IS_REFERENCE (t))
8200 buffer_add_value (buf, t, &val, domain);
8202 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8206 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8212 buffer_add_int (buf, 0);
8216 for (i = 0; i < cinfo->num_attrs; ++i) {
8217 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8220 buffer_add_int (buf, nattrs);
8222 for (i = 0; i < cinfo->num_attrs; ++i) {
8223 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8224 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8225 MonoArray *typed_args, *named_args;
8227 CattrNamedArg *arginfo = NULL;
8230 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8231 if (!mono_error_ok (&error)) {
8232 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8233 mono_error_cleanup (&error);
8234 return ERR_LOADER_ERROR;
8237 buffer_add_methodid (buf, domain, attr->ctor);
8241 buffer_add_int (buf, mono_array_length (typed_args));
8242 for (j = 0; j < mono_array_length (typed_args); ++j) {
8243 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8245 t = mono_method_signature (attr->ctor)->params [j];
8247 buffer_add_cattr_arg (buf, t, domain, val);
8250 buffer_add_int (buf, 0);
8255 buffer_add_int (buf, mono_array_length (named_args));
8257 for (j = 0; j < mono_array_length (named_args); ++j) {
8258 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8260 if (arginfo [j].prop) {
8261 buffer_add_byte (buf, 0x54);
8262 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8263 } else if (arginfo [j].field) {
8264 buffer_add_byte (buf, 0x53);
8265 buffer_add_fieldid (buf, domain, arginfo [j].field);
8267 g_assert_not_reached ();
8270 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8273 buffer_add_int (buf, 0);
8282 /* FIXME: Code duplication with icall.c */
8284 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8289 mono_class_setup_interfaces (klass, error);
8290 if (!mono_error_ok (error))
8293 for (i = 0; i < klass->interface_count; i++) {
8294 ic = klass->interfaces [i];
8295 g_hash_table_insert (ifaces, ic, ic);
8297 collect_interfaces (ic, ifaces, error);
8298 if (!mono_error_ok (error))
8304 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8316 case CMD_TYPE_GET_INFO: {
8317 buffer_add_string (buf, klass->name_space);
8318 buffer_add_string (buf, klass->name);
8320 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8321 buffer_add_string (buf, name);
8323 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8324 buffer_add_moduleid (buf, domain, klass->image);
8325 buffer_add_typeid (buf, domain, klass->parent);
8326 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8327 buffer_add_typeid (buf, domain, klass->element_class);
8329 buffer_add_id (buf, 0);
8330 buffer_add_int (buf, klass->type_token);
8331 buffer_add_byte (buf, klass->rank);
8332 buffer_add_int (buf, mono_class_get_flags (klass));
8334 type = &klass->byval_arg;
8335 // FIXME: Can't decide whenever a class represents a byref type
8338 if (type->type == MONO_TYPE_PTR)
8340 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8342 if (type->type == MONO_TYPE_VALUETYPE)
8344 if (klass->enumtype)
8346 if (mono_class_is_gtd (klass))
8348 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8350 buffer_add_byte (buf, b);
8353 while ((nested = mono_class_get_nested_types (klass, &iter)))
8355 buffer_add_int (buf, nnested);
8357 while ((nested = mono_class_get_nested_types (klass, &iter)))
8358 buffer_add_typeid (buf, domain, nested);
8359 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8360 if (mono_class_is_gtd (klass))
8361 buffer_add_typeid (buf, domain, klass);
8362 else if (mono_class_is_ginst (klass))
8363 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8365 buffer_add_id (buf, 0);
8367 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8370 if (mono_class_is_ginst (klass)) {
8371 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8373 count = inst->type_argc;
8374 buffer_add_int (buf, count);
8375 for (i = 0; i < count; i++)
8376 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8377 } else if (mono_class_is_gtd (klass)) {
8378 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8381 count = container->type_argc;
8382 buffer_add_int (buf, count);
8383 for (i = 0; i < count; i++) {
8384 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8385 buffer_add_typeid (buf, domain, pklass);
8388 buffer_add_int (buf, 0);
8393 case CMD_TYPE_GET_METHODS: {
8396 gpointer iter = NULL;
8399 mono_class_setup_methods (klass);
8401 nmethods = mono_class_num_methods (klass);
8403 buffer_add_int (buf, nmethods);
8405 while ((m = mono_class_get_methods (klass, &iter))) {
8406 buffer_add_methodid (buf, domain, m);
8409 g_assert (i == nmethods);
8412 case CMD_TYPE_GET_FIELDS: {
8415 gpointer iter = NULL;
8418 nfields = mono_class_num_fields (klass);
8420 buffer_add_int (buf, nfields);
8422 while ((f = mono_class_get_fields (klass, &iter))) {
8423 buffer_add_fieldid (buf, domain, f);
8424 buffer_add_string (buf, f->name);
8425 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8426 buffer_add_int (buf, f->type->attrs);
8429 g_assert (i == nfields);
8432 case CMD_TYPE_GET_PROPERTIES: {
8435 gpointer iter = NULL;
8438 nprops = mono_class_num_properties (klass);
8440 buffer_add_int (buf, nprops);
8442 while ((p = mono_class_get_properties (klass, &iter))) {
8443 buffer_add_propertyid (buf, domain, p);
8444 buffer_add_string (buf, p->name);
8445 buffer_add_methodid (buf, domain, p->get);
8446 buffer_add_methodid (buf, domain, p->set);
8447 buffer_add_int (buf, p->attrs);
8450 g_assert (i == nprops);
8453 case CMD_TYPE_GET_CATTRS: {
8454 MonoClass *attr_klass;
8455 MonoCustomAttrInfo *cinfo;
8457 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8458 /* attr_klass can be NULL */
8459 if (err != ERR_NONE)
8462 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8463 if (!is_ok (&error)) {
8464 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8465 return ERR_LOADER_ERROR;
8468 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8469 if (err != ERR_NONE)
8473 case CMD_TYPE_GET_FIELD_CATTRS: {
8474 MonoClass *attr_klass;
8475 MonoCustomAttrInfo *cinfo;
8476 MonoClassField *field;
8478 field = decode_fieldid (p, &p, end, NULL, &err);
8479 if (err != ERR_NONE)
8481 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8482 if (err != ERR_NONE)
8485 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8486 if (!is_ok (&error)) {
8487 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8488 return ERR_LOADER_ERROR;
8491 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8492 if (err != ERR_NONE)
8496 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8497 MonoClass *attr_klass;
8498 MonoCustomAttrInfo *cinfo;
8501 prop = decode_propertyid (p, &p, end, NULL, &err);
8502 if (err != ERR_NONE)
8504 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8505 if (err != ERR_NONE)
8508 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8509 if (!is_ok (&error)) {
8510 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8511 return ERR_LOADER_ERROR;
8514 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8515 if (err != ERR_NONE)
8519 case CMD_TYPE_GET_VALUES:
8520 case CMD_TYPE_GET_VALUES_2: {
8527 MonoThread *thread_obj;
8528 MonoInternalThread *thread = NULL;
8529 guint32 special_static_type;
8531 if (command == CMD_TYPE_GET_VALUES_2) {
8532 int objid = decode_objid (p, &p, end);
8535 err = get_object (objid, (MonoObject**)&thread_obj);
8536 if (err != ERR_NONE)
8539 thread = THREAD_TO_INTERNAL (thread_obj);
8542 len = decode_int (p, &p, end);
8543 for (i = 0; i < len; ++i) {
8544 f = decode_fieldid (p, &p, end, NULL, &err);
8545 if (err != ERR_NONE)
8548 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8549 return ERR_INVALID_FIELDID;
8550 special_static_type = mono_class_field_get_special_static_type (f);
8551 if (special_static_type != SPECIAL_STATIC_NONE) {
8552 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8553 return ERR_INVALID_FIELDID;
8556 /* Check that the field belongs to the object */
8558 for (k = klass; k; k = k->parent) {
8559 if (k == f->parent) {
8565 return ERR_INVALID_FIELDID;
8567 vtable = mono_class_vtable (domain, f->parent);
8568 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8569 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8570 if (!is_ok (&error))
8571 return ERR_INVALID_FIELDID;
8572 buffer_add_value (buf, f->type, val, domain);
8577 case CMD_TYPE_SET_VALUES: {
8585 len = decode_int (p, &p, end);
8586 for (i = 0; i < len; ++i) {
8587 f = decode_fieldid (p, &p, end, NULL, &err);
8588 if (err != ERR_NONE)
8591 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8592 return ERR_INVALID_FIELDID;
8593 if (mono_class_field_is_special_static (f))
8594 return ERR_INVALID_FIELDID;
8596 /* Check that the field belongs to the object */
8598 for (k = klass; k; k = k->parent) {
8599 if (k == f->parent) {
8605 return ERR_INVALID_FIELDID;
8607 // FIXME: Check for literal/const
8609 vtable = mono_class_vtable (domain, f->parent);
8610 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8611 err = decode_value (f->type, domain, val, p, &p, end);
8612 if (err != ERR_NONE) {
8616 if (MONO_TYPE_IS_REFERENCE (f->type))
8617 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8619 mono_field_static_set_value (vtable, f, val);
8624 case CMD_TYPE_GET_OBJECT: {
8625 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8626 if (!mono_error_ok (&error)) {
8627 mono_error_cleanup (&error);
8628 return ERR_INVALID_OBJECT;
8630 buffer_add_objid (buf, o);
8633 case CMD_TYPE_GET_SOURCE_FILES:
8634 case CMD_TYPE_GET_SOURCE_FILES_2: {
8635 char *source_file, *base;
8639 files = get_source_files_for_type (klass);
8641 buffer_add_int (buf, files->len);
8642 for (i = 0; i < files->len; ++i) {
8643 source_file = (char *)g_ptr_array_index (files, i);
8644 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8645 buffer_add_string (buf, source_file);
8647 base = dbg_path_get_basename (source_file);
8648 buffer_add_string (buf, base);
8651 g_free (source_file);
8653 g_ptr_array_free (files, TRUE);
8656 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8657 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8659 if (err != ERR_NONE)
8661 if (mono_class_is_assignable_from (klass, oklass))
8662 buffer_add_byte (buf, 1);
8664 buffer_add_byte (buf, 0);
8667 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8668 char *name = decode_string (p, &p, end);
8669 int i, flags = decode_int (p, &p, end);
8673 error_init (&error);
8674 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8675 if (!is_ok (&error)) {
8676 mono_error_cleanup (&error);
8677 return ERR_LOADER_ERROR;
8679 buffer_add_int (buf, array->len);
8680 for (i = 0; i < array->len; ++i) {
8681 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8682 buffer_add_methodid (buf, domain, method);
8685 g_ptr_array_free (array, TRUE);
8689 case CMD_TYPE_GET_INTERFACES: {
8691 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8692 MonoClass *tclass, *iface;
8693 GHashTableIter iter;
8697 for (parent = tclass; parent; parent = parent->parent) {
8698 mono_class_setup_interfaces (parent, &error);
8699 if (!mono_error_ok (&error))
8700 return ERR_LOADER_ERROR;
8701 collect_interfaces (parent, iface_hash, &error);
8702 if (!mono_error_ok (&error))
8703 return ERR_LOADER_ERROR;
8706 buffer_add_int (buf, g_hash_table_size (iface_hash));
8708 g_hash_table_iter_init (&iter, iface_hash);
8709 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8710 buffer_add_typeid (buf, domain, iface);
8711 g_hash_table_destroy (iface_hash);
8714 case CMD_TYPE_GET_INTERFACE_MAP: {
8715 int tindex, ioffset;
8716 gboolean variance_used;
8718 int len, nmethods, i;
8722 len = decode_int (p, &p, end);
8723 mono_class_setup_vtable (klass);
8725 for (tindex = 0; tindex < len; ++tindex) {
8726 iclass = decode_typeid (p, &p, end, NULL, &err);
8727 if (err != ERR_NONE)
8730 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8732 return ERR_INVALID_ARGUMENT;
8734 nmethods = mono_class_num_methods (iclass);
8735 buffer_add_int (buf, nmethods);
8738 while ((method = mono_class_get_methods (iclass, &iter))) {
8739 buffer_add_methodid (buf, domain, method);
8741 for (i = 0; i < nmethods; ++i)
8742 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8746 case CMD_TYPE_IS_INITIALIZED: {
8747 MonoVTable *vtable = mono_class_vtable (domain, klass);
8750 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8752 buffer_add_int (buf, 0);
8755 case CMD_TYPE_CREATE_INSTANCE: {
8759 obj = mono_object_new_checked (domain, klass, &error);
8760 mono_error_assert_ok (&error);
8761 buffer_add_objid (buf, obj);
8765 return ERR_NOT_IMPLEMENTED;
8772 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8775 MonoDomain *old_domain;
8779 klass = decode_typeid (p, &p, end, &domain, &err);
8780 if (err != ERR_NONE)
8783 old_domain = mono_domain_get ();
8785 mono_domain_set (domain, TRUE);
8787 err = type_commands_internal (command, klass, domain, p, end, buf);
8789 mono_domain_set (old_domain, TRUE);
8795 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8797 MonoMethodHeader *header;
8801 case CMD_METHOD_GET_NAME: {
8802 buffer_add_string (buf, method->name);
8805 case CMD_METHOD_GET_DECLARING_TYPE: {
8806 buffer_add_typeid (buf, domain, method->klass);
8809 case CMD_METHOD_GET_DEBUG_INFO: {
8811 MonoDebugMethodInfo *minfo;
8813 int i, j, n_il_offsets;
8815 GPtrArray *source_file_list;
8816 MonoSymSeqPoint *sym_seq_points;
8818 header = mono_method_get_header_checked (method, &error);
8820 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8821 buffer_add_int (buf, 0);
8822 buffer_add_string (buf, "");
8823 buffer_add_int (buf, 0);
8827 minfo = mono_debug_lookup_method (method);
8829 buffer_add_int (buf, header->code_size);
8830 buffer_add_string (buf, "");
8831 buffer_add_int (buf, 0);
8832 mono_metadata_free_mh (header);
8836 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8837 buffer_add_int (buf, header->code_size);
8838 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8839 buffer_add_int (buf, source_file_list->len);
8840 for (i = 0; i < source_file_list->len; ++i) {
8841 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8842 buffer_add_string (buf, sinfo->source_file);
8843 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8844 for (j = 0; j < 16; ++j)
8845 buffer_add_byte (buf, sinfo->hash [j]);
8849 buffer_add_string (buf, source_file);
8851 buffer_add_int (buf, n_il_offsets);
8852 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8853 for (i = 0; i < n_il_offsets; ++i) {
8854 MonoSymSeqPoint *sp = &sym_seq_points [i];
8855 const char *srcfile = "";
8857 if (source_files [i] != -1) {
8858 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8859 srcfile = sinfo->source_file;
8861 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);
8862 buffer_add_int (buf, sp->il_offset);
8863 buffer_add_int (buf, sp->line);
8864 if (CHECK_PROTOCOL_VERSION (2, 13))
8865 buffer_add_int (buf, source_files [i]);
8866 if (CHECK_PROTOCOL_VERSION (2, 19))
8867 buffer_add_int (buf, sp->column);
8868 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8869 buffer_add_int (buf, sp->end_line);
8870 buffer_add_int (buf, sp->end_column);
8873 g_free (source_file);
8874 g_free (source_files);
8875 g_free (sym_seq_points);
8876 g_ptr_array_free (source_file_list, TRUE);
8877 mono_metadata_free_mh (header);
8880 case CMD_METHOD_GET_PARAM_INFO: {
8881 MonoMethodSignature *sig = mono_method_signature (method);
8885 /* FIXME: mono_class_from_mono_type () and byrefs */
8887 /* FIXME: Use a smaller encoding */
8888 buffer_add_int (buf, sig->call_convention);
8889 buffer_add_int (buf, sig->param_count);
8890 buffer_add_int (buf, sig->generic_param_count);
8891 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8892 for (i = 0; i < sig->param_count; ++i) {
8894 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8897 /* Emit parameter names */
8898 names = g_new (char *, sig->param_count);
8899 mono_method_get_param_names (method, (const char **) names);
8900 for (i = 0; i < sig->param_count; ++i)
8901 buffer_add_string (buf, names [i]);
8906 case CMD_METHOD_GET_LOCALS_INFO: {
8909 MonoDebugLocalsInfo *locals;
8910 int *locals_map = NULL;
8912 header = mono_method_get_header_checked (method, &error);
8914 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8915 return ERR_INVALID_ARGUMENT;
8918 locals = mono_debug_lookup_locals (method);
8920 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8922 buffer_add_int (buf, 1);
8923 buffer_add_int (buf, 0);
8924 buffer_add_int (buf, header->code_size);
8926 buffer_add_int (buf, header->num_locals);
8928 for (i = 0; i < header->num_locals; ++i) {
8929 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8932 for (i = 0; i < header->num_locals; ++i) {
8934 sprintf (lname, "V_%d", i);
8935 buffer_add_string (buf, lname);
8938 for (i = 0; i < header->num_locals; ++i) {
8939 buffer_add_int (buf, 0);
8940 buffer_add_int (buf, header->code_size);
8943 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8945 buffer_add_int (buf, locals->num_blocks);
8947 for (i = 0; i < locals->num_blocks; ++i) {
8948 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8949 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8950 last_start = locals->code_blocks [i].start_offset;
8954 num_locals = locals->num_locals;
8955 buffer_add_int (buf, num_locals);
8958 for (i = 0; i < num_locals; ++i) {
8959 g_assert (locals->locals [i].index < header->num_locals);
8960 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8963 for (i = 0; i < num_locals; ++i)
8964 buffer_add_string (buf, locals->locals [i].name);
8966 for (i = 0; i < num_locals; ++i) {
8967 if (locals->locals [i].block) {
8968 buffer_add_int (buf, locals->locals [i].block->start_offset);
8969 buffer_add_int (buf, locals->locals [i].block->end_offset);
8971 buffer_add_int (buf, 0);
8972 buffer_add_int (buf, header->code_size);
8976 mono_metadata_free_mh (header);
8979 mono_debug_free_locals (locals);
8980 g_free (locals_map);
8984 case CMD_METHOD_GET_INFO:
8985 buffer_add_int (buf, method->flags);
8986 buffer_add_int (buf, method->iflags);
8987 buffer_add_int (buf, method->token);
8988 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8990 if (method->is_generic)
8992 if (mono_method_signature (method)->generic_param_count)
8994 buffer_add_byte (buf, attrs);
8995 if (method->is_generic || method->is_inflated) {
8998 if (method->is_generic) {
9001 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
9003 result = imethod->declaring;
9004 if (imethod->context.class_inst) {
9005 MonoClass *klass = ((MonoMethod *) imethod)->klass;
9006 /*Generic methods gets the context of the GTD.*/
9007 if (mono_class_get_context (klass)) {
9009 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
9010 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9015 buffer_add_methodid (buf, domain, result);
9017 buffer_add_id (buf, 0);
9019 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9020 if (mono_method_signature (method)->generic_param_count) {
9023 if (method->is_inflated) {
9024 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9026 count = inst->type_argc;
9027 buffer_add_int (buf, count);
9029 for (i = 0; i < count; i++)
9030 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9032 buffer_add_int (buf, 0);
9034 } else if (method->is_generic) {
9035 MonoGenericContainer *container = mono_method_get_generic_container (method);
9037 count = mono_method_signature (method)->generic_param_count;
9038 buffer_add_int (buf, count);
9039 for (i = 0; i < count; i++) {
9040 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9041 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9042 buffer_add_typeid (buf, domain, pklass);
9045 buffer_add_int (buf, 0);
9048 buffer_add_int (buf, 0);
9053 case CMD_METHOD_GET_BODY: {
9057 header = mono_method_get_header_checked (method, &error);
9059 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9060 buffer_add_int (buf, 0);
9062 if (CHECK_PROTOCOL_VERSION (2, 18))
9063 buffer_add_int (buf, 0);
9065 buffer_add_int (buf, header->code_size);
9066 for (i = 0; i < header->code_size; ++i)
9067 buffer_add_byte (buf, header->code [i]);
9069 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9070 buffer_add_int (buf, header->num_clauses);
9071 for (i = 0; i < header->num_clauses; ++i) {
9072 MonoExceptionClause *clause = &header->clauses [i];
9074 buffer_add_int (buf, clause->flags);
9075 buffer_add_int (buf, clause->try_offset);
9076 buffer_add_int (buf, clause->try_len);
9077 buffer_add_int (buf, clause->handler_offset);
9078 buffer_add_int (buf, clause->handler_len);
9079 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9080 buffer_add_typeid (buf, domain, clause->data.catch_class);
9081 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9082 buffer_add_int (buf, clause->data.filter_offset);
9086 mono_metadata_free_mh (header);
9091 case CMD_METHOD_RESOLVE_TOKEN: {
9092 guint32 token = decode_int (p, &p, end);
9095 switch (mono_metadata_token_code (token)) {
9096 case MONO_TOKEN_STRING: {
9101 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9102 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9104 s2 = mono_string_to_utf8_checked (s, &error);
9105 mono_error_assert_ok (&error);
9107 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9108 buffer_add_string (buf, s2);
9115 MonoClass *handle_class;
9117 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9118 val = mono_method_get_wrapper_data (method, token);
9119 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9121 if (handle_class == NULL) {
9122 // Can't figure out the token type
9123 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9127 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9129 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9132 if (handle_class == mono_defaults.typehandle_class) {
9133 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9134 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9135 buffer_add_typeid (buf, domain, (MonoClass *) val);
9137 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9138 } else if (handle_class == mono_defaults.fieldhandle_class) {
9139 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9140 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9141 } else if (handle_class == mono_defaults.methodhandle_class) {
9142 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9143 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9144 } else if (handle_class == mono_defaults.string_class) {
9147 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9148 mono_error_assert_ok (&error);
9149 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9150 buffer_add_string (buf, s);
9153 g_assert_not_reached ();
9160 case CMD_METHOD_GET_CATTRS: {
9162 MonoClass *attr_klass;
9163 MonoCustomAttrInfo *cinfo;
9165 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9166 /* attr_klass can be NULL */
9167 if (err != ERR_NONE)
9170 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9171 if (!is_ok (&error)) {
9172 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9173 return ERR_LOADER_ERROR;
9176 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9177 if (err != ERR_NONE)
9181 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9183 MonoType **type_argv;
9187 MonoGenericInst *ginst;
9188 MonoGenericContext tmp_context;
9189 MonoMethod *inflated;
9191 type_argc = decode_int (p, &p, end);
9192 type_argv = g_new0 (MonoType*, type_argc);
9193 for (i = 0; i < type_argc; ++i) {
9194 klass = decode_typeid (p, &p, end, &d, &err);
9195 if (err != ERR_NONE) {
9201 return ERR_INVALID_ARGUMENT;
9203 type_argv [i] = &klass->byval_arg;
9205 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9207 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9208 tmp_context.method_inst = ginst;
9210 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9211 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9212 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9213 return ERR_INVALID_ARGUMENT;
9214 buffer_add_methodid (buf, domain, inflated);
9218 return ERR_NOT_IMPLEMENTED;
9225 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9228 MonoDomain *old_domain;
9232 method = decode_methodid (p, &p, end, &domain, &err);
9233 if (err != ERR_NONE)
9236 old_domain = mono_domain_get ();
9238 mono_domain_set (domain, TRUE);
9240 err = method_commands_internal (command, method, domain, p, end, buf);
9242 mono_domain_set (old_domain, TRUE);
9248 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9250 int objid = decode_objid (p, &p, end);
9252 MonoThread *thread_obj;
9253 MonoInternalThread *thread;
9255 err = get_object (objid, (MonoObject**)&thread_obj);
9256 if (err != ERR_NONE)
9259 thread = THREAD_TO_INTERNAL (thread_obj);
9262 case CMD_THREAD_GET_NAME: {
9264 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9267 buffer_add_int (buf, 0);
9272 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9274 buffer_add_int (buf, len);
9275 buffer_add_data (buf, (guint8*)name, len);
9280 case CMD_THREAD_GET_FRAME_INFO: {
9281 DebuggerTlsData *tls;
9282 int i, start_frame, length;
9284 // Wait for suspending if it already started
9285 // FIXME: Races with suspend_count
9286 while (!is_suspended ()) {
9288 wait_for_suspend ();
9292 wait_for_suspend ();
9293 if (!is_suspended ())
9294 return ERR_NOT_SUSPENDED;
9297 start_frame = decode_int (p, &p, end);
9298 length = decode_int (p, &p, end);
9300 if (start_frame != 0 || length != -1)
9301 return ERR_NOT_IMPLEMENTED;
9303 mono_loader_lock ();
9304 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9305 mono_loader_unlock ();
9308 compute_frame_info (thread, tls);
9310 buffer_add_int (buf, tls->frame_count);
9311 for (i = 0; i < tls->frame_count; ++i) {
9312 buffer_add_int (buf, tls->frames [i]->id);
9313 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9314 buffer_add_int (buf, tls->frames [i]->il_offset);
9316 * Instead of passing the frame type directly to the client, we associate
9317 * it with the previous frame using a set of flags. This avoids lots of
9318 * conditional code in the client, since a frame whose type isn't
9319 * FRAME_TYPE_MANAGED has no method, location, etc.
9321 buffer_add_byte (buf, tls->frames [i]->flags);
9326 case CMD_THREAD_GET_STATE:
9327 buffer_add_int (buf, thread->state);
9329 case CMD_THREAD_GET_INFO:
9330 buffer_add_byte (buf, thread->threadpool_thread);
9332 case CMD_THREAD_GET_ID:
9333 buffer_add_long (buf, (guint64)(gsize)thread);
9335 case CMD_THREAD_GET_TID:
9336 buffer_add_long (buf, (guint64)thread->tid);
9338 case CMD_THREAD_SET_IP: {
9339 DebuggerTlsData *tls;
9342 MonoSeqPointInfo *seq_points;
9347 method = decode_methodid (p, &p, end, &domain, &err);
9348 if (err != ERR_NONE)
9350 il_offset = decode_long (p, &p, end);
9352 while (!is_suspended ()) {
9354 wait_for_suspend ();
9357 mono_loader_lock ();
9358 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9359 mono_loader_unlock ();
9362 compute_frame_info (thread, tls);
9363 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9364 return ERR_INVALID_ARGUMENT;
9366 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9368 g_assert (seq_points);
9371 return ERR_INVALID_ARGUMENT;
9373 // FIXME: Check that the ip change is safe
9375 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);
9376 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9380 return ERR_NOT_IMPLEMENTED;
9387 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9391 MonoThread *thread_obj;
9392 MonoInternalThread *thread;
9393 int pos, i, len, frame_idx;
9394 DebuggerTlsData *tls;
9396 MonoDebugMethodJitInfo *jit;
9397 MonoMethodSignature *sig;
9399 MonoMethodHeader *header;
9401 objid = decode_objid (p, &p, end);
9402 err = get_object (objid, (MonoObject**)&thread_obj);
9403 if (err != ERR_NONE)
9406 thread = THREAD_TO_INTERNAL (thread_obj);
9408 id = decode_id (p, &p, end);
9410 mono_loader_lock ();
9411 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9412 mono_loader_unlock ();
9415 for (i = 0; i < tls->frame_count; ++i) {
9416 if (tls->frames [i]->id == id)
9419 if (i == tls->frame_count)
9420 return ERR_INVALID_FRAMEID;
9423 frame = tls->frames [frame_idx];
9425 /* This is supported for frames without has_ctx etc. set */
9426 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9427 if (CHECK_PROTOCOL_VERSION (2, 38))
9428 buffer_add_domainid (buf, frame->domain);
9432 if (!frame->has_ctx)
9433 return ERR_ABSENT_INFORMATION;
9435 if (!ensure_jit (frame))
9436 return ERR_ABSENT_INFORMATION;
9440 sig = mono_method_signature (frame->actual_method);
9442 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9444 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9446 return ERR_ABSENT_INFORMATION;
9449 case CMD_STACK_FRAME_GET_VALUES: {
9451 len = decode_int (p, &p, end);
9452 header = mono_method_get_header_checked (frame->actual_method, &error);
9453 mono_error_assert_ok (&error); /* FIXME report error */
9455 for (i = 0; i < len; ++i) {
9456 pos = decode_int (p, &p, end);
9461 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9463 g_assert (pos >= 0 && pos < jit->num_params);
9465 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9467 MonoDebugLocalsInfo *locals;
9469 locals = mono_debug_lookup_locals (frame->method);
9471 g_assert (pos < locals->num_locals);
9472 pos = locals->locals [pos].index;
9473 mono_debug_free_locals (locals);
9475 g_assert (pos >= 0 && pos < jit->num_locals);
9477 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9479 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9482 mono_metadata_free_mh (header);
9485 case CMD_STACK_FRAME_GET_THIS: {
9486 if (frame->api_method->klass->valuetype) {
9487 if (!sig->hasthis) {
9488 MonoObject *p = NULL;
9489 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9491 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9494 if (!sig->hasthis) {
9495 MonoObject *p = NULL;
9496 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9498 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9503 case CMD_STACK_FRAME_SET_VALUES: {
9507 MonoDebugVarInfo *var;
9509 len = decode_int (p, &p, end);
9510 header = mono_method_get_header_checked (frame->actual_method, &error);
9511 mono_error_assert_ok (&error); /* FIXME report error */
9513 for (i = 0; i < len; ++i) {
9514 pos = decode_int (p, &p, end);
9519 g_assert (pos >= 0 && pos < jit->num_params);
9521 t = sig->params [pos];
9522 var = &jit->params [pos];
9524 MonoDebugLocalsInfo *locals;
9526 locals = mono_debug_lookup_locals (frame->method);
9528 g_assert (pos < locals->num_locals);
9529 pos = locals->locals [pos].index;
9530 mono_debug_free_locals (locals);
9532 g_assert (pos >= 0 && pos < jit->num_locals);
9534 t = header->locals [pos];
9535 var = &jit->locals [pos];
9538 if (MONO_TYPE_IS_REFERENCE (t))
9539 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9541 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9542 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9543 if (err != ERR_NONE)
9546 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9548 mono_metadata_free_mh (header);
9551 case CMD_STACK_FRAME_GET_DOMAIN: {
9552 if (CHECK_PROTOCOL_VERSION (2, 38))
9553 buffer_add_domainid (buf, frame->domain);
9556 case CMD_STACK_FRAME_SET_THIS: {
9559 MonoDebugVarInfo *var;
9561 t = &frame->actual_method->klass->byval_arg;
9562 /* Checked by the sender */
9563 g_assert (MONO_TYPE_ISSTRUCT (t));
9564 var = jit->this_var;
9567 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9568 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9569 if (err != ERR_NONE)
9572 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9576 return ERR_NOT_IMPLEMENTED;
9583 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9586 int objid, index, len, i, esize;
9590 objid = decode_objid (p, &p, end);
9591 err = get_object (objid, (MonoObject**)&arr);
9592 if (err != ERR_NONE)
9596 case CMD_ARRAY_REF_GET_LENGTH:
9597 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9599 buffer_add_int (buf, arr->max_length);
9600 buffer_add_int (buf, 0);
9602 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9603 buffer_add_int (buf, arr->bounds [i].length);
9604 buffer_add_int (buf, arr->bounds [i].lower_bound);
9608 case CMD_ARRAY_REF_GET_VALUES:
9609 index = decode_int (p, &p, end);
9610 len = decode_int (p, &p, end);
9612 g_assert (index >= 0 && len >= 0);
9613 // Reordered to avoid integer overflow
9614 g_assert (!(index > arr->max_length - len));
9616 esize = mono_array_element_size (arr->obj.vtable->klass);
9617 for (i = index; i < index + len; ++i) {
9618 elem = (gpointer*)((char*)arr->vector + (i * esize));
9619 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9622 case CMD_ARRAY_REF_SET_VALUES:
9623 index = decode_int (p, &p, end);
9624 len = decode_int (p, &p, end);
9626 g_assert (index >= 0 && len >= 0);
9627 // Reordered to avoid integer overflow
9628 g_assert (!(index > arr->max_length - len));
9630 esize = mono_array_element_size (arr->obj.vtable->klass);
9631 for (i = index; i < index + len; ++i) {
9632 elem = (gpointer*)((char*)arr->vector + (i * esize));
9634 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9638 return ERR_NOT_IMPLEMENTED;
9645 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9651 int i, index, length;
9653 gboolean use_utf16 = FALSE;
9655 objid = decode_objid (p, &p, end);
9656 err = get_object (objid, (MonoObject**)&str);
9657 if (err != ERR_NONE)
9661 case CMD_STRING_REF_GET_VALUE:
9662 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9663 for (i = 0; i < mono_string_length (str); ++i)
9664 if (mono_string_chars (str)[i] == 0)
9666 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9669 buffer_add_int (buf, mono_string_length (str) * 2);
9670 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9673 s = mono_string_to_utf8_checked (str, &error);
9674 mono_error_assert_ok (&error);
9675 buffer_add_string (buf, s);
9679 case CMD_STRING_REF_GET_LENGTH:
9680 buffer_add_long (buf, mono_string_length (str));
9682 case CMD_STRING_REF_GET_CHARS:
9683 index = decode_long (p, &p, end);
9684 length = decode_long (p, &p, end);
9685 if (index > mono_string_length (str) - length)
9686 return ERR_INVALID_ARGUMENT;
9687 c = mono_string_chars (str) + index;
9688 for (i = 0; i < length; ++i)
9689 buffer_add_short (buf, c [i]);
9692 return ERR_NOT_IMPLEMENTED;
9699 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9710 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9711 objid = decode_objid (p, &p, end);
9712 err = get_object (objid, &obj);
9713 if (err != ERR_NONE)
9714 buffer_add_int (buf, 1);
9716 buffer_add_int (buf, 0);
9720 objid = decode_objid (p, &p, end);
9721 err = get_object (objid, &obj);
9722 if (err != ERR_NONE)
9725 MonoClass *obj_type;
9726 gboolean remote_obj = FALSE;
9728 obj_type = obj->vtable->klass;
9729 if (mono_class_is_transparent_proxy (obj_type)) {
9730 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9734 g_assert (obj_type);
9737 case CMD_OBJECT_REF_GET_TYPE:
9738 /* This handles transparent proxies too */
9739 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9741 case CMD_OBJECT_REF_GET_VALUES:
9742 len = decode_int (p, &p, end);
9744 for (i = 0; i < len; ++i) {
9745 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9746 if (err != ERR_NONE)
9749 /* Check that the field belongs to the object */
9751 for (k = obj_type; k; k = k->parent) {
9752 if (k == f->parent) {
9758 return ERR_INVALID_FIELDID;
9760 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9764 if (mono_class_field_is_special_static (f))
9765 return ERR_INVALID_FIELDID;
9767 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9768 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9769 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9770 mono_field_static_get_value_checked (vtable, f, val, &error);
9771 if (!is_ok (&error)) {
9772 mono_error_cleanup (&error); /* FIXME report the error */
9773 return ERR_INVALID_OBJECT;
9775 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9778 guint8 *field_value = NULL;
9781 #ifndef DISABLE_REMOTING
9782 void *field_storage = NULL;
9783 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9784 if (!is_ok (&error)) {
9785 mono_error_cleanup (&error); /* FIXME report the error */
9786 return ERR_INVALID_OBJECT;
9789 g_assert_not_reached ();
9792 field_value = (guint8*)obj + f->offset;
9794 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9798 case CMD_OBJECT_REF_SET_VALUES:
9799 len = decode_int (p, &p, end);
9801 for (i = 0; i < len; ++i) {
9802 f = decode_fieldid (p, &p, end, NULL, &err);
9803 if (err != ERR_NONE)
9806 /* Check that the field belongs to the object */
9808 for (k = obj_type; k; k = k->parent) {
9809 if (k == f->parent) {
9815 return ERR_INVALID_FIELDID;
9817 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9821 if (mono_class_field_is_special_static (f))
9822 return ERR_INVALID_FIELDID;
9824 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9825 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9827 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9828 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9829 if (err != ERR_NONE) {
9833 mono_field_static_set_value (vtable, f, val);
9836 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9837 if (err != ERR_NONE)
9842 case CMD_OBJECT_REF_GET_ADDRESS:
9843 buffer_add_long (buf, (gssize)obj);
9845 case CMD_OBJECT_REF_GET_DOMAIN:
9846 buffer_add_domainid (buf, obj->vtable->domain);
9848 case CMD_OBJECT_REF_GET_INFO:
9849 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9850 buffer_add_domainid (buf, obj->vtable->domain);
9853 return ERR_NOT_IMPLEMENTED;
9860 command_set_to_string (CommandSet command_set)
9862 switch (command_set) {
9865 case CMD_SET_OBJECT_REF:
9866 return "OBJECT_REF";
9867 case CMD_SET_STRING_REF:
9868 return "STRING_REF";
9869 case CMD_SET_THREAD:
9871 case CMD_SET_ARRAY_REF:
9873 case CMD_SET_EVENT_REQUEST:
9874 return "EVENT_REQUEST";
9875 case CMD_SET_STACK_FRAME:
9876 return "STACK_FRAME";
9877 case CMD_SET_APPDOMAIN:
9879 case CMD_SET_ASSEMBLY:
9881 case CMD_SET_METHOD:
9885 case CMD_SET_MODULE:
9896 static const char* vm_cmds_str [] = {
9904 "SET_PROTOCOL_VERSION",
9907 "GET_TYPES_FOR_SOURCE_FILE",
9912 static const char* thread_cmds_str[] = {
9922 static const char* event_cmds_str[] = {
9925 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9928 static const char* appdomain_cmds_str[] = {
9930 "GET_FRIENDLY_NAME",
9932 "GET_ENTRY_ASSEMBLY",
9935 "CREATE_BOXED_VALUE"
9938 static const char* assembly_cmds_str[] = {
9941 "GET_MANIFEST_MODULE",
9948 static const char* module_cmds_str[] = {
9952 static const char* field_cmds_str[] = {
9956 static const char* method_cmds_str[] = {
9958 "GET_DECLARING_TYPE",
9966 "MAKE_GENERIC_METHOD"
9969 static const char* type_cmds_str[] = {
9977 "IS_ASSIGNABLE_FROM",
9981 "GET_PROPERTY_CATTRS",
9982 "GET_SOURCE_FILES_2",
9984 "GET_METHODS_BY_NAME_FLAGS",
9986 "GET_INTERFACE_MAP",
9990 static const char* stack_frame_cmds_str[] = {
9998 static const char* array_cmds_str[] = {
10004 static const char* string_cmds_str[] = {
10010 static const char* object_cmds_str[] = {
10021 cmd_to_string (CommandSet set, int command)
10028 cmds = vm_cmds_str;
10029 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10031 case CMD_SET_OBJECT_REF:
10032 cmds = object_cmds_str;
10033 cmds_len = G_N_ELEMENTS (object_cmds_str);
10035 case CMD_SET_STRING_REF:
10036 cmds = string_cmds_str;
10037 cmds_len = G_N_ELEMENTS (string_cmds_str);
10039 case CMD_SET_THREAD:
10040 cmds = thread_cmds_str;
10041 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10043 case CMD_SET_ARRAY_REF:
10044 cmds = array_cmds_str;
10045 cmds_len = G_N_ELEMENTS (array_cmds_str);
10047 case CMD_SET_EVENT_REQUEST:
10048 cmds = event_cmds_str;
10049 cmds_len = G_N_ELEMENTS (event_cmds_str);
10051 case CMD_SET_STACK_FRAME:
10052 cmds = stack_frame_cmds_str;
10053 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10055 case CMD_SET_APPDOMAIN:
10056 cmds = appdomain_cmds_str;
10057 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10059 case CMD_SET_ASSEMBLY:
10060 cmds = assembly_cmds_str;
10061 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10063 case CMD_SET_METHOD:
10064 cmds = method_cmds_str;
10065 cmds_len = G_N_ELEMENTS (method_cmds_str);
10068 cmds = type_cmds_str;
10069 cmds_len = G_N_ELEMENTS (type_cmds_str);
10071 case CMD_SET_MODULE:
10072 cmds = module_cmds_str;
10073 cmds_len = G_N_ELEMENTS (module_cmds_str);
10075 case CMD_SET_FIELD:
10076 cmds = field_cmds_str;
10077 cmds_len = G_N_ELEMENTS (field_cmds_str);
10079 case CMD_SET_EVENT:
10080 cmds = event_cmds_str;
10081 cmds_len = G_N_ELEMENTS (event_cmds_str);
10086 if (command > 0 && command <= cmds_len)
10087 return cmds [command - 1];
10093 wait_for_attach (void)
10095 #ifndef DISABLE_SOCKET_TRANSPORT
10096 if (listen_fd == -1) {
10097 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10101 /* Block and wait for client connection */
10102 conn_fd = socket_transport_accept (listen_fd);
10104 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10105 if (conn_fd == -1) {
10106 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10110 g_assert_not_reached ();
10114 disconnected = !transport_handshake ();
10115 if (disconnected) {
10116 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10126 * This thread handles communication with the debugger client using a JDWP
10129 static gsize WINAPI
10130 debugger_thread (void *arg)
10133 int res, len, id, flags, command = 0;
10134 CommandSet command_set = (CommandSet)0;
10135 guint8 header [HEADER_LENGTH];
10136 guint8 *data, *p, *end;
10140 gboolean attach_failed = FALSE;
10142 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10144 debugger_thread_id = mono_native_thread_id_get ();
10146 MonoInternalThread *internal = mono_thread_internal_current ();
10147 mono_thread_set_name_internal (internal, mono_string_new (mono_domain_get (), "Debugger agent"), TRUE, FALSE, &error);
10148 mono_error_assert_ok (&error);
10150 internal->state |= ThreadState_Background;
10151 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10153 if (agent_config.defer) {
10154 if (!wait_for_attach ()) {
10155 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10156 attach_failed = TRUE; // Don't abort process when we can't listen
10158 mono_set_is_debugger_attached (TRUE);
10159 /* Send start event to client */
10160 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10163 mono_set_is_debugger_attached (TRUE);
10166 while (!attach_failed) {
10167 res = transport_recv (header, HEADER_LENGTH);
10169 /* This will break if the socket is closed during shutdown too */
10170 if (res != HEADER_LENGTH) {
10171 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10176 end = header + HEADER_LENGTH;
10178 len = decode_int (p, &p, end);
10179 id = decode_int (p, &p, end);
10180 flags = decode_byte (p, &p, end);
10181 command_set = (CommandSet)decode_byte (p, &p, end);
10182 command = decode_byte (p, &p, end);
10184 g_assert (flags == 0);
10187 const char *cmd_str;
10188 char cmd_num [256];
10190 cmd_str = cmd_to_string (command_set, command);
10192 sprintf (cmd_num, "%d", command);
10196 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);
10199 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10200 if (len - HEADER_LENGTH > 0)
10202 res = transport_recv (data, len - HEADER_LENGTH);
10203 if (res != len - HEADER_LENGTH) {
10204 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10210 end = data + (len - HEADER_LENGTH);
10212 buffer_init (&buf, 128);
10217 /* Process the request */
10218 switch (command_set) {
10220 err = vm_commands (command, id, p, end, &buf);
10221 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10222 /* Sent after the invoke is complete */
10225 case CMD_SET_EVENT_REQUEST:
10226 err = event_commands (command, p, end, &buf);
10228 case CMD_SET_APPDOMAIN:
10229 err = domain_commands (command, p, end, &buf);
10231 case CMD_SET_ASSEMBLY:
10232 err = assembly_commands (command, p, end, &buf);
10234 case CMD_SET_MODULE:
10235 err = module_commands (command, p, end, &buf);
10237 case CMD_SET_FIELD:
10238 err = field_commands (command, p, end, &buf);
10241 err = type_commands (command, p, end, &buf);
10243 case CMD_SET_METHOD:
10244 err = method_commands (command, p, end, &buf);
10246 case CMD_SET_THREAD:
10247 err = thread_commands (command, p, end, &buf);
10249 case CMD_SET_STACK_FRAME:
10250 err = frame_commands (command, p, end, &buf);
10252 case CMD_SET_ARRAY_REF:
10253 err = array_commands (command, p, end, &buf);
10255 case CMD_SET_STRING_REF:
10256 err = string_commands (command, p, end, &buf);
10258 case CMD_SET_OBJECT_REF:
10259 err = object_commands (command, p, end, &buf);
10262 err = ERR_NOT_IMPLEMENTED;
10265 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10266 buffer_replies = TRUE;
10270 if (buffer_replies) {
10271 buffer_reply_packet (id, err, &buf);
10273 send_reply_packet (id, err, &buf);
10274 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10278 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10279 send_buffered_reply_packets ();
10280 buffer_replies = FALSE;
10284 buffer_free (&buf);
10286 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10290 mono_set_is_debugger_attached (FALSE);
10292 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10293 debugger_thread_exited = TRUE;
10294 mono_coop_cond_signal (&debugger_thread_exited_cond);
10295 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10297 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10299 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10300 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10301 start_debugger_thread ();
10307 #else /* DISABLE_DEBUGGER_AGENT */
10310 mono_debugger_agent_parse_options (char *options)
10312 g_error ("This runtime is configured with the debugger agent disabled.");
10316 mono_debugger_agent_init (void)
10321 mono_debugger_agent_breakpoint_hit (void *sigctx)
10326 mono_debugger_agent_single_step_event (void *sigctx)
10331 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10336 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10337 MonoContext *catch_ctx)
10342 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10347 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10352 mono_debugger_agent_user_break (void)
10358 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10363 mono_debugger_agent_debug_log_is_enabled (void)
10369 mono_debugger_agent_unhandled_exception (MonoException *exc)
10371 g_assert_not_reached ();
10375 debugger_agent_single_step_from_context (MonoContext *ctx)
10377 g_assert_not_reached ();
10381 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10383 g_assert_not_reached ();