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);
899 agent_config.enabled = TRUE;
900 agent_config.suspend = TRUE;
901 agent_config.server = FALSE;
902 agent_config.defer = FALSE;
903 agent_config.address = NULL;
905 //agent_config.log_level = 10;
907 args = g_strsplit (options, ",", -1);
908 for (ptr = args; ptr && *ptr; ptr ++) {
911 if (strncmp (arg, "transport=", 10) == 0) {
912 agent_config.transport = g_strdup (arg + 10);
913 } else if (strncmp (arg, "address=", 8) == 0) {
914 agent_config.address = g_strdup (arg + 8);
915 } else if (strncmp (arg, "loglevel=", 9) == 0) {
916 agent_config.log_level = atoi (arg + 9);
917 } else if (strncmp (arg, "logfile=", 8) == 0) {
918 agent_config.log_file = g_strdup (arg + 8);
919 } else if (strncmp (arg, "suspend=", 8) == 0) {
920 agent_config.suspend = parse_flag ("suspend", arg + 8);
921 } else if (strncmp (arg, "server=", 7) == 0) {
922 agent_config.server = parse_flag ("server", arg + 7);
923 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
924 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
925 } else if (strncmp (arg, "onthrow=", 8) == 0) {
926 /* We support multiple onthrow= options */
927 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
928 } else if (strncmp (arg, "onthrow", 7) == 0) {
929 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
930 } else if (strncmp (arg, "help", 4) == 0) {
933 } else if (strncmp (arg, "timeout=", 8) == 0) {
934 agent_config.timeout = atoi (arg + 8);
935 } else if (strncmp (arg, "launch=", 7) == 0) {
936 agent_config.launch = g_strdup (arg + 7);
937 } else if (strncmp (arg, "embedding=", 10) == 0) {
938 agent_config.embedding = atoi (arg + 10) == 1;
939 } else if (strncmp (arg, "keepalive=", 10) == 0) {
940 agent_config.keepalive = atoi (arg + 10);
941 } else if (strncmp (arg, "setpgid=", 8) == 0) {
942 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
949 if (agent_config.server && !agent_config.suspend) {
950 /* Waiting for deferred attachment */
951 agent_config.defer = TRUE;
952 if (agent_config.address == NULL) {
953 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
957 //agent_config.log_level = 0;
959 if (agent_config.transport == NULL) {
960 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
964 if (agent_config.address == NULL && !agent_config.server) {
965 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
970 if (!strcmp (agent_config.transport, "dt_socket")) {
971 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
972 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
979 mono_debugger_agent_init (void)
981 mono_coop_mutex_init_recursive (&debug_mutex);
983 if (!agent_config.enabled)
988 /* Need to know whenever a thread has acquired the loader mutex */
989 mono_loader_lock_track_ownership (TRUE);
991 event_requests = g_ptr_array_new ();
993 mono_coop_mutex_init (&debugger_thread_exited_mutex);
994 mono_coop_cond_init (&debugger_thread_exited_cond);
996 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
997 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
998 mono_profiler_install_runtime_initialized (runtime_initialized);
999 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
1000 mono_profiler_install_thread (thread_startup, thread_end);
1001 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
1002 mono_profiler_install_jit_end (jit_end);
1004 mono_native_tls_alloc (&debugger_tls_id, NULL);
1006 /* Needed by the hash_table_new_type () call below */
1007 mono_gc_base_init ();
1009 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");
1011 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1013 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");
1015 pending_assembly_loads = g_ptr_array_new ();
1016 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1018 log_level = agent_config.log_level;
1020 embedding = agent_config.embedding;
1021 disconnected = TRUE;
1023 if (agent_config.log_file) {
1024 log_file = fopen (agent_config.log_file, "w+");
1026 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1035 breakpoints_init ();
1038 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1040 * This is needed because currently we don't handle liveness info.
1042 mini_get_debug_options ()->mdb_optimizations = TRUE;
1044 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1045 /* This is needed because we can't set local variables in registers yet */
1046 mono_disable_optimizations (MONO_OPT_LINEARS);
1050 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1051 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1052 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1055 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1058 if (agent_config.setpgid)
1062 if (!agent_config.onuncaught && !agent_config.onthrow)
1063 finish_agent_init (TRUE);
1067 * finish_agent_init:
1069 * Finish the initialization of the agent. This involves connecting the transport
1070 * and starting the agent thread. This is either done at startup, or
1071 * in response to some event like an unhandled exception.
1074 finish_agent_init (gboolean on_startup)
1078 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1081 if (agent_config.launch) {
1084 // FIXME: Generated address
1085 // FIXME: Races with transport_connect ()
1087 argv [0] = agent_config.launch;
1088 argv [1] = agent_config.transport;
1089 argv [2] = agent_config.address;
1092 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1094 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1099 transport_connect (agent_config.address);
1102 /* Do some which is usually done after sending the VMStart () event */
1103 vm_start_event_sent = TRUE;
1104 start_debugger_thread ();
1109 mono_debugger_agent_cleanup (void)
1114 stop_debugger_thread ();
1116 breakpoints_cleanup ();
1125 #ifndef DISABLE_SOCKET_TRANSPORT
1130 * recv() + handle incomplete reads and EINTR
1133 socket_transport_recv (void *buf, int len)
1139 static gint64 last_keepalive;
1146 res = recv (fd, (char *) buf + total, len - total, flags);
1149 if (agent_config.keepalive) {
1150 gboolean need_keepalive = FALSE;
1151 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1152 need_keepalive = TRUE;
1153 } else if (res == -1) {
1154 /* This could happen if recv () is interrupted repeatedly */
1155 msecs = mono_msec_ticks ();
1156 if (msecs - last_keepalive >= agent_config.keepalive) {
1157 need_keepalive = TRUE;
1158 last_keepalive = msecs;
1161 if (need_keepalive) {
1162 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1166 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1174 set_keepalive (void)
1179 if (!agent_config.keepalive || !conn_fd)
1182 tv.tv_sec = agent_config.keepalive / 1000;
1183 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1185 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1186 g_assert (result >= 0);
1190 socket_transport_accept (int socket_fd)
1193 conn_fd = accept (socket_fd, NULL, NULL);
1196 if (conn_fd == -1) {
1197 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1199 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1206 socket_transport_send (void *data, int len)
1213 res = send (conn_fd, data, len, 0);
1214 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1225 * socket_transport_connect:
1227 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1230 socket_transport_connect (const char *address)
1232 MonoAddressInfo *result;
1233 MonoAddressEntry *rp;
1234 int sfd = -1, s, res;
1238 if (agent_config.address) {
1239 res = parse_address (agent_config.address, &host, &port);
1240 g_assert (res == 0);
1251 mono_network_init ();
1253 /* Obtain address(es) matching host/port */
1254 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1256 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1261 if (agent_config.server) {
1262 /* Wait for a connection */
1264 struct sockaddr_in addr;
1267 /* No address, generate one */
1268 sfd = socket (AF_INET, SOCK_STREAM, 0);
1271 /* This will bind the socket to a random port */
1272 res = listen (sfd, 16);
1274 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1279 addrlen = sizeof (addr);
1280 memset (&addr, 0, sizeof (addr));
1281 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1282 g_assert (res == 0);
1284 host = (char*)"127.0.0.1";
1285 port = ntohs (addr.sin_port);
1287 /* Emit the address to stdout */
1288 /* FIXME: Should print another interface, not localhost */
1289 printf ("%s:%d\n", host, port);
1291 /* Listen on the provided address */
1292 for (rp = result->entries; rp != NULL; rp = rp->next) {
1293 MonoSocketAddress sockaddr;
1297 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1299 sfd = socket (rp->family, rp->socktype,
1304 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1307 res = bind (sfd, &sockaddr.addr, sock_len);
1311 res = listen (sfd, 16);
1318 mono_free_address_info (result);
1321 if (agent_config.defer)
1324 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1326 if (agent_config.timeout) {
1331 tv.tv_usec = agent_config.timeout * 1000;
1333 FD_SET (sfd, &readfds);
1336 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1340 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1345 conn_fd = socket_transport_accept (sfd);
1349 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1351 /* Connect to the specified address */
1352 /* FIXME: Respect the timeout */
1353 for (rp = result->entries; rp != NULL; rp = rp->next) {
1354 MonoSocketAddress sockaddr;
1357 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1359 sfd = socket (rp->family, rp->socktype,
1365 res = connect (sfd, &sockaddr.addr, sock_len);
1369 break; /* Success */
1377 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1383 mono_free_address_info (result);
1386 if (!transport_handshake ())
1391 socket_transport_close1 (void)
1393 /* This will interrupt the agent thread */
1394 /* Close the read part only so it can still send back replies */
1395 /* Also shut down the connection listener so that we can exit normally */
1397 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1398 shutdown (conn_fd, SD_BOTH);
1399 shutdown (listen_fd, SD_BOTH);
1400 closesocket (listen_fd);
1402 shutdown (conn_fd, SHUT_RD);
1403 shutdown (listen_fd, SHUT_RDWR);
1411 socket_transport_close2 (void)
1414 shutdown (conn_fd, SD_BOTH);
1416 shutdown (conn_fd, SHUT_RDWR);
1421 register_socket_transport (void)
1423 DebuggerTransport trans;
1425 trans.name = "dt_socket";
1426 trans.connect = socket_transport_connect;
1427 trans.close1 = socket_transport_close1;
1428 trans.close2 = socket_transport_close2;
1429 trans.send = socket_transport_send;
1430 trans.recv = socket_transport_recv;
1432 register_transport (&trans);
1436 * socket_fd_transport_connect:
1440 socket_fd_transport_connect (const char *address)
1444 res = sscanf (address, "%d", &conn_fd);
1446 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1450 if (!transport_handshake ())
1455 register_socket_fd_transport (void)
1457 DebuggerTransport trans;
1459 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1460 trans.name = "socket-fd";
1461 trans.connect = socket_fd_transport_connect;
1462 trans.close1 = socket_transport_close1;
1463 trans.close2 = socket_transport_close2;
1464 trans.send = socket_transport_send;
1465 trans.recv = socket_transport_recv;
1467 register_transport (&trans);
1470 #endif /* DISABLE_SOCKET_TRANSPORT */
1476 #define MAX_TRANSPORTS 16
1478 static DebuggerTransport *transport;
1480 static DebuggerTransport transports [MAX_TRANSPORTS];
1481 static int ntransports;
1484 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1487 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1489 register_transport (trans);
1493 register_transport (DebuggerTransport *trans)
1495 g_assert (ntransports < MAX_TRANSPORTS);
1497 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1502 transport_init (void)
1506 #ifndef DISABLE_SOCKET_TRANSPORT
1507 register_socket_transport ();
1508 register_socket_fd_transport ();
1511 for (i = 0; i < ntransports; ++i) {
1512 if (!strcmp (agent_config.transport, transports [i].name))
1515 if (i == ntransports) {
1516 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1517 for (i = 0; i < ntransports; ++i)
1518 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1519 fprintf (stderr, "\n");
1522 transport = &transports [i];
1526 transport_connect (const char *address)
1528 transport->connect (address);
1532 transport_close1 (void)
1534 transport->close1 ();
1538 transport_close2 (void)
1540 transport->close2 ();
1544 transport_send (void *buf, int len)
1546 return transport->send (buf, len);
1550 transport_recv (void *buf, int len)
1552 return transport->recv (buf, len);
1556 mono_debugger_agent_transport_handshake (void)
1558 return transport_handshake ();
1562 transport_handshake (void)
1564 char handshake_msg [128];
1568 disconnected = TRUE;
1570 /* Write handshake message */
1571 sprintf (handshake_msg, "DWP-Handshake");
1574 res = transport_send (handshake_msg, strlen (handshake_msg));
1575 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1577 g_assert (res != -1);
1580 res = transport_recv (buf, strlen (handshake_msg));
1581 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1582 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1587 * To support older clients, the client sends its protocol version after connecting
1588 * using a command. Until that is received, default to our protocol version.
1590 major_version = MAJOR_VERSION;
1591 minor_version = MINOR_VERSION;
1592 protocol_version_set = FALSE;
1594 #ifndef DISABLE_SOCKET_TRANSPORT
1595 // FIXME: Move this somewhere else
1597 * Set TCP_NODELAY on the socket so the client receives events/command
1598 * results immediately.
1602 int result = setsockopt (conn_fd,
1607 g_assert (result >= 0);
1613 disconnected = FALSE;
1618 stop_debugger_thread (void)
1623 transport_close1 ();
1626 * Wait for the thread to exit.
1628 * If we continue with the shutdown without waiting for it, then the client might
1629 * not receive an answer to its last command like a resume.
1631 if (!is_debugger_thread ()) {
1633 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1634 if (!debugger_thread_exited)
1635 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1636 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1637 } while (!debugger_thread_exited);
1640 transport_close2 ();
1644 start_debugger_thread (void)
1647 MonoInternalThread *thread;
1649 thread = mono_thread_create_internal (mono_get_root_domain (), debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, &error);
1650 mono_error_assert_ok (&error);
1652 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1653 g_assert (debugger_thread_handle);
1657 * Functions to decode protocol data
1661 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1664 g_assert (*endbuf <= limit);
1669 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1672 g_assert (*endbuf <= limit);
1674 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1677 static inline gint64
1678 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1680 guint32 high = decode_int (buf, &buf, limit);
1681 guint32 low = decode_int (buf, &buf, limit);
1685 return ((((guint64)high) << 32) | ((guint64)low));
1689 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1691 return decode_int (buf, endbuf, limit);
1695 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1697 int len = decode_int (buf, &buf, limit);
1705 s = (char *)g_malloc (len + 1);
1708 memcpy (s, buf, len);
1717 * Functions to encode protocol data
1721 buffer_init (Buffer *buf, int size)
1723 buf->buf = (guint8 *)g_malloc (size);
1725 buf->end = buf->buf + size;
1729 buffer_len (Buffer *buf)
1731 return buf->p - buf->buf;
1735 buffer_make_room (Buffer *buf, int size)
1737 if (buf->end - buf->p < size) {
1738 int new_size = buf->end - buf->buf + size + 32;
1739 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1740 size = buf->p - buf->buf;
1743 buf->end = buf->buf + new_size;
1748 buffer_add_byte (Buffer *buf, guint8 val)
1750 buffer_make_room (buf, 1);
1756 buffer_add_short (Buffer *buf, guint32 val)
1758 buffer_make_room (buf, 2);
1759 buf->p [0] = (val >> 8) & 0xff;
1760 buf->p [1] = (val >> 0) & 0xff;
1765 buffer_add_int (Buffer *buf, guint32 val)
1767 buffer_make_room (buf, 4);
1768 buf->p [0] = (val >> 24) & 0xff;
1769 buf->p [1] = (val >> 16) & 0xff;
1770 buf->p [2] = (val >> 8) & 0xff;
1771 buf->p [3] = (val >> 0) & 0xff;
1776 buffer_add_long (Buffer *buf, guint64 l)
1778 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1779 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1783 buffer_add_id (Buffer *buf, int id)
1785 buffer_add_int (buf, (guint64)id);
1789 buffer_add_data (Buffer *buf, guint8 *data, int len)
1791 buffer_make_room (buf, len);
1792 memcpy (buf->p, data, len);
1797 buffer_add_string (Buffer *buf, const char *str)
1802 buffer_add_int (buf, 0);
1805 buffer_add_int (buf, len);
1806 buffer_add_data (buf, (guint8*)str, len);
1811 buffer_add_buffer (Buffer *buf, Buffer *data)
1813 buffer_add_data (buf, data->buf, buffer_len (data));
1817 buffer_free (Buffer *buf)
1823 send_packet (int command_set, int command, Buffer *data)
1829 id = InterlockedIncrement (&packet_id);
1831 len = data->p - data->buf + 11;
1832 buffer_init (&buf, len);
1833 buffer_add_int (&buf, len);
1834 buffer_add_int (&buf, id);
1835 buffer_add_byte (&buf, 0); /* flags */
1836 buffer_add_byte (&buf, command_set);
1837 buffer_add_byte (&buf, command);
1838 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1840 res = transport_send (buf.buf, len);
1848 send_reply_packets (int npackets, ReplyPacket *packets)
1855 for (i = 0; i < npackets; ++i)
1856 len += buffer_len (packets [i].data) + 11;
1857 buffer_init (&buf, len);
1858 for (i = 0; i < npackets; ++i) {
1859 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1860 buffer_add_int (&buf, packets [i].id);
1861 buffer_add_byte (&buf, 0x80); /* flags */
1862 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1863 buffer_add_byte (&buf, packets [i].error);
1864 buffer_add_buffer (&buf, packets [i].data);
1867 res = transport_send (buf.buf, len);
1875 send_reply_packet (int id, int error, Buffer *data)
1879 memset (&packet, 0, sizeof (ReplyPacket));
1881 packet.error = error;
1884 return send_reply_packets (1, &packet);
1888 send_buffered_reply_packets (void)
1892 send_reply_packets (nreply_packets, reply_packets);
1893 for (i = 0; i < nreply_packets; ++i)
1894 buffer_free (reply_packets [i].data);
1895 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1900 buffer_reply_packet (int id, int error, Buffer *data)
1904 if (nreply_packets == 128)
1905 send_buffered_reply_packets ();
1907 p = &reply_packets [nreply_packets];
1910 p->data = g_new0 (Buffer, 1);
1911 buffer_init (p->data, buffer_len (data));
1912 buffer_add_buffer (p->data, data);
1921 * Represents an object accessible by the debugger client.
1924 /* Unique id used in the wire protocol to refer to objects */
1927 * A weakref gc handle pointing to the object. The gc handle is used to
1928 * detect if the object was garbage collected.
1933 /* Maps objid -> ObjRef */
1934 /* Protected by the loader lock */
1935 static GHashTable *objrefs;
1936 /* Protected by the loader lock */
1937 static GHashTable *obj_to_objref;
1938 /* Protected by the dbg lock */
1939 static MonoGHashTable *suspended_objs;
1942 free_objref (gpointer value)
1944 ObjRef *o = (ObjRef *)value;
1946 mono_gchandle_free (o->handle);
1954 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1955 obj_to_objref = g_hash_table_new (NULL, NULL);
1956 suspended_objs = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1960 objrefs_cleanup (void)
1962 g_hash_table_destroy (objrefs);
1967 * Return an ObjRef for OBJ.
1970 get_objref (MonoObject *obj)
1973 GSList *reflist = NULL, *l;
1979 if (suspend_count) {
1981 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1984 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1988 mono_loader_lock ();
1990 /* FIXME: The tables can grow indefinitely */
1992 if (mono_gc_is_moving ()) {
1994 * Objects can move, so use a hash table mapping hash codes to lists of
1995 * ObjRef structures.
1997 hash = mono_object_hash (obj);
1999 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2000 for (l = reflist; l; l = l->next) {
2001 ref = (ObjRef *)l->data;
2002 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2003 mono_loader_unlock ();
2008 /* Use a hash table with masked pointers to internalize object references */
2009 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2010 /* ref might refer to a different object with the same addr which was GCd */
2011 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2012 mono_loader_unlock ();
2017 ref = g_new0 (ObjRef, 1);
2018 ref->id = InterlockedIncrement (&objref_id);
2019 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2021 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2023 if (mono_gc_is_moving ()) {
2024 reflist = g_slist_append (reflist, ref);
2025 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2027 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2030 mono_loader_unlock ();
2036 true_pred (gpointer key, gpointer value, gpointer user_data)
2042 clear_suspended_objs (void)
2045 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2050 get_objid (MonoObject *obj)
2055 return get_objref (obj)->id;
2059 * Set OBJ to the object identified by OBJID.
2060 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2064 get_object_allow_null (int objid, MonoObject **obj)
2074 return ERR_INVALID_OBJECT;
2076 mono_loader_lock ();
2078 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2081 *obj = mono_gchandle_get_target (ref->handle);
2082 mono_loader_unlock ();
2084 return ERR_INVALID_OBJECT;
2087 mono_loader_unlock ();
2088 return ERR_INVALID_OBJECT;
2093 get_object (int objid, MonoObject **obj)
2095 ErrorCode err = get_object_allow_null (objid, obj);
2097 if (err != ERR_NONE)
2100 return ERR_INVALID_OBJECT;
2105 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2107 return decode_id (buf, endbuf, limit);
2111 buffer_add_objid (Buffer *buf, MonoObject *o)
2113 buffer_add_id (buf, get_objid (o));
2132 * Represents a runtime structure accessible to the debugger client
2135 /* Unique id used in the wire protocol */
2137 /* Domain of the runtime structure, NULL if the domain was unloaded */
2144 MonoAssembly *assembly;
2145 MonoClassField *field;
2147 MonoProperty *property;
2152 /* Maps runtime structure -> Id */
2153 /* Protected by the dbg lock */
2154 GHashTable *val_to_id [ID_NUM];
2155 /* Classes whose class load event has been sent */
2156 /* Protected by the loader lock */
2157 GHashTable *loaded_classes;
2158 /* Maps MonoClass->GPtrArray of file names */
2159 GHashTable *source_files;
2160 /* Maps source file basename -> GSList of classes */
2161 GHashTable *source_file_to_class;
2162 /* Same with ignore-case */
2163 GHashTable *source_file_to_class_ignorecase;
2167 /* Protected by the dbg lock */
2168 static GPtrArray *ids [ID_NUM];
2175 for (i = 0; i < ID_NUM; ++i)
2176 ids [i] = g_ptr_array_new ();
2184 for (i = 0; i < ID_NUM; ++i) {
2186 for (j = 0; j < ids [i]->len; ++j)
2187 g_free (g_ptr_array_index (ids [i], j));
2188 g_ptr_array_free (ids [i], TRUE);
2195 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2197 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2199 GHashTableIter iter;
2200 GPtrArray *file_names;
2205 for (i = 0; i < ID_NUM; ++i)
2206 if (info->val_to_id [i])
2207 g_hash_table_destroy (info->val_to_id [i]);
2208 g_hash_table_destroy (info->loaded_classes);
2210 g_hash_table_iter_init (&iter, info->source_files);
2211 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2212 for (i = 0; i < file_names->len; ++i)
2213 g_free (g_ptr_array_index (file_names, i));
2214 g_ptr_array_free (file_names, TRUE);
2217 g_hash_table_iter_init (&iter, info->source_file_to_class);
2218 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2223 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2224 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2232 domain_jit_info (domain)->agent_info = NULL;
2234 /* Clear ids referencing structures in the domain */
2236 for (i = 0; i < ID_NUM; ++i) {
2238 for (j = 0; j < ids [i]->len; ++j) {
2239 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2240 if (id->domain == domain)
2247 mono_loader_lock ();
2248 g_hash_table_remove (domains, domain);
2249 mono_loader_unlock ();
2252 static AgentDomainInfo*
2253 get_agent_domain_info (MonoDomain *domain)
2255 AgentDomainInfo *info = NULL;
2257 mono_domain_lock (domain);
2259 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2261 info = g_new0 (AgentDomainInfo, 1);
2262 domain_jit_info (domain)->agent_info = info;
2263 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2264 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2265 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2266 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2269 mono_domain_unlock (domain);
2275 get_id (MonoDomain *domain, IdType type, gpointer val)
2278 AgentDomainInfo *info;
2283 info = get_agent_domain_info (domain);
2287 if (info->val_to_id [type] == NULL)
2288 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2290 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2296 id = g_new0 (Id, 1);
2298 id->id = ids [type]->len + 1;
2299 id->domain = domain;
2302 g_hash_table_insert (info->val_to_id [type], val, id);
2303 g_ptr_array_add (ids [type], id);
2310 static inline gpointer
2311 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2315 int id = decode_id (buf, endbuf, limit);
2324 // FIXME: error handling
2326 g_assert (id > 0 && id <= ids [type]->len);
2328 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2331 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2332 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2333 *err = ERR_UNLOADED;
2338 *domain = res->domain;
2340 return res->data.val;
2344 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2346 int id = get_id (domain, type, val);
2348 buffer_add_id (buf, id);
2352 static inline MonoClass*
2353 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2357 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2358 if (G_UNLIKELY (log_level >= 2) && klass) {
2361 s = mono_type_full_name (&klass->byval_arg);
2362 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2368 static inline MonoAssembly*
2369 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2371 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2374 static inline MonoImage*
2375 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2377 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2380 static inline MonoMethod*
2381 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2385 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2386 if (G_UNLIKELY (log_level >= 2) && m) {
2389 s = mono_method_full_name (m, TRUE);
2390 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2396 static inline MonoClassField*
2397 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2399 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2402 static inline MonoDomain*
2403 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2405 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2408 static inline MonoProperty*
2409 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2411 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2415 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2417 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2418 if (G_UNLIKELY (log_level >= 2) && klass) {
2421 s = mono_type_full_name (&klass->byval_arg);
2422 if (is_debugger_thread ())
2423 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2425 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2431 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2433 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2434 if (G_UNLIKELY (log_level >= 2) && method) {
2437 s = mono_method_full_name (method, 1);
2438 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2444 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2448 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2449 if (G_UNLIKELY (log_level >= 2) && assembly)
2450 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2454 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2456 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2460 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2462 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2466 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2468 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2472 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2474 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2477 static void invoke_method (void);
2484 * save_thread_context:
2486 * Set CTX as the current threads context which is used for computing stack traces.
2487 * This function is signal-safe.
2490 save_thread_context (MonoContext *ctx)
2492 DebuggerTlsData *tls;
2494 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2498 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2500 mono_thread_state_init_from_current (&tls->context);
2503 /* Number of threads suspended */
2505 * If this is equal to the size of thread_to_tls, the runtime is considered
2508 static gint32 threads_suspend_count;
2510 static MonoCoopMutex suspend_mutex;
2512 /* Cond variable used to wait for suspend_count becoming 0 */
2513 static MonoCoopCond suspend_cond;
2515 /* Semaphore used to wait for a thread becoming suspended */
2516 static MonoCoopSem suspend_sem;
2521 mono_coop_mutex_init (&suspend_mutex);
2522 mono_coop_cond_init (&suspend_cond);
2523 mono_coop_sem_init (&suspend_sem, 0);
2528 StackFrameInfo last_frame;
2529 gboolean last_frame_set;
2533 } GetLastFrameUserData;
2536 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2538 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2540 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2543 if (!data->last_frame_set) {
2544 /* Store the last frame */
2545 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2546 data->last_frame_set = TRUE;
2549 /* Store the context/lmf for the frame above the last frame */
2550 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2551 data->lmf = info->lmf;
2552 data->domain = info->domain;
2558 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2560 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2562 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2563 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2564 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2571 * Process interruption of a thread. This should be signal safe.
2573 * This always runs in the debugger thread.
2576 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2579 MonoNativeThreadId tid;
2583 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2584 tid = mono_thread_info_get_tid (info);
2586 // FIXME: Races when the thread leaves managed code before hitting a single step
2589 if (ji && !ji->is_trampoline) {
2590 /* Running managed code, will be suspended by the single step code */
2591 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2594 * Running native code, will be suspended when it returns to/enters
2595 * managed code. Treat it as already suspended.
2596 * This might interrupt the code in process_single_step_inner (), we use the
2597 * tls->suspending flag to avoid races when that happens.
2599 if (!tls->suspended && !tls->suspending) {
2600 GetLastFrameUserData data;
2602 // FIXME: printf is not signal safe, but this is only used during
2603 // debugger debugging
2605 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2606 //save_thread_context (&ctx);
2609 /* Already terminated */
2613 * We are in a difficult position: we want to be able to provide stack
2614 * traces for this thread, but we can't use the current ctx+lmf, since
2615 * the thread is still running, so it might return to managed code,
2616 * making these invalid.
2617 * So we start a stack walk and save the first frame, along with the
2618 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2619 * suspended when it returns to managed code, so the parent's ctx should
2622 data.last_frame_set = FALSE;
2623 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2624 if (data.last_frame_set) {
2625 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2627 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2629 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2630 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2632 tls->async_state.valid = FALSE;
2635 mono_memory_barrier ();
2637 tls->suspended = TRUE;
2638 mono_coop_sem_post (&suspend_sem);
2644 * reset_native_thread_suspend_state:
2646 * Reset the suspended flag and state on native threads
2649 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2651 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2653 if (!tls->really_suspended && tls->suspended) {
2654 tls->suspended = FALSE;
2656 * The thread might still be running if it was executing native code, so the state won't be invalided by
2657 * suspend_current ().
2659 tls->context.valid = FALSE;
2660 tls->async_state.valid = FALSE;
2661 invalidate_frames (tls);
2666 DebuggerTlsData *tls;
2667 gboolean valid_info;
2670 static SuspendThreadResult
2671 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2673 InterruptData *data = (InterruptData *)user_data;
2676 data->valid_info = TRUE;
2677 ji = mono_jit_info_table_find_internal (
2678 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2679 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2683 /* This is signal safe */
2684 thread_interrupt (data->tls, info, ji);
2685 return MonoResumeThread;
2691 * Notify a thread that it needs to suspend.
2694 notify_thread (gpointer key, gpointer value, gpointer user_data)
2696 MonoInternalThread *thread = (MonoInternalThread *)key;
2697 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2698 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2700 if (mono_thread_internal_is_current (thread) || tls->terminated)
2703 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2705 /* This is _not_ equivalent to mono_thread_internal_abort () */
2706 InterruptData interrupt_data = { 0 };
2707 interrupt_data.tls = tls;
2709 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2710 if (!interrupt_data.valid_info) {
2711 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2713 * Attached thread which died without detaching.
2715 tls->terminated = TRUE;
2720 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2722 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2726 if (mono_loader_lock_is_owned_by_self ()) {
2728 * Shortcut for the check in suspend_current (). This speeds up processing
2729 * when executing long running code inside the loader lock, i.e. assembly load
2735 if (is_debugger_thread ())
2738 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2739 if (suspend_count - tls->resume_count > 0)
2740 tls->suspending = TRUE;
2742 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2744 if (suspend_count - tls->resume_count == 0) {
2746 * We are executing a single threaded invoke but the single step for
2747 * suspending is still active.
2748 * FIXME: This slows down single threaded invokes.
2750 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2754 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2756 /* Can't suspend in these methods */
2757 method = jinfo_get_method (ji);
2758 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2761 save_thread_context (ctx);
2769 * Increase the suspend count of the VM. While the suspend count is greater
2770 * than 0, runtime threads are suspended at certain points during execution.
2775 mono_loader_lock ();
2777 mono_coop_mutex_lock (&suspend_mutex);
2781 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2783 if (suspend_count == 1) {
2784 // FIXME: Is it safe to call this inside the lock ?
2785 start_single_stepping ();
2786 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2789 mono_coop_mutex_unlock (&suspend_mutex);
2791 if (suspend_count == 1)
2793 * Suspend creation of new threadpool threads, since they cannot run
2795 mono_threadpool_suspend ();
2797 mono_loader_unlock ();
2803 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2809 g_assert (is_debugger_thread ());
2811 mono_loader_lock ();
2813 mono_coop_mutex_lock (&suspend_mutex);
2815 g_assert (suspend_count > 0);
2818 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2820 if (suspend_count == 0) {
2821 // FIXME: Is it safe to call this inside the lock ?
2822 stop_single_stepping ();
2823 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2826 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2827 mono_coop_cond_broadcast (&suspend_cond);
2829 mono_coop_mutex_unlock (&suspend_mutex);
2830 //g_assert (err == 0);
2832 if (suspend_count == 0)
2833 mono_threadpool_resume ();
2835 mono_loader_unlock ();
2841 * Resume just one thread.
2844 resume_thread (MonoInternalThread *thread)
2846 DebuggerTlsData *tls;
2848 g_assert (is_debugger_thread ());
2850 mono_loader_lock ();
2852 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2855 mono_coop_mutex_lock (&suspend_mutex);
2857 g_assert (suspend_count > 0);
2859 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2861 tls->resume_count += suspend_count;
2864 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2865 * but only the one whose resume_count field is > 0 will be resumed.
2867 mono_coop_cond_broadcast (&suspend_cond);
2869 mono_coop_mutex_unlock (&suspend_mutex);
2870 //g_assert (err == 0);
2872 mono_loader_unlock ();
2876 free_frames (StackFrame **frames, int nframes)
2880 for (i = 0; i < nframes; ++i) {
2881 if (frames [i]->jit)
2882 mono_debug_free_method_jit_info (frames [i]->jit);
2883 g_free (frames [i]);
2889 invalidate_frames (DebuggerTlsData *tls)
2892 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2895 free_frames (tls->frames, tls->frame_count);
2896 tls->frame_count = 0;
2899 free_frames (tls->restore_frames, tls->restore_frame_count);
2900 tls->restore_frame_count = 0;
2901 tls->restore_frames = NULL;
2907 * Suspend the current thread until the runtime is resumed. If the thread has a
2908 * pending invoke, then the invoke is executed before this function returns.
2911 suspend_current (void)
2913 DebuggerTlsData *tls;
2915 g_assert (!is_debugger_thread ());
2917 if (mono_loader_lock_is_owned_by_self ()) {
2919 * If we own the loader mutex, can't suspend until we release it, since the
2920 * whole runtime can deadlock otherwise.
2925 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2928 mono_coop_mutex_lock (&suspend_mutex);
2930 tls->suspending = FALSE;
2931 tls->really_suspended = TRUE;
2933 if (!tls->suspended) {
2934 tls->suspended = TRUE;
2935 mono_coop_sem_post (&suspend_sem);
2938 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2940 while (suspend_count - tls->resume_count > 0) {
2941 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2944 tls->suspended = FALSE;
2945 tls->really_suspended = FALSE;
2947 threads_suspend_count --;
2949 mono_coop_mutex_unlock (&suspend_mutex);
2951 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2953 if (tls->pending_invoke) {
2954 /* Save the original context */
2955 tls->pending_invoke->has_ctx = TRUE;
2956 tls->pending_invoke->ctx = tls->context.ctx;
2961 /* The frame info becomes invalid after a resume */
2962 tls->context.valid = FALSE;
2963 tls->async_state.valid = FALSE;
2964 invalidate_frames (tls);
2968 count_thread (gpointer key, gpointer value, gpointer user_data)
2970 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2972 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
2973 *(int*)user_data = *(int*)user_data + 1;
2977 count_threads_to_wait_for (void)
2981 mono_loader_lock ();
2982 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2983 mono_loader_unlock ();
2991 * Wait until the runtime is completely suspended.
2994 wait_for_suspend (void)
2996 int nthreads, nwait, err;
2997 gboolean waited = FALSE;
2999 // FIXME: Threads starting/stopping ?
3000 mono_loader_lock ();
3001 nthreads = mono_g_hash_table_size (thread_to_tls);
3002 mono_loader_unlock ();
3005 nwait = count_threads_to_wait_for ();
3007 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3008 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3009 g_assert (err == 0);
3017 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3023 * Return whenever the runtime is suspended.
3028 return count_threads_to_wait_for () == 0;
3032 no_seq_points_found (MonoMethod *method, int offset)
3035 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3037 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3041 DebuggerTlsData *tls;
3043 } ComputeFramesUserData;
3046 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3048 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3050 MonoMethod *method, *actual_method, *api_method;
3054 if (info->type != FRAME_TYPE_MANAGED) {
3055 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3056 /* Mark the last frame as an invoke frame */
3058 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3064 method = jinfo_get_method (info->ji);
3066 method = info->method;
3067 actual_method = info->actual_method;
3068 api_method = method;
3073 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3076 if (info->il_offset == -1) {
3077 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3078 if (ud->frames == NULL) {
3079 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3080 info->il_offset = sp.il_offset;
3082 if (info->il_offset == -1)
3083 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3086 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);
3088 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3089 if (!CHECK_PROTOCOL_VERSION (2, 17))
3090 /* Older clients can't handle this flag */
3092 api_method = mono_marshal_method_from_wrapper (method);
3095 actual_method = api_method;
3096 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3099 frame = g_new0 (StackFrame, 1);
3100 frame->method = method;
3101 frame->actual_method = actual_method;
3102 frame->api_method = api_method;
3103 frame->il_offset = info->il_offset;
3104 frame->native_offset = info->native_offset;
3105 frame->flags = flags;
3106 frame->ji = info->ji;
3107 if (info->reg_locations)
3108 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3111 frame->has_ctx = TRUE;
3113 frame->domain = info->domain;
3115 ud->frames = g_slist_append (ud->frames, frame);
3121 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3123 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3126 * 'tls->filter_ctx' is the location of the throw site.
3128 * mono_walk_stack() will never actually hit the throw site, but unwind
3129 * directly from the filter to the call site; we abort stack unwinding here
3130 * once this happens and resume from the throw site.
3133 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3136 return process_frame (info, ctx, user_data);
3140 * Return a malloc-ed list of StackFrame structures.
3143 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3145 ComputeFramesUserData user_data;
3146 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3151 user_data.tls = tls;
3152 user_data.frames = NULL;
3154 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3156 nframes = g_slist_length (user_data.frames);
3157 res = g_new0 (StackFrame*, nframes);
3158 l = user_data.frames;
3159 for (i = 0; i < nframes; ++i) {
3160 res [i] = (StackFrame *)l->data;
3163 *out_nframes = nframes;
3169 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3171 ComputeFramesUserData user_data;
3173 int i, findex, new_frame_count;
3174 StackFrame **new_frames, *f;
3175 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3177 // FIXME: Locking on tls
3178 if (tls->frames && tls->frames_up_to_date)
3181 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3183 user_data.tls = tls;
3184 user_data.frames = NULL;
3185 if (tls->terminated) {
3186 tls->frame_count = 0;
3188 } if (!tls->really_suspended && tls->async_state.valid) {
3189 /* Have to use the state saved by the signal handler */
3190 process_frame (&tls->async_last_frame, NULL, &user_data);
3191 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3192 } else if (tls->filter_state.valid) {
3194 * We are inside an exception filter.
3196 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3198 if (tls->context.valid)
3199 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3201 * After that, we resume unwinding from the location where the exception has been thrown.
3203 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3204 } else if (tls->context.valid) {
3205 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3208 tls->frame_count = 0;
3212 new_frame_count = g_slist_length (user_data.frames);
3213 new_frames = g_new0 (StackFrame*, new_frame_count);
3215 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3216 f = (StackFrame *)tmp->data;
3219 * Reuse the id for already existing stack frames, so invokes don't invalidate
3220 * the still valid stack frames.
3222 for (i = 0; i < tls->frame_count; ++i) {
3223 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3224 f->id = tls->frames [i]->id;
3229 if (i >= tls->frame_count)
3230 f->id = InterlockedIncrement (&frame_id);
3232 new_frames [findex ++] = f;
3235 g_slist_free (user_data.frames);
3237 invalidate_frames (tls);
3239 tls->frames = new_frames;
3240 tls->frame_count = new_frame_count;
3241 tls->frames_up_to_date = TRUE;
3245 * GHFunc to emit an appdomain creation event
3246 * @param key Don't care
3247 * @param value A loaded appdomain
3248 * @param user_data Don't care
3251 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3253 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3254 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3258 * GHFunc to emit a thread start event
3259 * @param key A thread id
3260 * @param value A thread object
3261 * @param user_data Don't care
3264 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3266 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3267 process_profiler_event (EVENT_KIND_THREAD_START, value);
3271 * GFunc to emit an assembly load event
3272 * @param value A loaded assembly
3273 * @param user_data Don't care
3276 emit_assembly_load (gpointer value, gpointer user_data)
3278 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3282 * GFunc to emit a type load event
3283 * @param value A loaded type
3284 * @param user_data Don't care
3287 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3289 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3293 strdup_tolower (char *s)
3298 for (p = s2; *p; ++p)
3304 * Same as g_path_get_basename () but handles windows paths as well,
3305 * which can occur in .mdb files created by pdb2mdb.
3308 dbg_path_get_basename (const char *filename)
3312 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3313 return g_path_get_basename (filename);
3317 /* No separator -> filename */
3318 r = strrchr (filename, '\\');
3320 return g_strdup (filename);
3322 /* Trailing slash, remove component */
3324 char *copy = g_strdup (filename);
3325 copy [r-filename] = 0;
3326 r = strrchr (copy, '\\');
3330 return g_strdup ("/");
3332 r = g_strdup (&r[1]);
3337 return g_strdup (&r[1]);
3341 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3343 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3345 MonoCustomAttrInfo *ainfo;
3347 if (ji->dbg_attrs_inited)
3351 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3353 if (!step_through_klass)
3354 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3356 if (!non_user_klass)
3357 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3359 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3360 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3362 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3363 ji->dbg_hidden = TRUE;
3364 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3365 ji->dbg_step_through = TRUE;
3366 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3367 ji->dbg_non_user_code = TRUE;
3368 mono_custom_attrs_free (ainfo);
3371 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3372 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3374 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3375 ji->dbg_step_through = TRUE;
3376 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3377 ji->dbg_non_user_code = TRUE;
3378 mono_custom_attrs_free (ainfo);
3381 mono_memory_barrier ();
3382 ji->dbg_attrs_inited = TRUE;
3390 * create_event_list:
3392 * Return a list of event request ids matching EVENT, starting from REQS, which
3393 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3395 * We return request ids, instead of requests, to simplify threading, since
3396 * requests could be deleted anytime when the loader lock is not held.
3397 * LOCKING: Assumes the loader lock is held.
3400 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3403 GSList *events = NULL;
3405 *suspend_policy = SUSPEND_POLICY_NONE;
3408 reqs = event_requests;
3413 for (i = 0; i < reqs->len; ++i) {
3414 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3415 if (req->event_kind == event) {
3416 gboolean filtered = FALSE;
3419 for (j = 0; j < req->nmodifiers; ++j) {
3420 Modifier *mod = &req->modifiers [j];
3422 if (mod->kind == MOD_KIND_COUNT) {
3424 if (mod->data.count > 0) {
3425 if (mod->data.count > 0) {
3427 if (mod->data.count == 0)
3431 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3432 if (mod->data.thread != mono_thread_internal_current ())
3434 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3435 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3437 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3439 if (ei->caught && !mod->caught)
3441 if (!ei->caught && !mod->uncaught)
3443 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3445 gboolean found = FALSE;
3446 MonoAssembly **assemblies = mod->data.assemblies;
3449 for (k = 0; assemblies [k]; ++k)
3450 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3455 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3456 gpointer iter = NULL;
3458 MonoDebugSourceInfo *sinfo;
3459 char *source_file, *s;
3460 gboolean found = FALSE;
3462 GPtrArray *source_file_list;
3464 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3465 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3468 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3469 for (i = 0; i < source_file_list->len; ++i) {
3470 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3472 * Do a case-insesitive match by converting the file name to
3475 s = strdup_tolower (sinfo->source_file);
3476 if (g_hash_table_lookup (mod->data.source_files, s))
3479 char *s2 = dbg_path_get_basename (sinfo->source_file);
3480 char *s3 = strdup_tolower (s2);
3482 if (g_hash_table_lookup (mod->data.source_files, s3))
3489 g_ptr_array_free (source_file_list, TRUE);
3494 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3497 s = mono_type_full_name (&ei->klass->byval_arg);
3498 if (!g_hash_table_lookup (mod->data.type_names, s))
3501 } else if (mod->kind == MOD_KIND_STEP) {
3502 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3503 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3504 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3505 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3507 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3508 init_jit_info_dbg_attrs (ji);
3512 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3513 init_jit_info_dbg_attrs (ji);
3514 if (ji->dbg_step_through)
3517 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3518 init_jit_info_dbg_attrs (ji);
3519 if (ji->dbg_non_user_code)
3526 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3527 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3532 /* Send a VM START/DEATH event by default */
3533 if (event == EVENT_KIND_VM_START)
3534 events = g_slist_append (events, GINT_TO_POINTER (0));
3535 if (event == EVENT_KIND_VM_DEATH)
3536 events = g_slist_append (events, GINT_TO_POINTER (0));
3541 static G_GNUC_UNUSED const char*
3542 event_to_string (EventKind event)
3545 case EVENT_KIND_VM_START: return "VM_START";
3546 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3547 case EVENT_KIND_THREAD_START: return "THREAD_START";
3548 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3549 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3550 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3551 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3552 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3553 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3554 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3555 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3556 case EVENT_KIND_STEP: return "STEP";
3557 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3558 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3559 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3560 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3561 case EVENT_KIND_USER_LOG: return "USER_LOG";
3563 g_assert_not_reached ();
3571 * Send an event to the client, suspending the vm if needed.
3572 * LOCKING: Since this can suspend the calling thread, no locks should be held
3574 * The EVENTS list is freed by this function.
3577 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3581 MonoDomain *domain = mono_domain_get ();
3582 MonoThread *thread = NULL;
3583 MonoObject *keepalive_obj = NULL;
3584 gboolean send_success = FALSE;
3589 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3593 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3594 // FIXME: We miss those events
3595 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3599 if (vm_death_event_sent) {
3600 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3604 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3605 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3610 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3614 if (event == EVENT_KIND_KEEPALIVE)
3615 suspend_policy = SUSPEND_POLICY_NONE;
3620 if (agent_config.defer) {
3621 /* Make sure the thread id is always set when doing deferred debugging */
3622 if (is_debugger_thread ()) {
3623 /* Don't suspend on events from the debugger thread */
3624 suspend_policy = SUSPEND_POLICY_NONE;
3625 thread = mono_thread_get_main ();
3627 else thread = mono_thread_current ();
3629 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3630 // FIXME: Send these with a NULL thread, don't suspend the current thread
3635 nevents = g_slist_length (events);
3636 buffer_init (&buf, 128);
3637 buffer_add_byte (&buf, suspend_policy);
3638 buffer_add_int (&buf, nevents);
3640 for (l = events; l; l = l->next) {
3641 buffer_add_byte (&buf, event); // event kind
3642 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3646 if (event == EVENT_KIND_VM_DEATH) {
3650 thread = mono_thread_current ();
3652 if (event == EVENT_KIND_VM_START && arg != NULL)
3653 thread = (MonoThread *)arg;
3656 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3659 case EVENT_KIND_THREAD_START:
3660 case EVENT_KIND_THREAD_DEATH:
3662 case EVENT_KIND_APPDOMAIN_CREATE:
3663 case EVENT_KIND_APPDOMAIN_UNLOAD:
3664 buffer_add_domainid (&buf, (MonoDomain *)arg);
3666 case EVENT_KIND_METHOD_ENTRY:
3667 case EVENT_KIND_METHOD_EXIT:
3668 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3670 case EVENT_KIND_ASSEMBLY_LOAD:
3671 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3673 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3674 DebuggerTlsData *tls;
3676 /* The domain the assembly belonged to is not equal to the current domain */
3677 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3679 g_assert (tls->domain_unloading);
3681 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3684 case EVENT_KIND_TYPE_LOAD:
3685 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3687 case EVENT_KIND_BREAKPOINT:
3688 case EVENT_KIND_STEP:
3689 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3690 buffer_add_long (&buf, il_offset);
3692 case EVENT_KIND_VM_START:
3693 buffer_add_domainid (&buf, mono_get_root_domain ());
3695 case EVENT_KIND_VM_DEATH:
3696 if (CHECK_PROTOCOL_VERSION (2, 27))
3697 buffer_add_int (&buf, mono_environment_exitcode_get ());
3699 case EVENT_KIND_EXCEPTION: {
3700 EventInfo *ei = (EventInfo *)arg;
3701 buffer_add_objid (&buf, ei->exc);
3703 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3704 * later after the suspension. (#12494).
3706 keepalive_obj = ei->exc;
3709 case EVENT_KIND_USER_BREAK:
3711 case EVENT_KIND_USER_LOG: {
3712 EventInfo *ei = (EventInfo *)arg;
3713 buffer_add_int (&buf, ei->level);
3714 buffer_add_string (&buf, ei->category ? ei->category : "");
3715 buffer_add_string (&buf, ei->message ? ei->message : "");
3718 case EVENT_KIND_KEEPALIVE:
3719 suspend_policy = SUSPEND_POLICY_NONE;
3722 g_assert_not_reached ();
3726 if (event == EVENT_KIND_VM_START) {
3727 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3728 if (!agent_config.defer)
3729 start_debugger_thread ();
3732 if (event == EVENT_KIND_VM_DEATH) {
3733 vm_death_event_sent = TRUE;
3734 suspend_policy = SUSPEND_POLICY_NONE;
3737 if (mono_runtime_is_shutting_down ())
3738 suspend_policy = SUSPEND_POLICY_NONE;
3740 if (suspend_policy != SUSPEND_POLICY_NONE) {
3742 * Save the thread context and start suspending before sending the packet,
3743 * since we could be receiving the resume request before send_packet ()
3746 save_thread_context (ctx);
3750 /* This will keep this object alive */
3751 get_objref (keepalive_obj);
3754 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3758 g_slist_free (events);
3761 if (!send_success) {
3762 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3766 if (event == EVENT_KIND_VM_START) {
3767 vm_start_event_sent = TRUE;
3770 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);
3772 switch (suspend_policy) {
3773 case SUSPEND_POLICY_NONE:
3775 case SUSPEND_POLICY_ALL:
3778 case SUSPEND_POLICY_EVENT_THREAD:
3782 g_assert_not_reached ();
3787 process_profiler_event (EventKind event, gpointer arg)
3791 EventInfo ei, *ei_arg = NULL;
3793 if (event == EVENT_KIND_TYPE_LOAD) {
3794 ei.klass = (MonoClass *)arg;
3798 mono_loader_lock ();
3799 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3800 mono_loader_unlock ();
3802 process_event (event, arg, 0, NULL, events, suspend_policy);
3806 runtime_initialized (MonoProfiler *prof)
3808 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3809 if (agent_config.defer)
3810 start_debugger_thread ();
3814 runtime_shutdown (MonoProfiler *prof)
3816 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3818 mono_debugger_agent_cleanup ();
3822 thread_startup (MonoProfiler *prof, uintptr_t tid)
3824 MonoInternalThread *thread = mono_thread_internal_current ();
3825 MonoInternalThread *old_thread;
3826 DebuggerTlsData *tls;
3828 if (is_debugger_thread ())
3831 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3833 mono_loader_lock ();
3834 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3835 mono_loader_unlock ();
3837 if (thread == old_thread) {
3839 * For some reason, thread_startup () might be called for the same thread
3840 * multiple times (attach ?).
3842 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3846 * thread_end () might not be called for some threads, and the tid could
3849 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3850 mono_loader_lock ();
3851 mono_g_hash_table_remove (thread_to_tls, old_thread);
3852 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3853 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3854 mono_loader_unlock ();
3858 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3860 // FIXME: Free this somewhere
3861 tls = g_new0 (DebuggerTlsData, 1);
3862 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3863 tls->thread = thread;
3864 mono_native_tls_set_value (debugger_tls_id, tls);
3866 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3868 mono_loader_lock ();
3869 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3870 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3871 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3872 mono_loader_unlock ();
3874 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3877 * suspend_vm () could have missed this thread, so wait for a resume.
3883 thread_end (MonoProfiler *prof, uintptr_t tid)
3885 MonoInternalThread *thread;
3886 DebuggerTlsData *tls = NULL;
3888 mono_loader_lock ();
3889 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3891 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3892 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3894 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3895 tls->terminated = TRUE;
3896 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3897 MONO_GC_UNREGISTER_ROOT (tls->thread);
3901 mono_loader_unlock ();
3903 /* We might be called for threads started before we registered the start callback */
3905 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3907 if (mono_thread_internal_is_current (thread) && !mono_native_tls_get_value (debugger_tls_id)
3910 * This can happen on darwin since we deregister threads using pthread dtors.
3911 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3916 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3921 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3923 mono_loader_lock ();
3924 g_hash_table_insert (domains, domain, domain);
3925 mono_loader_unlock ();
3927 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3931 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3933 DebuggerTlsData *tls;
3935 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3936 if (is_debugger_thread ())
3940 * Remember the currently unloading appdomain as it is needed to generate
3941 * proper ids for unloading assemblies.
3943 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3945 tls->domain_unloading = domain;
3949 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3951 DebuggerTlsData *tls;
3953 if (is_debugger_thread ())
3956 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3958 tls->domain_unloading = NULL;
3960 clear_breakpoints_for_domain (domain);
3962 mono_loader_lock ();
3963 /* Invalidate each thread's frame stack */
3964 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3965 mono_loader_unlock ();
3967 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3971 * invalidate_each_thread:
3973 * A GHFunc to invalidate frames.
3974 * value must be a DebuggerTlsData*
3977 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3979 invalidate_frames ((DebuggerTlsData *)value);
3983 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3985 /* Sent later in jit_end () */
3987 g_ptr_array_add (pending_assembly_loads, assembly);
3992 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3994 if (is_debugger_thread ())
3997 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3999 clear_event_requests_for_assembly (assembly);
4000 clear_types_for_assembly (assembly);
4004 send_type_load (MonoClass *klass)
4006 gboolean type_load = FALSE;
4007 MonoDomain *domain = mono_domain_get ();
4008 AgentDomainInfo *info = NULL;
4010 info = get_agent_domain_info (domain);
4012 mono_loader_lock ();
4014 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4016 g_hash_table_insert (info->loaded_classes, klass, klass);
4019 mono_loader_unlock ();
4022 emit_type_load (klass, klass, NULL);
4026 * Emit load events for all types currently loaded in the domain.
4027 * Takes the loader and domain locks.
4028 * user_data is unused.
4031 send_types_for_domain (MonoDomain *domain, void *user_data)
4033 MonoDomain* old_domain;
4034 AgentDomainInfo *info = NULL;
4036 info = get_agent_domain_info (domain);
4039 old_domain = mono_domain_get ();
4041 mono_domain_set (domain, TRUE);
4043 mono_loader_lock ();
4044 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4045 mono_loader_unlock ();
4047 mono_domain_set (old_domain, TRUE);
4051 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4054 MonoDomain* old_domain;
4056 old_domain = mono_domain_get ();
4058 mono_domain_set (domain, TRUE);
4060 mono_domain_assemblies_lock (domain);
4061 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4062 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4063 emit_assembly_load (ass, NULL);
4065 mono_domain_assemblies_unlock (domain);
4067 mono_domain_set (old_domain, TRUE);
4071 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4074 * We emit type load events when the first method of the type is JITted,
4075 * since the class load profiler callbacks might be called with the
4076 * loader lock held. They could also occur in the debugger thread.
4077 * Same for assembly load events.
4080 MonoAssembly *assembly = NULL;
4082 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4084 if (pending_assembly_loads->len > 0) {
4085 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4086 g_ptr_array_remove_index (pending_assembly_loads, 0);
4091 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4097 send_type_load (method->klass);
4100 add_pending_breakpoints (method, jinfo);
4104 * BREAKPOINTS/SINGLE STEPPING
4108 * Contains information about an inserted breakpoint.
4111 long il_offset, native_offset;
4115 } BreakpointInstance;
4118 * Contains generic information about a breakpoint.
4122 * The method where the breakpoint is placed. Can be NULL in which case it
4123 * is inserted into every method. This is used to implement method entry/
4124 * exit events. Can be a generic method definition, in which case the
4125 * breakpoint is inserted into every instance.
4131 * A list of BreakpointInstance structures describing where the breakpoint
4132 * was inserted. There could be more than one because of
4133 * generics/appdomains/method entry/exit.
4135 GPtrArray *children;
4138 /* List of breakpoints */
4139 /* Protected by the loader lock */
4140 static GPtrArray *breakpoints;
4141 /* Maps breakpoint locations to the number of breakpoints at that location */
4142 static GHashTable *bp_locs;
4145 breakpoints_init (void)
4147 breakpoints = g_ptr_array_new ();
4148 bp_locs = g_hash_table_new (NULL, NULL);
4152 * insert_breakpoint:
4154 * Insert the breakpoint described by BP into the method described by
4158 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4161 BreakpointInstance *inst;
4162 SeqPointIterator it;
4163 gboolean it_has_sp = FALSE;
4168 mono_seq_point_iterator_init (&it, seq_points);
4169 while (mono_seq_point_iterator_next (&it)) {
4170 if (it.seq_point.il_offset == bp->il_offset) {
4178 * The set of IL offsets with seq points doesn't completely match the
4179 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4181 mono_seq_point_iterator_init (&it, seq_points);
4182 while (mono_seq_point_iterator_next (&it)) {
4183 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4184 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4185 it.seq_point.il_offset + 1 == bp->il_offset) {
4193 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4195 mono_seq_point_iterator_init (&it, seq_points);
4196 while (mono_seq_point_iterator_next (&it))
4197 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4200 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4201 g_warning ("%s", s);
4205 g_warning ("%s", s);
4211 inst = g_new0 (BreakpointInstance, 1);
4212 inst->il_offset = it.seq_point.il_offset;
4213 inst->native_offset = it.seq_point.native_offset;
4214 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4216 inst->domain = domain;
4218 mono_loader_lock ();
4220 g_ptr_array_add (bp->children, inst);
4222 mono_loader_unlock ();
4225 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4226 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4229 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4230 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4231 } else if (count == 0) {
4232 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4233 mono_arch_set_breakpoint (ji, inst->ip);
4239 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);
4243 remove_breakpoint (BreakpointInstance *inst)
4245 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4247 MonoJitInfo *ji = inst->ji;
4248 guint8 *ip = inst->ip;
4251 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4252 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4255 g_assert (count > 0);
4257 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4258 mono_arch_clear_breakpoint (ji, ip);
4259 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4267 * This doesn't take any locks.
4269 static inline gboolean
4270 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4276 if (method == bp->method)
4278 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4281 if (bp->method->is_inflated && method->is_inflated) {
4282 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4283 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4285 /* Open generic methods should match closed generic methods of the same class */
4286 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4287 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4288 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4290 /* FIXME: Handle !mvar */
4291 if (t1->type != MONO_TYPE_MVAR)
4302 * add_pending_breakpoints:
4304 * Insert pending breakpoints into the newly JITted method METHOD.
4307 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4310 MonoSeqPointInfo *seq_points;
4312 MonoMethod *jmethod;
4317 domain = mono_domain_get ();
4319 mono_loader_lock ();
4321 for (i = 0; i < breakpoints->len; ++i) {
4322 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4323 gboolean found = FALSE;
4325 if (!bp_matches_method (bp, method))
4328 for (j = 0; j < bp->children->len; ++j) {
4329 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4336 MonoMethod *declaring = NULL;
4338 jmethod = jinfo_get_method (ji);
4339 if (jmethod->is_inflated)
4340 declaring = mono_method_get_declaring_generic_method (jmethod);
4342 mono_domain_lock (domain);
4343 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4344 if (!seq_points && declaring)
4345 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4346 mono_domain_unlock (domain);
4348 /* Could be AOT code */
4350 g_assert (seq_points);
4352 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4356 mono_loader_unlock ();
4360 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4368 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4372 /* Might be AOTed code */
4373 mono_class_init (method->klass);
4374 code = mono_aot_get_method_checked (domain, method, &oerror);
4376 mono_error_assert_ok (&oerror);
4377 ji = mono_jit_info_table_find (domain, (char *)code);
4382 insert_breakpoint (seq_points, domain, ji, bp, error);
4386 clear_breakpoint (MonoBreakpoint *bp);
4391 * Set a breakpoint at IL_OFFSET in METHOD.
4392 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4393 * METHOD can also be a generic method definition, in which case a breakpoint
4394 * is placed in all instances of the method.
4395 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4398 static MonoBreakpoint*
4399 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4402 GHashTableIter iter, iter2;
4405 MonoSeqPointInfo *seq_points;
4407 GPtrArray *method_domains;
4408 GPtrArray *method_seq_points;
4415 // - suspend/resume the vm to prevent code patching problems
4416 // - multiple breakpoints on the same location
4417 // - dynamic methods
4420 bp = g_new0 (MonoBreakpoint, 1);
4421 bp->method = method;
4422 bp->il_offset = il_offset;
4424 bp->children = g_ptr_array_new ();
4426 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);
4428 methods = g_ptr_array_new ();
4429 method_domains = g_ptr_array_new ();
4430 method_seq_points = g_ptr_array_new ();
4432 mono_loader_lock ();
4433 g_hash_table_iter_init (&iter, domains);
4434 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4435 mono_domain_lock (domain);
4436 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4437 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4438 if (bp_matches_method (bp, m)) {
4439 /* Save the info locally to simplify the code inside the domain lock */
4440 g_ptr_array_add (methods, m);
4441 g_ptr_array_add (method_domains, domain);
4442 g_ptr_array_add (method_seq_points, seq_points);
4445 mono_domain_unlock (domain);
4448 for (i = 0; i < methods->len; ++i) {
4449 m = (MonoMethod *)g_ptr_array_index (methods, i);
4450 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4451 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4452 set_bp_in_method (domain, m, seq_points, bp, error);
4455 g_ptr_array_add (breakpoints, bp);
4456 mono_loader_unlock ();
4458 g_ptr_array_free (methods, TRUE);
4459 g_ptr_array_free (method_domains, TRUE);
4460 g_ptr_array_free (method_seq_points, TRUE);
4462 if (error && !mono_error_ok (error)) {
4463 clear_breakpoint (bp);
4471 clear_breakpoint (MonoBreakpoint *bp)
4475 // FIXME: locking, races
4476 for (i = 0; i < bp->children->len; ++i) {
4477 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4479 remove_breakpoint (inst);
4484 mono_loader_lock ();
4485 g_ptr_array_remove (breakpoints, bp);
4486 mono_loader_unlock ();
4488 g_ptr_array_free (bp->children, TRUE);
4493 breakpoints_cleanup (void)
4497 mono_loader_lock ();
4499 while (i < event_requests->len) {
4500 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4502 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4503 clear_breakpoint ((MonoBreakpoint *)req->info);
4504 g_ptr_array_remove_index_fast (event_requests, i);
4511 for (i = 0; i < breakpoints->len; ++i)
4512 g_free (g_ptr_array_index (breakpoints, i));
4514 g_ptr_array_free (breakpoints, TRUE);
4515 g_hash_table_destroy (bp_locs);
4520 mono_loader_unlock ();
4524 * clear_breakpoints_for_domain:
4526 * Clear breakpoint instances which reference DOMAIN.
4529 clear_breakpoints_for_domain (MonoDomain *domain)
4533 /* This could be called after shutdown */
4537 mono_loader_lock ();
4538 for (i = 0; i < breakpoints->len; ++i) {
4539 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4542 while (j < bp->children->len) {
4543 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4545 if (inst->domain == domain) {
4546 remove_breakpoint (inst);
4550 g_ptr_array_remove_index_fast (bp->children, j);
4556 mono_loader_unlock ();
4560 * ss_calculate_framecount:
4562 * Ensure DebuggerTlsData fields are filled out.
4564 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4566 if (!tls->context.valid)
4567 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4568 compute_frame_info (tls->thread, tls);
4572 ensure_jit (StackFrame* frame)
4575 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4576 if (!frame->jit && frame->api_method->is_inflated)
4577 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4581 /* This could happen for aot images with no jit debug info */
4582 s = mono_method_full_name (frame->api_method, TRUE);
4583 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4594 * Return FALSE if single stepping needs to continue.
4597 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4599 MonoDebugMethodInfo *minfo;
4600 MonoDebugSourceLocation *loc = NULL;
4601 gboolean hit = TRUE;
4603 if (req->async_stepout_method == method) {
4604 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);
4608 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4610 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4612 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);
4616 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4617 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4619 ss_calculate_framecount (tls, ctx);
4621 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4622 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4623 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4624 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4625 /* Hit the breakpoint in a recursive call, don't halt */
4626 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");
4631 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4632 ss_calculate_framecount (tls, ctx);
4633 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4634 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);
4639 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4641 for (int i = 0; i < asyncMethod->num_awaits; i++)
4643 if (asyncMethod->yield_offsets[i] == sp->il_offset || asyncMethod->resume_offsets[i] == sp->il_offset) {
4644 mono_debug_free_method_async_debug_info (asyncMethod);
4648 mono_debug_free_method_async_debug_info (asyncMethod);
4651 if (req->size != STEP_SIZE_LINE)
4654 /* Have to check whenever a different source line was reached */
4655 minfo = mono_debug_lookup_method (method);
4658 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4661 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);
4662 ss_req->last_method = method;
4664 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4665 ss_calculate_framecount (tls, ctx);
4666 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4667 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4673 ss_req->last_method = method;
4674 ss_req->last_line = loc->row;
4675 mono_debug_free_source_location (loc);
4682 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4684 return bp->method && bp->method->klass->image->assembly == assembly;
4688 get_this (StackFrame *frame)
4690 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4691 MonoDebugVarInfo *var = frame->jit->this_var;
4692 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4695 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4696 addr += (gint32)var->offset;
4697 return *(MonoObject**)addr;
4700 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4701 //since thread probably changed...
4703 get_this_async_id (StackFrame *frame)
4705 return get_objid (get_this (frame));
4708 static MonoMethod* set_notification_method_cache = NULL;
4711 get_set_notification_method ()
4713 if(set_notification_method_cache != NULL)
4714 return set_notification_method_cache;
4716 MonoClass* async_builder_class = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder");
4717 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4718 mono_error_assert_ok (&error);
4719 g_assert (array->len == 1);
4720 set_notification_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4721 g_ptr_array_free (array, TRUE);
4722 return set_notification_method_cache;
4726 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4728 MonoObject* obj = get_this (frame);
4730 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4731 g_assert (builder_field);
4732 MonoObject* builder;
4734 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4735 mono_error_assert_ok (&error);
4739 gboolean arg = TRUE;
4741 mono_runtime_invoke_checked (get_set_notification_method(), mono_object_unbox (builder), args, &error);
4742 mono_error_assert_ok (&error);
4743 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4746 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4749 get_notify_debugger_of_wait_completion_method ()
4751 if (notify_debugger_of_wait_completion_method_cache != NULL)
4752 return notify_debugger_of_wait_completion_method_cache;
4754 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4755 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4756 mono_error_assert_ok (&error);
4757 g_assert (array->len == 1);
4758 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4759 g_ptr_array_free (array, TRUE);
4760 return notify_debugger_of_wait_completion_method_cache;
4764 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4768 int i, j, suspend_policy;
4769 guint32 native_offset;
4771 BreakpointInstance *inst;
4772 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4773 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4774 EventKind kind = EVENT_KIND_BREAKPOINT;
4775 MonoContext *ctx = &tls->restore_state.ctx;
4777 MonoSeqPointInfo *info;
4781 // FIXME: Speed this up
4783 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4784 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4785 g_assert (ji && !ji->is_trampoline);
4786 method = jinfo_get_method (ji);
4788 /* Compute the native offset of the breakpoint from the ip */
4789 native_offset = ip - (guint8*)ji->code_start;
4792 * Skip the instruction causing the breakpoint signal.
4795 mono_arch_skip_breakpoint (ctx, ji);
4797 if (method->wrapper_type || tls->disable_breakpoints)
4800 bp_reqs = g_ptr_array_new ();
4801 ss_reqs = g_ptr_array_new ();
4802 ss_reqs_orig = g_ptr_array_new ();
4804 mono_loader_lock ();
4807 * The ip points to the instruction causing the breakpoint event, which is after
4808 * the offset recorded in the seq point map, so find the prev seq point before ip.
4810 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4813 no_seq_points_found (method, native_offset);
4815 g_assert (found_sp);
4817 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);
4820 for (i = 0; i < breakpoints->len; ++i) {
4821 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4826 for (j = 0; j < bp->children->len; ++j) {
4827 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4828 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4829 if (bp->req->event_kind == EVENT_KIND_STEP) {
4830 g_ptr_array_add (ss_reqs_orig, bp->req);
4832 g_ptr_array_add (bp_reqs, bp->req);
4837 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4838 /* Maybe a method entry/exit event */
4839 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4840 kind = EVENT_KIND_METHOD_ENTRY;
4841 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4842 kind = EVENT_KIND_METHOD_EXIT;
4845 /* Process single step requests */
4846 for (i = 0; i < ss_reqs_orig->len; ++i) {
4847 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4848 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4851 //if we hit async_stepout_method, it's our no matter which thread
4852 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4853 //We have different thread and we don't have async stepping in progress
4854 //it's breakpoint in parallel thread, ignore it
4855 if (ss_req->async_id == 0)
4858 tls->context.valid = FALSE;
4859 tls->async_state.valid = FALSE;
4860 invalidate_frames (tls);
4861 ss_calculate_framecount(tls, ctx);
4862 //make sure we have enough data to get current async method instance id
4863 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4866 //Check method is async before calling get_this_async_id
4867 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4871 mono_debug_free_method_async_debug_info (asyncMethod);
4873 //breakpoint was hit in parallelly executing async method, ignore it
4874 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4878 //Update stepping request to new thread/frame_count that we are continuing on
4879 //so continuing with normal stepping works as expected
4880 if (ss_req->async_stepout_method || ss_req->async_id) {
4881 tls->context.valid = FALSE;
4882 tls->async_state.valid = FALSE;
4883 invalidate_frames (tls);
4884 ss_calculate_framecount (tls, ctx);
4885 ss_req->thread = mono_thread_internal_current ();
4886 ss_req->nframes = tls->frame_count;
4889 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4891 g_ptr_array_add (ss_reqs, req);
4893 /* Start single stepping again from the current sequence point */
4894 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4897 if (ss_reqs->len > 0)
4898 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4899 if (bp_reqs->len > 0)
4900 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4901 if (kind != EVENT_KIND_BREAKPOINT)
4902 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4904 mono_loader_unlock ();
4906 g_ptr_array_free (bp_reqs, TRUE);
4907 g_ptr_array_free (ss_reqs, TRUE);
4910 * FIXME: The first event will suspend, so the second will only be sent after the
4914 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4916 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4917 if (enter_leave_events)
4918 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4921 /* Process a breakpoint/single step event after resuming from a signal handler */
4923 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4925 DebuggerTlsData *tls;
4926 MonoThreadUnwindState orig_restore_state;
4929 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4930 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4931 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4932 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4936 /* This is called when resuming from a signal handler, so it shouldn't return */
4937 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4938 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4939 mono_restore_context (&ctx);
4940 g_assert_not_reached ();
4944 process_breakpoint (void)
4946 process_signal_event (process_breakpoint_inner);
4950 resume_from_signal_handler (void *sigctx, void *func)
4952 DebuggerTlsData *tls;
4955 /* Save the original context in TLS */
4956 // FIXME: This might not work on an altstack ?
4957 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4959 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4962 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4963 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4964 // clob:c could be added to op_seq_point.
4966 mono_sigctx_to_monoctx (sigctx, &ctx);
4967 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4968 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4969 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4971 MONO_CONTEXT_SET_IP (&ctx, func);
4973 mono_monoctx_to_sigctx (&ctx, sigctx);
4975 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4976 mono_ppc_set_func_into_sigctx (sigctx, func);
4981 mono_debugger_agent_breakpoint_hit (void *sigctx)
4984 * We are called from a signal handler, and running code there causes all kinds of
4985 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4986 * So set up the signal context to return to the real breakpoint handler function.
4988 resume_from_signal_handler (sigctx, process_breakpoint);
4992 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4994 if (frame->managed) {
4995 *(MonoContext*)data = *ctx;
5004 * Called by System.Diagnostics.Debugger:Break ().
5007 mono_debugger_agent_user_break (void)
5009 if (agent_config.enabled) {
5014 /* Obtain a context */
5015 MONO_CONTEXT_SET_IP (&ctx, NULL);
5016 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
5017 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
5019 mono_loader_lock ();
5020 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5021 mono_loader_unlock ();
5023 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5024 } else if (debug_options.native_debugger_break) {
5030 ss_depth_to_string (StepDepth depth)
5033 case STEP_DEPTH_OVER:
5035 case STEP_DEPTH_OUT:
5037 case STEP_DEPTH_INTO:
5040 g_assert_not_reached ();
5046 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5051 int il_offset, suspend_policy;
5054 MonoContext *ctx = &tls->restore_state.ctx;
5057 MonoSeqPointInfo *info;
5059 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5061 /* Skip the instruction causing the single step */
5063 mono_arch_skip_single_step (ctx);
5065 if (suspend_count > 0) {
5066 /* Fastpath during invokes, see in process_suspend () */
5067 if (suspend_count - tls->resume_count == 0)
5069 process_suspend (tls, ctx);
5074 // FIXME: A suspend race
5077 if (mono_thread_internal_current () != ss_req->thread)
5080 if (log_level > 0) {
5081 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5083 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);
5086 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5087 g_assert (ji && !ji->is_trampoline);
5088 method = jinfo_get_method (ji);
5091 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5096 * Stopping in memset makes half-initialized vtypes visible.
5097 * Stopping in memcpy makes half-copied vtypes visible.
5099 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5103 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5104 * hence we prefer this check here.
5106 if (ss_req->user_assemblies) {
5107 gboolean found = FALSE;
5108 for (int k = 0; ss_req->user_assemblies[k]; k++)
5109 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5119 * The ip points to the instruction causing the single step event, which is before
5120 * the offset recorded in the seq point map, so find the next seq point after ip.
5122 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
5125 il_offset = sp.il_offset;
5127 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5130 /* Start single stepping again from the current sequence point */
5131 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5133 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5134 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5135 !strcmp (method->name, ".cctor"))
5138 // FIXME: Has to lock earlier
5140 reqs = g_ptr_array_new ();
5142 mono_loader_lock ();
5144 g_ptr_array_add (reqs, ss_req->req);
5146 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5148 g_ptr_array_free (reqs, TRUE);
5150 mono_loader_unlock ();
5152 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5156 process_single_step (void)
5158 process_signal_event (process_single_step_inner);
5162 * mono_debugger_agent_single_step_event:
5164 * Called from a signal handler to handle a single step event.
5167 mono_debugger_agent_single_step_event (void *sigctx)
5169 /* Resume to process_single_step through the signal context */
5171 // FIXME: Since step out/over is implemented using step in, the step in case should
5172 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5175 if (is_debugger_thread ()) {
5177 * This could happen despite our best effors when the runtime calls
5178 * assembly/type resolve hooks.
5179 * FIXME: Breakpoints too.
5183 mono_sigctx_to_monoctx (sigctx, &ctx);
5184 mono_arch_skip_single_step (&ctx);
5185 mono_monoctx_to_sigctx (&ctx, sigctx);
5189 resume_from_signal_handler (sigctx, process_single_step);
5193 debugger_agent_single_step_from_context (MonoContext *ctx)
5195 DebuggerTlsData *tls;
5196 MonoThreadUnwindState orig_restore_state;
5198 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5199 /* Fastpath during invokes, see in process_suspend () */
5200 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5203 if (is_debugger_thread ())
5208 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5209 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5210 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5211 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5213 process_single_step_inner (tls, FALSE);
5215 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5216 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5220 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5222 DebuggerTlsData *tls;
5223 MonoThreadUnwindState orig_restore_state;
5226 if (is_debugger_thread ())
5229 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5230 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5232 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5234 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5235 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5236 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5238 process_breakpoint_inner (tls, FALSE);
5240 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5241 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5242 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5243 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5247 * start_single_stepping:
5249 * Turn on single stepping. Can be called multiple times, for example,
5250 * by a single step event request + a suspend.
5253 start_single_stepping (void)
5255 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5256 int val = InterlockedIncrement (&ss_count);
5259 mono_arch_start_single_stepping ();
5261 g_assert_not_reached ();
5266 stop_single_stepping (void)
5268 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5269 int val = InterlockedDecrement (&ss_count);
5272 mono_arch_stop_single_stepping ();
5274 g_assert_not_reached ();
5281 * Stop the single stepping operation given by SS_REQ.
5284 ss_stop (SingleStepReq *ss_req)
5289 for (l = ss_req->bps; l; l = l->next) {
5290 clear_breakpoint ((MonoBreakpoint *)l->data);
5292 g_slist_free (ss_req->bps);
5296 ss_req->async_id = 0;
5297 ss_req->async_stepout_method = NULL;
5298 if (ss_req->global) {
5299 stop_single_stepping ();
5300 ss_req->global = FALSE;
5307 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5310 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5312 if (ss_req_bp_cache) {
5313 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5314 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5316 for (GSList *l = bps; l; l = l->next) {
5317 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5318 if (bp->method == method && bp->il_offset == il_offset)
5327 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5330 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5332 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5333 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5334 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5340 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5343 ss_bp_hash (gconstpointer data)
5345 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5346 guint hash = (guint) (uintptr_t) s->method;
5347 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5348 hash ^= ((guint)s->il_offset) >> 16;
5352 #define MAX_LINEAR_SCAN_BPS 7
5357 * Create a new breakpoint and add it to a step request.
5358 * Will adjust the bp count and cache used by ss_start.
5361 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5362 MonoMethod *method, guint32 il_offset)
5364 // This list is getting too long, switch to using the hash table
5365 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5366 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5367 for (GSList *l = ss_req->bps; l; l = l->next)
5368 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5371 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5372 // Create and add breakpoint
5373 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5374 ss_req->bps = g_slist_append (ss_req->bps, bp);
5375 if (*ss_req_bp_cache)
5376 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5377 (*ss_req_bp_count)++;
5379 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);
5384 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5388 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5389 mono_seq_point_init_next (info, *sp, next);
5390 for (int i = 0; i < sp->next_len; i++) {
5391 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5392 if (!is_last_non_empty (&next [i], info)) {
5408 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5409 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5410 * belong to the same thread as CTX.
5411 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5414 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5415 gboolean step_to_catch, StackFrame **frames, int nframes)
5417 int i, j, frame_index;
5418 SeqPoint *next_sp, *parent_sp = NULL;
5419 SeqPoint local_sp, local_parent_sp;
5421 MonoSeqPointInfo *parent_info;
5422 MonoMethod *parent_sp_method = NULL;
5423 gboolean enable_global = FALSE;
5425 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5426 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5427 int ss_req_bp_count = g_slist_length (ss_req->bps);
5428 GHashTable *ss_req_bp_cache = NULL;
5430 /* Stop the previous operation */
5434 * Implement single stepping using breakpoints if possible.
5436 if (step_to_catch) {
5437 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5441 if (ctx && !frames) {
5442 /* Need parent frames */
5443 if (!tls->context.valid)
5444 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5445 compute_frame_info (tls->thread, tls);
5446 frames = tls->frames;
5447 nframes = tls->frame_count;
5450 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5452 /* Need to stop in catch clauses as well */
5453 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5454 StackFrame *frame = frames [i];
5457 MonoJitInfo *jinfo = frame->ji;
5458 for (j = 0; j < jinfo->num_clauses; ++j) {
5459 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5460 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5462 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5464 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5465 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5470 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5471 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5473 // Check if we hit yield_offset during normal stepping, because if we did...
5474 // Go into special async stepping mode which places breakpoint on resumeOffset
5475 // of this await call and sets async_id so we can distinguish it from parallel executions
5476 for (i = 0; i < asyncMethod->num_awaits; i++) {
5477 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5478 ss_req->async_id = get_this_async_id (frames [0]);
5479 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5480 if (ss_req_bp_cache)
5481 g_hash_table_destroy (ss_req_bp_cache);
5482 mono_debug_free_method_async_debug_info (asyncMethod);
5486 //If we are at end of async method and doing step-in or step-over...
5487 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5488 if (is_last_non_empty (sp, info)) {
5489 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5491 if (ss_req->depth == STEP_DEPTH_OUT) {
5492 set_set_notification_for_wait_completion_flag (frames [0]);
5493 ss_req->async_id = get_this_async_id (frames [0]);
5494 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5495 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5496 if (ss_req_bp_cache)
5497 g_hash_table_destroy (ss_req_bp_cache);
5498 mono_debug_free_method_async_debug_info (asyncMethod);
5504 mono_debug_free_method_async_debug_info (asyncMethod);
5507 * Find the first sequence point in the current or in a previous frame which
5508 * is not the last in its method.
5510 if (ss_req->depth == STEP_DEPTH_OUT) {
5511 /* Ignore seq points in current method */
5512 while (frame_index < nframes) {
5513 StackFrame *frame = frames [frame_index];
5515 method = frame->method;
5516 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5517 sp = (found_sp)? &local_sp : NULL;
5519 if (sp && sp->next_len != 0)
5522 // There could be method calls before the next seq point in the caller when using nested calls
5523 //enable_global = TRUE;
5525 if (sp && sp->next_len == 0) {
5527 while (frame_index < nframes) {
5528 StackFrame *frame = frames [frame_index];
5530 method = frame->method;
5531 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5532 sp = (found_sp)? &local_sp : NULL;
5533 if (sp && sp->next_len != 0)
5539 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5540 while (frame_index < nframes) {
5541 StackFrame *frame = frames [frame_index];
5543 parent_sp_method = frame->method;
5544 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5545 parent_sp = found_sp ? &local_parent_sp : NULL;
5546 if (found_sp && parent_sp->next_len != 0)
5554 if (sp && sp->next_len > 0) {
5555 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5557 mono_seq_point_init_next (info, *sp, next);
5558 for (i = 0; i < sp->next_len; i++) {
5561 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5567 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5569 mono_seq_point_init_next (parent_info, *parent_sp, next);
5570 for (i = 0; i < parent_sp->next_len; i++) {
5573 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5578 if (ss_req->nframes == 0)
5579 ss_req->nframes = nframes;
5581 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5582 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5584 * This is needed since if we leave managed code, and later return to it, step over
5585 * is not going to stop.
5586 * This approach is a bit ugly, since we change the step depth, but it only affects
5587 * clients who reuse the same step request, and only in this special case.
5589 ss_req->depth = STEP_DEPTH_INTO;
5592 if (ss_req->depth == STEP_DEPTH_INTO) {
5593 /* Enable global stepping so we stop at method entry too */
5594 enable_global = TRUE;
5598 * The ctx/frame info computed above will become invalid when we continue.
5600 tls->context.valid = FALSE;
5601 tls->async_state.valid = FALSE;
5602 invalidate_frames (tls);
5605 if (enable_global) {
5606 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5607 ss_req->global = TRUE;
5608 start_single_stepping ();
5609 } else if (!ss_req->bps) {
5610 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5611 ss_req->global = TRUE;
5612 start_single_stepping ();
5614 ss_req->global = FALSE;
5617 if (ss_req_bp_cache)
5618 g_hash_table_destroy (ss_req_bp_cache);
5622 * Start single stepping of thread THREAD
5625 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5627 DebuggerTlsData *tls;
5628 MonoSeqPointInfo *info = NULL;
5629 SeqPoint *sp = NULL;
5632 MonoMethod *method = NULL;
5633 MonoDebugMethodInfo *minfo;
5634 gboolean step_to_catch = FALSE;
5635 gboolean set_ip = FALSE;
5636 StackFrame **frames = NULL;
5639 if (suspend_count == 0)
5640 return ERR_NOT_SUSPENDED;
5642 wait_for_suspend ();
5644 // FIXME: Multiple requests
5646 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5647 return ERR_NOT_IMPLEMENTED;
5650 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5652 ss_req = g_new0 (SingleStepReq, 1);
5654 ss_req->thread = thread;
5655 ss_req->size = size;
5656 ss_req->depth = depth;
5657 ss_req->filter = filter;
5660 for (int i = 0; i < req->nmodifiers; i++) {
5661 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5662 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5667 mono_loader_lock ();
5668 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5669 mono_loader_unlock ();
5671 if (!tls->context.valid) {
5672 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5673 return ERR_INVALID_ARGUMENT;
5676 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5678 * Need to start single stepping from restore_state and not from the current state
5681 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5684 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5686 if (tls->catch_state.valid) {
5688 StackFrameInfo frame;
5689 MonoContext new_ctx;
5690 MonoLMF *lmf = NULL;
5693 * We are stopped at a throw site. Stepping should go to the catch site.
5696 /* Find the the jit info for the catch context */
5697 res = mono_find_jit_info_ext (
5698 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5699 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5700 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5702 g_assert (frame.type == FRAME_TYPE_MANAGED);
5705 * Find the seq point corresponding to the landing site ip, which is the first seq
5708 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5709 sp = (found_sp)? &local_sp : NULL;
5711 no_seq_points_found (frame.method, frame.native_offset);
5714 method = frame.method;
5716 step_to_catch = TRUE;
5717 /* This make sure the seq point is not skipped by process_single_step () */
5718 ss_req->last_sp = NULL;
5721 if (!step_to_catch) {
5722 StackFrame *frame = NULL;
5725 if (frames && nframes)
5728 compute_frame_info (thread, tls);
5730 if (tls->frame_count)
5731 frame = tls->frames [0];
5734 if (ss_req->size == STEP_SIZE_LINE) {
5736 ss_req->last_method = frame->method;
5737 ss_req->last_line = -1;
5739 minfo = mono_debug_lookup_method (frame->method);
5740 if (minfo && frame->il_offset != -1) {
5741 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5744 ss_req->last_line = loc->row;
5752 if (!method && frame->il_offset != -1) {
5753 /* FIXME: Sort the table and use a binary search */
5754 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5755 sp = (found_sp)? &local_sp : NULL;
5757 no_seq_points_found (frame->method, frame->native_offset);
5759 method = frame->method;
5764 ss_req->start_method = method;
5766 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5769 free_frames (frames, nframes);
5775 ss_destroy (SingleStepReq *req)
5778 g_assert (ss_req == req);
5787 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5790 gboolean found = TRUE;
5794 for (l = ss_req->bps; l; l = l->next) {
5795 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5796 clear_breakpoint ((MonoBreakpoint *)l->data);
5797 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5806 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5809 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5816 if (!agent_config.enabled)
5819 mono_loader_lock ();
5820 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5821 mono_loader_unlock ();
5826 ei.category = mono_string_to_utf8_checked (category, &error);
5827 mono_error_cleanup (&error);
5831 ei.message = mono_string_to_utf8_checked (message, &error);
5832 mono_error_cleanup (&error);
5835 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5837 g_free (ei.category);
5838 g_free (ei.message);
5842 mono_debugger_agent_debug_log_is_enabled (void)
5844 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5845 return agent_config.enabled;
5848 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5850 mono_debugger_agent_unhandled_exception (MonoException *exc)
5859 memset (&ei, 0, sizeof (EventInfo));
5860 ei.exc = (MonoObject*)exc;
5862 mono_loader_lock ();
5863 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5864 mono_loader_unlock ();
5866 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5871 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5872 MonoContext *catch_ctx)
5874 int i, j, suspend_policy;
5876 MonoJitInfo *ji, *catch_ji;
5878 DebuggerTlsData *tls = NULL;
5880 if (thread_to_tls != NULL) {
5881 MonoInternalThread *thread = mono_thread_internal_current ();
5883 mono_loader_lock ();
5884 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5885 mono_loader_unlock ();
5887 if (tls && tls->abort_requested)
5889 if (tls && tls->disable_breakpoints)
5893 memset (&ei, 0, sizeof (EventInfo));
5895 /* Just-In-Time debugging */
5897 if (agent_config.onuncaught && !inited) {
5898 finish_agent_init (FALSE);
5901 * Send an unsolicited EXCEPTION event with a dummy request id.
5903 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5904 ei.exc = (MonoObject*)exc;
5905 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5908 } else if (agent_config.onthrow && !inited) {
5910 gboolean found = FALSE;
5912 for (l = agent_config.onthrow; l; l = l->next) {
5913 char *ex_type = (char *)l->data;
5914 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5916 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5923 finish_agent_init (FALSE);
5926 * Send an unsolicited EXCEPTION event with a dummy request id.
5928 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5929 ei.exc = (MonoObject*)exc;
5930 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5938 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5940 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5944 ei.exc = (MonoObject*)exc;
5945 ei.caught = catch_ctx != NULL;
5947 mono_loader_lock ();
5949 /* Treat exceptions which are caught in non-user code as unhandled */
5950 for (i = 0; i < event_requests->len; ++i) {
5951 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5952 if (req->event_kind != EVENT_KIND_EXCEPTION)
5955 for (j = 0; j < req->nmodifiers; ++j) {
5956 Modifier *mod = &req->modifiers [j];
5958 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5960 gboolean found = FALSE;
5961 MonoAssembly **assemblies = mod->data.assemblies;
5964 for (k = 0; assemblies [k]; ++k)
5965 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5974 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5975 mono_loader_unlock ();
5977 if (tls && ei.caught && catch_ctx) {
5978 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5979 tls->catch_state.ctx = *catch_ctx;
5980 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5981 tls->catch_state.valid = TRUE;
5984 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5987 tls->catch_state.valid = FALSE;
5991 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5993 DebuggerTlsData *tls;
5998 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6003 * We're about to invoke an exception filter during the first pass of exception handling.
6005 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
6006 * 'orig_ctx' is the context where the exception has been thrown.
6009 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6011 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6012 * the call site (line 37) and then continue to Main(), but it would never
6013 * include the throw site (line 32).
6015 * Since exception filters are invoked during the first pass of exception handling,
6016 * the stack frames of the throw site are still intact, so we should include them
6019 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6021 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6022 * but report the location of the 'throw' to the user.
6026 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6030 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6032 DebuggerTlsData *tls;
6037 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6041 tls->filter_state.valid = FALSE;
6045 * buffer_add_value_full:
6047 * Add the encoding of the value at ADDR described by T to the buffer.
6048 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6052 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6053 gboolean as_vtype, GHashTable *parent_vtypes)
6056 gboolean boxed_vtype = FALSE;
6059 if (!(*(void**)addr)) {
6060 /* This can happen with compiler generated locals */
6061 //printf ("%s\n", mono_type_full_name (t));
6062 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6065 g_assert (*(void**)addr);
6066 addr = *(void**)addr;
6071 case MONO_TYPE_BOOLEAN:
6074 case MONO_TYPE_CHAR:
6094 case MONO_TYPE_VOID:
6095 buffer_add_byte (buf, t->type);
6097 case MONO_TYPE_BOOLEAN:
6100 buffer_add_byte (buf, t->type);
6101 buffer_add_int (buf, *(gint8*)addr);
6103 case MONO_TYPE_CHAR:
6106 buffer_add_byte (buf, t->type);
6107 buffer_add_int (buf, *(gint16*)addr);
6112 buffer_add_byte (buf, t->type);
6113 buffer_add_int (buf, *(gint32*)addr);
6118 buffer_add_byte (buf, t->type);
6119 buffer_add_long (buf, *(gint64*)addr);
6123 /* Treat it as a vtype */
6125 case MONO_TYPE_PTR: {
6126 gssize val = *(gssize*)addr;
6128 buffer_add_byte (buf, t->type);
6129 buffer_add_long (buf, val);
6133 case MONO_TYPE_STRING:
6134 case MONO_TYPE_SZARRAY:
6135 case MONO_TYPE_OBJECT:
6136 case MONO_TYPE_CLASS:
6137 case MONO_TYPE_ARRAY:
6138 obj = *(MonoObject**)addr;
6141 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6143 if (obj->vtable->klass->valuetype) {
6144 t = &obj->vtable->klass->byval_arg;
6145 addr = mono_object_unbox (obj);
6148 } else if (obj->vtable->klass->rank) {
6149 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6150 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6151 buffer_add_byte (buf, MONO_TYPE_CLASS);
6153 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6155 buffer_add_objid (buf, obj);
6159 case MONO_TYPE_VALUETYPE:
6160 case MONO_TYPE_TYPEDBYREF: {
6164 MonoClass *klass = mono_class_from_mono_type (t);
6169 * Handle boxed vtypes recursively referencing themselves using fields.
6172 parent_vtypes = g_hash_table_new (NULL, NULL);
6173 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6175 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6176 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6177 buffer_add_int (buf, vtype_index - 1);
6179 /* The client can't handle PARENT_VTYPE */
6180 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6184 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6188 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6189 buffer_add_byte (buf, klass->enumtype);
6190 buffer_add_typeid (buf, domain, klass);
6194 while ((f = mono_class_get_fields (klass, &iter))) {
6195 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6197 if (mono_field_is_deleted (f))
6201 buffer_add_int (buf, nfields);
6204 while ((f = mono_class_get_fields (klass, &iter))) {
6205 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6207 if (mono_field_is_deleted (f))
6209 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6213 g_hash_table_remove (parent_vtypes, addr);
6214 if (g_hash_table_size (parent_vtypes) == 0) {
6215 g_hash_table_destroy (parent_vtypes);
6216 parent_vtypes = NULL;
6221 case MONO_TYPE_GENERICINST:
6222 if (mono_type_generic_inst_is_valuetype (t)) {
6234 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6236 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6240 obj_is_of_type (MonoObject *obj, MonoType *t)
6242 MonoClass *klass = obj->vtable->klass;
6243 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6244 if (mono_class_is_transparent_proxy (klass)) {
6245 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6246 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6256 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6259 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6265 gpointer iter = NULL;
6269 is_enum = decode_byte (buf, &buf, limit);
6270 /* Enums are sent as a normal vtype */
6272 return ERR_NOT_IMPLEMENTED;
6273 klass = decode_typeid (buf, &buf, limit, &d, &err);
6274 if (err != ERR_NONE)
6277 if (t && klass != mono_class_from_mono_type (t)) {
6278 char *name = mono_type_full_name (t);
6279 char *name2 = mono_type_full_name (&klass->byval_arg);
6280 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6283 return ERR_INVALID_ARGUMENT;
6286 nfields = decode_int (buf, &buf, limit);
6287 while ((f = mono_class_get_fields (klass, &iter))) {
6288 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6290 if (mono_field_is_deleted (f))
6292 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6293 if (err != ERR_NONE)
6297 g_assert (nfields == 0);
6305 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6309 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6310 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6311 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6312 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6313 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6314 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6315 char *name = mono_type_full_name (t);
6316 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6318 return ERR_INVALID_ARGUMENT;
6322 case MONO_TYPE_BOOLEAN:
6323 *(guint8*)addr = decode_int (buf, &buf, limit);
6325 case MONO_TYPE_CHAR:
6326 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6329 *(gint8*)addr = decode_int (buf, &buf, limit);
6332 *(guint8*)addr = decode_int (buf, &buf, limit);
6335 *(gint16*)addr = decode_int (buf, &buf, limit);
6338 *(guint16*)addr = decode_int (buf, &buf, limit);
6341 *(gint32*)addr = decode_int (buf, &buf, limit);
6344 *(guint32*)addr = decode_int (buf, &buf, limit);
6347 *(gint64*)addr = decode_long (buf, &buf, limit);
6350 *(guint64*)addr = decode_long (buf, &buf, limit);
6353 *(guint32*)addr = decode_int (buf, &buf, limit);
6356 *(guint64*)addr = decode_long (buf, &buf, limit);
6359 /* We send these as I8, so we get them back as such */
6360 g_assert (type == MONO_TYPE_I8);
6361 *(gssize*)addr = decode_long (buf, &buf, limit);
6363 case MONO_TYPE_GENERICINST:
6364 if (MONO_TYPE_ISSTRUCT (t)) {
6365 /* The client sends these as a valuetype */
6373 /* We send these as vtypes, so we get them back as such */
6374 g_assert (type == MONO_TYPE_VALUETYPE);
6377 case MONO_TYPE_VALUETYPE:
6378 if (type == MONO_TYPE_OBJECT) {
6380 int objid = decode_objid (buf, &buf, limit);
6384 err = get_object (objid, (MonoObject**)&obj);
6385 if (err != ERR_NONE)
6388 return ERR_INVALID_ARGUMENT;
6389 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6390 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6391 return ERR_INVALID_ARGUMENT;
6393 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6395 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6396 if (err != ERR_NONE)
6402 if (MONO_TYPE_IS_REFERENCE (t)) {
6403 if (type == MONO_TYPE_OBJECT) {
6404 int objid = decode_objid (buf, &buf, limit);
6408 err = get_object (objid, (MonoObject**)&obj);
6409 if (err != ERR_NONE)
6413 if (!obj_is_of_type (obj, t)) {
6414 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6415 return ERR_INVALID_ARGUMENT;
6418 if (obj && obj->vtable->domain != domain)
6419 return ERR_INVALID_ARGUMENT;
6421 mono_gc_wbarrier_generic_store (addr, obj);
6422 } else if (type == VALUE_TYPE_ID_NULL) {
6423 *(MonoObject**)addr = NULL;
6424 } else if (type == MONO_TYPE_VALUETYPE) {
6433 /* This can happen when round-tripping boxed vtypes */
6435 * Obtain vtype class.
6436 * Same as the beginning of the handle_vtype case above.
6439 is_enum = decode_byte (buf, &buf, limit);
6441 return ERR_NOT_IMPLEMENTED;
6442 klass = decode_typeid (buf, &buf, limit, &d, &err);
6443 if (err != ERR_NONE)
6446 /* Decode the vtype into a temporary buffer, then box it. */
6447 vtype_buf_size = mono_class_value_size (klass, NULL);
6448 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6449 g_assert (vtype_buf);
6452 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6453 if (err != ERR_NONE) {
6457 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6458 mono_error_cleanup (&error);
6461 char *name = mono_type_full_name (t);
6462 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6464 return ERR_INVALID_ARGUMENT;
6478 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6482 int type = decode_byte (buf, &buf, limit);
6484 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6485 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6486 guint8 *nullable_buf;
6489 * First try decoding it as a Nullable`1
6491 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6492 if (err == ERR_NONE)
6496 * Then try decoding as a primitive value or null.
6498 if (targ->type == type) {
6499 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6500 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6501 if (err != ERR_NONE) {
6502 g_free (nullable_buf);
6505 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6506 if (!is_ok (&error)) {
6507 mono_error_cleanup (&error);
6508 return ERR_INVALID_OBJECT;
6510 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6511 g_free (nullable_buf);
6514 } else if (type == VALUE_TYPE_ID_NULL) {
6515 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6521 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6525 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6529 guint8 *addr, *gaddr;
6532 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6533 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6536 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6537 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6539 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6541 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6542 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6543 addr += (gint32)var->offset;
6545 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6547 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6549 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6552 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6553 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6554 /* Same as regoffset, but with an indirection */
6555 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6556 addr += (gint32)var->offset;
6558 gaddr = (guint8 *)*(gpointer*)addr;
6560 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6562 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6563 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6564 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6565 MonoGSharedVtMethodRuntimeInfo *info;
6571 g_assert (info_var);
6572 g_assert (locals_var);
6574 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6575 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6576 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6577 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6578 addr += (gint32)info_var->offset;
6579 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6580 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6581 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6583 g_assert_not_reached ();
6587 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6588 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6589 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6590 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6591 addr += (gint32)locals_var->offset;
6592 locals = (guint8 *)*(gpointer*)addr;
6593 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6594 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6596 g_assert_not_reached ();
6600 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6602 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6607 g_assert_not_reached ();
6612 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6616 guint8 *addr, *gaddr;
6618 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6619 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6621 if (MONO_TYPE_IS_REFERENCE (t))
6622 size = sizeof (gpointer);
6624 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6627 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6628 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6630 gboolean is_signed = FALSE;
6633 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6636 // FIXME: Write barriers
6637 mono_gc_memmove_atomic (addr, val, size);
6642 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6647 v = is_signed ? *(gint8*)val : *(guint8*)val;
6650 v = is_signed ? *(gint16*)val : *(guint16*)val;
6653 v = is_signed ? *(gint32*)val : *(guint32*)val;
6656 v = is_signed ? *(gint64*)val : *(guint64*)val;
6659 g_assert_not_reached ();
6662 /* Set value on the stack or in the return ctx */
6663 if (reg_locations [reg]) {
6664 /* Saved on the stack */
6665 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6666 *(reg_locations [reg]) = v;
6669 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6670 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6673 // FIXME: Move these to mono-context.h/c.
6674 mono_arch_context_set_int_reg (ctx, reg, v);
6676 // FIXME: Can't set registers, so we disable linears
6681 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6682 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6683 addr += (gint32)var->offset;
6685 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6688 addr = *(guint8**)addr;
6694 // FIXME: Write barriers
6695 mono_gc_memmove_atomic (addr, val, size);
6697 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6698 /* Same as regoffset, but with an indirection */
6699 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6700 addr += (gint32)var->offset;
6702 gaddr = (guint8 *)*(gpointer*)addr;
6704 // FIXME: Write barriers
6705 mono_gc_memmove_atomic (gaddr, val, size);
6707 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6711 g_assert_not_reached ();
6716 clear_event_request (int req_id, int etype)
6720 mono_loader_lock ();
6721 for (i = 0; i < event_requests->len; ++i) {
6722 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6724 if (req->id == req_id && req->event_kind == etype) {
6725 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6726 clear_breakpoint ((MonoBreakpoint *)req->info);
6727 if (req->event_kind == EVENT_KIND_STEP)
6728 ss_destroy ((SingleStepReq *)req->info);
6729 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6730 clear_breakpoint ((MonoBreakpoint *)req->info);
6731 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6732 clear_breakpoint ((MonoBreakpoint *)req->info);
6733 g_ptr_array_remove_index_fast (event_requests, i);
6738 mono_loader_unlock ();
6742 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6746 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6747 m->kind = MOD_KIND_NONE;
6748 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6749 int count = 0, match_count = 0, pos;
6750 MonoAssembly **newassemblies;
6752 for (i = 0; m->data.assemblies [i]; ++i) {
6754 if (m->data.assemblies [i] == assembly)
6759 // +1 because we don't know length and we use last element to check for end
6760 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6763 for (i = 0; i < count; ++i)
6764 if (m->data.assemblies [i] != assembly)
6765 newassemblies [pos ++] = m->data.assemblies [i];
6766 g_assert (pos == count - match_count);
6767 g_free (m->data.assemblies);
6768 m->data.assemblies = newassemblies;
6774 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6778 for (i = 0; i < req->nmodifiers; ++i) {
6779 Modifier *m = &req->modifiers [i];
6781 clear_assembly_from_modifier (req, m, assembly);
6786 * clear_event_requests_for_assembly:
6788 * Clear all events requests which reference ASSEMBLY.
6791 clear_event_requests_for_assembly (MonoAssembly *assembly)
6796 mono_loader_lock ();
6800 for (i = 0; i < event_requests->len; ++i) {
6801 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6803 clear_assembly_from_modifiers (req, assembly);
6805 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6806 clear_event_request (req->id, req->event_kind);
6811 if (req->event_kind == EVENT_KIND_STEP)
6812 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6815 mono_loader_unlock ();
6819 * type_comes_from_assembly:
6821 * GHRFunc that returns TRUE if klass comes from assembly
6824 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6826 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6830 * clear_types_for_assembly:
6832 * Clears types from loaded_classes for a given assembly
6835 clear_types_for_assembly (MonoAssembly *assembly)
6837 MonoDomain *domain = mono_domain_get ();
6838 AgentDomainInfo *info = NULL;
6840 if (!domain || !domain_jit_info (domain))
6841 /* Can happen during shutdown */
6844 info = get_agent_domain_info (domain);
6846 mono_loader_lock ();
6847 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6848 mono_loader_unlock ();
6852 add_thread (gpointer key, gpointer value, gpointer user_data)
6854 MonoInternalThread *thread = (MonoInternalThread *)value;
6855 Buffer *buf = (Buffer *)user_data;
6857 buffer_add_objid (buf, (MonoObject*)thread);
6861 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6864 guint8 *end = invoke->endp;
6868 MonoMethodSignature *sig;
6871 MonoObject *this_arg, *res, *exc;
6874 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6877 MonoStopwatch watch;
6879 if (invoke->method) {
6881 * Invoke this method directly, currently only Environment.Exit () is supported.
6884 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>");
6886 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6887 mono_error_assert_ok (&error);
6889 g_assert_not_reached ();
6892 m = decode_methodid (p, &p, end, &domain, &err);
6893 if (err != ERR_NONE)
6895 sig = mono_method_signature (m);
6897 if (m->klass->valuetype)
6898 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6900 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6901 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6902 /* Should be null */
6903 int type = decode_byte (p, &p, end);
6904 if (type != VALUE_TYPE_ID_NULL) {
6905 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6906 return ERR_INVALID_ARGUMENT;
6908 memset (this_buf, 0, mono_class_instance_size (m->klass));
6909 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6913 int type = decode_byte (p, &tmp_p, end);
6914 if (type == VALUE_TYPE_ID_NULL) {
6915 memset (this_buf, 0, mono_class_instance_size (m->klass));
6918 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6919 if (err != ERR_NONE)
6923 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6924 if (err != ERR_NONE)
6928 if (!m->klass->valuetype)
6929 this_arg = *(MonoObject**)this_buf;
6933 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6935 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6936 return ERR_INVALID_ARGUMENT;
6938 m = mono_object_get_virtual_method (this_arg, m);
6939 /* Transform this to the format the rest of the code expects it to be */
6940 if (m->klass->valuetype) {
6941 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6942 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6944 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6946 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6947 return ERR_INVALID_ARGUMENT;
6949 m = mono_object_get_virtual_method (this_arg, m);
6950 if (m->klass->valuetype) {
6951 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6952 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6956 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>");
6958 if (this_arg && this_arg->vtable->domain != domain)
6961 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6962 if (!strcmp (m->name, ".ctor")) {
6963 if (mono_class_is_abstract (m->klass))
6964 return ERR_INVALID_ARGUMENT;
6967 this_arg = mono_object_new_checked (domain, m->klass, &error);
6968 mono_error_assert_ok (&error);
6971 return ERR_INVALID_ARGUMENT;
6975 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6976 return ERR_INVALID_ARGUMENT;
6978 nargs = decode_int (p, &p, end);
6979 if (nargs != sig->param_count)
6980 return ERR_INVALID_ARGUMENT;
6981 /* Use alloca to get gc tracking */
6982 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6983 memset (arg_buf, 0, nargs * sizeof (gpointer));
6984 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6985 for (i = 0; i < nargs; ++i) {
6986 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6987 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6988 if (err != ERR_NONE)
6990 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6993 if (sig->params [i]->byref) {
6994 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6995 *(gpointer*)arg_buf [i] = args [i];
6996 args [i] = arg_buf [i];
6999 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
7000 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
7001 if (err != ERR_NONE)
7003 args [i] = arg_buf [i];
7010 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7011 tls->disable_breakpoints = TRUE;
7013 tls->disable_breakpoints = FALSE;
7016 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7018 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7019 if (invoke->has_ctx) {
7022 lmf_addr = mono_get_lmf_addr ();
7025 memset (&ext, 0, sizeof (ext));
7026 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7028 ext.debugger_invoke = TRUE;
7029 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7031 mono_set_lmf ((MonoLMF*)&ext);
7035 mono_stopwatch_start (&watch);
7036 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7037 if (exc == NULL && !mono_error_ok (&error)) {
7038 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7040 mono_error_cleanup (&error); /* FIXME report error */
7042 mono_stopwatch_stop (&watch);
7043 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));
7045 buffer_add_byte (buf, 0);
7046 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7048 gboolean out_this = FALSE;
7049 gboolean out_args = FALSE;
7051 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7053 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7055 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7056 if (sig->ret->type == MONO_TYPE_VOID) {
7057 if (!strcmp (m->name, ".ctor")) {
7058 if (!m->klass->valuetype)
7059 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7061 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7063 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7065 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7066 buffer_add_value (buf, sig->ret, &res, domain);
7067 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7068 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7069 MonoClass *k = mono_class_from_mono_type (sig->ret);
7070 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7072 g_assert (nullable_buf);
7073 mono_nullable_init (nullable_buf, res, k);
7074 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7077 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7083 /* Return the new value of the receiver after the call */
7084 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7086 buffer_add_int (buf, nargs);
7087 for (i = 0; i < nargs; ++i) {
7088 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7089 buffer_add_value (buf, sig->params [i], &args [i], domain);
7090 else if (sig->params [i]->byref)
7091 /* add_value () does an indirection */
7092 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7094 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7099 tls->disable_breakpoints = FALSE;
7101 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7102 if (invoke->has_ctx)
7103 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7107 // FIXME: byref arguments
7115 * Invoke the method given by tls->pending_invoke in the current thread.
7118 invoke_method (void)
7120 DebuggerTlsData *tls;
7126 MonoContext restore_ctx;
7129 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7133 * Store the `InvokeData *' in `tls->invoke' until we're done with
7134 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7137 mono_loader_lock ();
7139 invoke = tls->pending_invoke;
7141 tls->pending_invoke = NULL;
7143 invoke->last_invoke = tls->invoke;
7144 tls->invoke = invoke;
7146 mono_loader_unlock ();
7148 tls->frames_up_to_date = FALSE;
7154 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7155 buffer_init (&buf, 128);
7158 /* Fail the other invokes as well */
7160 err = do_invoke_method (tls, &buf, invoke, p, &p);
7163 if (tls->abort_requested) {
7164 if (CHECK_PROTOCOL_VERSION (2, 42))
7165 err = ERR_INVOKE_ABORTED;
7168 /* Start suspending before sending the reply */
7169 if (mindex == invoke->nmethods - 1) {
7170 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7171 for (i = 0; i < invoke->suspend_count; ++i)
7176 send_reply_packet (id, err, &buf);
7181 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7183 if (invoke->has_ctx)
7184 save_thread_context (&restore_ctx);
7186 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7187 g_assert (tls->resume_count);
7188 tls->resume_count -= invoke->suspend_count;
7191 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7194 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7196 * It is possible that mono_thread_internal_abort () was called
7197 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7198 * because we reset the abort here.
7201 mono_loader_lock ();
7203 if (tls->abort_requested)
7204 mono_thread_internal_reset_abort (tls->thread);
7206 tls->invoke = tls->invoke->last_invoke;
7207 tls->abort_requested = FALSE;
7209 mono_loader_unlock ();
7218 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7220 MonoThread *thread = (MonoThread *)value;
7221 DebuggerTlsData *tls;
7224 mono_loader_lock ();
7225 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7227 res = tls->really_suspended;
7228 mono_loader_unlock ();
7234 get_source_files_for_type (MonoClass *klass)
7236 gpointer iter = NULL;
7238 MonoDebugSourceInfo *sinfo;
7242 files = g_ptr_array_new ();
7244 while ((method = mono_class_get_methods (klass, &iter))) {
7245 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7246 GPtrArray *source_file_list;
7249 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7250 for (j = 0; j < source_file_list->len; ++j) {
7251 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7252 for (i = 0; i < files->len; ++i)
7253 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7255 if (i == files->len)
7256 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7258 g_ptr_array_free (source_file_list, TRUE);
7266 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7269 case CMD_VM_VERSION: {
7270 char *build_info, *version;
7272 build_info = mono_get_runtime_build_info ();
7273 version = g_strdup_printf ("mono %s", build_info);
7275 buffer_add_string (buf, version); /* vm version */
7276 buffer_add_int (buf, MAJOR_VERSION);
7277 buffer_add_int (buf, MINOR_VERSION);
7278 g_free (build_info);
7282 case CMD_VM_SET_PROTOCOL_VERSION: {
7283 major_version = decode_int (p, &p, end);
7284 minor_version = decode_int (p, &p, end);
7285 protocol_version_set = TRUE;
7286 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7289 case CMD_VM_ALL_THREADS: {
7291 mono_loader_lock ();
7292 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7293 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7294 mono_loader_unlock ();
7297 case CMD_VM_SUSPEND:
7299 wait_for_suspend ();
7302 if (suspend_count == 0)
7303 return ERR_NOT_SUSPENDED;
7305 clear_suspended_objs ();
7307 case CMD_VM_DISPOSE:
7308 /* Clear all event requests */
7309 mono_loader_lock ();
7310 while (event_requests->len > 0) {
7311 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7313 clear_event_request (req->id, req->event_kind);
7315 mono_loader_unlock ();
7317 while (suspend_count > 0)
7319 disconnected = TRUE;
7320 vm_start_event_sent = FALSE;
7323 MonoInternalThread *thread;
7324 DebuggerTlsData *tls;
7325 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7326 MonoClass *env_class;
7328 MonoMethod *exit_method = NULL;
7332 exit_code = decode_int (p, &p, end);
7334 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7336 /* Have to send a reply before exiting */
7337 send_reply_packet (id, 0, buf);
7339 /* Clear all event requests */
7340 mono_loader_lock ();
7341 while (event_requests->len > 0) {
7342 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7344 clear_event_request (req->id, req->event_kind);
7346 mono_loader_unlock ();
7349 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7350 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7351 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7352 * better than doing the shutdown ourselves, since it avoids various races.
7356 wait_for_suspend ();
7358 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7359 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7361 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7364 mono_loader_lock ();
7365 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7366 mono_loader_unlock ();
7368 if (thread && exit_method) {
7369 mono_loader_lock ();
7370 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7371 mono_loader_unlock ();
7373 args = g_new0 (gpointer, 1);
7374 args [0] = g_malloc (sizeof (int));
7375 *(int*)(args [0]) = exit_code;
7377 tls->pending_invoke = g_new0 (InvokeData, 1);
7378 tls->pending_invoke->method = exit_method;
7379 tls->pending_invoke->args = args;
7380 tls->pending_invoke->nmethods = 1;
7382 while (suspend_count > 0)
7386 * No thread found, do it ourselves.
7387 * FIXME: This can race with normal shutdown etc.
7389 while (suspend_count > 0)
7392 if (!mono_runtime_try_shutdown ())
7395 mono_environment_exitcode_set (exit_code);
7397 /* Suspend all managed threads since the runtime is going away */
7398 DEBUG_PRINTF (1, "Suspending all threads...\n");
7399 mono_thread_suspend_all_other_threads ();
7400 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7401 mono_runtime_quit ();
7402 transport_close2 ();
7403 DEBUG_PRINTF (1, "Exiting...\n");
7409 case CMD_VM_INVOKE_METHOD:
7410 case CMD_VM_INVOKE_METHODS: {
7411 int objid = decode_objid (p, &p, end);
7413 DebuggerTlsData *tls;
7414 int i, count, flags, nmethods;
7417 err = get_object (objid, (MonoObject**)&thread);
7418 if (err != ERR_NONE)
7421 flags = decode_int (p, &p, end);
7423 if (command == CMD_VM_INVOKE_METHODS)
7424 nmethods = decode_int (p, &p, end);
7428 // Wait for suspending if it already started
7430 wait_for_suspend ();
7431 if (!is_suspended ())
7432 return ERR_NOT_SUSPENDED;
7434 mono_loader_lock ();
7435 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7436 mono_loader_unlock ();
7439 if (!tls->really_suspended)
7440 /* The thread is still running native code, can't do invokes */
7441 return ERR_NOT_SUSPENDED;
7444 * Store the invoke data into tls, the thread will execute it after it is
7447 if (tls->pending_invoke)
7448 return ERR_NOT_SUSPENDED;
7449 tls->pending_invoke = g_new0 (InvokeData, 1);
7450 tls->pending_invoke->id = id;
7451 tls->pending_invoke->flags = flags;
7452 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7453 memcpy (tls->pending_invoke->p, p, end - p);
7454 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7455 tls->pending_invoke->suspend_count = suspend_count;
7456 tls->pending_invoke->nmethods = nmethods;
7458 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7459 resume_thread (THREAD_TO_INTERNAL (thread));
7462 count = suspend_count;
7463 for (i = 0; i < count; ++i)
7468 case CMD_VM_ABORT_INVOKE: {
7469 int objid = decode_objid (p, &p, end);
7471 DebuggerTlsData *tls;
7475 err = get_object (objid, (MonoObject**)&thread);
7476 if (err != ERR_NONE)
7479 invoke_id = decode_int (p, &p, end);
7481 mono_loader_lock ();
7482 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7485 if (tls->abort_requested) {
7486 DEBUG_PRINTF (1, "Abort already requested.\n");
7487 mono_loader_unlock ();
7492 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7493 * actually the correct invocation.
7495 * Careful, we do not stop the thread that's doing the invocation, so we can't
7496 * inspect its stack. However, invoke_method() also acquires the loader lock
7497 * when it's done, so we're safe here.
7501 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7502 mono_loader_unlock ();
7503 return ERR_NO_INVOCATION;
7506 tls->abort_requested = TRUE;
7508 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7509 mono_loader_unlock ();
7513 case CMD_VM_SET_KEEPALIVE: {
7514 int timeout = decode_int (p, &p, end);
7515 agent_config.keepalive = timeout;
7517 #ifndef DISABLE_SOCKET_TRANSPORT
7524 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7525 GHashTableIter iter, kiter;
7530 char *fname, *basename;
7531 gboolean ignore_case;
7532 GSList *class_list, *l;
7533 GPtrArray *res_classes, *res_domains;
7535 fname = decode_string (p, &p, end);
7536 ignore_case = decode_byte (p, &p, end);
7538 basename = dbg_path_get_basename (fname);
7540 res_classes = g_ptr_array_new ();
7541 res_domains = g_ptr_array_new ();
7543 mono_loader_lock ();
7544 g_hash_table_iter_init (&iter, domains);
7545 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7546 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7548 /* Update 'source_file_to_class' cache */
7549 g_hash_table_iter_init (&kiter, info->loaded_classes);
7550 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7551 if (!g_hash_table_lookup (info->source_files, klass)) {
7552 files = get_source_files_for_type (klass);
7553 g_hash_table_insert (info->source_files, klass, files);
7555 for (i = 0; i < files->len; ++i) {
7556 char *s = (char *)g_ptr_array_index (files, i);
7557 char *s2 = dbg_path_get_basename (s);
7560 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7562 class_list = g_slist_prepend (class_list, klass);
7563 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7565 class_list = g_slist_prepend (class_list, klass);
7566 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7569 /* The _ignorecase hash contains the lowercase path */
7570 s3 = strdup_tolower (s2);
7571 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7573 class_list = g_slist_prepend (class_list, klass);
7574 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7576 class_list = g_slist_prepend (class_list, klass);
7577 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7589 s = strdup_tolower (basename);
7590 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7593 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7596 for (l = class_list; l; l = l->next) {
7597 klass = (MonoClass *)l->data;
7599 g_ptr_array_add (res_classes, klass);
7600 g_ptr_array_add (res_domains, domain);
7603 mono_loader_unlock ();
7608 buffer_add_int (buf, res_classes->len);
7609 for (i = 0; i < res_classes->len; ++i)
7610 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7611 g_ptr_array_free (res_classes, TRUE);
7612 g_ptr_array_free (res_domains, TRUE);
7615 case CMD_VM_GET_TYPES: {
7616 GHashTableIter iter;
7620 gboolean ignore_case;
7621 GPtrArray *res_classes, *res_domains;
7622 MonoTypeNameParse info;
7624 name = decode_string (p, &p, end);
7625 ignore_case = decode_byte (p, &p, end);
7627 if (!mono_reflection_parse_type (name, &info)) {
7629 mono_reflection_free_type_info (&info);
7630 return ERR_INVALID_ARGUMENT;
7633 res_classes = g_ptr_array_new ();
7634 res_domains = g_ptr_array_new ();
7636 mono_loader_lock ();
7637 g_hash_table_iter_init (&iter, domains);
7638 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7640 gboolean type_resolve;
7644 mono_domain_assemblies_lock (domain);
7645 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7646 ass = (MonoAssembly *)tmp->data;
7650 type_resolve = TRUE;
7651 /* FIXME really okay to call while holding locks? */
7652 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7653 mono_error_cleanup (&error);
7655 g_ptr_array_add (res_classes, mono_type_get_class (t));
7656 g_ptr_array_add (res_domains, domain);
7660 mono_domain_assemblies_unlock (domain);
7662 mono_loader_unlock ();
7665 mono_reflection_free_type_info (&info);
7667 buffer_add_int (buf, res_classes->len);
7668 for (i = 0; i < res_classes->len; ++i)
7669 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7670 g_ptr_array_free (res_classes, TRUE);
7671 g_ptr_array_free (res_domains, TRUE);
7674 case CMD_VM_START_BUFFERING:
7675 case CMD_VM_STOP_BUFFERING:
7676 /* Handled in the main loop */
7679 return ERR_NOT_IMPLEMENTED;
7686 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7692 case CMD_EVENT_REQUEST_SET: {
7694 int i, event_kind, suspend_policy, nmodifiers;
7698 MonoThread *step_thread;
7699 int step_thread_id = 0;
7700 StepDepth depth = STEP_DEPTH_INTO;
7701 StepSize size = STEP_SIZE_MIN;
7702 StepFilter filter = STEP_FILTER_NONE;
7706 event_kind = decode_byte (p, &p, end);
7707 suspend_policy = decode_byte (p, &p, end);
7708 nmodifiers = decode_byte (p, &p, end);
7710 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7711 req->id = InterlockedIncrement (&event_request_id);
7712 req->event_kind = event_kind;
7713 req->suspend_policy = suspend_policy;
7714 req->nmodifiers = nmodifiers;
7717 for (i = 0; i < nmodifiers; ++i) {
7718 mod = (ModifierKind)decode_byte (p, &p, end);
7720 req->modifiers [i].kind = mod;
7721 if (mod == MOD_KIND_COUNT) {
7722 req->modifiers [i].data.count = decode_int (p, &p, end);
7723 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7724 method = decode_methodid (p, &p, end, &domain, &err);
7725 if (err != ERR_NONE)
7727 location = decode_long (p, &p, end);
7728 } else if (mod == MOD_KIND_STEP) {
7729 step_thread_id = decode_id (p, &p, end);
7730 size = (StepSize)decode_int (p, &p, end);
7731 depth = (StepDepth)decode_int (p, &p, end);
7732 if (CHECK_PROTOCOL_VERSION (2, 16))
7733 filter = (StepFilter)decode_int (p, &p, end);
7734 req->modifiers [i].data.filter = filter;
7735 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7736 /* Treat STEP_THOUGH the same as HIDDEN */
7737 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7738 } else if (mod == MOD_KIND_THREAD_ONLY) {
7739 int id = decode_id (p, &p, end);
7741 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7742 if (err != ERR_NONE) {
7746 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7747 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7749 if (err != ERR_NONE)
7751 req->modifiers [i].caught = decode_byte (p, &p, end);
7752 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7753 if (CHECK_PROTOCOL_VERSION (2, 25))
7754 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7756 req->modifiers [i].subclasses = TRUE;
7757 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" : "");
7759 req->modifiers [i].data.exc_class = exc_class;
7761 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7763 return ERR_INVALID_ARGUMENT;
7766 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7767 int n = decode_int (p, &p, end);
7770 // +1 because we don't know length and we use last element to check for end
7771 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7772 for (j = 0; j < n; ++j) {
7773 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7774 if (err != ERR_NONE) {
7775 g_free (req->modifiers [i].data.assemblies);
7779 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7780 int n = decode_int (p, &p, end);
7783 modifier = &req->modifiers [i];
7784 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7785 for (j = 0; j < n; ++j) {
7786 char *s = decode_string (p, &p, end);
7790 s2 = strdup_tolower (s);
7791 g_hash_table_insert (modifier->data.source_files, s2, s2);
7795 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7796 int n = decode_int (p, &p, end);
7799 modifier = &req->modifiers [i];
7800 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7801 for (j = 0; j < n; ++j) {
7802 char *s = decode_string (p, &p, end);
7805 g_hash_table_insert (modifier->data.type_names, s, s);
7809 return ERR_NOT_IMPLEMENTED;
7813 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7816 req->info = set_breakpoint (method, location, req, &error);
7817 if (!mono_error_ok (&error)) {
7819 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7820 mono_error_cleanup (&error);
7821 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7823 } else if (req->event_kind == EVENT_KIND_STEP) {
7824 g_assert (step_thread_id);
7826 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7827 if (err != ERR_NONE) {
7832 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7833 if (err != ERR_NONE) {
7837 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7838 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7839 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7840 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7841 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7842 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7844 if (req->nmodifiers) {
7846 return ERR_NOT_IMPLEMENTED;
7850 mono_loader_lock ();
7851 g_ptr_array_add (event_requests, req);
7853 if (agent_config.defer) {
7854 /* Transmit cached data to the client on receipt of the event request */
7855 switch (req->event_kind) {
7856 case EVENT_KIND_APPDOMAIN_CREATE:
7857 /* Emit load events for currently loaded domains */
7858 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7860 case EVENT_KIND_ASSEMBLY_LOAD:
7861 /* Emit load events for currently loaded assemblies */
7862 mono_domain_foreach (send_assemblies_for_domain, NULL);
7864 case EVENT_KIND_THREAD_START:
7865 /* Emit start events for currently started threads */
7866 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7868 case EVENT_KIND_TYPE_LOAD:
7869 /* Emit type load events for currently loaded types */
7870 mono_domain_foreach (send_types_for_domain, NULL);
7876 mono_loader_unlock ();
7878 buffer_add_int (buf, req->id);
7881 case CMD_EVENT_REQUEST_CLEAR: {
7882 int etype = decode_byte (p, &p, end);
7883 int req_id = decode_int (p, &p, end);
7885 // FIXME: Make a faster mapping from req_id to request
7886 mono_loader_lock ();
7887 clear_event_request (req_id, etype);
7888 mono_loader_unlock ();
7891 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7894 mono_loader_lock ();
7896 while (i < event_requests->len) {
7897 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7899 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7900 clear_breakpoint ((MonoBreakpoint *)req->info);
7902 g_ptr_array_remove_index_fast (event_requests, i);
7908 mono_loader_unlock ();
7912 return ERR_NOT_IMPLEMENTED;
7919 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7925 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7926 buffer_add_domainid (buf, mono_get_root_domain ());
7929 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7930 domain = decode_domainid (p, &p, end, NULL, &err);
7931 if (err != ERR_NONE)
7933 buffer_add_string (buf, domain->friendly_name);
7936 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7941 domain = decode_domainid (p, &p, end, NULL, &err);
7942 if (err != ERR_NONE)
7944 mono_loader_lock ();
7946 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7949 buffer_add_int (buf, count);
7950 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7951 ass = (MonoAssembly *)tmp->data;
7952 buffer_add_assemblyid (buf, domain, ass);
7954 mono_loader_unlock ();
7957 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7958 domain = decode_domainid (p, &p, end, NULL, &err);
7959 if (err != ERR_NONE)
7962 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7965 case CMD_APPDOMAIN_GET_CORLIB: {
7966 domain = decode_domainid (p, &p, end, NULL, &err);
7967 if (err != ERR_NONE)
7970 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7973 case CMD_APPDOMAIN_CREATE_STRING: {
7977 domain = decode_domainid (p, &p, end, NULL, &err);
7978 if (err != ERR_NONE)
7980 s = decode_string (p, &p, end);
7982 o = mono_string_new (domain, s);
7983 buffer_add_objid (buf, (MonoObject*)o);
7986 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7989 MonoDomain *domain2;
7992 domain = decode_domainid (p, &p, end, NULL, &err);
7993 if (err != ERR_NONE)
7995 klass = decode_typeid (p, &p, end, &domain2, &err);
7996 if (err != ERR_NONE)
8000 g_assert (domain == domain2);
8002 o = mono_object_new_checked (domain, klass, &error);
8003 mono_error_assert_ok (&error);
8005 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
8006 if (err != ERR_NONE)
8009 buffer_add_objid (buf, o);
8013 return ERR_NOT_IMPLEMENTED;
8020 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8022 HANDLE_FUNCTION_ENTER();
8023 ErrorCode err = ERR_NONE;
8025 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8026 if (MONO_HANDLE_IS_NULL (o)) {
8027 err = ERR_INVALID_OBJECT;
8030 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8032 HANDLE_FUNCTION_RETURN_VAL (err);
8037 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8043 ass = decode_assemblyid (p, &p, end, &domain, &err);
8044 if (err != ERR_NONE)
8048 case CMD_ASSEMBLY_GET_LOCATION: {
8049 buffer_add_string (buf, mono_image_get_filename (ass->image));
8052 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8056 if (ass->image->dynamic) {
8057 buffer_add_id (buf, 0);
8059 token = mono_image_get_entry_point (ass->image);
8061 buffer_add_id (buf, 0);
8064 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8066 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8067 buffer_add_methodid (buf, domain, m);
8072 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8073 buffer_add_moduleid (buf, domain, ass->image);
8076 case CMD_ASSEMBLY_GET_OBJECT: {
8078 err = get_assembly_object_command (domain, ass, buf, &error);
8079 mono_error_cleanup (&error);
8082 case CMD_ASSEMBLY_GET_DOMAIN: {
8083 buffer_add_domainid (buf, domain);
8086 case CMD_ASSEMBLY_GET_TYPE: {
8088 char *s = decode_string (p, &p, end);
8089 gboolean ignorecase = decode_byte (p, &p, end);
8090 MonoTypeNameParse info;
8092 gboolean type_resolve, res;
8093 MonoDomain *d = mono_domain_get ();
8095 /* This is needed to be able to find referenced assemblies */
8096 res = mono_domain_set (domain, FALSE);
8099 if (!mono_reflection_parse_type (s, &info)) {
8102 if (info.assembly.name)
8104 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8105 if (!is_ok (&error)) {
8106 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8107 mono_reflection_free_type_info (&info);
8109 return ERR_INVALID_ARGUMENT;
8112 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8113 mono_reflection_free_type_info (&info);
8116 mono_domain_set (d, TRUE);
8120 case CMD_ASSEMBLY_GET_NAME: {
8122 MonoAssembly *mass = ass;
8124 name = g_strdup_printf (
8125 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8127 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8128 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8129 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8130 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8132 buffer_add_string (buf, name);
8137 return ERR_NOT_IMPLEMENTED;
8144 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8150 case CMD_MODULE_GET_INFO: {
8151 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8154 basename = g_path_get_basename (image->name);
8155 buffer_add_string (buf, basename); // name
8156 buffer_add_string (buf, image->module_name); // scopename
8157 buffer_add_string (buf, image->name); // fqname
8158 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8159 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8164 return ERR_NOT_IMPLEMENTED;
8171 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8177 case CMD_FIELD_GET_INFO: {
8178 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8180 buffer_add_string (buf, f->name);
8181 buffer_add_typeid (buf, domain, f->parent);
8182 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8183 buffer_add_int (buf, f->type->attrs);
8187 return ERR_NOT_IMPLEMENTED;
8194 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8196 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8197 /* Special case these so the client doesn't have to handle Type objects */
8199 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8200 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8201 } else if (MONO_TYPE_IS_REFERENCE (t))
8202 buffer_add_value (buf, t, &val, domain);
8204 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8208 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8214 buffer_add_int (buf, 0);
8218 for (i = 0; i < cinfo->num_attrs; ++i) {
8219 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8222 buffer_add_int (buf, nattrs);
8224 for (i = 0; i < cinfo->num_attrs; ++i) {
8225 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8226 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8227 MonoArray *typed_args, *named_args;
8229 CattrNamedArg *arginfo = NULL;
8232 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8233 if (!mono_error_ok (&error)) {
8234 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8235 mono_error_cleanup (&error);
8236 return ERR_LOADER_ERROR;
8239 buffer_add_methodid (buf, domain, attr->ctor);
8243 buffer_add_int (buf, mono_array_length (typed_args));
8244 for (j = 0; j < mono_array_length (typed_args); ++j) {
8245 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8247 t = mono_method_signature (attr->ctor)->params [j];
8249 buffer_add_cattr_arg (buf, t, domain, val);
8252 buffer_add_int (buf, 0);
8257 buffer_add_int (buf, mono_array_length (named_args));
8259 for (j = 0; j < mono_array_length (named_args); ++j) {
8260 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8262 if (arginfo [j].prop) {
8263 buffer_add_byte (buf, 0x54);
8264 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8265 } else if (arginfo [j].field) {
8266 buffer_add_byte (buf, 0x53);
8267 buffer_add_fieldid (buf, domain, arginfo [j].field);
8269 g_assert_not_reached ();
8272 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8275 buffer_add_int (buf, 0);
8284 /* FIXME: Code duplication with icall.c */
8286 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8291 mono_class_setup_interfaces (klass, error);
8292 if (!mono_error_ok (error))
8295 for (i = 0; i < klass->interface_count; i++) {
8296 ic = klass->interfaces [i];
8297 g_hash_table_insert (ifaces, ic, ic);
8299 collect_interfaces (ic, ifaces, error);
8300 if (!mono_error_ok (error))
8306 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8318 case CMD_TYPE_GET_INFO: {
8319 buffer_add_string (buf, klass->name_space);
8320 buffer_add_string (buf, klass->name);
8322 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8323 buffer_add_string (buf, name);
8325 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8326 buffer_add_moduleid (buf, domain, klass->image);
8327 buffer_add_typeid (buf, domain, klass->parent);
8328 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8329 buffer_add_typeid (buf, domain, klass->element_class);
8331 buffer_add_id (buf, 0);
8332 buffer_add_int (buf, klass->type_token);
8333 buffer_add_byte (buf, klass->rank);
8334 buffer_add_int (buf, mono_class_get_flags (klass));
8336 type = &klass->byval_arg;
8337 // FIXME: Can't decide whenever a class represents a byref type
8340 if (type->type == MONO_TYPE_PTR)
8342 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8344 if (type->type == MONO_TYPE_VALUETYPE)
8346 if (klass->enumtype)
8348 if (mono_class_is_gtd (klass))
8350 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8352 buffer_add_byte (buf, b);
8355 while ((nested = mono_class_get_nested_types (klass, &iter)))
8357 buffer_add_int (buf, nnested);
8359 while ((nested = mono_class_get_nested_types (klass, &iter)))
8360 buffer_add_typeid (buf, domain, nested);
8361 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8362 if (mono_class_is_gtd (klass))
8363 buffer_add_typeid (buf, domain, klass);
8364 else if (mono_class_is_ginst (klass))
8365 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8367 buffer_add_id (buf, 0);
8369 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8372 if (mono_class_is_ginst (klass)) {
8373 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8375 count = inst->type_argc;
8376 buffer_add_int (buf, count);
8377 for (i = 0; i < count; i++)
8378 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8379 } else if (mono_class_is_gtd (klass)) {
8380 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8383 count = container->type_argc;
8384 buffer_add_int (buf, count);
8385 for (i = 0; i < count; i++) {
8386 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8387 buffer_add_typeid (buf, domain, pklass);
8390 buffer_add_int (buf, 0);
8395 case CMD_TYPE_GET_METHODS: {
8398 gpointer iter = NULL;
8401 mono_class_setup_methods (klass);
8403 nmethods = mono_class_num_methods (klass);
8405 buffer_add_int (buf, nmethods);
8407 while ((m = mono_class_get_methods (klass, &iter))) {
8408 buffer_add_methodid (buf, domain, m);
8411 g_assert (i == nmethods);
8414 case CMD_TYPE_GET_FIELDS: {
8417 gpointer iter = NULL;
8420 nfields = mono_class_num_fields (klass);
8422 buffer_add_int (buf, nfields);
8424 while ((f = mono_class_get_fields (klass, &iter))) {
8425 buffer_add_fieldid (buf, domain, f);
8426 buffer_add_string (buf, f->name);
8427 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8428 buffer_add_int (buf, f->type->attrs);
8431 g_assert (i == nfields);
8434 case CMD_TYPE_GET_PROPERTIES: {
8437 gpointer iter = NULL;
8440 nprops = mono_class_num_properties (klass);
8442 buffer_add_int (buf, nprops);
8444 while ((p = mono_class_get_properties (klass, &iter))) {
8445 buffer_add_propertyid (buf, domain, p);
8446 buffer_add_string (buf, p->name);
8447 buffer_add_methodid (buf, domain, p->get);
8448 buffer_add_methodid (buf, domain, p->set);
8449 buffer_add_int (buf, p->attrs);
8452 g_assert (i == nprops);
8455 case CMD_TYPE_GET_CATTRS: {
8456 MonoClass *attr_klass;
8457 MonoCustomAttrInfo *cinfo;
8459 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8460 /* attr_klass can be NULL */
8461 if (err != ERR_NONE)
8464 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8465 if (!is_ok (&error)) {
8466 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8467 return ERR_LOADER_ERROR;
8470 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8471 if (err != ERR_NONE)
8475 case CMD_TYPE_GET_FIELD_CATTRS: {
8476 MonoClass *attr_klass;
8477 MonoCustomAttrInfo *cinfo;
8478 MonoClassField *field;
8480 field = decode_fieldid (p, &p, end, NULL, &err);
8481 if (err != ERR_NONE)
8483 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8484 if (err != ERR_NONE)
8487 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8488 if (!is_ok (&error)) {
8489 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8490 return ERR_LOADER_ERROR;
8493 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8494 if (err != ERR_NONE)
8498 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8499 MonoClass *attr_klass;
8500 MonoCustomAttrInfo *cinfo;
8503 prop = decode_propertyid (p, &p, end, NULL, &err);
8504 if (err != ERR_NONE)
8506 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8507 if (err != ERR_NONE)
8510 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8511 if (!is_ok (&error)) {
8512 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8513 return ERR_LOADER_ERROR;
8516 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8517 if (err != ERR_NONE)
8521 case CMD_TYPE_GET_VALUES:
8522 case CMD_TYPE_GET_VALUES_2: {
8529 MonoThread *thread_obj;
8530 MonoInternalThread *thread = NULL;
8531 guint32 special_static_type;
8533 if (command == CMD_TYPE_GET_VALUES_2) {
8534 int objid = decode_objid (p, &p, end);
8537 err = get_object (objid, (MonoObject**)&thread_obj);
8538 if (err != ERR_NONE)
8541 thread = THREAD_TO_INTERNAL (thread_obj);
8544 len = decode_int (p, &p, end);
8545 for (i = 0; i < len; ++i) {
8546 f = decode_fieldid (p, &p, end, NULL, &err);
8547 if (err != ERR_NONE)
8550 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8551 return ERR_INVALID_FIELDID;
8552 special_static_type = mono_class_field_get_special_static_type (f);
8553 if (special_static_type != SPECIAL_STATIC_NONE) {
8554 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8555 return ERR_INVALID_FIELDID;
8558 /* Check that the field belongs to the object */
8560 for (k = klass; k; k = k->parent) {
8561 if (k == f->parent) {
8567 return ERR_INVALID_FIELDID;
8569 vtable = mono_class_vtable (domain, f->parent);
8570 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8571 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8572 if (!is_ok (&error))
8573 return ERR_INVALID_FIELDID;
8574 buffer_add_value (buf, f->type, val, domain);
8579 case CMD_TYPE_SET_VALUES: {
8587 len = decode_int (p, &p, end);
8588 for (i = 0; i < len; ++i) {
8589 f = decode_fieldid (p, &p, end, NULL, &err);
8590 if (err != ERR_NONE)
8593 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8594 return ERR_INVALID_FIELDID;
8595 if (mono_class_field_is_special_static (f))
8596 return ERR_INVALID_FIELDID;
8598 /* Check that the field belongs to the object */
8600 for (k = klass; k; k = k->parent) {
8601 if (k == f->parent) {
8607 return ERR_INVALID_FIELDID;
8609 // FIXME: Check for literal/const
8611 vtable = mono_class_vtable (domain, f->parent);
8612 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8613 err = decode_value (f->type, domain, val, p, &p, end);
8614 if (err != ERR_NONE) {
8618 if (MONO_TYPE_IS_REFERENCE (f->type))
8619 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8621 mono_field_static_set_value (vtable, f, val);
8626 case CMD_TYPE_GET_OBJECT: {
8627 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8628 if (!mono_error_ok (&error)) {
8629 mono_error_cleanup (&error);
8630 return ERR_INVALID_OBJECT;
8632 buffer_add_objid (buf, o);
8635 case CMD_TYPE_GET_SOURCE_FILES:
8636 case CMD_TYPE_GET_SOURCE_FILES_2: {
8637 char *source_file, *base;
8641 files = get_source_files_for_type (klass);
8643 buffer_add_int (buf, files->len);
8644 for (i = 0; i < files->len; ++i) {
8645 source_file = (char *)g_ptr_array_index (files, i);
8646 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8647 buffer_add_string (buf, source_file);
8649 base = dbg_path_get_basename (source_file);
8650 buffer_add_string (buf, base);
8653 g_free (source_file);
8655 g_ptr_array_free (files, TRUE);
8658 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8659 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8661 if (err != ERR_NONE)
8663 if (mono_class_is_assignable_from (klass, oklass))
8664 buffer_add_byte (buf, 1);
8666 buffer_add_byte (buf, 0);
8669 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8670 char *name = decode_string (p, &p, end);
8671 int i, flags = decode_int (p, &p, end);
8675 error_init (&error);
8676 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8677 if (!is_ok (&error)) {
8678 mono_error_cleanup (&error);
8679 return ERR_LOADER_ERROR;
8681 buffer_add_int (buf, array->len);
8682 for (i = 0; i < array->len; ++i) {
8683 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8684 buffer_add_methodid (buf, domain, method);
8687 g_ptr_array_free (array, TRUE);
8691 case CMD_TYPE_GET_INTERFACES: {
8693 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8694 MonoClass *tclass, *iface;
8695 GHashTableIter iter;
8699 for (parent = tclass; parent; parent = parent->parent) {
8700 mono_class_setup_interfaces (parent, &error);
8701 if (!mono_error_ok (&error))
8702 return ERR_LOADER_ERROR;
8703 collect_interfaces (parent, iface_hash, &error);
8704 if (!mono_error_ok (&error))
8705 return ERR_LOADER_ERROR;
8708 buffer_add_int (buf, g_hash_table_size (iface_hash));
8710 g_hash_table_iter_init (&iter, iface_hash);
8711 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8712 buffer_add_typeid (buf, domain, iface);
8713 g_hash_table_destroy (iface_hash);
8716 case CMD_TYPE_GET_INTERFACE_MAP: {
8717 int tindex, ioffset;
8718 gboolean variance_used;
8720 int len, nmethods, i;
8724 len = decode_int (p, &p, end);
8725 mono_class_setup_vtable (klass);
8727 for (tindex = 0; tindex < len; ++tindex) {
8728 iclass = decode_typeid (p, &p, end, NULL, &err);
8729 if (err != ERR_NONE)
8732 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8734 return ERR_INVALID_ARGUMENT;
8736 nmethods = mono_class_num_methods (iclass);
8737 buffer_add_int (buf, nmethods);
8740 while ((method = mono_class_get_methods (iclass, &iter))) {
8741 buffer_add_methodid (buf, domain, method);
8743 for (i = 0; i < nmethods; ++i)
8744 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8748 case CMD_TYPE_IS_INITIALIZED: {
8749 MonoVTable *vtable = mono_class_vtable (domain, klass);
8752 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8754 buffer_add_int (buf, 0);
8757 case CMD_TYPE_CREATE_INSTANCE: {
8761 obj = mono_object_new_checked (domain, klass, &error);
8762 mono_error_assert_ok (&error);
8763 buffer_add_objid (buf, obj);
8767 return ERR_NOT_IMPLEMENTED;
8774 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8777 MonoDomain *old_domain;
8781 klass = decode_typeid (p, &p, end, &domain, &err);
8782 if (err != ERR_NONE)
8785 old_domain = mono_domain_get ();
8787 mono_domain_set (domain, TRUE);
8789 err = type_commands_internal (command, klass, domain, p, end, buf);
8791 mono_domain_set (old_domain, TRUE);
8797 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8799 MonoMethodHeader *header;
8803 case CMD_METHOD_GET_NAME: {
8804 buffer_add_string (buf, method->name);
8807 case CMD_METHOD_GET_DECLARING_TYPE: {
8808 buffer_add_typeid (buf, domain, method->klass);
8811 case CMD_METHOD_GET_DEBUG_INFO: {
8813 MonoDebugMethodInfo *minfo;
8815 int i, j, n_il_offsets;
8817 GPtrArray *source_file_list;
8818 MonoSymSeqPoint *sym_seq_points;
8820 header = mono_method_get_header_checked (method, &error);
8822 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8823 buffer_add_int (buf, 0);
8824 buffer_add_string (buf, "");
8825 buffer_add_int (buf, 0);
8829 minfo = mono_debug_lookup_method (method);
8831 buffer_add_int (buf, header->code_size);
8832 buffer_add_string (buf, "");
8833 buffer_add_int (buf, 0);
8834 mono_metadata_free_mh (header);
8838 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8839 buffer_add_int (buf, header->code_size);
8840 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8841 buffer_add_int (buf, source_file_list->len);
8842 for (i = 0; i < source_file_list->len; ++i) {
8843 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8844 buffer_add_string (buf, sinfo->source_file);
8845 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8846 for (j = 0; j < 16; ++j)
8847 buffer_add_byte (buf, sinfo->hash [j]);
8851 buffer_add_string (buf, source_file);
8853 buffer_add_int (buf, n_il_offsets);
8854 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8855 for (i = 0; i < n_il_offsets; ++i) {
8856 MonoSymSeqPoint *sp = &sym_seq_points [i];
8857 const char *srcfile = "";
8859 if (source_files [i] != -1) {
8860 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8861 srcfile = sinfo->source_file;
8863 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);
8864 buffer_add_int (buf, sp->il_offset);
8865 buffer_add_int (buf, sp->line);
8866 if (CHECK_PROTOCOL_VERSION (2, 13))
8867 buffer_add_int (buf, source_files [i]);
8868 if (CHECK_PROTOCOL_VERSION (2, 19))
8869 buffer_add_int (buf, sp->column);
8870 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8871 buffer_add_int (buf, sp->end_line);
8872 buffer_add_int (buf, sp->end_column);
8875 g_free (source_file);
8876 g_free (source_files);
8877 g_free (sym_seq_points);
8878 g_ptr_array_free (source_file_list, TRUE);
8879 mono_metadata_free_mh (header);
8882 case CMD_METHOD_GET_PARAM_INFO: {
8883 MonoMethodSignature *sig = mono_method_signature (method);
8887 /* FIXME: mono_class_from_mono_type () and byrefs */
8889 /* FIXME: Use a smaller encoding */
8890 buffer_add_int (buf, sig->call_convention);
8891 buffer_add_int (buf, sig->param_count);
8892 buffer_add_int (buf, sig->generic_param_count);
8893 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8894 for (i = 0; i < sig->param_count; ++i) {
8896 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8899 /* Emit parameter names */
8900 names = g_new (char *, sig->param_count);
8901 mono_method_get_param_names (method, (const char **) names);
8902 for (i = 0; i < sig->param_count; ++i)
8903 buffer_add_string (buf, names [i]);
8908 case CMD_METHOD_GET_LOCALS_INFO: {
8911 MonoDebugLocalsInfo *locals;
8912 int *locals_map = NULL;
8914 header = mono_method_get_header_checked (method, &error);
8916 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8917 return ERR_INVALID_ARGUMENT;
8920 locals = mono_debug_lookup_locals (method);
8922 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8924 buffer_add_int (buf, 1);
8925 buffer_add_int (buf, 0);
8926 buffer_add_int (buf, header->code_size);
8928 buffer_add_int (buf, header->num_locals);
8930 for (i = 0; i < header->num_locals; ++i) {
8931 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8934 for (i = 0; i < header->num_locals; ++i) {
8936 sprintf (lname, "V_%d", i);
8937 buffer_add_string (buf, lname);
8940 for (i = 0; i < header->num_locals; ++i) {
8941 buffer_add_int (buf, 0);
8942 buffer_add_int (buf, header->code_size);
8945 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8947 buffer_add_int (buf, locals->num_blocks);
8949 for (i = 0; i < locals->num_blocks; ++i) {
8950 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8951 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8952 last_start = locals->code_blocks [i].start_offset;
8956 num_locals = locals->num_locals;
8957 buffer_add_int (buf, num_locals);
8960 for (i = 0; i < num_locals; ++i) {
8961 g_assert (locals->locals [i].index < header->num_locals);
8962 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8965 for (i = 0; i < num_locals; ++i)
8966 buffer_add_string (buf, locals->locals [i].name);
8968 for (i = 0; i < num_locals; ++i) {
8969 if (locals->locals [i].block) {
8970 buffer_add_int (buf, locals->locals [i].block->start_offset);
8971 buffer_add_int (buf, locals->locals [i].block->end_offset);
8973 buffer_add_int (buf, 0);
8974 buffer_add_int (buf, header->code_size);
8978 mono_metadata_free_mh (header);
8981 mono_debug_free_locals (locals);
8982 g_free (locals_map);
8986 case CMD_METHOD_GET_INFO:
8987 buffer_add_int (buf, method->flags);
8988 buffer_add_int (buf, method->iflags);
8989 buffer_add_int (buf, method->token);
8990 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8992 if (method->is_generic)
8994 if (mono_method_signature (method)->generic_param_count)
8996 buffer_add_byte (buf, attrs);
8997 if (method->is_generic || method->is_inflated) {
9000 if (method->is_generic) {
9003 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
9005 result = imethod->declaring;
9006 if (imethod->context.class_inst) {
9007 MonoClass *klass = ((MonoMethod *) imethod)->klass;
9008 /*Generic methods gets the context of the GTD.*/
9009 if (mono_class_get_context (klass)) {
9011 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
9012 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9017 buffer_add_methodid (buf, domain, result);
9019 buffer_add_id (buf, 0);
9021 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9022 if (mono_method_signature (method)->generic_param_count) {
9025 if (method->is_inflated) {
9026 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9028 count = inst->type_argc;
9029 buffer_add_int (buf, count);
9031 for (i = 0; i < count; i++)
9032 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9034 buffer_add_int (buf, 0);
9036 } else if (method->is_generic) {
9037 MonoGenericContainer *container = mono_method_get_generic_container (method);
9039 count = mono_method_signature (method)->generic_param_count;
9040 buffer_add_int (buf, count);
9041 for (i = 0; i < count; i++) {
9042 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9043 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9044 buffer_add_typeid (buf, domain, pklass);
9047 buffer_add_int (buf, 0);
9050 buffer_add_int (buf, 0);
9055 case CMD_METHOD_GET_BODY: {
9059 header = mono_method_get_header_checked (method, &error);
9061 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9062 buffer_add_int (buf, 0);
9064 if (CHECK_PROTOCOL_VERSION (2, 18))
9065 buffer_add_int (buf, 0);
9067 buffer_add_int (buf, header->code_size);
9068 for (i = 0; i < header->code_size; ++i)
9069 buffer_add_byte (buf, header->code [i]);
9071 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9072 buffer_add_int (buf, header->num_clauses);
9073 for (i = 0; i < header->num_clauses; ++i) {
9074 MonoExceptionClause *clause = &header->clauses [i];
9076 buffer_add_int (buf, clause->flags);
9077 buffer_add_int (buf, clause->try_offset);
9078 buffer_add_int (buf, clause->try_len);
9079 buffer_add_int (buf, clause->handler_offset);
9080 buffer_add_int (buf, clause->handler_len);
9081 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9082 buffer_add_typeid (buf, domain, clause->data.catch_class);
9083 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9084 buffer_add_int (buf, clause->data.filter_offset);
9088 mono_metadata_free_mh (header);
9093 case CMD_METHOD_RESOLVE_TOKEN: {
9094 guint32 token = decode_int (p, &p, end);
9097 switch (mono_metadata_token_code (token)) {
9098 case MONO_TOKEN_STRING: {
9103 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9104 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9106 s2 = mono_string_to_utf8_checked (s, &error);
9107 mono_error_assert_ok (&error);
9109 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9110 buffer_add_string (buf, s2);
9117 MonoClass *handle_class;
9119 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9120 val = mono_method_get_wrapper_data (method, token);
9121 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9123 if (handle_class == NULL) {
9124 // Can't figure out the token type
9125 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9129 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9131 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9134 if (handle_class == mono_defaults.typehandle_class) {
9135 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9136 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9137 buffer_add_typeid (buf, domain, (MonoClass *) val);
9139 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9140 } else if (handle_class == mono_defaults.fieldhandle_class) {
9141 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9142 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9143 } else if (handle_class == mono_defaults.methodhandle_class) {
9144 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9145 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9146 } else if (handle_class == mono_defaults.string_class) {
9149 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9150 mono_error_assert_ok (&error);
9151 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9152 buffer_add_string (buf, s);
9155 g_assert_not_reached ();
9162 case CMD_METHOD_GET_CATTRS: {
9164 MonoClass *attr_klass;
9165 MonoCustomAttrInfo *cinfo;
9167 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9168 /* attr_klass can be NULL */
9169 if (err != ERR_NONE)
9172 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9173 if (!is_ok (&error)) {
9174 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9175 return ERR_LOADER_ERROR;
9178 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9179 if (err != ERR_NONE)
9183 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9185 MonoType **type_argv;
9189 MonoGenericInst *ginst;
9190 MonoGenericContext tmp_context;
9191 MonoMethod *inflated;
9193 type_argc = decode_int (p, &p, end);
9194 type_argv = g_new0 (MonoType*, type_argc);
9195 for (i = 0; i < type_argc; ++i) {
9196 klass = decode_typeid (p, &p, end, &d, &err);
9197 if (err != ERR_NONE) {
9203 return ERR_INVALID_ARGUMENT;
9205 type_argv [i] = &klass->byval_arg;
9207 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9209 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9210 tmp_context.method_inst = ginst;
9212 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9213 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9214 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9215 return ERR_INVALID_ARGUMENT;
9216 buffer_add_methodid (buf, domain, inflated);
9220 return ERR_NOT_IMPLEMENTED;
9227 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9230 MonoDomain *old_domain;
9234 method = decode_methodid (p, &p, end, &domain, &err);
9235 if (err != ERR_NONE)
9238 old_domain = mono_domain_get ();
9240 mono_domain_set (domain, TRUE);
9242 err = method_commands_internal (command, method, domain, p, end, buf);
9244 mono_domain_set (old_domain, TRUE);
9250 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9252 int objid = decode_objid (p, &p, end);
9254 MonoThread *thread_obj;
9255 MonoInternalThread *thread;
9257 err = get_object (objid, (MonoObject**)&thread_obj);
9258 if (err != ERR_NONE)
9261 thread = THREAD_TO_INTERNAL (thread_obj);
9264 case CMD_THREAD_GET_NAME: {
9266 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9269 buffer_add_int (buf, 0);
9274 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9276 buffer_add_int (buf, len);
9277 buffer_add_data (buf, (guint8*)name, len);
9282 case CMD_THREAD_GET_FRAME_INFO: {
9283 DebuggerTlsData *tls;
9284 int i, start_frame, length;
9286 // Wait for suspending if it already started
9287 // FIXME: Races with suspend_count
9288 while (!is_suspended ()) {
9290 wait_for_suspend ();
9294 wait_for_suspend ();
9295 if (!is_suspended ())
9296 return ERR_NOT_SUSPENDED;
9299 start_frame = decode_int (p, &p, end);
9300 length = decode_int (p, &p, end);
9302 if (start_frame != 0 || length != -1)
9303 return ERR_NOT_IMPLEMENTED;
9305 mono_loader_lock ();
9306 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9307 mono_loader_unlock ();
9310 compute_frame_info (thread, tls);
9312 buffer_add_int (buf, tls->frame_count);
9313 for (i = 0; i < tls->frame_count; ++i) {
9314 buffer_add_int (buf, tls->frames [i]->id);
9315 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9316 buffer_add_int (buf, tls->frames [i]->il_offset);
9318 * Instead of passing the frame type directly to the client, we associate
9319 * it with the previous frame using a set of flags. This avoids lots of
9320 * conditional code in the client, since a frame whose type isn't
9321 * FRAME_TYPE_MANAGED has no method, location, etc.
9323 buffer_add_byte (buf, tls->frames [i]->flags);
9328 case CMD_THREAD_GET_STATE:
9329 buffer_add_int (buf, thread->state);
9331 case CMD_THREAD_GET_INFO:
9332 buffer_add_byte (buf, thread->threadpool_thread);
9334 case CMD_THREAD_GET_ID:
9335 buffer_add_long (buf, (guint64)(gsize)thread);
9337 case CMD_THREAD_GET_TID:
9338 buffer_add_long (buf, (guint64)thread->tid);
9340 case CMD_THREAD_SET_IP: {
9341 DebuggerTlsData *tls;
9344 MonoSeqPointInfo *seq_points;
9349 method = decode_methodid (p, &p, end, &domain, &err);
9350 if (err != ERR_NONE)
9352 il_offset = decode_long (p, &p, end);
9354 while (!is_suspended ()) {
9356 wait_for_suspend ();
9359 mono_loader_lock ();
9360 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9361 mono_loader_unlock ();
9364 compute_frame_info (thread, tls);
9365 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9366 return ERR_INVALID_ARGUMENT;
9368 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9370 g_assert (seq_points);
9373 return ERR_INVALID_ARGUMENT;
9375 // FIXME: Check that the ip change is safe
9377 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);
9378 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9382 return ERR_NOT_IMPLEMENTED;
9389 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9393 MonoThread *thread_obj;
9394 MonoInternalThread *thread;
9395 int pos, i, len, frame_idx;
9396 DebuggerTlsData *tls;
9398 MonoDebugMethodJitInfo *jit;
9399 MonoMethodSignature *sig;
9401 MonoMethodHeader *header;
9403 objid = decode_objid (p, &p, end);
9404 err = get_object (objid, (MonoObject**)&thread_obj);
9405 if (err != ERR_NONE)
9408 thread = THREAD_TO_INTERNAL (thread_obj);
9410 id = decode_id (p, &p, end);
9412 mono_loader_lock ();
9413 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9414 mono_loader_unlock ();
9417 for (i = 0; i < tls->frame_count; ++i) {
9418 if (tls->frames [i]->id == id)
9421 if (i == tls->frame_count)
9422 return ERR_INVALID_FRAMEID;
9425 frame = tls->frames [frame_idx];
9427 /* This is supported for frames without has_ctx etc. set */
9428 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9429 if (CHECK_PROTOCOL_VERSION (2, 38))
9430 buffer_add_domainid (buf, frame->domain);
9434 if (!frame->has_ctx)
9435 return ERR_ABSENT_INFORMATION;
9437 if (!ensure_jit (frame))
9438 return ERR_ABSENT_INFORMATION;
9442 sig = mono_method_signature (frame->actual_method);
9444 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9446 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9448 return ERR_ABSENT_INFORMATION;
9451 case CMD_STACK_FRAME_GET_VALUES: {
9453 len = decode_int (p, &p, end);
9454 header = mono_method_get_header_checked (frame->actual_method, &error);
9455 mono_error_assert_ok (&error); /* FIXME report error */
9457 for (i = 0; i < len; ++i) {
9458 pos = decode_int (p, &p, end);
9463 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9465 g_assert (pos >= 0 && pos < jit->num_params);
9467 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9469 MonoDebugLocalsInfo *locals;
9471 locals = mono_debug_lookup_locals (frame->method);
9473 g_assert (pos < locals->num_locals);
9474 pos = locals->locals [pos].index;
9475 mono_debug_free_locals (locals);
9477 g_assert (pos >= 0 && pos < jit->num_locals);
9479 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9481 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9484 mono_metadata_free_mh (header);
9487 case CMD_STACK_FRAME_GET_THIS: {
9488 if (frame->api_method->klass->valuetype) {
9489 if (!sig->hasthis) {
9490 MonoObject *p = NULL;
9491 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9493 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9496 if (!sig->hasthis) {
9497 MonoObject *p = NULL;
9498 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9500 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9505 case CMD_STACK_FRAME_SET_VALUES: {
9509 MonoDebugVarInfo *var;
9511 len = decode_int (p, &p, end);
9512 header = mono_method_get_header_checked (frame->actual_method, &error);
9513 mono_error_assert_ok (&error); /* FIXME report error */
9515 for (i = 0; i < len; ++i) {
9516 pos = decode_int (p, &p, end);
9521 g_assert (pos >= 0 && pos < jit->num_params);
9523 t = sig->params [pos];
9524 var = &jit->params [pos];
9526 MonoDebugLocalsInfo *locals;
9528 locals = mono_debug_lookup_locals (frame->method);
9530 g_assert (pos < locals->num_locals);
9531 pos = locals->locals [pos].index;
9532 mono_debug_free_locals (locals);
9534 g_assert (pos >= 0 && pos < jit->num_locals);
9536 t = header->locals [pos];
9537 var = &jit->locals [pos];
9540 if (MONO_TYPE_IS_REFERENCE (t))
9541 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9543 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9544 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9545 if (err != ERR_NONE)
9548 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9550 mono_metadata_free_mh (header);
9553 case CMD_STACK_FRAME_GET_DOMAIN: {
9554 if (CHECK_PROTOCOL_VERSION (2, 38))
9555 buffer_add_domainid (buf, frame->domain);
9558 case CMD_STACK_FRAME_SET_THIS: {
9561 MonoDebugVarInfo *var;
9563 t = &frame->actual_method->klass->byval_arg;
9564 /* Checked by the sender */
9565 g_assert (MONO_TYPE_ISSTRUCT (t));
9566 var = jit->this_var;
9569 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9570 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9571 if (err != ERR_NONE)
9574 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9578 return ERR_NOT_IMPLEMENTED;
9585 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9588 int objid, index, len, i, esize;
9592 objid = decode_objid (p, &p, end);
9593 err = get_object (objid, (MonoObject**)&arr);
9594 if (err != ERR_NONE)
9598 case CMD_ARRAY_REF_GET_LENGTH:
9599 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9601 buffer_add_int (buf, arr->max_length);
9602 buffer_add_int (buf, 0);
9604 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9605 buffer_add_int (buf, arr->bounds [i].length);
9606 buffer_add_int (buf, arr->bounds [i].lower_bound);
9610 case CMD_ARRAY_REF_GET_VALUES:
9611 index = decode_int (p, &p, end);
9612 len = decode_int (p, &p, end);
9614 g_assert (index >= 0 && len >= 0);
9615 // Reordered to avoid integer overflow
9616 g_assert (!(index > arr->max_length - len));
9618 esize = mono_array_element_size (arr->obj.vtable->klass);
9619 for (i = index; i < index + len; ++i) {
9620 elem = (gpointer*)((char*)arr->vector + (i * esize));
9621 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9624 case CMD_ARRAY_REF_SET_VALUES:
9625 index = decode_int (p, &p, end);
9626 len = decode_int (p, &p, end);
9628 g_assert (index >= 0 && len >= 0);
9629 // Reordered to avoid integer overflow
9630 g_assert (!(index > arr->max_length - len));
9632 esize = mono_array_element_size (arr->obj.vtable->klass);
9633 for (i = index; i < index + len; ++i) {
9634 elem = (gpointer*)((char*)arr->vector + (i * esize));
9636 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9640 return ERR_NOT_IMPLEMENTED;
9647 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9653 int i, index, length;
9655 gboolean use_utf16 = FALSE;
9657 objid = decode_objid (p, &p, end);
9658 err = get_object (objid, (MonoObject**)&str);
9659 if (err != ERR_NONE)
9663 case CMD_STRING_REF_GET_VALUE:
9664 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9665 for (i = 0; i < mono_string_length (str); ++i)
9666 if (mono_string_chars (str)[i] == 0)
9668 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9671 buffer_add_int (buf, mono_string_length (str) * 2);
9672 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9675 s = mono_string_to_utf8_checked (str, &error);
9676 mono_error_assert_ok (&error);
9677 buffer_add_string (buf, s);
9681 case CMD_STRING_REF_GET_LENGTH:
9682 buffer_add_long (buf, mono_string_length (str));
9684 case CMD_STRING_REF_GET_CHARS:
9685 index = decode_long (p, &p, end);
9686 length = decode_long (p, &p, end);
9687 if (index > mono_string_length (str) - length)
9688 return ERR_INVALID_ARGUMENT;
9689 c = mono_string_chars (str) + index;
9690 for (i = 0; i < length; ++i)
9691 buffer_add_short (buf, c [i]);
9694 return ERR_NOT_IMPLEMENTED;
9701 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9712 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9713 objid = decode_objid (p, &p, end);
9714 err = get_object (objid, &obj);
9715 if (err != ERR_NONE)
9716 buffer_add_int (buf, 1);
9718 buffer_add_int (buf, 0);
9722 objid = decode_objid (p, &p, end);
9723 err = get_object (objid, &obj);
9724 if (err != ERR_NONE)
9727 MonoClass *obj_type;
9728 gboolean remote_obj = FALSE;
9730 obj_type = obj->vtable->klass;
9731 if (mono_class_is_transparent_proxy (obj_type)) {
9732 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9736 g_assert (obj_type);
9739 case CMD_OBJECT_REF_GET_TYPE:
9740 /* This handles transparent proxies too */
9741 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9743 case CMD_OBJECT_REF_GET_VALUES:
9744 len = decode_int (p, &p, end);
9746 for (i = 0; i < len; ++i) {
9747 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9748 if (err != ERR_NONE)
9751 /* Check that the field belongs to the object */
9753 for (k = obj_type; k; k = k->parent) {
9754 if (k == f->parent) {
9760 return ERR_INVALID_FIELDID;
9762 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9766 if (mono_class_field_is_special_static (f))
9767 return ERR_INVALID_FIELDID;
9769 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9770 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9771 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9772 mono_field_static_get_value_checked (vtable, f, val, &error);
9773 if (!is_ok (&error)) {
9774 mono_error_cleanup (&error); /* FIXME report the error */
9775 return ERR_INVALID_OBJECT;
9777 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9780 guint8 *field_value = NULL;
9783 #ifndef DISABLE_REMOTING
9784 void *field_storage = NULL;
9785 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9786 if (!is_ok (&error)) {
9787 mono_error_cleanup (&error); /* FIXME report the error */
9788 return ERR_INVALID_OBJECT;
9791 g_assert_not_reached ();
9794 field_value = (guint8*)obj + f->offset;
9796 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9800 case CMD_OBJECT_REF_SET_VALUES:
9801 len = decode_int (p, &p, end);
9803 for (i = 0; i < len; ++i) {
9804 f = decode_fieldid (p, &p, end, NULL, &err);
9805 if (err != ERR_NONE)
9808 /* Check that the field belongs to the object */
9810 for (k = obj_type; k; k = k->parent) {
9811 if (k == f->parent) {
9817 return ERR_INVALID_FIELDID;
9819 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9823 if (mono_class_field_is_special_static (f))
9824 return ERR_INVALID_FIELDID;
9826 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9827 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9829 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9830 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9831 if (err != ERR_NONE) {
9835 mono_field_static_set_value (vtable, f, val);
9838 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9839 if (err != ERR_NONE)
9844 case CMD_OBJECT_REF_GET_ADDRESS:
9845 buffer_add_long (buf, (gssize)obj);
9847 case CMD_OBJECT_REF_GET_DOMAIN:
9848 buffer_add_domainid (buf, obj->vtable->domain);
9850 case CMD_OBJECT_REF_GET_INFO:
9851 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9852 buffer_add_domainid (buf, obj->vtable->domain);
9855 return ERR_NOT_IMPLEMENTED;
9862 command_set_to_string (CommandSet command_set)
9864 switch (command_set) {
9867 case CMD_SET_OBJECT_REF:
9868 return "OBJECT_REF";
9869 case CMD_SET_STRING_REF:
9870 return "STRING_REF";
9871 case CMD_SET_THREAD:
9873 case CMD_SET_ARRAY_REF:
9875 case CMD_SET_EVENT_REQUEST:
9876 return "EVENT_REQUEST";
9877 case CMD_SET_STACK_FRAME:
9878 return "STACK_FRAME";
9879 case CMD_SET_APPDOMAIN:
9881 case CMD_SET_ASSEMBLY:
9883 case CMD_SET_METHOD:
9887 case CMD_SET_MODULE:
9898 static const char* vm_cmds_str [] = {
9906 "SET_PROTOCOL_VERSION",
9909 "GET_TYPES_FOR_SOURCE_FILE",
9914 static const char* thread_cmds_str[] = {
9924 static const char* event_cmds_str[] = {
9927 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9930 static const char* appdomain_cmds_str[] = {
9932 "GET_FRIENDLY_NAME",
9934 "GET_ENTRY_ASSEMBLY",
9937 "CREATE_BOXED_VALUE"
9940 static const char* assembly_cmds_str[] = {
9943 "GET_MANIFEST_MODULE",
9950 static const char* module_cmds_str[] = {
9954 static const char* field_cmds_str[] = {
9958 static const char* method_cmds_str[] = {
9960 "GET_DECLARING_TYPE",
9968 "MAKE_GENERIC_METHOD"
9971 static const char* type_cmds_str[] = {
9979 "IS_ASSIGNABLE_FROM",
9983 "GET_PROPERTY_CATTRS",
9984 "GET_SOURCE_FILES_2",
9986 "GET_METHODS_BY_NAME_FLAGS",
9988 "GET_INTERFACE_MAP",
9992 static const char* stack_frame_cmds_str[] = {
10000 static const char* array_cmds_str[] = {
10006 static const char* string_cmds_str[] = {
10012 static const char* object_cmds_str[] = {
10023 cmd_to_string (CommandSet set, int command)
10030 cmds = vm_cmds_str;
10031 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10033 case CMD_SET_OBJECT_REF:
10034 cmds = object_cmds_str;
10035 cmds_len = G_N_ELEMENTS (object_cmds_str);
10037 case CMD_SET_STRING_REF:
10038 cmds = string_cmds_str;
10039 cmds_len = G_N_ELEMENTS (string_cmds_str);
10041 case CMD_SET_THREAD:
10042 cmds = thread_cmds_str;
10043 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10045 case CMD_SET_ARRAY_REF:
10046 cmds = array_cmds_str;
10047 cmds_len = G_N_ELEMENTS (array_cmds_str);
10049 case CMD_SET_EVENT_REQUEST:
10050 cmds = event_cmds_str;
10051 cmds_len = G_N_ELEMENTS (event_cmds_str);
10053 case CMD_SET_STACK_FRAME:
10054 cmds = stack_frame_cmds_str;
10055 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10057 case CMD_SET_APPDOMAIN:
10058 cmds = appdomain_cmds_str;
10059 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10061 case CMD_SET_ASSEMBLY:
10062 cmds = assembly_cmds_str;
10063 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10065 case CMD_SET_METHOD:
10066 cmds = method_cmds_str;
10067 cmds_len = G_N_ELEMENTS (method_cmds_str);
10070 cmds = type_cmds_str;
10071 cmds_len = G_N_ELEMENTS (type_cmds_str);
10073 case CMD_SET_MODULE:
10074 cmds = module_cmds_str;
10075 cmds_len = G_N_ELEMENTS (module_cmds_str);
10077 case CMD_SET_FIELD:
10078 cmds = field_cmds_str;
10079 cmds_len = G_N_ELEMENTS (field_cmds_str);
10081 case CMD_SET_EVENT:
10082 cmds = event_cmds_str;
10083 cmds_len = G_N_ELEMENTS (event_cmds_str);
10088 if (command > 0 && command <= cmds_len)
10089 return cmds [command - 1];
10095 wait_for_attach (void)
10097 #ifndef DISABLE_SOCKET_TRANSPORT
10098 if (listen_fd == -1) {
10099 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10103 /* Block and wait for client connection */
10104 conn_fd = socket_transport_accept (listen_fd);
10106 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10107 if (conn_fd == -1) {
10108 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10112 g_assert_not_reached ();
10116 disconnected = !transport_handshake ();
10117 if (disconnected) {
10118 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10128 * This thread handles communication with the debugger client using a JDWP
10131 static gsize WINAPI
10132 debugger_thread (void *arg)
10135 int res, len, id, flags, command = 0;
10136 CommandSet command_set = (CommandSet)0;
10137 guint8 header [HEADER_LENGTH];
10138 guint8 *data, *p, *end;
10142 gboolean attach_failed = FALSE;
10144 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10146 debugger_thread_id = mono_native_thread_id_get ();
10148 MonoInternalThread *internal = mono_thread_internal_current ();
10149 mono_thread_set_name_internal (internal, mono_string_new (mono_domain_get (), "Debugger agent"), TRUE, FALSE, &error);
10150 mono_error_assert_ok (&error);
10152 internal->state |= ThreadState_Background;
10153 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10155 if (agent_config.defer) {
10156 if (!wait_for_attach ()) {
10157 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10158 attach_failed = TRUE; // Don't abort process when we can't listen
10160 mono_set_is_debugger_attached (TRUE);
10161 /* Send start event to client */
10162 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10165 mono_set_is_debugger_attached (TRUE);
10168 while (!attach_failed) {
10169 res = transport_recv (header, HEADER_LENGTH);
10171 /* This will break if the socket is closed during shutdown too */
10172 if (res != HEADER_LENGTH) {
10173 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10178 end = header + HEADER_LENGTH;
10180 len = decode_int (p, &p, end);
10181 id = decode_int (p, &p, end);
10182 flags = decode_byte (p, &p, end);
10183 command_set = (CommandSet)decode_byte (p, &p, end);
10184 command = decode_byte (p, &p, end);
10186 g_assert (flags == 0);
10189 const char *cmd_str;
10190 char cmd_num [256];
10192 cmd_str = cmd_to_string (command_set, command);
10194 sprintf (cmd_num, "%d", command);
10198 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);
10201 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10202 if (len - HEADER_LENGTH > 0)
10204 res = transport_recv (data, len - HEADER_LENGTH);
10205 if (res != len - HEADER_LENGTH) {
10206 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10212 end = data + (len - HEADER_LENGTH);
10214 buffer_init (&buf, 128);
10219 /* Process the request */
10220 switch (command_set) {
10222 err = vm_commands (command, id, p, end, &buf);
10223 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10224 /* Sent after the invoke is complete */
10227 case CMD_SET_EVENT_REQUEST:
10228 err = event_commands (command, p, end, &buf);
10230 case CMD_SET_APPDOMAIN:
10231 err = domain_commands (command, p, end, &buf);
10233 case CMD_SET_ASSEMBLY:
10234 err = assembly_commands (command, p, end, &buf);
10236 case CMD_SET_MODULE:
10237 err = module_commands (command, p, end, &buf);
10239 case CMD_SET_FIELD:
10240 err = field_commands (command, p, end, &buf);
10243 err = type_commands (command, p, end, &buf);
10245 case CMD_SET_METHOD:
10246 err = method_commands (command, p, end, &buf);
10248 case CMD_SET_THREAD:
10249 err = thread_commands (command, p, end, &buf);
10251 case CMD_SET_STACK_FRAME:
10252 err = frame_commands (command, p, end, &buf);
10254 case CMD_SET_ARRAY_REF:
10255 err = array_commands (command, p, end, &buf);
10257 case CMD_SET_STRING_REF:
10258 err = string_commands (command, p, end, &buf);
10260 case CMD_SET_OBJECT_REF:
10261 err = object_commands (command, p, end, &buf);
10264 err = ERR_NOT_IMPLEMENTED;
10267 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10268 buffer_replies = TRUE;
10272 if (buffer_replies) {
10273 buffer_reply_packet (id, err, &buf);
10275 send_reply_packet (id, err, &buf);
10276 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10280 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10281 send_buffered_reply_packets ();
10282 buffer_replies = FALSE;
10286 buffer_free (&buf);
10288 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10292 mono_set_is_debugger_attached (FALSE);
10294 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10295 debugger_thread_exited = TRUE;
10296 mono_coop_cond_signal (&debugger_thread_exited_cond);
10297 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10299 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10301 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10302 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10303 start_debugger_thread ();
10309 #else /* DISABLE_DEBUGGER_AGENT */
10312 mono_debugger_agent_parse_options (char *options)
10314 g_error ("This runtime is configured with the debugger agent disabled.");
10318 mono_debugger_agent_init (void)
10323 mono_debugger_agent_breakpoint_hit (void *sigctx)
10328 mono_debugger_agent_single_step_event (void *sigctx)
10333 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10338 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10339 MonoContext *catch_ctx)
10344 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10349 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10354 mono_debugger_agent_user_break (void)
10360 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10365 mono_debugger_agent_debug_log_is_enabled (void)
10371 mono_debugger_agent_unhandled_exception (MonoException *exc)
10373 g_assert_not_reached ();
10377 debugger_agent_single_step_from_context (MonoContext *ctx)
10379 g_assert_not_reached ();
10383 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10385 g_assert_not_reached ();